zztaeha

C functions

349 functions in daegun 2.0.0, as its headers declare them and its library exports them, filed by header. Each says what it does, what its outs receive, what is borrowed and what is yours to free, and which statuses it answers, with an example that was compiled and run against 2.0.0.

The examples assume font, an open const daegun_font *, and leave withreturn 1 where a call fails, where a real program would free what it holds first.The rules hold for every call here, so no entry repeats them: a NULL where a pointer is required answers DAEGUN_NULL, and a call that fails leaves a handle out NULL.

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_abi_version
uint32_t daegun_abi_version(void);

The version of the C ABI the library was built with, to check against the header your program was compiled with.

The number is (major << 16) | (minor << 8) | patch, which is 0x020000 here. It is the version of the ABI, not of the library: daegun_version gives the release.

The minor goes up when calls or constants are added, or an options struct grows at its end, so a library with a higher minor still serves your program. The major goes up when an existing call, constant or any other struct changes. So refuse a library whose major differs from that of DAEGUN_ABI_VERSION, or whose minor is lower, since a lower minor lacks calls you may use. DAEGUN_ABI_COMPATIBLE makes exactly that test.

Check once at startup. It matters most with a shared library, where the one found at run time may not be the one your program was built against.

uint32_t abi = daegun_abi_version();
if (!DAEGUN_ABI_COMPATIBLE(abi)) {
    fprintf(stderr, "daegun's ABI is %u.%u.%u, and this program was built for %u.%u\n",
            DAEGUN_ABI_MAJOR(abi), DAEGUN_ABI_MINOR(abi), DAEGUN_ABI_PATCH(abi),
            DAEGUN_ABI_MAJOR(DAEGUN_ABI_VERSION), DAEGUN_ABI_MINOR(DAEGUN_ABI_VERSION));
    return 1;
}
daegun_version
daegun_str daegun_version(void);

The library's release, such as 2.0.0, for a log or a bug report.

Returns a daegun_str that points at a static string, valid for the life of the program, with nothing to free. It names the release and nothing more: whether a library can serve your program is for daegun_abi_version to say.

daegun_str version = daegun_version();
fprintf(stderr, "running daegun %s\n", version.data);
/* version.data is "2.0.0". */
daegun_last_error
daegun_str daegun_last_error(void);

The reason the last failure on the calling thread gave, as text.

A status says what kind of failure a call met, and this says what exactly: which table, which byte, which argument. It returns a daegun_str of UTF-8 text for a log or an error message.

Every failure writes a reason: DAEGUN_MALFORMED, DAEGUN_INVALID_ARGUMENT, DAEGUN_UNSUPPORTED, DAEGUN_MISSING, DAEGUN_LIMIT_EXCEEDED, DAEGUN_NO_OUTLINE and DAEGUN_OVERFLOW. The other three write none and leave the reason as it was: DAEGUN_OK, DAEGUN_NULL, which is a pointer of your own, and DAEGUN_ABSENT, which is an answer. So the reason tells you about the call you just made only if that call answered a failure. Check the status first, then read the reason right away.

The reason is kept per thread, like errno, because handles are shared between threads and one slot for all of them would hand one thread another's failure. Read it on the thread that made the failing call. The string is valid until the next failure on that thread writes a new reason, or until the thread ends, so copy it to keep it. daegun_thread_release leaves it in place.

Until a thread has had a failure, the string is empty: len is 0 and data points at a lone NUL. A failure inside a thread-exit destructor of yours may leave no reason, as the thread's slot can be gone by then.

uint8_t junk[64];
memset(junk, 0xAB, sizeof junk);
daegun_font *opened = NULL;
if (daegun_font_open(junk, sizeof junk, &opened) != DAEGUN_OK) {
    daegun_str reason = daegun_last_error();
    fprintf(stderr, "can't open the font: %s\n", reason.data);
    /* Prints "can't open the font: TTF/OTF: not a font file (signature: 0xABABABAB)". */
}
daegun_font_free(opened);
daegun_thread_release
void daegun_thread_release(void);

Lets go of what the calling thread keeps between calls.

To make repeated calls fast, each thread keeps some working state of its own: the locations it last read at, its hinters, its recent runs, scratch memory it reuses, and freed handles kept for its next one of the same kind. This call drops all of that for the thread that calls it.

Call it when a thread goes idle, as a worker in a pool does, or once a font is freed. What a thread last read and hinted with holds on to those fonts' bytes, so a freed font may stay in memory until the thread hints or reads at locations of other fonts, ends, or calls this.

Nothing is lost by it. Other threads keep their own state, this thread's next call builds again what it needs, and what daegun_last_error returns stays as it was.

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

/* The batch is done and the thread is about to wait for more work. */
daegun_thread_release();

/* The next call builds again what it needs, and answers as before. */
run = NULL;
if (daegun_font_shape(font, "Wave", 4, NULL, NULL, &run) != DAEGUN_OK) return 1;
double width = 0.0;
if (daegun_shaped_run_width(run, &width) != DAEGUN_OK) return 1;
daegun_shaped_run_free(run);
daegun_status_name
daegun_str daegun_status_name(daegun_status status);

A status's name as text, such as DAEGUN_INVALID_ARGUMENT, for a log.

Returns a daegun_str that points at a static string, valid for the life of the program, with nothing to free. The name is the constant's own spelling. A value that is no status of this library, the retired -5 among them, gives unknown.

It pairs with daegun_last_error: the name says what kind of failure it was, and the reason says what exactly went wrong.

daegun_shaped_run *run = NULL;
daegun_status status = daegun_font_shape(font, "a\xff", 2, NULL, NULL, &run);
daegun_str name = daegun_status_name(status);
/* name.data is "DAEGUN_INVALID_ARGUMENT", as the text is not UTF-8. */
daegun_shaped_run_free(run);
daegun_tag_from_string
daegun_status daegun_tag_from_string(
    const char *text,
    size_t text_len,
    daegun_tag *out
);

Reads a tag from text, for a tag that arrives at run time or a language that can't use DAEGUN_TAG.

The text is one to four printable ASCII characters, with any number of spaces after them. A tag shorter than four characters is padded with spaces, as fonts store it, so lao and lao give the same tag. The text comes as a pointer and its length in bytes, and needs no NUL.

Anything else answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was: empty text, more than four characters, a space before or between them, a character outside printable ASCII, or text that is not UTF-8. The reason is in daegun_last_error.

text may be NULL only with a text_len of 0. That is empty text, so it is refused the same way.

In C, DAEGUN_TAG does the same work at compile time. This call is for a tag read from a file, a command line or a user, and for a language such as Swift that cannot call a C macro.

daegun_tag tag = 0;
if (daegun_tag_from_string("wght", 4, &tag) != DAEGUN_OK) return 1;
/* The same tag as DAEGUN_TAG('w', 'g', 'h', 't'). */

if (daegun_tag_from_string("lao", 3, &tag) != DAEGUN_OK) return 1;
/* A short tag is padded with a space: DAEGUN_TAG('l', 'a', 'o', ' '). */
daegun_blob_data
const uint8_t *daegun_blob_data(const daegun_blob *blob, size_t *out_count);

A blob's bytes, and how many there are.

Returns a borrowed pointer and sets *out_count to the number of bytes. They are valid until daegun_blob_free. Don't free the pointer itself. NULL comes back, with the count left as it was, only if blob or out_count is NULL.

/* The default instance of Inter, as a font file. */
daegun_blob *file = NULL;
if (daegun_font_instance(font, NULL, &file) != DAEGUN_OK) return 1;

size_t size = 0;
const uint8_t *bytes = daegun_blob_data(file, &size);
/* A font file with TrueType outlines starts with the bytes 00 01 00 00. */

daegun_blob_free(file);
daegun_blob_free
void daegun_blob_free(daegun_blob *blob);

Frees a blob.

NULL is fine and does nothing, so a cleanup path may free without checking. The bytes that daegun_blob_data lent are invalid afterward.

daegun_blob *file = NULL;
daegun_status status = daegun_font_instance(font, NULL, &file);
if (status == DAEGUN_OK) {
    /* read the bytes */
}
/* Safe either way: a call that fails leaves `file` NULL. */
daegun_blob_free(file);
  • May be NULL: blob.
daegun_str_list_count
daegun_status daegun_str_list_count(
    const daegun_str_list *list,
    size_t *out
);

How many strings a list holds.

Writes the count to *out. The indexes daegun_str_list_at takes run from 0 to one below it.

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;
/* count is 2937, one name for each glyph of Inter. */

daegun_str_list_free(names);
daegun_str_list_at
daegun_status daegun_str_list_at(
    const daegun_str_list *list,
    size_t index,
    daegun_str *out
);

One string of a list, by index.

Fills *out with a daegun_str borrowed from the list, valid until daegun_str_list_free. Never free it.

An index past the last string answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was. It does not answer an empty string, because a list may hold an empty string of its own, as daegun_font_glyph_names gives for a glyph with no name, and you must be able to tell the two apart.

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

daegun_str name;
if (daegun_str_list_at(names, 2, &name) != DAEGUN_OK) return 1;
/* Glyph 2 of Inter is named "A". */

daegun_str_list_free(names);
daegun_str_list_free
void daegun_str_list_free(daegun_str_list *list);

Frees a list and every string in it.

NULL is fine and does nothing, so a cleanup path may free without checking. Every string that daegun_str_list_at lent is invalid afterward.

daegun_str_list *names = NULL;
daegun_status status = daegun_font_glyph_names(font, &names);
if (status == DAEGUN_OK) {
    /* read the names */
}
/* Safe either way: a call that fails leaves `names` NULL. */
daegun_str_list_free(names);
  • May be NULL: list.
daegun_text_str
daegun_status daegun_text_str(const daegun_text *text, daegun_str *out);

The string a text handle holds.

Fills *out with a daegun_str borrowed from the handle: UTF-8, NUL-terminated, with its length in bytes. It is valid until daegun_text_free. Never free it.

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;
printf("%s\n", name.data);
/* Prints "Inter Variable", which is 14 bytes long. */

daegun_text_free(family);
daegun_text_free
void daegun_text_free(daegun_text *text);

Frees a text handle.

NULL is fine and does nothing, so a cleanup path may free without checking. The string that daegun_text_str lent is invalid afterward.

daegun_text *family = NULL;
daegun_status status = daegun_font_family_name(font, NULL, &family);
if (status == DAEGUN_OK) {
    /* read the name */
}
/* Safe either way: a call that does not answer DAEGUN_OK leaves `family` NULL. */
daegun_text_free(family);
  • May be NULL: text.

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_font_open
daegun_status daegun_font_open(
    const uint8_t *data,
    size_t len,
    daegun_font **out
);

Opens a font from the bytes of a TrueType or OpenType font file, copying them.

The font comes back through out and is yours until daegun_font_free. The bytes are copied, so you may free or reuse data the moment the call returns. Two other calls avoid the copy: daegun_font_open_owned takes over a buffer, and daegun_font_open_static reads bytes that live as long as the program.

It reads one font file. The bytes of a collection, a .ttc or .otc file that packs several fonts, answer DAEGUN_MALFORMED here. Open a face of one with daegun_font_open_collection.

DAEGUN_MALFORMED means the bytes are not a font file: there are fewer than 12 of them, they do not start with a font signature, or the table directory is cut short. DAEGUN_MISSING means the file reads but lacks what every measurement rests on: a units per em above zero in its header table (head, or the bhed an Apple bitmap font has in its place), or a glyph count in maxp. A maxp in a version daegun does not read is not refused: the font opens with a glyph count of 0.

On any failure *out is set to NULL. DAEGUN_MALFORMED and DAEGUN_MISSING leave their reason in daegun_last_error. DAEGUN_NULL leaves none, so the reason of an earlier failure stays there.

A file cut short is not always refused. A table whose bytes run past the end of the data is left out, as if the font had none (hmtx and vmtx are cut to what is there instead). So a truncated file answers DAEGUN_MISSING where head or maxp was lost, and otherwise opens without the tables that were cut off.

data may be NULL only with a len of 0. Those are empty bytes, which answer DAEGUN_MALFORMED.

Every call but daegun_font_free takes a font as const, so any number of threads may use one font at the same time.

daegun_font *font = NULL;
daegun_status status = daegun_font_open(data, len, &font);
if (status != DAEGUN_OK) {
    /* A NULL pointer of yours leaves no reason behind. Every other failure does. */
    const char *why = status == DAEGUN_NULL ? "a NULL pointer" : daegun_last_error().data;
    fprintf(stderr, "%s: %s\n", daegun_status_name(status).data, why);
    return 1;
}
/* The bytes were copied, so `data` may be freed from here on. */

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

daegun_font_free(font);
daegun_font_buffer_free
void daegun_font_buffer_free(uint8_t *data, size_t len);

Frees a buffer from daegun_font_buffer_new that you never handed to daegun_font_open_owned.

It is for the path where something goes wrong before the hand-over, such as a read that comes up short. len must be the length you asked daegun_font_buffer_new for, not how many bytes you filled: the buffer is freed as an allocation of exactly that size. NULL is fine and does nothing.

Never call it after daegun_font_open_owned. That call takes the buffer whether it succeeds or fails, so freeing it here as well would free it twice.

size_t size = 4096;
uint8_t *buf = daegun_font_buffer_new(size);
if (!buf) return 1;

/* Say the read failed here. The buffer was never handed to daegun_font_open_owned, so it is
   still yours: free it with the length you asked for. */
daegun_font_buffer_free(buf, size);

/* NULL is fine, so one cleanup path also covers an allocation that failed. */
daegun_font_buffer_free(NULL, size);
  • May be NULL: data.
daegun_font_open_owned
daegun_status daegun_font_open_owned(
    uint8_t *data,
    size_t len,
    size_t index,
    daegun_font **out
);

Opens a font from a buffer daegun allocated for you, taking the buffer over in place of copying it.

data must come from daegun_font_buffer_new, and len must be exactly the length you asked that call for. The font reads its tables straight out of the buffer, so nothing is copied. That holds for a face of a collection too, which keeps the whole collection in memory.

The buffer stops being yours when you call, whatever the answer. On DAEGUN_OK it is the font's own memory, released through daegun_font_free. On any failure it is freed before the call returns, and that includes a NULL out, which answers DAEGUN_NULL. Either way, never pass it to daegun_font_buffer_free afterward, and never read it again.

index picks the face: 0 for a font file, or one of the faces of a collection as daegun_face_count counts them.

DAEGUN_INVALID_ARGUMENT means index is past the faces the bytes hold, which for anything but a collection is every index but 0. DAEGUN_MALFORMED means the bytes are no font, or a collection's header or the face's table directory is cut short. DAEGUN_MISSING means the face lacks the units per em or the glyph count that daegun_font_open requires. On any failure *out is NULL.

data may be NULL only with a len of 0. A len of 0 is empty bytes whatever data is: no buffer is taken, as daegun_font_buffer_new gives none that long, and index 0 answers DAEGUN_MALFORMED.

uint8_t *buf = daegun_font_buffer_new(len);
if (!buf) return 1;
memcpy(buf, data, len); /* stands in for reading the file into the buffer */

daegun_font *font = NULL;
daegun_status status = daegun_font_open_owned(buf, len, 0, &font);
/* `buf` belongs to the font now, pass or fail. */
if (status != DAEGUN_OK) return 1;

uint16_t upem = 0;
if (daegun_font_units_per_em(font, &upem) != DAEGUN_OK) return 1;
/* 2048 for Inter Variable. */

daegun_font_free(font); /* frees the buffer with it */
daegun_font_buffer_new
uint8_t *daegun_font_buffer_new(size_t len);

Allocates a buffer to read a font file into, so that daegun_font_open_owned can take it without a copy.

daegun_font_open copies the bytes you give it. This is the way around that copy: ask for a buffer the size of the file, read the file into it, and hand it to daegun_font_open_owned, which keeps the buffer as the font's own memory.

The buffer holds exactly len bytes, all zero until you fill them. The length is part of the buffer: the same len goes to daegun_font_open_owned or to daegun_font_buffer_free, even if you filled less, so find out the file's size before you ask.

It is not an ordinary pointer. daegun has its own allocator, so never pass the buffer to free. It leaves your hands one of two ways: daegun_font_open_owned takes it, or daegun_font_buffer_free frees it if you never got that far.

It returns NULL for a len of 0, and when a buffer that large cannot be had. This is the one call in the library that answers a failed allocation. Anywhere else, running out of memory ends the process, so the NULL here is worth checking.

/* `fp` is the font file, open for reading, and `len` is its size in bytes. */
uint8_t *buf = daegun_font_buffer_new(len);
if (!buf || fread(buf, 1, len, fp) != len) {
    daegun_font_buffer_free(buf, len); /* never handed over, so still yours. NULL is fine. */
    fclose(fp);
    return 1;
}
fclose(fp);

daegun_font *font = NULL;
daegun_status status = daegun_font_open_owned(buf, len, 0, &font);
/* `buf` belongs to the font now, pass or fail. Don't free it and don't read it. */
if (status != DAEGUN_OK) return 1;

/* Use the font. Freeing it frees the buffer too. */
daegun_font_free(font);
daegun_font_open_collection
daegun_status daegun_font_open_collection(
    const uint8_t *data,
    size_t len,
    size_t index,
    daegun_font **out
);

Opens one face of a font collection, or a font file as its own face 0, copying the bytes it keeps.

A collection, a .ttc or .otc file, packs several fonts into one file. index picks one, counting from 0, and daegun_face_count says how many there are. A plain font file works too, as its own face 0, so one code path opens either kind.

The bytes are copied as daegun_font_open copies them, so data may be freed once the call returns. From a collection it copies the tables of the face you chose and not the whole file (a face whose tables overlap heavily keeps a copy of the whole file instead). From a font file it copies the whole file. The font comes back through out and is freed with daegun_font_free.

DAEGUN_INVALID_ARGUMENT means index is past the faces the bytes hold: at or past the count for a collection, and any index but 0 for bytes that are not one. DAEGUN_MALFORMED means the bytes are no font, or the collection's header or the face's table directory is cut short. DAEGUN_MISSING means the face lacks the units per em or the glyph count that daegun_font_open requires. On any failure *out is NULL. Each of these three leaves its reason in daegun_last_error, and DAEGUN_NULL leaves none.

data may be NULL only with a len of 0: empty bytes, which answer DAEGUN_MALFORMED at index 0.

/* `ttc` holds the bytes of a collection file of two fonts, `ttc_len` of them. */
size_t faces = 0;
if (daegun_face_count(ttc, ttc_len, &faces) != DAEGUN_OK) return 1;

for (size_t i = 0; i < faces; i++) {
    daegun_font *face = NULL;
    if (daegun_font_open_collection(ttc, ttc_len, i, &face) != DAEGUN_OK) return 1;

    daegun_text *family = NULL;
    daegun_str name;
    if (daegun_font_family_name(face, NULL, &family) != DAEGUN_OK) return 1;
    if (daegun_text_str(family, &name) != DAEGUN_OK) return 1;
    /* name.data is "EB Garamond" for face 0 and "Inter Variable" for face 1. */

    daegun_text_free(family);
    daegun_font_free(face);
}
daegun_font_open_static
daegun_status daegun_font_open_static(
    const uint8_t *data,
    size_t len,
    size_t index,
    daegun_font **out
);

Opens a font, or one face of a collection, reading the bytes where they lie: nothing is copied.

For bytes that live as long as the program does: a font built into the binary as a static array, which C23's #embed makes from a file, or a file mapped into memory and never unmapped. The font points into data and reads its tables in place. A face of a collection reads the collection's bytes in place too.

The bytes must stay valid and unchanged for the rest of the program, not only until daegun_font_free. The font reads them in place, and so does every location, run or other handle made from it, any of which may outlive the font. If you cannot keep that promise, use daegun_font_open, which copies, or daegun_font_open_owned, which takes the memory over.

index is 0 for a font file, or one of the faces of a collection as daegun_face_count counts them. The font comes back through out, and daegun_font_free frees the font but never data.

It refuses what daegun_font_open_collection refuses. DAEGUN_INVALID_ARGUMENT means index is past the faces the bytes hold, which for anything but a collection is every index but 0. DAEGUN_MALFORMED means the bytes are no font, or a header or table directory is cut short. DAEGUN_MISSING means the face lacks the units per em or the glyph count that daegun_font_open requires. On any failure *out is NULL.

data may be NULL only with a len of 0: empty bytes, which answer DAEGUN_MALFORMED at index 0.

/* `data` must outlive every use of the font: a static array, an #embed, or a file mapped
   and never unmapped. */
daegun_font *font = NULL;
if (daegun_font_open_static(data, len, 0, &font) != DAEGUN_OK) return 1;

bool variable = false;
if (daegun_font_is_variable(font, &variable) != DAEGUN_OK) return 1;
/* true: this is Inter Variable, read straight out of `data`. */

/* This frees the font, not `data`. */
daegun_font_free(font);
daegun_font_free
void daegun_font_free(daegun_font *font);

Frees a font.

Every font from daegun_font_open, daegun_font_open_owned, daegun_font_open_collection or daegun_font_open_static is freed with it, once. NULL is fine and does nothing, as with free, and an open that fails leaves its handle NULL, so a cleanup path may free without checking.

No other handle borrows from a font. A run, a layout, a location or a set of names made from it stays valid after the font is freed, so the order of your frees does not matter. What ends with the font is what it lent you directly, such as the bytes daegun_font_table points at.

Any thread may free a font, once no call is still using it. Its memory may not go back at once: a thread that used the font keeps the locations it last read at and what it last hinted with, and those can hold the font's bytes until the thread moves on to other fonts, ends, or calls daegun_thread_release.

daegun_font *font = NULL;
daegun_status status = daegun_font_open(data, len, &font);
if (status == DAEGUN_OK) {
    /* use the font */
}
/* Safe either way: an open that fails leaves `font` NULL. */
daegun_font_free(font);
  • May be NULL: font.
daegun_face_count
daegun_status daegun_face_count(
    const uint8_t *data,
    size_t len,
    size_t *out
);

How many faces the bytes of a font file or a font collection hold.

Writes the count to *out: the number of faces for a collection, 1 for a font file, and 0 for bytes that are neither. Each face opens at its index, from 0 to the count less one, with daegun_font_open_collection, daegun_font_open_static or daegun_font_open_owned.

It takes bytes and not a font, because it answers what you ask before you know which face to open. It reads the file's header and none of its tables, and it never fails on bad data: bytes that are no font answer DAEGUN_OK with a count of 0, and so do no bytes at all, which is what a NULL data with a len of 0 means.

For a collection the count is the number its header states, cut down to the face offsets the file is long enough to hold. For anything else it is 1 where there are at least 12 bytes that start with a font signature. So a count above 0 does not promise that a face opens: only the open call reads the tables.

/* `ttc` holds the bytes of a collection file, and `data` those of a single font file. */
size_t in_collection = 0, in_file = 0;
if (daegun_face_count(ttc, ttc_len, &in_collection) != DAEGUN_OK) return 1;
if (daegun_face_count(data, len, &in_file) != DAEGUN_OK) return 1;
/* in_collection is 2, and in_file is 1. */

for (size_t i = 0; i < in_collection; i++) {
    daegun_font *face = NULL;
    if (daegun_font_open_collection(ttc, ttc_len, i, &face) != DAEGUN_OK) return 1;
    /* use face i */
    daegun_font_free(face);
}
daegun_font_glyph_count
daegun_status daegun_font_glyph_count(
    const daegun_font *font,
    uint32_t *out
);

How many glyphs the font has.

Writes the count to *out. Glyph ids run from 0, which is .notdef, to the count less one, so this is the bound for a loop over every glyph and for checking an id that came from elsewhere.

It is the count the maxp table states. A font with more than 65,535 glyphs states the larger number in a MAXP table, and daegun takes that one only where the font's outline tables hold that many glyphs. A maxp whose version is neither 0.5 nor 1.x counts 0 glyphs. The count is worked out once, when the font opens.

uint32_t glyphs = 0;
if (daegun_font_glyph_count(font, &glyphs) != DAEGUN_OK) return 1;

for (uint32_t gid = 0; gid < glyphs; gid++) {
    /* gid is a glyph of the font. */
}
/* glyphs is 2937 for Inter Variable. */
daegun_font_units_per_em
daegun_status daegun_font_units_per_em(
    const daegun_font *font,
    uint16_t *out
);

The font's units per em: the size of the grid that every metric, advance and outline is measured on.

Writes it to *out. daegun answers in font units, and this is the number that turns them into a size: a value in font units, times the pixel size, over the units per em, is that value in pixels. 1000 and 2048 are the common ones.

It is read when the font opens, from the head table or the bhed an Apple bitmap font has in its place. It is never 0, as daegun_font_open refuses a font that gives none.

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

double ascender = 0.0;
if (daegun_font_ascender(font, NULL, &ascender) != DAEGUN_OK) return 1;
double ascender_px = ascender * 16.0 / upem;
/* Inter has 2048 units per em and an ascender of 1984, which is 15.5 pixels at 16 px. */
daegun_font_is_variable
daegun_status daegun_font_is_variable(const daegun_font *font, bool *out);

Whether the font is a variable font: one whose fvar table declares at least one axis.

Writes true or false to *out. A variable font holds a range of designs along its axes, such as every weight from thin to black, and a location made with daegun_font_location picks one of them.

A static font has one design. It answers false, daegun_font_axes gives it no axes, and every location means its one design.

The call reads the axis count in the fvar header and nothing more. A font whose fvar states axes that cannot be read answers true here while daegun_font_axes gives none, and it then behaves as a static font. Where the two disagree, go by the axes.

bool variable = false;
if (daegun_font_is_variable(font, &variable) != DAEGUN_OK) return 1;
if (variable) {
    /* Offer a weight slider, built from daegun_font_axes. */
}
/* true for Inter Variable. */
daegun_font_axes
daegun_status daegun_font_axes(
    const daegun_font *font,
    daegun_axis *out,
    size_t out_len,
    size_t *out_count
);

The font's variation axes, in the order its fvar table declares them.

Fills your buffer with one daegun_axis per axis: its tag, its range, its default and the ID of its name. A static font has none, and neither has a font whose fvar table cannot be read: the call still answers DAEGUN_OK, with a count of 0.

out is your buffer with room for out_len axes. *out_count is set to the number the font has on DAEGUN_OK and where the buffer is too small, and left as it was on any other answer. A NULL buffer with a length of 0 asks for that number alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes nothing into it, so you can size the buffer from the count and call again. A buffer that overlaps out_count answers DAEGUN_INVALID_ARGUMENT too, and then nothing at all is written.

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

/* A static font has none, and malloc(0) may give NULL, so ask for room for one at least. */
daegun_axis *axes = malloc((count ? count : 1) * sizeof *axes);
if (!axes) return 1;
if (daegun_font_axes(font, axes, count, &count) != DAEGUN_OK) {
    free(axes);
    return 1;
}
for (size_t i = 0; i < count; i++) {
    /* The axis axes[i].tag runs from axes[i].min to axes[i].max. */
}
/* Inter has 2: opsz from 14 to 32, then wght from 100 to 900. */
free(axes);
daegun_font_named_instances
daegun_status daegun_font_named_instances(
    const daegun_font *font,
    daegun_named_instances **out
);

The named instances of a variable font, in the order its fvar table lists them.

A named instance is a place in the design space that the font's designer gave a name, such as Light or Bold: the entries of a style menu. The result is a daegun_named_instances handle through out, read by index and freed with daegun_named_instances_free.

A font with no fvar table, or one whose fvar table cannot be read, still answers DAEGUN_OK, with a handle that holds no instances. The handle holds copies, so it may outlive the font.

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;
for (size_t i = 0; i < count; i++) {
    daegun_str name;
    if (daegun_named_instances_name(instances, i, &name) != DAEGUN_OK) continue;
    /* Add name.data to a style menu. */
}
/* Inter names 9, from "Thin" to "Black". */

daegun_named_instances_free(instances);
daegun_named_instances_count
daegun_status daegun_named_instances_count(
    const daegun_named_instances *list,
    size_t *out
);

How many named instances a list holds.

Writes the count to *out. It is 0 for a font with no fvar table, or one whose fvar table cannot be read. The indexes the other daegun_named_instances_ calls take run from 0 to the count less one.

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;
/* count is 9 for Inter Variable. */

daegun_named_instances_free(instances);
daegun_named_instances_name
daegun_status daegun_named_instances_name(
    const daegun_named_instances *list,
    size_t index,
    daegun_str *out
);

A named instance's name, such as Bold or Display Light.

Writes a daegun_str to *out: the subfamily name the font's name table holds for the instance, which is the text a style menu shows. The string is NUL-terminated and carries its length in bytes. It is borrowed from the list, so it is valid until daegun_named_instances_free and there is nothing of its own to free.

DAEGUN_ABSENT means the instance is there but the name table has no name under the ID it points at, or the name lies past the limit daegun_font_names describes. DAEGUN_INVALID_ARGUMENT means index is past the last instance. Both leave *out as it was.

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

daegun_str name;
if (daegun_named_instances_name(instances, 6, &name) != DAEGUN_OK) return 1;
/* Instance 6 of Inter: name.data is "Bold" and name.len is 4. */

daegun_named_instances_free(instances);
daegun_named_instances_postscript_name
daegun_status daegun_named_instances_postscript_name(
    const daegun_named_instances *list,
    size_t index,
    daegun_str *out
);

A named instance's PostScript name, such as InterVariable-Bold.

The name a PDF or a PostScript printer knows the instance by, where the font gives one. Writes a daegun_str to *out, NUL-terminated and borrowed from the list: valid until daegun_named_instances_free.

DAEGUN_ABSENT means the instance states no PostScript name, the name table has none under the ID it states, or the name lies past the limit daegun_font_names describes. DAEGUN_INVALID_ARGUMENT means index is past the last instance. Both leave *out as it was.

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

daegun_str postscript;
daegun_status status = daegun_named_instances_postscript_name(instances, 6, &postscript);
if (status == DAEGUN_OK) {
    /* Instance 6 of Inter: postscript.data is "InterVariable-Bold". */
} else if (status == DAEGUN_ABSENT) {
    /* The font gives this instance no PostScript name. */
}

daegun_named_instances_free(instances);
daegun_named_instances_coords
const daegun_coord *daegun_named_instances_coords(
    const daegun_named_instances *list,
    size_t index,
    size_t *out_count
);

A named instance's coordinates: one daegun_coord per axis, ready to make a location from.

Returns a borrowed array and sets *out_count to its length, which is the number of axes the font has. The coordinates are in the order of the axes, each with its axis's tag and a value in that axis's own units. Pass the array and the count to daegun_font_location to get the location of the instance.

The array is valid until daegun_named_instances_free. Don't free it. NULL comes back, with the count left as it was, if index is past the last instance or if list or out_count is NULL.

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

/* Instance 6 of Inter is Bold. */
size_t count = 0;
const daegun_coord *coords = daegun_named_instances_coords(instances, 6, &count);
if (!coords) return 1;
/* Two coordinates, in the order of Inter's axes: opsz 14, then wght 700. */

daegun_location *bold = NULL;
if (daegun_font_location(font, coords, count, &bold) != DAEGUN_OK) return 1;
/* `bold` now picks that instance in any call that takes a location. */

daegun_location_free(bold);
daegun_named_instances_free(instances);
daegun_named_instances_free
void daegun_named_instances_free(daegun_named_instances *list);

Frees a list of named instances.

NULL is fine and does nothing. Every string and coordinate array the list lent is invalid afterward. A location made from those coordinates is a handle of its own and stays valid.

daegun_named_instances *instances = NULL;
daegun_status status = daegun_font_named_instances(font, &instances);
if (status == DAEGUN_OK) {
    /* read the instances */
}
/* Safe either way: a call that fails leaves `instances` NULL. */
daegun_named_instances_free(instances);
  • May be NULL: list.
daegun_font_location
daegun_status daegun_font_location(
    const daegun_font *font,
    const daegun_coord *coords,
    size_t coords_len,
    daegun_location **out
);

Makes a location: a place in a variable font's design space, such as weight 700 at optical size 28.

A variable font holds a range of designs along its axes, and a location picks one. You state it as an array of daegun_coord, each a tag and a value in that axis's own units, and get a daegun_location handle back through out. The work of resolving it is done once, here. Then every call that depends on a location takes the handle: metrics, advances, outlines, shaping, layout, color and instancing.

Nothing you put in the coords is an error. A value past its axis's range is clamped to it. Where a tag comes twice, the last one counts. A tag the font has no axis for is ignored, and so is a value that is not a finite number. An axis you leave out stays at its default, and the order of the coords does not matter.

NULL is the default instance. Wherever a call takes a const daegun_location *, NULL means the font as it is with every axis at its default, so a caller who wants that never needs this call. A location made of no coords means the same, which is why coords may be NULL when coords_len is 0. For a static font every location is its one design.

A location borrows nothing from its font. It may outlive the font, and you free it with daegun_location_free whenever you like. Threads may share one.

It also keeps the coords as you gave them. Passed to a font other than the one that made it, it is resolved again from those, so a value the first font clamped, or an axis the first font lacked, means to the second font what you asked for.

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

daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, "Wave", 4, bold, NULL, &run) != DAEGUN_OK) return 1;
double width = 0.0;
if (daegun_shaped_run_width(run, &width) != DAEGUN_OK) return 1;
/* 5327 units wide here. With NULL for the location, the default instance, it is 5339. */

daegun_shaped_run_free(run);
daegun_location_free(bold);
daegun_location_free
void daegun_location_free(daegun_location *location);

Frees a location.

NULL is fine and does nothing. The arrays that daegun_location_coords and daegun_location_normalized lent from it are invalid afterward.

Nothing else depends on it. Runs, layouts and whatever else was made at the location are handles of their own and stay valid, and the font may be freed before the location or after it.

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

/* A location borrows nothing from its font, so the two are freed in either order. */
daegun_font_free(face);
daegun_location_free(bold);
  • May be NULL: location.
daegun_location_coords
const daegun_coord *daegun_location_coords(
    const daegun_location *location,
    size_t *out_count
);

The coordinates a location resolved to, as the font that made it sets them.

Returns a borrowed array of daegun_coord and sets *out_count to its length. These are not the coords you passed in but what the font made of them: in the order of the font's axes, each value clamped to its axis's range, tags the font lacks dropped, and one entry at most per axis.

An axis that sits at its default is left out. So the array names only the axes that differ from the default instance, and a location that is the default instance has a count of 0, with a pointer that is still not NULL.

The array is valid until daegun_location_free. Don't free it. NULL comes back, with the count left as it was, only if location or out_count is NULL. That goes for the NULL that stands for the default instance elsewhere: here there is no handle to read.

/* A weight far past the axis, an optical size at its default, and an axis Inter lacks. */
const daegun_coord asked[] = {
    { DAEGUN_TAG('w', 'g', 'h', 't'), 2000.0 },
    { DAEGUN_TAG('o', 'p', 's', 'z'), 14.0 },
    { DAEGUN_TAG('X', 'X', 'X', 'X'), 1.0 },
};
daegun_location *location = NULL;
if (daegun_font_location(font, asked, 3, &location) != DAEGUN_OK) return 1;

size_t count = 0;
const daegun_coord *coords = daegun_location_coords(location, &count);
/* One coordinate is left: wght at 900, the top of Inter's weight axis. */

daegun_location_free(location);
daegun_location_normalized
const double *daegun_location_normalized(
    const daegun_location *location,
    size_t *out_count
);

A location's normalized coordinates: one number from -1 to 1 for each axis of the font, as its variation tables use them.

Returns a borrowed array of doubles and sets *out_count to its length. There is one for each axis of the font that made the location, in the order of its axes: 0 is the axis's default, -1 its minimum and 1 its maximum. The font's avar table, which bends that scale between those points, is already applied, so these are the numbers variation data is looked up with.

The array is empty wherever every one of them is 0: at the default instance, for a static font, and at a place so near the default that each rounds to 0. The count is then 0, not the number of axes, so read a count of 0 as all zeros.

The array is valid until daegun_location_free. NULL comes back, with the count left as it was, only if location or out_count is NULL.

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;

size_t count = 0;
const double *normalized = daegun_location_normalized(bold, &count);
/* Two numbers, one for each axis of Inter: 0 for opsz, left at its default, and about 0.54
   for wght. A straight line from the default of 400 to the top of 900 would put 700 at 0.6.
   Inter's avar table moves it. */

daegun_location_free(bold);
daegun_font_family_name
daegun_status daegun_font_family_name(
    const daegun_font *font,
    const daegun_location *location,
    daegun_text **out
);

The font's family name, such as Inter Variable.

It is the typographic family name, name ID 16, where the font states one, and otherwise the family name, name ID 1. Each is read as daegun_font_name reads a name, so that entry says which record of the name table is taken.

The name comes back through out as a daegun_text, an owned string. daegun_text_str lends you its bytes as a NUL-terminated daegun_str, valid until you free the text with daegun_text_free.

location picks the instance of a variable font, and NULL is the default instance, with the names read there as daegun_font_name tells. At weight 900, its named instance Black, Inter's name ID 1 reads Inter Variable Black and its ID 16 reads Inter Variable, so this call answers Inter Variable there as it does at the default instance.

DAEGUN_ABSENT means the font states neither name. *out is then NULL.

daegun_text *family = NULL;
daegun_status status = daegun_font_family_name(font, NULL, &family);
if (status == DAEGUN_OK) {
    daegun_str name;
    if (daegun_text_str(family, &name) != DAEGUN_OK) return 1;
    /* name.data is "Inter Variable" and name.len is 14. It is valid until the free below. */
} else if (status == DAEGUN_ABSENT) {
    /* The font states no family name. */
}
daegun_text_free(family);
daegun_font_style
daegun_status daegun_font_style(
    const daegun_font *font,
    const daegun_location *location,
    int32_t *out
);

Whether the font is upright, italic or oblique.

Writes a DAEGUN_STYLE_ code to *out: DAEGUN_STYLE_NORMAL, DAEGUN_STYLE_ITALIC or DAEGUN_STYLE_OBLIQUE. At the default instance it comes from the font's own flags, not from the shapes or the names: oblique where the selection flags of the OS/2 table say so, else italic where those flags or the style flags of the head table say so, else normal.

location picks the instance of a variable font, and NULL is the default instance. At any other location the flags read are the ones daegun gives the instance there, and it works them out again. Oblique follows a slnt axis where the font has one: off 0 on it the instance is oblique (where its OS/2 table is version 4 or later, the first with that flag), and at 0 it is not. A font without that axis keeps its own oblique flag. Italic at a named instance follows an ital axis at 0.5 or more or a slnt axis off 0, and the font's own OS/2 flag where it has neither axis. The head flag is not read there.

At a location that is no named instance, italic follows the style name instead: it is set where name ID 2 has the word Italic or Oblique. So an italic font whose name ID 2 does not say so can answer DAEGUN_STYLE_NORMAL away from the default instance.

This is not the style's name. The text a font calls its style, such as Bold Italic, is name ID 2, which daegun_font_name reads. Weight is not in the answer either: a bold upright font is DAEGUN_STYLE_NORMAL.

int32_t style = 0;
if (daegun_font_style(font, NULL, &style) != DAEGUN_OK) return 1;

const char *css = "normal";
if (style == DAEGUN_STYLE_ITALIC) css = "italic";
else if (style == DAEGUN_STYLE_OBLIQUE) css = "oblique";
/* Inter Variable is upright: style is DAEGUN_STYLE_NORMAL, and css stays "normal". */
daegun_font_name
daegun_status daegun_font_name(
    const daegun_font *font,
    uint16_t name_id,
    const daegun_location *location,
    daegun_text **out
);

One name from the font's name table, by its name ID.

The name table holds what a font says about itself, each string under a numbered ID: 0 is the copyright, 1 the family, 2 the style within the family (the subfamily, such as Bold Italic), 4 the full name, 5 the version and 6 the PostScript name. IDs from 256 up are the font's own, such as the names of its axes and named instances.

A font may store one name several times, for different platforms and languages. This call takes one: an English record for Windows, else another Windows record, else an English Mac record in Mac Roman, else another in Mac Roman, else a Unicode record, and of several of a kind the first in the table's order. Records in an encoding daegun does not decode, such as the Mac scripts other than Roman and the older Windows encodings for Chinese, Japanese and Korean, are passed over. The name is trimmed of NULs and white space at both ends. For the name in each language, use daegun_font_localized_names.

location picks the instance of a variable font. At NULL, the default instance, the names are the font's own as stored, which the file daegun_font_instance builds there need not share. At any other location they are those of the instance there, as daegun_font_instance writes it, so they can differ from place to place: at Inter's weight of 700, its named instance Bold, name ID 2 reads Bold where the default instance reads Regular.

The name comes back through out as a daegun_text. Read it with daegun_text_str and free it with daegun_text_free. A NUL inside a name is replaced with U+FFFD, so the string never ends early.

DAEGUN_ABSENT means the table has no record under that ID that daegun reads, or the name is empty once trimmed. *out is then NULL.

daegun_text *text = NULL;
if (daegun_font_name(font, 4, NULL, &text) != DAEGUN_OK) return 1; /* 4 is the full name */
daegun_str full;
if (daegun_text_str(text, &full) != DAEGUN_OK) return 1;
/* full.data is "Inter Variable". */
daegun_text_free(text);

/* A name the font does not have is an answer, not a failure. */
daegun_status status = daegun_font_name(font, 16, NULL, &text);
/* Inter states no typographic family, so status is DAEGUN_ABSENT and `text` is NULL. */
daegun_text_free(text);
daegun_font_names
daegun_status daegun_font_names(
    const daegun_font *font,
    const daegun_location *location,
    daegun_names **out
);

Every name the font's name table holds at a location, each with its name ID.

The result is a daegun_names handle through out, with one entry for each name ID the table has a name under, in ascending order of ID. Each entry is the string daegun_font_name gives for that ID, taken and trimmed the same way, and an ID whose name is empty once trimmed is left out. Read it with daegun_names_count and daegun_names_at, and free it with daegun_names_free.

Use it to list a font's names, or to look up several at once: all the strings sit in one buffer inside the handle. The handle holds copies, so it may outlive the font.

location picks the instance of a variable font, and NULL is the default instance. A font with no name table still answers DAEGUN_OK, with a handle that holds no names.

There is one limit. The strings are read in order of ID until their stored bytes pass four times the size of the table, and the IDs after that are left out, though daegun_font_name still reads each of them. Only a table that points many records at one long string reaches it.

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;
for (size_t i = 0; i < count; i++) {
    uint16_t id = 0;
    daegun_str name;
    if (daegun_names_at(names, i, &id, &name) != DAEGUN_OK) return 1;
    /* Name `id` is name.data. The ids rise with i. */
}
/* This Inter holds 62 names. */

daegun_names_free(names);
daegun_names_count
daegun_status daegun_names_count(const daegun_names *names, size_t *out);

How many names a daegun_names holds.

Writes the count to *out. The indexes daegun_names_at takes run from 0 to the count less one. It is a count of entries and not the highest name ID, as the IDs a font uses have gaps.

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;
/* count is 62 for this Inter. */

daegun_names_free(names);
daegun_names_at
daegun_status daegun_names_at(
    const daegun_names *names,
    size_t index,
    uint16_t *out_id,
    daegun_str *out
);

One name of a daegun_names by its index: its name ID and its string.

index counts entries, not name IDs. The entries are in ascending order of ID, so *out_id rises with the index and skips the IDs the font does not use. Both outs are required.

*out is a daegun_str borrowed from the handle: NUL-terminated, with its length in bytes, and valid until daegun_names_free. A NUL inside a name has been replaced with U+FFFD.

DAEGUN_INVALID_ARGUMENT means index is past the last entry. Neither out is written then.

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

uint16_t id = 0;
daegun_str name;
if (daegun_names_at(names, 1, &id, &name) != DAEGUN_OK) return 1;
/* The second entry of Inter: id is 1, the family, and name.data is "Inter Variable". */

daegun_names_free(names);
daegun_names_free
void daegun_names_free(daegun_names *names);

Frees a daegun_names.

NULL is fine and does nothing. Every string daegun_names_at lent from it is invalid afterward.

daegun_names *names = NULL;
daegun_status status = daegun_font_names(font, NULL, &names);
if (status == DAEGUN_OK) {
    /* read the names */
}
/* Safe either way: a call that fails leaves `names` NULL. */
daegun_names_free(names);
  • May be NULL: names.
daegun_font_localized_names
daegun_status daegun_font_localized_names(
    const daegun_font *font,
    uint16_t name_id,
    const daegun_location *location,
    daegun_localized_names **out
);

One name of the font, by its name ID, in each language the name table records it in.

A font made for more than one market often carries its family and style names in several languages. This call collects them for one name ID: each entry is a language, as a BCP 47 tag such as en or ja, and the name in that language. The result is a daegun_localized_names handle through out, read with daegun_localized_names_count and daegun_localized_names_at and freed with daegun_localized_names_free.

The entries are sorted by language tag, and a language comes once. Where two records give the same language, as a Windows record and a Mac record may both give English, the one daegun_font_name would take is kept. A record whose language daegun cannot name is listed under und. Only records in an encoding daegun decodes are listed, so a name stored only in another, such as a Japanese name in Shift-JIS, is missing, and so is one that is empty once trimmed.

The limit of daegun_font_names applies here too. The languages are read in tag order until their stored bytes pass four times the size of the table, and the ones after that are left out, though daegun_font_name still reads the name. Only a table that points many records at one long string reaches it.

Ask at NULL for the full list. location picks the instance of a variable font, and NULL is the default instance, where the font's whole name table is read. At any other location daegun reads the name table it keeps for that place, which it normally cuts down to one record for each ID, the one daegun_font_name takes. The other languages are then gone: Source Han Sans gives its family name in en and ja at the default instance, and in en alone at a weight of 555.

An ID the table has no record for still answers DAEGUN_OK, with a handle that holds no entries.

/* The family name, ID 1, of Source Han Sans, at the default instance, where every language is listed. */
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;
for (size_t i = 0; i < count; i++) {
    daegun_str language, name;
    if (daegun_localized_names_at(names, i, &language, &name) != DAEGUN_OK) return 1;
    /* Two entries: "en" with "Source Han Sans JP VF", then "ja" with "源ノ角ゴシック JP VF". */
}

daegun_localized_names_free(names);
daegun_localized_names_count
daegun_status daegun_localized_names_count(
    const daegun_localized_names *names,
    size_t *out
);

How many languages a daegun_localized_names holds the name in.

Writes the count to *out. It is 0 where the font has no record for the name ID that was asked for. The indexes daegun_localized_names_at takes run from 0 to the count less one.

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;
/* count is 2 for Source Han Sans: English and Japanese. */

daegun_localized_names_free(names);
daegun_localized_names_at
daegun_status daegun_localized_names_at(
    const daegun_localized_names *names,
    size_t index,
    daegun_str *out_language,
    daegun_str *out
);

One entry of a daegun_localized_names: a language and the name in it.

*out_language is the language as a BCP 47 tag, such as ja or zh-TW, or und where the record names no language daegun reads. *out is the name in it. Both are daegun_str views borrowed from the handle: NUL-terminated, with their lengths in bytes, and valid until daegun_localized_names_free. Both outs are required.

The entries are sorted by language tag. DAEGUN_INVALID_ARGUMENT means index is past the last entry, and neither out is written then.

daegun_localized_names *names = NULL;
if (daegun_font_localized_names(font, 1, NULL, &names) != DAEGUN_OK) return 1;

daegun_str language, name;
if (daegun_localized_names_at(names, 1, &language, &name) != DAEGUN_OK) return 1;
/* The second entry of Source Han Sans: language.data is "ja", and name.data is
   "源ノ角ゴシック JP VF", which is 27 bytes of UTF-8. */

daegun_localized_names_free(names);
daegun_localized_names_free
void daegun_localized_names_free(daegun_localized_names *names);

Frees a daegun_localized_names.

NULL is fine and does nothing. Every string daegun_localized_names_at lent from it is invalid afterward.

daegun_localized_names *names = NULL;
daegun_status status = daegun_font_localized_names(font, 1, NULL, &names);
if (status == DAEGUN_OK) {
    /* read the names */
}
/* Safe either way: a call that fails leaves `names` NULL. */
daegun_localized_names_free(names);
  • May be NULL: names.
daegun_font_table
daegun_status daegun_font_table(
    const daegun_font *font,
    daegun_tag tag,
    daegun_bytes *out
);

The bytes of one of the font's tables, exactly as the file stores them.

Writes a daegun_bytes view to *out: a pointer to the table and its length. Nothing is parsed or copied. The view is borrowed from the font and valid until daegun_font_free, so copy the bytes if you need them longer. There is nothing to free.

tag is the table's four-letter tag, as DAEGUN_TAG('h', 'e', 'a', 'd'). A tag of fewer letters is padded with spaces, as in DAEGUN_TAG('C', 'F', 'F', ' ').

These are the tables of the font as it was opened, not of an instance. In a variable font, glyf here holds the outlines of the default design, and the variation tables sit beside it. daegun_font_instance_tables gives the tables as they are at a location.

DAEGUN_ABSENT means the font has no table with that tag, and *out is left as it was. A table the file's directory lists with a length of 0 counts as absent too. The one exception is glyf, which may be empty and then answers DAEGUN_OK with a length of 0.

A table whose bytes run past the end of a file that was cut short is absent as well. hmtx and vmtx are the exception: they are cut to the bytes that are there. A directory entry whose tag is not four printable characters is skipped.

A file that holds both TrueType and CFF outlines keeps the kind its header names: where the file starts with OTTO, its glyf and loca are absent, and otherwise its CFF and CFF2.

daegun_bytes head = { NULL, 0 };
if (daegun_font_table(font, DAEGUN_TAG('h', 'e', 'a', 'd'), &head) != DAEGUN_OK) return 1;
/* The units per em are a big-endian uint16 at byte 18 of head. */
uint16_t upem = 0;
if (daegun_read_u16_be(head.data, head.len, 18, &upem) != DAEGUN_OK) return 1;
/* head is 54 bytes long, and upem is 2048 for Inter. */

/* A table the font lacks is an answer, not a failure, and leaves the view as it was. */
daegun_bytes cff = { NULL, 0 };
daegun_status status = daegun_font_table(font, DAEGUN_TAG('C', 'F', 'F', ' '), &cff);
/* Inter has TrueType outlines and no CFF table, so status is DAEGUN_ABSENT. */
daegun_font_table_tags
daegun_status daegun_font_table_tags(
    const daegun_font *font,
    daegun_tag *out,
    size_t out_len,
    size_t *out_count
);

The tag of every table the font has, in tag order, into your buffer.

Fills out with one daegun_tag per table. Tag order is the order of the tags as numbers, which is the order of their bytes, so uppercase tags such as GSUB come before lowercase ones such as cmap. Pass a tag to daegun_font_table for the bytes. The list holds exactly the tables that call would find, so one the file lists with a length of 0 is left out here too.

out is your buffer with room for out_len tags. NULL with a length of 0 asks for the count alone: the call answers DAEGUN_OK and sets *out_count. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes nothing into it, with *out_count still set to the number needed, so you can size the buffer and call again. A buffer that overlaps out_count answers DAEGUN_INVALID_ARGUMENT too, and then nothing at all is written.

A font has at most 65,535 tables, as its directory counts them in 16 bits. Ask for the count first, as the example does.

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

daegun_tag *tags = malloc(count * sizeof *tags);
if (!tags) return 1;
if (daegun_font_table_tags(font, tags, count, &count) != DAEGUN_OK) {
    free(tags);
    return 1;
}
/* How many bytes the font's tables take together. */
size_t total = 0;
for (size_t i = 0; i < count; i++) {
    daegun_bytes table;
    if (daegun_font_table(font, tags[i], &table) == DAEGUN_OK) total += table.len;
}
/* Inter Variable has 19 tables, from GDEF to post, and they come to 879376 bytes. */
free(tags);
daegun_font_has_table
daegun_status daegun_font_has_table(
    const daegun_font *font,
    daegun_tag tag,
    bool *out
);

Whether the font has a table with that tag.

Writes true to *out where daegun_font_table would find the table, and false where it would not. A table of length 0 counts as missing, as it does there.

It tells you what kind of font you hold before you ask for more: glyf means TrueType outlines, CFF or CFF2 PostScript ones, COLR color glyphs and MATH math layout.

bool has_glyf = false, has_colr = true;
if (daegun_font_has_table(font, DAEGUN_TAG('g', 'l', 'y', 'f'), &has_glyf) != DAEGUN_OK) return 1;
if (daegun_font_has_table(font, DAEGUN_TAG('C', 'O', 'L', 'R'), &has_colr) != DAEGUN_OK) return 1;
/* Inter has TrueType outlines and no color glyphs: has_glyf is true and has_colr is false. */
daegun_font_instance
daegun_status daegun_font_instance(
    const daegun_font *font,
    const daegun_location *location,
    daegun_blob **out
);

Builds a static font file from a variable font at one location.

The result is the bytes of a whole font with the variation applied: outlines, metrics and names as they are at location, and no variation tables. Write it to disk, hand it to software that cannot read variable fonts, or open it again with daegun_font_open.

It comes back through out as a daegun_blob. daegun_blob_data lends you its bytes and their count, valid until you free the blob with daegun_blob_free. The blob shares the bytes with the font's instance cache, DAEGUN_CACHE_INSTANCE, in place of copying them, and they count toward that cache's budget. Asking again for the same location builds nothing and hands back the same bytes, for as long as the cache keeps that location. A blob you hold stays valid whatever the cache drops, and after the font is freed.

NULL for location is the default instance. On a variable font that is still an instance: a static font with every axis at its default, not the file you opened. A font with no fvar table, or one whose fvar cannot be read, is its own instance: you get its tables written out as a font file, whatever the location.

A location the instancer cannot build answers its failure, with *out set to NULL and the reason in daegun_last_error: DAEGUN_MISSING for a table the instance cannot do without and the font lacks, such as glyf, loca or hmtx, DAEGUN_MALFORMED for one it has to read and cannot, such as a head table cut short, and DAEGUN_LIMIT_EXCEEDED for a font that asks for more work or memory than daegun allows. The failure is kept with the location too, so a location that fails is not built again at each call.

Not every broken table is a failure. A variation table that does not read, such as a damaged gvar, leaves its part of the font as stored, and the call still answers DAEGUN_OK.

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_blob *file = NULL;
daegun_status status = daegun_font_instance(font, bold, &file);
if (status != DAEGUN_OK) {
    fprintf(stderr, "%s: %s\n", daegun_status_name(status).data, daegun_last_error().data);
    daegun_location_free(bold);
    return 1;
}
size_t size = 0;
const uint8_t *bytes = daegun_blob_data(file, &size);
/* `bytes` is a whole static font at weight 700, `size` bytes long: write it to a file, or
   open it as any other font. */
daegun_font *fixed = NULL;
if (daegun_font_open(bytes, size, &fixed) != DAEGUN_OK) return 1;
bool variable = true;
if (daegun_font_is_variable(fixed, &variable) != DAEGUN_OK) return 1;
/* variable is false: the instance has no axes left. */

daegun_font_free(fixed);
daegun_blob_free(file);
daegun_location_free(bold);
daegun_font_instance_tables
daegun_status daegun_font_instance_tables(
    const daegun_font *font,
    const daegun_location *location,
    daegun_table_map **out
);

The tables of the instance at a location, by tag, without putting them together into a file.

These are the tables daegun_font_instance writes, as a daegun_table_map through out: the variation applied, and the variation tables gone. Use it to read one table of an instance, or to change the tables before you build a file from them with daegun_table_map_build.

Every table is copied into the map, those the location leaves untouched as well, so the map borrows nothing from the font and stays valid after daegun_font_free. You own it: free it with daegun_table_map_free. Unlike daegun_font_instance, nothing is kept in the font's instance cache, so each call on a variable font builds the tables again.

NULL for location is the default instance, which on a variable font is still an instance, without its variation tables. A font with no fvar table, or one whose fvar cannot be read, gives a copy of its own tables as stored, whatever the location. To copy a variable font's tables as stored, variations and all, read each one with daegun_font_table.

A location the instancer cannot build answers as daegun_font_instance does: DAEGUN_MISSING, DAEGUN_MALFORMED or DAEGUN_LIMIT_EXCEEDED, with *out set to NULL and the reason in daegun_last_error.

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_table_map *tables = NULL;
if (daegun_font_instance_tables(font, bold, &tables) != DAEGUN_OK) return 1;

size_t count = 0;
if (daegun_table_map_count(tables, &count) != DAEGUN_OK) return 1;
/* count is 14. Inter stores 19 tables, and the 5 that hold its variations are gone. */

/* Its outlines were built for this weight, so its glyf table is not the one the font stores. */
daegun_bytes built, stored;
if (daegun_table_map_get(tables, DAEGUN_TAG('g', 'l', 'y', 'f'), &built) != DAEGUN_OK) return 1;
if (daegun_font_table(font, DAEGUN_TAG('g', 'l', 'y', 'f'), &stored) != DAEGUN_OK) return 1;

daegun_table_map_free(tables);
daegun_location_free(bold);
daegun_table_map_free
void daegun_table_map_free(daegun_table_map *map);

Frees a table map.

NULL is fine and does nothing, and a call that fails to make a map leaves its handle NULL, so a cleanup path may free without checking. Every view that daegun_table_map_bytes_at or daegun_table_map_get lent from the map is invalid afterward.

A font file built from the map with daegun_table_map_build is a blob of its own and stays valid.

daegun_table_map *tables = NULL;
daegun_status status = daegun_font_instance_tables(font, NULL, &tables);
if (status == DAEGUN_OK) {
    /* read or change the tables */
}
/* Safe either way: a call that fails leaves `tables` NULL. */
daegun_table_map_free(tables);
  • May be NULL: map.
daegun_table_map_new
daegun_table_map *daegun_table_map_new(void);

Makes an empty table map.

It holds no tables until daegun_table_map_set adds some. Use it to put a font file together from tables of your own, or to copy a font's stored tables and change them before you build.

It returns the map, never NULL, and the map is yours until daegun_table_map_free.

An empty map makes no font: daegun_table_map_build answers DAEGUN_OK for it, with a blob of no bytes.

/* A copy of the font's tables as it stores them, variations and all, ready to change. */
daegun_tag tags[64];
size_t count = 0;
if (daegun_font_table_tags(font, tags, 64, &count) != DAEGUN_OK) return 1;

daegun_table_map *map = daegun_table_map_new();
for (size_t i = 0; i < count; i++) {
    daegun_bytes table;
    if (daegun_font_table(font, tags[i], &table) != DAEGUN_OK) continue;
    if (daegun_table_map_set(map, tags[i], table.data, table.len) != DAEGUN_OK) return 1;
}

size_t held = 0;
if (daegun_table_map_count(map, &held) != DAEGUN_OK) return 1;
/* held is 19, every table Inter has. */
daegun_table_map_free(map);
daegun_table_map_count
daegun_status daegun_table_map_count(
    const daegun_table_map *map,
    size_t *out
);

How many tables a table map holds.

Writes the count to *out. The indexes that daegun_table_map_tag_at and daegun_table_map_bytes_at take run from 0 to the count less one. A new map holds 0.

daegun_table_map *tables = NULL;
if (daegun_font_instance_tables(font, NULL, &tables) != DAEGUN_OK) return 1;

size_t count = 0;
if (daegun_table_map_count(tables, &count) != DAEGUN_OK) return 1;
/* count is 14 for the default instance of Inter. */

daegun_table_map_free(tables);
daegun_table_map_tag_at
daegun_status daegun_table_map_tag_at(
    const daegun_table_map *map,
    size_t index,
    daegun_tag *out
);

The tag of the table at an index of a table map.

The tables are in tag order, whatever order they were set in. That is the order of the tags as numbers, so uppercase tags such as GSUB come before lowercase ones such as cmap. daegun_table_map_bytes_at gives the bytes at the same index.

Setting a new tag or removing one shifts the indexes of the tables after it, so read the count again after a change.

DAEGUN_INVALID_ARGUMENT means index is past the last table, and *out is left as it was.

daegun_table_map *tables = NULL;
if (daegun_font_instance_tables(font, NULL, &tables) != DAEGUN_OK) return 1;
size_t count = 0;
if (daegun_table_map_count(tables, &count) != DAEGUN_OK) return 1;

daegun_tag first = 0, last = 0;
for (size_t i = 0; i < count; i++) {
    daegun_tag tag = 0;
    if (daegun_table_map_tag_at(tables, i, &tag) != DAEGUN_OK) return 1;
    /* `tag` names the table at index i. The tags rise with i. */
    if (i == 0) first = tag;
    last = tag;
}
/* For this instance of Inter, first is GDEF and last is post. */

daegun_table_map_free(tables);
daegun_table_map_bytes_at
daegun_status daegun_table_map_bytes_at(
    const daegun_table_map *map,
    size_t index,
    daegun_bytes *out
);

The bytes of the table at an index of a table map.

Writes a daegun_bytes view to *out: a pointer into the map's own copy of the table, and its length. An empty table gives a length of 0. daegun_table_map_tag_at gives the tag at the same index.

The view is borrowed, with nothing to free. It is valid until the map is freed or changed, so treat it as gone after any daegun_table_map_set or daegun_table_map_remove on the map, whichever tag that call named. Copy the bytes if you need them longer.

DAEGUN_INVALID_ARGUMENT means index is past the last table, and *out is left as it was.

daegun_table_map *tables = NULL;
if (daegun_font_instance_tables(font, NULL, &tables) != DAEGUN_OK) return 1;
size_t count = 0;
if (daegun_table_map_count(tables, &count) != DAEGUN_OK) return 1;

size_t total = 0;
for (size_t i = 0; i < count; i++) {
    daegun_bytes table;
    if (daegun_table_map_bytes_at(tables, i, &table) != DAEGUN_OK) return 1;
    total += table.len;
}
/* total is how many bytes the tables of the instance take together. */

daegun_table_map_free(tables);
daegun_table_map_get
daegun_status daegun_table_map_get(
    const daegun_table_map *map,
    daegun_tag tag,
    daegun_bytes *out
);

The bytes of the table with a given tag in a table map.

Writes a daegun_bytes view to *out: a pointer into the map's own copy of the table, and its length. The view is borrowed as the one from daegun_table_map_bytes_at is: valid until the map is freed, or changed by daegun_table_map_set or daegun_table_map_remove.

DAEGUN_ABSENT means the map has no table with that tag, and *out is left as it was. A table that is there but empty answers DAEGUN_OK with a length of 0, so the two can be told apart.

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_table_map *tables = NULL;
if (daegun_font_instance_tables(font, bold, &tables) != DAEGUN_OK) return 1;

/* The weight class is a big-endian uint16 at byte 4 of the OS/2 table. */
daegun_bytes os2;
if (daegun_table_map_get(tables, DAEGUN_TAG('O', 'S', '/', '2'), &os2) != DAEGUN_OK) return 1;
uint16_t weight = 0;
if (daegun_read_u16_be(os2.data, os2.len, 4, &weight) != DAEGUN_OK) return 1;
/* weight is 700 in this instance. The table the font stores says 400. */

/* The instance has no variation tables left. */
daegun_bytes fvar = { NULL, 0 };
daegun_status status = daegun_table_map_get(tables, DAEGUN_TAG('f', 'v', 'a', 'r'), &fvar);
/* status is DAEGUN_ABSENT, and `fvar` is as it was. */

daegun_table_map_free(tables);
daegun_location_free(bold);
daegun_table_map_set
daegun_status daegun_table_map_set(
    daegun_table_map *map,
    daegun_tag tag,
    const uint8_t *data,
    size_t len
);

Puts a table into a table map under a tag, in place of any the tag already held.

The map copies len bytes from data, so the buffer is yours to free or reuse once the call returns. A tag the map lacks is added at its place in tag order, and one it has gets the new bytes in place of the old.

data may be NULL only with a len of 0, which stores an empty table. NULL with a length answers DAEGUN_NULL and changes nothing.

Any tag and any bytes are taken as given. The map does not check that the tag names a real table or that the bytes make a valid one: that shows when the result is built and opened.

The call takes the map as non-const, so no other thread may use the map while it runs, and every view the map lent before the call is invalid after it.

daegun_table_map *tables = NULL;
if (daegun_font_instance_tables(font, NULL, &tables) != DAEGUN_OK) return 1;

/* Add a table of your own. The map copies the bytes, so `note` need not outlive the call. */
const uint8_t note[] = { 'h', 'e', 'l', 'l', 'o' };
const daegun_tag tag = DAEGUN_TAG('n', 'o', 't', 'e');
if (daegun_table_map_set(tables, tag, note, sizeof note) != DAEGUN_OK) return 1;

/* Setting the tag again replaces what it held, here with an empty table. */
if (daegun_table_map_set(tables, tag, NULL, 0) != DAEGUN_OK) return 1;

daegun_bytes back = { NULL, 99 };
if (daegun_table_map_get(tables, tag, &back) != DAEGUN_OK) return 1;
size_t count = 0;
if (daegun_table_map_count(tables, &count) != DAEGUN_OK) return 1;
/* back.len is 0, and count is 15: the 14 tables of the instance and the one added. */

daegun_table_map_free(tables);
daegun_table_map_remove
daegun_status daegun_table_map_remove(
    daegun_table_map *map,
    daegun_tag tag
);

Takes the table with a given tag out of a table map.

Removing a tag the map lacks does nothing and still answers DAEGUN_OK, so there is no need to look first. The tables after the one removed move down an index.

The call takes the map as non-const, so no other thread may use the map while it runs, and every view the map lent before the call is invalid after it.

daegun_table_map *tables = NULL;
if (daegun_font_instance_tables(font, NULL, &tables) != DAEGUN_OK) return 1;

/* Strip the layout tables from the instance. */
const daegun_tag layout[] = {
    DAEGUN_TAG('G', 'D', 'E', 'F'), DAEGUN_TAG('G', 'P', 'O', 'S'), DAEGUN_TAG('G', 'S', 'U', 'B'),
};
for (size_t i = 0; i < 3; i++) {
    if (daegun_table_map_remove(tables, layout[i]) != DAEGUN_OK) return 1;
}
/* Removing a tag that is not there does nothing. */
daegun_status again = daegun_table_map_remove(tables, DAEGUN_TAG('G', 'P', 'O', 'S'));

size_t count = 0;
if (daegun_table_map_count(tables, &count) != DAEGUN_OK) return 1;
/* again is DAEGUN_OK, and count is 11: the 14 tables of the instance less the three. */

daegun_table_map_free(tables);
daegun_font_set_cache_budget
daegun_status daegun_font_set_cache_budget(
    const daegun_font *font,
    int32_t cache,
    size_t bytes
);

Sets how many bytes one of the font's caches may hold.

A budget is a ceiling the cache grows toward as the font is used, never memory set aside. cache is one of the DAEGUN_CACHE_ codes, and bytes is the most its entries may count for. When an entry would take the cache past its budget, the entries used longest ago are dropped until the rest fit, and an entry that alone costs more than the budget is not kept. A lower budget applies at once, by the same rule, so what was used last stays.

The budgets start at 8 MiB for DAEGUN_CACHE_SHAPE, 64 MiB for DAEGUN_CACHE_INSTANCE, 4 MiB for DAEGUN_CACHE_OUTLINE and 0 for DAEGUN_CACHE_RASTER, which is therefore off until you give it one.

A budget of 0 turns a cache off: it holds nothing, and each call does its work afresh, with the same results. The exception is DAEGUN_CACHE_INSTANCE, which keeps the location used last whatever its budget, since otherwise every call at that location would build it again. So a font used at one location runs well on an instance budget of 0.

The shape cache drops by a looser rule than strict order of use: a run read again since it came in outlives the runs that were not, newer ones included. A shape budget of 4 MiB or more is split evenly over 16 lists, each with its own lock and its own share to keep to, so threads shaping at the same time do not all meet at one lock. A budget of 0 sets the lists aside, and threads shaping then meet at no lock. And a run is kept only where it costs no more than an eighth of its list, or 64 KiB where that is more.

A font keeps its first 32 shaping plans for good, a plan being the font lookups worked out for one script, direction, language and set of features. Any plans past those are held under the shape budget too: once there are some, they get a sixteenth of it and the runs the rest.

DAEGUN_INVALID_ARGUMENT means cache is none of the DAEGUN_CACHE_ codes. Nothing is changed then.

/* Text that never repeats gains nothing from kept runs, so turn the shape cache off. */
if (daegun_font_set_cache_budget(font, DAEGUN_CACHE_SHAPE, 0) != DAEGUN_OK) return 1;

/* A megabyte for images of glyphs, in a cache that is off until it has a budget. */
if (daegun_font_set_cache_budget(font, DAEGUN_CACHE_RASTER, 1 << 20) != DAEGUN_OK) return 1;

/* A code that names no cache is refused. */
daegun_status status = daegun_font_set_cache_budget(font, 99, 0);
/* status is DAEGUN_INVALID_ARGUMENT. */
daegun_font_cache_stats
daegun_status daegun_font_cache_stats(
    const daegun_font *font,
    int32_t cache,
    daegun_cache_stats *out
);

How many entries one of the font's caches holds now, and how many bytes they count for.

Writes a daegun_cache_stats to *out, as of the call. Its bytes are the cache's own count of what its entries cost, the figure the budget is held against. DAEGUN_CACHE_INSTANCE adds what dropped locations left for the next one to reuse, at most one location's worth, which no budget holds and which a new budget or daegun_font_clear_cache lets go.

An entry is a shaped run in DAEGUN_CACHE_SHAPE, a location in DAEGUN_CACHE_INSTANCE, an outline in DAEGUN_CACHE_OUTLINE and an image in DAEGUN_CACHE_RASTER. The shape cache also counts the shaping plans it holds past the first 32. A cache that has not been used reports zeros.

DAEGUN_INVALID_ARGUMENT means cache is none of the DAEGUN_CACHE_ codes, and *out is left as it was.

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

daegun_cache_stats stats;
if (daegun_font_cache_stats(font, DAEGUN_CACHE_SHAPE, &stats) != DAEGUN_OK) return 1;
/* On a font that has shaped nothing else, stats.entries is 1, the run kept, and stats.bytes
   is what it counts for of the budget. */

daegun_shaped_run_free(run);
daegun_font_clear_cache
daegun_status daegun_font_clear_cache(
    const daegun_font *font,
    int32_t cache
);

Empties one of the font's caches.

Everything the cache holds is dropped, and its budget stays as it was, so it fills again as the font is used. For DAEGUN_CACHE_INSTANCE that includes the newest location, which a budget alone never drops. A cache in a pool gives the pool back the bytes it held.

What you already hold stays valid: a run from daegun_font_shape or a blob from daegun_font_instance is a handle of its own. Use this to give memory back after a burst of work, as when a document closes.

DAEGUN_INVALID_ARGUMENT means cache is none of the DAEGUN_CACHE_ codes.

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

/* The document closed, so give the memory back. */
if (daegun_font_clear_cache(font, DAEGUN_CACHE_SHAPE) != DAEGUN_OK) return 1;

daegun_cache_stats stats;
if (daegun_font_cache_stats(font, DAEGUN_CACHE_SHAPE, &stats) != DAEGUN_OK) return 1;
/* stats.entries and stats.bytes are both 0. The run you hold is still good. */
size_t n = 0;
const uint32_t *glyphs = daegun_shaped_run_glyphs(run, &n);

daegun_shaped_run_free(run);
daegun_cache_pool_free
void daegun_cache_pool_free(daegun_cache_pool *pool);

Frees a cache pool handle.

NULL is fine and does nothing. Any thread may free the pool, once no call is using the handle.

It frees your handle, not the cap. A cache still in the pool holds the pool itself: it goes on drawing from it and keeping to the pool's budget, shared with the other caches still in it, until it leaves through daegun_font_set_cache_pool with a NULL pool or its font is freed. The pool goes for good when the last of them has left.

After the free there is no handle to read the pool or change its budget with. So take each cache out first, as the example does, unless a cap that can no longer change is what you want for those fonts.

daegun_cache_pool *pool = daegun_cache_pool_new(1 << 20);
if (daegun_font_set_cache_pool(font, DAEGUN_CACHE_SHAPE, pool) != DAEGUN_OK) return 1;
/* ... the font is used ... */

/* Take the cache out first: one left in a freed pool stays capped by the pool's budget. */
if (daegun_font_set_cache_pool(font, DAEGUN_CACHE_SHAPE, NULL) != DAEGUN_OK) return 1;
daegun_cache_pool_free(pool);

/* NULL is fine, so a cleanup path may free without checking. */
daegun_cache_pool_free(NULL);
  • May be NULL: pool.
daegun_cache_pool_new
daegun_cache_pool *daegun_cache_pool_new(size_t bytes);

Makes a cache pool with a budget in bytes.

bytes is the most that the caches in the pool may hold together. It is a ceiling they grow into, never memory set aside: a new pool holds nothing, and fills as the fonts whose caches joined it with daegun_font_set_cache_pool are used.

It returns the pool, never NULL, and the handle is yours until daegun_cache_pool_free.

A budget of 0 keeps every cache in the pool empty, except that each font's instance cache still keeps its newest location.

/* 16 MiB for what three of this font's caches hold, shared with any other font that joins. */
daegun_cache_pool *pool = daegun_cache_pool_new((size_t)16 << 20);
const int32_t caches[] = { DAEGUN_CACHE_SHAPE, DAEGUN_CACHE_INSTANCE, DAEGUN_CACHE_OUTLINE };
for (size_t i = 0; i < 3; i++) {
    if (daegun_font_set_cache_pool(font, caches[i], pool) != DAEGUN_OK) return 1;
}

daegun_cache_stats held;
if (daegun_cache_pool_stats(pool, &held) != DAEGUN_OK) return 1;
/* held.entries is 0: nothing is set aside, and the pool fills as the font is used. */

for (size_t i = 0; i < 3; i++) {
    if (daegun_font_set_cache_pool(font, caches[i], NULL) != DAEGUN_OK) return 1;
}
daegun_cache_pool_free(pool);
daegun_cache_pool_set_budget
daegun_status daegun_cache_pool_set_budget(
    const daegun_cache_pool *pool,
    size_t bytes
);

Changes a pool's budget in bytes.

A lower budget applies at once: the entries used longest ago across the pool's caches are dropped until the rest fit, though each font's instance cache keeps its newest location whatever the budget. A higher one lets the caches grow again as they are used. The budget each cache has of its own applies beside it as before.

The pool is taken as const, so this may be called while other threads use the fonts in it.

daegun_cache_pool *pool = daegun_cache_pool_new(1 << 20);
if (daegun_font_set_cache_pool(font, DAEGUN_CACHE_SHAPE, pool) != DAEGUN_OK) return 1;
daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, "Wave", 4, NULL, NULL, &run) != DAEGUN_OK) return 1;
daegun_shaped_run_free(run);

/* The app went to the background, so give the memory back. */
if (daegun_cache_pool_set_budget(pool, 0) != DAEGUN_OK) return 1;

daegun_cache_stats held;
if (daegun_cache_pool_stats(pool, &held) != DAEGUN_OK) return 1;
/* held.entries is 0: the run the pool held was dropped at once. */

if (daegun_font_set_cache_pool(font, DAEGUN_CACHE_SHAPE, NULL) != DAEGUN_OK) return 1;
daegun_cache_pool_free(pool);
daegun_cache_pool_stats
daegun_status daegun_cache_pool_stats(
    const daegun_cache_pool *pool,
    daegun_cache_stats *out
);

How many entries the caches in a pool hold together, and how many bytes they count for.

Writes a daegun_cache_stats to *out: the sum over every cache that has joined, across all fonts, as of the call. Its bytes are the figure the pool's budget is held against. daegun_font_cache_stats gives the share of one cache.

daegun_cache_pool *pool = daegun_cache_pool_new(1 << 20);
if (daegun_font_set_cache_pool(font, DAEGUN_CACHE_SHAPE, pool) != DAEGUN_OK) return 1;
daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, "Wave", 4, NULL, NULL, &run) != DAEGUN_OK) return 1;
daegun_shaped_run_free(run);

daegun_cache_stats pooled, own;
if (daegun_cache_pool_stats(pool, &pooled) != DAEGUN_OK) return 1;
if (daegun_font_cache_stats(font, DAEGUN_CACHE_SHAPE, &own) != DAEGUN_OK) return 1;
/* With one cache in the pool, the pool's figures are that cache's: one run, and its bytes. */

if (daegun_font_set_cache_pool(font, DAEGUN_CACHE_SHAPE, NULL) != DAEGUN_OK) return 1;
daegun_cache_pool_free(pool);
daegun_font_set_cache_pool
daegun_status daegun_font_set_cache_pool(
    const daegun_font *font,
    int32_t cache,
    const daegun_cache_pool *pool
);

Puts one of the font's caches into a cache pool, a budget shared with the caches of other fonts, or takes it out again.

With a pool, the cache that cache names joins it, and what the cache already holds comes with it. With NULL for pool it leaves, keeps what it holds and answers to its own budget alone again. A cache is in one pool at a time, so joining another moves it.

In a pool a cache keeps to two limits. Past its own budget it drops its own entries, those used longest ago first, as before. Past the pool's budget the entry used longest ago across every cache in the pool goes, whichever font it belongs to. Give a cache a budget of SIZE_MAX with daegun_font_set_cache_budget to leave the pool alone in charge.

DAEGUN_CACHE_RASTER starts with a budget of 0, and joining a pool does not change that: give it a budget of its own as well, or it stays off.

The instance cache keeps each font's newest location past the pool's budget, as it does past its own. A font that is freed gives its bytes back to the pool. In a pool every cache drops by the looser rule the shape cache always follows: an entry read again since it came in outlives the entries that were not.

Joining with the shape cache also brings in the shaping plans the font holds past its first 32. They then get a sixteenth of the shape budget, and the runs the rest.

The cache holds the pool itself, not your handle, so the handle may be freed while caches are in the pool. daegun_cache_pool_free says what that leaves.

DAEGUN_INVALID_ARGUMENT means cache is none of the DAEGUN_CACHE_ codes.

/* `inter` and `garamond` are two open fonts. */
daegun_cache_pool *pool = daegun_cache_pool_new(1 << 20);
if (daegun_font_set_cache_pool(inter, DAEGUN_CACHE_SHAPE, pool) != DAEGUN_OK) return 1;
if (daegun_font_set_cache_pool(garamond, DAEGUN_CACHE_SHAPE, pool) != DAEGUN_OK) return 1;

daegun_shaped_run *first = NULL, *second = NULL;
if (daegun_font_shape(inter, "Shared", 6, NULL, NULL, &first) != DAEGUN_OK) return 1;
if (daegun_font_shape(garamond, "Shared", 6, NULL, NULL, &second) != DAEGUN_OK) return 1;
daegun_cache_stats held;
if (daegun_cache_pool_stats(pool, &held) != DAEGUN_OK) return 1;
/* held.entries is 2: the pool counts one run from each font. */

/* A cache that leaves keeps its run, and takes it out of the pool's count. */
if (daegun_font_set_cache_pool(inter, DAEGUN_CACHE_SHAPE, NULL) != DAEGUN_OK) return 1;
if (daegun_cache_pool_stats(pool, &held) != DAEGUN_OK) return 1;
/* held.entries is 1 now, and Inter's own shape cache still holds its run. */

daegun_shaped_run_free(first);
daegun_shaped_run_free(second);
if (daegun_font_set_cache_pool(garamond, DAEGUN_CACHE_SHAPE, NULL) != DAEGUN_OK) return 1;
daegun_cache_pool_free(pool);
daegun_font_prewarm
daegun_status daegun_font_prewarm(
    const daegun_font *font,
    const uint32_t *gids,
    size_t gids_len,
    const daegun_location *location,
    size_t *out_added
);

Draws glyphs ahead of time into the font's outline cache, so that drawing them later replays a kept outline.

For each glyph id in gids it decodes the outline at location and keeps it in DAEGUN_CACHE_OUTLINE. From then on daegun_font_outline replays the kept copy in place of decoding the glyph, and so do the other calls that draw an unhinted outline, such as daegun_font_glyph_bounds, and daegun_font_prepared_outline when it does not hint. This is the only call that fills that cache: drawing a glyph that was not prewarmed keeps nothing.

*out_added receives how many outlines went in, and may be NULL if you have no use for the count. A glyph adds none if it is already there, if it draws nothing (as a space does), if it fails to draw or is past the font's last glyph, or if its outline alone costs more than the cache's budget. The count is of what went in, not of what is left: where the glyphs together cost more than the budget, the earlier ones are dropped again to make room for the later.

gids may be NULL only with a gids_len of 0, which adds nothing. The glyph array of a shaped run, from daegun_shaped_run_glyphs, goes in as it is. NULL for location is the default instance. Outlines are kept by location, so prewarm at each location you draw at.

No glyph makes the call fail: one that cannot be drawn is passed over.

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

/* Draw the four glyphs of the run once, ahead of the frame that needs them. */
size_t added = 0;
if (daegun_font_prewarm(font, glyphs, n, NULL, &added) != DAEGUN_OK) return 1;
/* added is 4. Asking again adds 0, as the glyphs are already there. */

/* Later, when the frame draws them, each call replays a kept outline. */
daegun_bounds box;
if (daegun_font_glyph_bounds(font, glyphs[0], NULL, &box) != DAEGUN_OK) return 1;

daegun_shaped_run_free(run);
daegun_font_set_index_allowance
daegun_status daegun_font_set_index_allowance(
    const daegun_font *font,
    size_t bytes
);

Sets how many bytes the font may still spend on the indexes it builds over its tables.

As a font is shaped, daegun builds indexes over its tables: one for the character map, and others for the glyph sets and classes its layout lookups test. They turn searches into direct lookups. The allowance caps what they may take in all, so a hostile font cannot make them grow without bound.

It is not a budget like a cache's. It is an amount left to spend: building an index draws it down, and nothing is dropped to make room. Where too little is left for an index, that index is not built and its lookups read the table directly, with the same results.

It starts at 4 MiB plus eight times the bytes of the font's tables. This call replaces what is left with bytes. At 0 no new index is built until bytes come back, which happens when the shape cache drops a shaping plan, past the font's first 32, that drew some, as an Indic script's plan can. The indexes themselves belong to the font, whichever location first needed them, so dropping a location gives nothing back.

/* No indexes for this font: its lookups read the tables directly. */
if (daegun_font_set_index_allowance(font, 0) != DAEGUN_OK) return 1;

daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, "Wave", 4, NULL, NULL, &run) != DAEGUN_OK) return 1;
double width = 0.0;
if (daegun_shaped_run_width(run, &width) != DAEGUN_OK) return 1;
/* width is 5339.0, the run the indexes would have given. */

daegun_shaped_run_free(run);
daegun_font_index_allowance
daegun_status daegun_font_index_allowance(
    const daegun_font *font,
    size_t *out
);

How many bytes the font may still spend on the indexes it builds over its tables.

Writes to *out what is left, not what is used. It starts at 4 MiB plus eight times the bytes of the font's tables, falls as indexes are built, and rises again where the shape cache drops a shaping plan that drew from it. Compare two readings to see what a piece of work drew, or read it after daegun_font_set_index_allowance to see what remains.

size_t before = 0, after = 0;
if (daegun_font_index_allowance(font, &before) != DAEGUN_OK) return 1;

daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, "Wave", 4, NULL, NULL, &run) != DAEGUN_OK) return 1;
if (daegun_font_index_allowance(font, &after) != DAEGUN_OK) return 1;
size_t spent = before - after;
/* Shaping built indexes over the font's tables, and they came out of the allowance, so
   spent is above 0. */

daegun_shaped_run_free(run);

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_font_ascender
daegun_status daegun_font_ascender(
    const daegun_font *font,
    const daegun_location *location,
    double *out
);

How far the font reaches above the baseline, as its hhea table states it.

Writes the ascender of hhea, the font's horizontal header, to *out: in font units with y up, so positive for an ordinary font. For pixels, multiply by the pixel size over the units per em, which daegun_font_units_per_em gives.

A font whose hhea is missing or does not read answers 0. The one exception is a font of bitmaps alone, with no outlines: it answers from the line metrics of its largest strike (a strike being the set of bitmaps drawn for one size), scaled to font units.

This is the header's own number. To space lines, use daegun_font_line_metrics, which also weighs what the OS/2 table says and falls back on a share of the em where the font states nothing usable.

location picks the instance of a variable font, NULL being the default one. At a location you get what a font file pinned there by daegun_font_instance would state: the ascender moved by the font's MVAR table, which holds how its metrics change across the design space, and rounded to a whole unit. Where daegun can't build that instance, the font's own tables answer, the same as at the default.

double ascender = 0.0, descender = 0.0;
if (daegun_font_ascender(font, NULL, &ascender) != DAEGUN_OK) return 1;
if (daegun_font_descender(font, NULL, &descender) != DAEGUN_OK) return 1;
/* Inter: 1984 units above the baseline and 494 below it, of 2048 to the em. */
daegun_font_descender
daegun_status daegun_font_descender(
    const daegun_font *font,
    const daegun_location *location,
    double *out
);

How far the font reaches below the baseline, as its hhea table states it.

Writes the descender of hhea to *out, in font units with y up. It lies below the baseline, so for an ordinary font it is negative: subtract it from the ascender to get a height, don't add it.

The fallbacks are those of daegun_font_ascender: 0 for a font whose hhea is missing or does not read, or the metrics of the largest strike for a font of bitmaps alone (a strike being the set of bitmaps drawn for one size).

location picks the instance of a variable font, NULL being the default one. At a location the value is the one the instance there would state, and where daegun can't build that instance, the font's own.

double ascender = 0.0, descender = 0.0;
if (daegun_font_ascender(font, NULL, &ascender) != DAEGUN_OK) return 1;
if (daegun_font_descender(font, NULL, &descender) != DAEGUN_OK) return 1;
/* The descender is negative, so the height from the lowest point to the highest is a difference. */
double height = ascender - descender;
/* Inter: 1984 - (-494) = 2478 units. */
daegun_font_cap_height
daegun_status daegun_font_cap_height(
    const daegun_font *font,
    const daegun_location *location,
    double *out
);

The height of the font's capital letters above the baseline.

Writes the cap height the OS/2 table states, its sCapHeight, to *out in font units. It's the measure to center a line of capitals on.

Where the font gives none, the call writes the ascender instead, the value daegun_font_ascender answers, so you always get a height to work with. That happens for a font with no OS/2 table, for a table older than version 2 or cut short before the field, and for one that states 0.

location picks the instance of a variable font, NULL being the default one. At a location the value is the one the instance there would state, moved by the font's MVAR table where that varies it. Where daegun can't build that instance, the font's own tables answer.

double cap = 0.0;
if (daegun_font_cap_height(font, NULL, &cap) != DAEGUN_OK) return 1;
uint16_t upem = 0;
if (daegun_font_units_per_em(font, &upem) != DAEGUN_OK) return 1;

/* Center capitals in a button 40 px tall, at 16 px: the baseline goes this far below its top. */
double baseline = (40.0 + cap * 16.0 / upem) / 2.0;
/* Inter's capitals are 1490 units tall, so the baseline goes 25.8203125 px down. */
daegun_font_italic_angle
daegun_status daegun_font_italic_angle(
    const daegun_font *font,
    const daegun_location *location,
    double *out
);

The slant of the font's upright strokes, in degrees.

Writes the italic angle of the post table to *out: degrees counterclockwise from vertical. A face that leans to the right, as an italic does, has a negative angle, and an upright one has 0. Use it to slant a text caret so that it leans with the letters.

A font with no post table, or with one cut off within its first 16 bytes, answers 0.

location picks the instance of a variable font, NULL being the default one. At a location the angle is the one the instance there would state: for a font with a slnt axis, the value of that axis there, held within 90 degrees either way. A font without that axis has the same angle at every location, since MVAR can't vary it. Where daegun can't build that instance, the font's own table answers.

double angle = 0.0;
if (daegun_font_italic_angle(font, NULL, &angle) != DAEGUN_OK) return 1;
/* A caret drawn along the slant moves this far to the right for each unit it rises. */
double lean = tan(-angle * 3.14159265358979323846 / 180.0);
/* An italic face that leans 13 degrees to the right answers -13, and lean is about 0.231. */
daegun_font_bounds
daegun_status daegun_font_bounds(
    const daegun_font *font,
    daegun_bounds *out
);

The box the font states around all of its glyphs.

Writes a daegun_bounds in font units, y up: the xMin, yMin, xMax and yMax of the head table, a box the font means to hold every one of its glyphs.

It is read as the file stores it. daegun doesn't measure the glyphs to check it, and the call takes no location, because the stored box is not varied: it describes the font as the file holds it, which for a variable font is its default instance. For the box of one glyph, measured at a location, use daegun_font_glyph_bounds.

DAEGUN_ABSENT means the head table, or the bhed that stands in for it in an Apple bitmap font, is too short to hold the four numbers. A font can't open without one of the two, so this is rare. *out is then left as it was.

daegun_bounds box;
daegun_status status = daegun_font_bounds(font, &box);
if (status == DAEGUN_ABSENT) return 0; /* head is too short to hold a box */
if (status != DAEGUN_OK) return 1;
uint16_t upem = 0;
if (daegun_font_units_per_em(font, &upem) != DAEGUN_OK) return 1;

/* The size of the box in pixels at 16 px. */
double width = (box.x_max - box.x_min) * 16.0 / upem;
double height = (box.y_max - box.y_min) * 16.0 / upem;
/* Inter's box runs from (-1513, -660) to (5290, 2269): about 53.1 by 22.9 px. */
daegun_font_line_metrics
daegun_status daegun_font_line_metrics(
    const daegun_font *font,
    const daegun_location *location,
    int32_t orientation,
    daegun_line_metrics *out
);

The line spacing a font asks for: its ascent, descent and line gap, for horizontal or vertical text.

Fills a daegun_line_metrics in font units, y up. This is the call to space lines with. A font states its line metrics in up to three places that often disagree, and this call picks among them in a fixed order.

For DAEGUN_HORIZONTAL it takes the first of these that describes a line with some height. The typographic metrics of OS/2, if the font's USE_TYPO_METRICS bit asks for them, the bit daegun_os2_uses_typo_metrics reads. The ascender, descender and line gap of hhea, or for a font of bitmaps alone with no hhea, the metrics of its largest strike (a strike being the set of bitmaps drawn for one size). The typographic metrics of OS/2 without the bit. The Windows metrics of OS/2, with a gap of 0. And last, 0.8 of the em above the baseline and 0.2 below it, with a gap of 0.

For DAEGUN_VERTICAL it takes the ascent, descent and line gap of vhea, the vertical header, or for a font of bitmaps alone with no vhea, the metrics of its largest strike. Where neither describes a column with some width, it answers half an em to either side of the column's center line and a gap of 0.

An orientation that is neither constant answers DAEGUN_INVALID_ARGUMENT, and *out is left as it was.

location picks the instance of a variable font, NULL being the default one. At a location the tables read are those of the instance there, the ones a font file made by daegun_font_instance would hold, so metrics the font varies through its MVAR table come out varied. Where daegun can't build that instance, the font's own tables answer, the same as at the default.

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

/* Lines of 16 px text: the first baseline sits the ascent below the top, and each next one
   a line height further down. */
double first_baseline = line.ascent * 16.0 / upem;
double step = height * 16.0 / upem;
/* Inter: 15.5 px to the first baseline, then 19.359375 px a line. */
daegun_line_metrics_line_height
daegun_status daegun_line_metrics_line_height(
    const daegun_line_metrics *metrics,
    double *out
);

The distance from one baseline to the next: the ascent less the descent, plus the line gap.

Writes ascent - descent + line_gap to *out, in the units the struct is in. The descent is subtracted because it is negative below the baseline. Adding the three fields looks right and gives a line too short by twice the descent.

It reads only the struct you pass and no font, so it works as well on metrics you scaled to pixels or filled in yourself.

daegun_line_metrics line;
if (daegun_font_line_metrics(font, NULL, DAEGUN_HORIZONTAL, &line) != DAEGUN_OK) return 1;
double height = 0.0;
if (daegun_line_metrics_line_height(&line, &height) != DAEGUN_OK) return 1;
/* Inter: 1984 - (-494) + 0 = 2478 units from one baseline to the next. */
daegun_font_pdf_flags
daegun_status daegun_font_pdf_flags(
    const daegun_font *font,
    const daegun_location *location,
    uint32_t *out
);

The flags a PDF font descriptor sets for the font.

Writes the Flags number of a PDF font descriptor to *out: a set of DAEGUN_PDF_ bits, each with the value PDF gives it, so a PDF writer stores the number as it is. Test a bit with &.

DAEGUN_PDF_FIXED_PITCH, DAEGUN_PDF_SERIF, DAEGUN_PDF_SCRIPT and DAEGUN_PDF_ITALIC are as the font states them in its post and OS/2 tables. Exactly one of DAEGUN_PDF_SYMBOLIC and DAEGUN_PDF_NONSYMBOLIC is always set, worked out from the characters the font maps. PDF's other flags, such as AllCap and ForceBold, are never set.

location picks the instance of a variable font, NULL being the default one. At a location the tables read are those of the instance there, and where daegun can't build that instance, the font's own.

uint32_t flags = 0;
if (daegun_font_pdf_flags(font, NULL, &flags) != DAEGUN_OK) return 1;
bool serif = (flags & DAEGUN_PDF_SERIF) != 0;
bool symbolic = (flags & DAEGUN_PDF_SYMBOLIC) != 0;
/* STIX Two Math is a serif font that maps far more than Latin: both are true, and flags is 6. */
daegun_font_os2
daegun_status daegun_font_os2(
    const daegun_font *font,
    const daegun_location *location,
    daegun_os2 *out
);

Reads the font's OS/2 table: its weight, width, style bits, embedding license and line metrics.

Fills a daegun_os2. Its has_ flags say which fields the table held, since a short table leaves the later ones out.

DAEGUN_ABSENT means the font has no OS/2 table, or one too short to hold even its version. Not every font has one. *out is then left as it was.

location picks the instance of a variable font, NULL being the default one. At a location the struct holds the OS/2 of the instance there, the one a font file made by daegun_font_instance would carry: the weight class follows the wght axis and the width class the wdth axis, the style bits are set for that instance, and the metrics are moved by the font's MVAR table. Where daegun can't build that instance, the font's own table answers, the same as at the default.

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_os2 os2;
daegun_status status = daegun_font_os2(font, bold, &os2);
daegun_location_free(bold);
if (status == DAEGUN_ABSENT) return 0; /* the font has no OS/2 table */
if (status != DAEGUN_OK) return 1;
/* Inter at weight 700: the weight class reads 700, where the default instance reads 400. */
daegun_os2_is_italic
daegun_status daegun_os2_is_italic(const daegun_os2 *os2, bool *out);

Whether the font is marked italic.

Writes true when selection of the daegun_os2 has its italic bit, 0x0001, set. It answers false where has_selection is false.

The call reads the struct alone, not a font, so the answer is for the location the struct was read at.

A font may set the oblique bit beside this one. daegun_font_style weighs the two and answers one style.

daegun_os2 os2;
if (daegun_font_os2(font, NULL, &os2) != DAEGUN_OK) return 1;
bool italic = false;
if (daegun_os2_is_italic(&os2, &italic) != DAEGUN_OK) return 1;
/* true for an italic face, as this one is. Inter answers false. */
daegun_os2_is_bold
daegun_status daegun_os2_is_bold(const daegun_os2 *os2, bool *out);

Whether the font is marked bold.

Writes true when selection of the daegun_os2 has its bold bit, 0x0020, set. It answers false where has_selection is false.

This is the bit that pairs a family into regular and bold, not a measure of weight: a Black or a SemiBold face usually leaves it clear. For how heavy the font is, read weight_class.

The call reads the struct alone, so the answer is for the location the struct was read at.

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

daegun_os2 os2;
daegun_status status = daegun_font_os2(font, at_700, &os2);
daegun_location_free(at_700);
if (status != DAEGUN_OK) return 1;
bool bold = false;
if (daegun_os2_is_bold(&os2, &bold) != DAEGUN_OK) return 1;
/* Inter at weight 700 is its Bold: true. At its default weight the answer is false. */
daegun_os2_is_regular
daegun_status daegun_os2_is_regular(const daegun_os2 *os2, bool *out);

Whether the font is marked as the regular style of its family.

Writes true when selection of the daegun_os2 has its regular bit, 0x0040, set: the font is neither bold nor italic. It answers false where has_selection is false.

The call reads the struct alone, so the answer is for the location the struct was read at.

daegun_os2 os2;
if (daegun_font_os2(font, NULL, &os2) != DAEGUN_OK) return 1;
bool regular = false;
if (daegun_os2_is_regular(&os2, &regular) != DAEGUN_OK) return 1;
/* Inter's default instance is its Regular: true. */
daegun_os2_is_oblique
daegun_status daegun_os2_is_oblique(const daegun_os2 *os2, bool *out);

Whether the font is marked oblique: an upright design slanted, as opposed to a true italic.

Writes true when selection of the daegun_os2 has its oblique bit, 0x0200, set. It answers false where has_selection is false.

The bit is read whatever the version of the table. Version 4 of OS/2 defined it and earlier versions reserve it, but fonts set it there too.

The call reads the struct alone, so the answer is for the location the struct was read at.

daegun_os2 os2;
if (daegun_font_os2(font, NULL, &os2) != DAEGUN_OK) return 1;
bool italic = false, oblique = false;
if (daegun_os2_is_italic(&os2, &italic) != DAEGUN_OK) return 1;
if (daegun_os2_is_oblique(&os2, &oblique) != DAEGUN_OK) return 1;
const char *css = oblique ? "oblique" : italic ? "italic" : "normal";
/* Inter is upright: both are false, and css is "normal". */
daegun_os2_uses_typo_metrics
daegun_status daegun_os2_uses_typo_metrics(
    const daegun_os2 *os2,
    bool *out
);

Whether the font asks for its typographic metrics to space lines.

Writes true when selection of the daegun_os2 has its USE_TYPO_METRICS bit, 0x0080, set. It answers false where has_selection is false.

A font that sets the bit wants lines spaced by typo_ascender, typo_descender and typo_line_gap, and not by the metrics of its hhea table. daegun_font_line_metrics follows it, so you need this call only when you pick among the metrics yourself.

The bit is read whatever the version of the table. Version 4 of OS/2 defined it and earlier versions reserve it, but fonts set it there too.

The call reads the struct alone, so the answer is for the location the struct was read at.

daegun_os2 os2;
if (daegun_font_os2(font, NULL, &os2) != DAEGUN_OK) return 1;
bool typo = false;
if (daegun_os2_uses_typo_metrics(&os2, &typo) != DAEGUN_OK) return 1;
/* Inter sets the bit: true. Source Serif 4 leaves it clear. */
daegun_font_typographic_metrics
daegun_status daegun_font_typographic_metrics(
    const daegun_font *font,
    const daegun_location *location,
    daegun_typographic_metrics *out
);

Reads the font's measures for setting text: x-height, underline, strikeout, subscript and superscript.

Fills a daegun_typographic_metrics in font units. The x-height, strikeout, subscript and superscript are read from the OS/2 table and the underline from post.

A font that lacks a table, or whose table stops short of a value, is no failure: the has_ flag of that group reads false and its fields read 0. So check the flags, not the status, to learn what the font gave.

location picks the instance of a variable font, NULL being the default one. At a location the values are those of the instance there, the ones a font file made by daegun_font_instance would hold: a font's MVAR table can make an underline thicker as the weight grows, each value rounded to a whole unit. Where daegun can't build that instance, the font's own tables answer.

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_typographic_metrics regular, heavy;
if (daegun_font_typographic_metrics(font, NULL, &regular) != DAEGUN_OK) return 1;
if (daegun_font_typographic_metrics(font, bold, &heavy) != DAEGUN_OK) return 1;
/* Inter's underline is 140 units thick at its default weight, and 190 at weight 700. */

daegun_location_free(bold);
daegun_font_tracking
daegun_status daegun_font_tracking(
    const daegun_font *font,
    double point_size,
    int32_t orientation,
    double *out
);

The space the font's trak table adds between glyphs at a point size.

Tracking is spacing added evenly through a run of text. Some fonts made for Apple platforms carry a trak table for it, to set small text looser and large text tighter. The table holds a few tracks, such as tight, normal and loose, each with a value at a few point sizes. This call writes the value of the normal track, the one numbered 0, at point_size to *out, in font units: the amount to add to an advance. A negative value tightens. Where the table has no track numbered 0, the value is worked out from the tracks nearest it.

point_size is in points, not pixels. Between two sizes the table lists, the value lies on the straight line between theirs, and a size past either end takes that end's value. A size that is not a finite number above zero is read as DAEGUN_DEFAULT_POINT_SIZE.

orientation is DAEGUN_HORIZONTAL or DAEGUN_VERTICAL, since the table keeps data for each way apart. Any other code answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

A font with no trak table answers 0, and so does one whose table is of a version daegun does not read or holds nothing for that orientation. The call takes no location: it reads the font's own table.

You seldom need the number to set text. daegun_font_shape already adds it, rounded to a whole unit, to each glyph that starts a grapheme, at the point_size of its options, for a font that has a STAT table beside its trak. A base with its marks gets it once, and so does a ligature, however many characters it joins.

double tracking = 0.0;
if (daegun_font_tracking(font, 12.0, DAEGUN_HORIZONTAL, &tracking) != DAEGUN_OK) return 1;
/* What to add to each advance of 12 pt text, in font units. Inter has no trak table, so it is 0.
   A font whose table gives 10 units at 10 pt and -10 at 20 pt answers 6. */
daegun_font_stat
daegun_status daegun_font_stat(
    const daegun_font *font,
    const daegun_location *location,
    daegun_stat **out
);

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

Hands back a daegun_stat through out. You own it: read it with the daegun_stat_ calls and free it with daegun_stat_free. Its names are read here, once, from the font's name table, as daegun_font_names reads them.

DAEGUN_ABSENT means the font has no STAT table, or one cut short before the end of its header. *out is then NULL, as it is after any failure, so freeing it stays safe.

With NULL for location you get the table as the font file holds it. For a variable font that describes the whole design space: every value the font names on every axis.

At a location you get the STAT of the instance there, the one a font file made by daegun_font_instance would carry, with its names read from the names of that instance. It keeps every axis, but of the values on an axis the font varies, only one that holds at that location, picked as OpenType picks it: at Source Serif 4's weight 650, Bold, from 650 to 750, stays and Semibold, from 550 to 650, goes. A value marked older_sibling stays whenever it holds, a combination only where all its pairs hold, and values on axes the font does not vary all stay. Inter names 12 values, and its instance at weight 700 keeps 3. Where daegun can't build that instance, the font's own table answers.

daegun_stat *stat = NULL;
daegun_status status = daegun_font_stat(font, NULL, &stat);
if (status == DAEGUN_ABSENT) return 0; /* the font has no STAT table */
if (status != DAEGUN_OK) return 1;

size_t count = 0;
if (daegun_stat_value_count(stat, &count) != DAEGUN_OK) return 1;
/* Inter names 12 values across its design space. */

daegun_stat_free(stat);
daegun_stat_axes
const daegun_stat_axis *daegun_stat_axes(
    const daegun_stat *stat,
    size_t *out_count
);

The design axes a STAT describes, in the table's order.

Returns a borrowed array of daegun_stat_axis and sets *out_count to its length. The axis_index of a value is an index into this array, and daegun_stat_axis_name takes the same index.

The array is valid until daegun_stat_free. Don't free it. NULL comes back, with the count left as it was, only if stat or out_count is NULL.

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);
bool has_weight = false;
for (size_t i = 0; i < count; i++) {
    if (axes[i].tag == DAEGUN_TAG('w', 'g', 'h', 't')) has_weight = true;
}
/* Inter's STAT describes 3 axes, weight among them. */

daegun_stat_free(stat);
daegun_stat_axis_name
daegun_status daegun_stat_axis_name(
    const daegun_stat *stat,
    size_t index,
    daegun_str *out
);

The display name of one of a STAT's axes, such as Weight.

index is the axis's place in the array daegun_stat_axes lends. The call writes a daegun_str to *out: UTF-8 with its length in bytes, and a NUL after it. The string is borrowed from the handle and valid until daegun_stat_free. Don't free it.

DAEGUN_ABSENT means the axis has no name: the font's name table has no usable record for the name the axis points at, or a hostile font named more text than daegun hands out. The has_name of the daegun_stat_axis says so in advance. An index past the last axis answers DAEGUN_INVALID_ARGUMENT. Either way *out is left as it was.

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

daegun_str name;
daegun_status status = daegun_stat_axis_name(stat, 1, &name);
if (status == DAEGUN_OK) {
    /* name.data is "Weight", 6 bytes long: what Inter calls its wght axis. */
} else if (status == DAEGUN_ABSENT) {
    /* The axis has no name. Show its tag. */
}

daegun_stat_free(stat);
daegun_stat_value_count
daegun_status daegun_stat_value_count(const daegun_stat *stat, size_t *out);

How many values a STAT names.

Writes the count to *out. daegun_stat_value_at and daegun_stat_value_name take an index below it, in the table's order.

It counts the values daegun could read. One in a format it does not know, or on an axis the table does not list, is left out. A STAT may describe axes and name no value, and the count is then 0.

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

size_t count = 0;
if (daegun_stat_value_count(stat, &count) != DAEGUN_OK) return 1;
/* count is 12 for Inter. */

daegun_stat_free(stat);
daegun_stat_elided_fallback_name
daegun_status daegun_stat_elided_fallback_name(
    const daegun_stat *stat,
    daegun_str *out
);

The name to give a style when every one of its value names is left out.

A style name put together from the names of the values at a location skips those marked elidable, and for a family's plain style that can leave nothing. This is the name to show then, such as Regular.

The call writes a daegun_str to *out: UTF-8 with its length in bytes, and a NUL after it, borrowed from the handle and valid until daegun_stat_free. Don't free it.

DAEGUN_ABSENT means the table gives none. Read with a NULL location, a STAT of version 1.0 has no such field. Read at a location of a variable font, the handle holds the instance's table, and there a version 1.0 table answers the instance's subfamily name, name ID 2, such as Bold. Any table may also point at a name the font's name table lacks, or at more text than daegun hands out, which only a hostile font reaches. On DAEGUN_ABSENT, *out is left as it was.

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

daegun_str name;
daegun_status status = daegun_stat_elided_fallback_name(stat, &name);
if (status == DAEGUN_OK) {
    /* name.data is "Regular" for Inter. */
} else if (status == DAEGUN_ABSENT) {
    /* The table names no fallback. */
}

daegun_stat_free(stat);
daegun_stat_free
void daegun_stat_free(daegun_stat *stat);

Frees a STAT handle.

For a handle from daegun_font_stat. NULL is fine and does nothing, so a cleanup path may free without checking. Every array and string the handle lent is invalid afterward.

daegun_stat *stat = NULL;
daegun_status status = daegun_font_stat(font, NULL, &stat);
if (status == DAEGUN_OK) {
    /* read the axes and the values */
}
/* Safe either way: a call that fails leaves `stat` NULL. */
daegun_stat_free(stat);
  • May be NULL: stat.
daegun_stat_value_at
daegun_status daegun_stat_value_at(
    const daegun_stat *stat,
    size_t index,
    daegun_stat_value *out
);

One of the values a STAT names, by index.

Fills a daegun_stat_value with a copy that is yours to keep. index runs from 0 to one less than daegun_stat_value_count answers, in the table's order. Read kind first: it says which of the other fields mean anything.

An index past the last value answers DAEGUN_INVALID_ARGUMENT, and *out is left as it was.

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

for (size_t i = 0; i < count; i++) {
    daegun_stat_value v;
    if (daegun_stat_value_at(stat, i, &v) != DAEGUN_OK) break;
    switch (v.kind) {
    case DAEGUN_STAT_SINGLE: /* v.value on axis v.axis_index */ break;
    case DAEGUN_STAT_RANGE:  /* v.min to v.max, named for v.value */ break;
    case DAEGUN_STAT_LINKED: /* v.value, linked to v.linked_value */ break;
    case DAEGUN_STAT_COMBO:  /* v.combo_count pairs from v.combo_start */ break;
    }
}
/* Inter's value 5 is linked: 400 on its weight axis, linked to 700 and elidable. */

daegun_stat_free(stat);
daegun_stat_value_name
daegun_status daegun_stat_value_name(
    const daegun_stat *stat,
    size_t index,
    daegun_str *out
);

The name a STAT gives one of its values, such as Bold.

index is the one daegun_stat_value_at takes. The call writes a daegun_str to *out: UTF-8 with its length in bytes, and a NUL after it. The string is borrowed from the handle and valid until daegun_stat_free. Don't free it.

DAEGUN_ABSENT means the value has no name: the font's name table has no usable record for the name the value points at, or a hostile font named more text than daegun hands out. The has_name of the daegun_stat_value says so in advance. An index past the last value answers DAEGUN_INVALID_ARGUMENT. Either way *out is left as it was.

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

for (size_t i = 0; i < count; i++) {
    daegun_str name;
    daegun_status status = daegun_stat_value_name(stat, i, &name);
    if (status == DAEGUN_ABSENT) continue; /* a value with no name */
    if (status != DAEGUN_OK) break;
    /* name.data is the name of value i. Inter's first three are "Text", "Display" and "Thin". */
}

daegun_stat_free(stat);
daegun_stat_combo_values
const daegun_axis_value *daegun_stat_combo_values(
    const daegun_stat *stat,
    size_t *out_count
);

The axis and value pairs of every combination value a STAT names, in one array.

A DAEGUN_STAT_COMBO value names a point on several axes at once, as a list of pairs. The lists of all such values lie end to end in this one array, and the combo_start and combo_count of a daegun_stat_value say which stretch of it is its own.

Returns a borrowed array of daegun_axis_value and sets *out_count to its length, which is 0 for a table with no such value. The array is valid until daegun_stat_free. Don't free it. NULL comes back, with the count left as it was, only if stat or out_count is NULL.

daegun_stat *stat = NULL;
if (daegun_font_stat(font, NULL, &stat) != DAEGUN_OK) return 1;
size_t count = 0, pair_count = 0;
if (daegun_stat_value_count(stat, &count) != DAEGUN_OK) return 1;
const daegun_axis_value *pairs = daegun_stat_combo_values(stat, &pair_count);

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) continue;
    for (uint32_t k = v.combo_start; k < v.combo_start + v.combo_count; k++) {
        /* Value i holds where the axis at index pairs[k].axis_index is at pairs[k].value. */
    }
}
/* Inter names no such value, so pair_count is 0. */

daegun_stat_free(stat);

Glyphs

daegun/glyphs.h: from characters to glyphs, and what each glyph measures. Its id for a character, its advance, its box, its vertical origin, its ligature carets, its class and its name.

daegun_font_glyph_id
daegun_status daegun_font_glyph_id(
    const daegun_font *font,
    uint32_t codepoint,
    uint32_t *out
);

The glyph the font maps a character to.

A lookup in the font's cmap table, its map from characters to glyphs. codepoint is a Unicode code point, and the glyph id is written to *out.

DAEGUN_ABSENT means the font has no glyph for the character, which is the cue to try another font or to draw glyph 0, .notdef. It is an answer, not a failure, and it leaves *out as it was. A character the font maps to glyph 0 counts as absent too, so the call never writes 0.

DAEGUN_INVALID_ARGUMENT means codepoint is no character: a surrogate, U+D800 to U+DFFF, or a value past U+10FFFF. *out is left as it was.

This is one character to one glyph and nothing more. It knows nothing of ligatures, of the forms a letter takes inside a word, or of marks, so the glyphs of real text come from daegun_font_shape.

uint32_t glyph = 0;
daegun_status status = daegun_font_glyph_id(font, 'A', &glyph);
if (status == DAEGUN_ABSENT) {
    /* The font has no glyph for it: try another font, or draw glyph 0. */
} else if (status != DAEGUN_OK) {
    return 1;
}
/* Inter keeps its A at index 2. */
daegun_font_has_glyph
daegun_status daegun_font_has_glyph(
    const daegun_font *font,
    uint32_t codepoint,
    bool *out
);

Whether the font has a glyph for a character.

Writes true to *out where the font maps the character to a glyph, and false where it has none. A character the font maps to glyph 0, .notdef, counts as one it lacks. It is the test font fallback turns on: go through your fonts and take the first that has the character.

DAEGUN_INVALID_ARGUMENT means codepoint is no character: a surrogate, U+D800 to U+DFFF, or a value past U+10FFFF. *out is left as it was.

bool has = false;
/* U+8A9E is a Japanese character, which Inter has no glyph for. */
if (daegun_font_has_glyph(font, 0x8A9E, &has) != DAEGUN_OK) return 1;
if (!has) {
    /* Look for the character in another font. */
}
daegun_font_glyph_ids
daegun_status daegun_font_glyph_ids(
    const daegun_font *font,
    const char *text,
    size_t text_len,
    uint32_t *out_gids,
    uint8_t *out_present,
    size_t out_len,
    size_t *out_count
);

The glyph for each character of a text, with a flag for each that says whether the font has one.

The text is UTF-8 with its length in bytes, so it needs no NUL, and it is read one character at a time. For character i the call writes the glyph id to out_gids[i] and a byte to out_present[i]: 1 where the font has a glyph for the character and 0 where it has none. A character with no glyph gets id 0, the .notdef glyph, so the ids can be drawn as they are. Each lookup is the one daegun_font_glyph_id makes.

Both buffers have room for out_len entries. out_present may be NULL, whatever out_len is, if you don't need the flags. *out_count is set to the number of characters. That is never more than text_len, as no character takes less than a byte, so buffers with room for text_len entries always fit.

A NULL out_gids with an out_len of 0 asks for the count alone, and text may be NULL where text_len is 0, which gives a count of 0. A buffer too small answers DAEGUN_INVALID_ARGUMENT with the count set, and writes nothing into either buffer. Text that is not UTF-8 answers DAEGUN_INVALID_ARGUMENT too, as do buffers that share bytes with the text, with each other or with the count, and those leave the count as it was.

It maps characters and does not shape them: no ligatures, no kerning, no reordering and no joined forms for a script such as Arabic. For text you mean to draw, use daegun_font_shape.

const char *text = "a語b";
uint32_t glyphs[8];
uint8_t present[8];
size_t count = 0;
/* strlen(text) is 5, and room for that many entries always fits. */
if (daegun_font_glyph_ids(font, text, strlen(text), glyphs, present, 8, &count) != DAEGUN_OK) return 1;
/* count is 3, one per character. Inter has no glyph for the middle one, so glyphs[1] is 0
   and present[1] is 0. */
daegun_font_coverage
daegun_status daegun_font_coverage(
    const daegun_font *font,
    uint32_t *out_codepoints,
    uint32_t *out_gids,
    size_t out_len,
    size_t *out_count
);

Every character the font maps to a glyph, in code point order, each with its glyph.

It fills two buffers of yours at matching indices: out_codepoints[i] is a character and out_gids[i] the glyph the font maps it to, in rising order of code point. Either buffer may be NULL to leave that half out. Use it to list what a font supports, or to build a table for font fallback.

Surrogates and values past U+10FFFF are left out, and so is a character the font maps to glyph 0, so no entry holds glyph 0.

*out_count is set to the number of pairs. With both buffers NULL the call answers with the count alone, so the usual way is to call once for the count, allocate, and call again. A buffer you pass has room for out_len entries, and one too small answers DAEGUN_INVALID_ARGUMENT with the count set and nothing written. Buffers that share bytes with each other or with the count answer the same, and leave the count as it was.

Each call reads the font's whole map, so keep the result instead of asking again.

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

uint32_t *codepoints = malloc(count * sizeof *codepoints);
uint32_t *glyphs = malloc(count * sizeof *glyphs);
if (codepoints && glyphs
    && daegun_font_coverage(font, codepoints, glyphs, count, &count) == DAEGUN_OK) {
    /* Inter maps 2852 characters. codepoints[i] maps to glyphs[i], in rising code point order:
       entry 1 is the space, which is glyph 1777. */
}
free(codepoints);
free(glyphs);
daegun_font_variation_glyph_id
daegun_status daegun_font_variation_glyph_id(
    const daegun_font *font,
    uint32_t codepoint,
    uint32_t selector,
    uint32_t *out
);

The glyph for a character followed by a variation selector.

A variation selector is an invisible character that asks for one particular form of the character before it: U+FE0F asks for the emoji form of a symbol, and U+E0100 onward pick among the registered forms of a CJK ideograph. The font's cmap table lists the pairs it knows, and this looks one up.

Where the font lists the pair with a glyph of its own, that glyph is written to *out. Where it lists the pair as the character's usual form, you get what daegun_font_glyph_id gives for the character.

DAEGUN_ABSENT means the font does not list the pair, and the plain glyph of the character is then the one to draw. It also answers DAEGUN_ABSENT where the font lists the pair as the usual form of a character it has no glyph for. A pair the font maps to glyph 0 counts as unlisted, so the call never writes 0. DAEGUN_INVALID_ARGUMENT means codepoint or selector is a surrogate or a value past U+10FFFF. Both statuses leave *out as it was.

daegun_font_shape applies variation selectors already. Call this when you map characters to glyphs yourself.

/* The ideograph U+845B followed by the variation selector U+E0100. */
uint32_t glyph = 0;
daegun_status status = daegun_font_variation_glyph_id(font, 0x845B, 0xE0100, &glyph);
if (status == DAEGUN_ABSENT) {
    /* The font has no such form: draw the plain glyph of the character. */
    status = daegun_font_glyph_id(font, 0x845B, &glyph);
}
if (status != DAEGUN_OK) return 1;
/* Source Han Sans has the form as glyph 16321, where the character alone is glyph 11184. */
daegun_font_glyph_bounds
daegun_status daegun_font_glyph_bounds(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    daegun_bounds *out
);

The box a glyph's outline covers.

Writes a daegun_bounds to *out. The box is tight: it fits the curves themselves, not their control points, so it is the extent of the ink. It is in font units, y up, measured from the glyph's origin on the baseline.

location picks the instance of a variable font. NULL is the default instance, and works for any font.

DAEGUN_ABSENT means there is no outline to measure. The glyph is empty, as a space is, or the id is past the last glyph, or the outline can't be decoded, or the font holds no outline for it, as a font of bitmap emoji holds none. *out is left as it was. That differs from a box of zero size, so do not read it as one.

The call decodes the outline to measure it, so it is more than a table lookup. Keep the box if you need it often. For the box a font states around all of its glyphs, see daegun_font_bounds.

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

daegun_bounds box;
daegun_status status = daegun_font_glyph_bounds(font, glyph, NULL, &box);
if (status == DAEGUN_OK) {
    double width = box.x_max - box.x_min, height = box.y_max - box.y_min;
    /* Inter's A is 1309 units wide and 1490 tall, and stands on the baseline. */
} else if (status == DAEGUN_ABSENT) {
    /* The glyph draws nothing, as a space does. */
}
daegun_font_advances
daegun_status daegun_font_advances(
    const daegun_font *font,
    const uint32_t *gids,
    size_t gids_len,
    const daegun_location *location,
    int32_t orientation,
    double *out
);

The advance of each glyph in an array, written into a buffer of yours.

out[i] receives the advance of gids[i] in font units: its width along a line with DAEGUN_HORIZONTAL, or its height down one with DAEGUN_VERTICAL. out needs room for gids_len advances, and there is no count to read back. With a gids_len of 0 nothing is written, and both arrays may then be NULL.

Each advance is what daegun_font_advance gives for that glyph: the glyph's own, with no kerning. The call reads the location once for the whole array and writes straight into your buffer, which makes it the call for a line of glyphs. location picks the instance of a variable font, NULL being the default one.

DAEGUN_INVALID_ARGUMENT means orientation is neither of the two constants, or out shares bytes with gids. Nothing is written then.

uint32_t glyphs[4];
size_t count = 0;
if (daegun_font_glyph_ids(font, "Wave", 4, glyphs, NULL, 4, &count) != DAEGUN_OK) return 1;

double advances[4];
if (daegun_font_advances(font, glyphs, count, NULL, DAEGUN_HORIZONTAL, advances) != DAEGUN_OK) return 1;
double width = 0.0;
for (size_t i = 0; i < count; i++) width += advances[i];
/* Inter's add up to 5513 units, the width of "Wave" before kerning. */
daegun_font_advance
daegun_status daegun_font_advance(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    int32_t orientation,
    double *out
);

How far one glyph moves the pen: its width along a horizontal line, or its height down a vertical one.

Writes the glyph's own advance to *out, in font units. orientation is DAEGUN_HORIZONTAL or DAEGUN_VERTICAL, and location picks the instance of a variable font, NULL being the default one. For pixels, multiply by the pixel size over the font's units per em, which daegun_font_units_per_em gives.

It is the advance of the glyph alone, with no kerning against its neighbors. To measure or set text, use daegun_font_shape, whose advances already hold the kerning.

With DAEGUN_HORIZONTAL the advance comes from the font's hmtx table, or in a font of bitmaps alone that has none, from the metrics its bitmaps state. Where neither gives one, the glyph advances by half an em.

With DAEGUN_VERTICAL it comes from the font's vmtx table, or in a font of bitmaps alone that has none, from the metrics its bitmaps state. Where neither gives one, the glyph advances by the height of the font's line, the same for every glyph. That height is the typographic ascender less the typographic descender of the OS/2 table where the font asks for those to be used (its USE_TYPO_METRICS flag), else the ascender less the descender of the hhea table, or for a font of bitmaps alone without one, of its largest bitmap size. A font with none of these takes one em. Where the font asks for the typographic pair, this is not what daegun_font_ascender and daegun_font_descender give, which read hhea.

A glyph id past the font's last glyph is not a failure: the call answers DAEGUN_OK. Where the font has the metrics table for that direction it writes 0 at the default instance, though at another location a variable font may move it by what its variations add. Where the font has no such table it writes the amount above.

DAEGUN_INVALID_ARGUMENT means orientation is neither of the two constants, and *out is left as it was. For many glyphs at once, daegun_font_advances fills a buffer in one call.

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

double across = 0.0, down = 0.0;
if (daegun_font_advance(font, glyph, NULL, DAEGUN_HORIZONTAL, &across) != DAEGUN_OK) return 1;
if (daegun_font_advance(font, glyph, NULL, DAEGUN_VERTICAL, &down) != DAEGUN_OK) return 1;
/* Inter's A moves the pen 1413 units along a horizontal line, and 2478 down a vertical one. */

/* The same glyph at weight 900 of this variable font. */
daegun_coord coords[] = { { DAEGUN_TAG('w', 'g', 'h', 't'), 900.0 } };
daegun_location *black = NULL;
if (daegun_font_location(font, coords, 1, &black) != DAEGUN_OK) return 1;
daegun_status status = daegun_font_advance(font, glyph, black, DAEGUN_HORIZONTAL, &across);
daegun_location_free(black);
if (status != DAEGUN_OK) return 1;
/* It is wider there: 1628 units. */
daegun_font_vertical_origin
daegun_status daegun_font_vertical_origin(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    double *out
);

Where a glyph's origin lies for vertical text, as a height above its baseline.

Horizontal text sets each glyph on the baseline. Vertical text hangs each glyph from a point at its top instead, its vertical origin. This writes to *out how far above the baseline that point lies, in font units. location picks the instance of a variable font, NULL being the default one.

The font decides it in one of three ways. A font with a VORG table states it, glyph by glyph or by its default. Failing that, a font with TrueType outlines and vertical metrics, a vmtx table, puts it at the top of the glyph's box plus the glyph's top side bearing. Any other font centers the glyph's box in a span as tall as its line and answers the top of that span: the top of the box plus half of what the line's height has left over, rounded down to a whole unit. The line's height is the one daegun_font_advance falls back to down a line, which is not always what daegun_font_ascender and daegun_font_descender give. The box is the outline's, or for a color glyph the box of its image or its clip box, so it can exist where daegun_font_glyph_bounds finds none.

Every glyph id gets an answer, so the call has no failure of its own. A glyph that draws nothing, such as a space, gets half the line's height where boxes are centered, and its top side bearing alone under the vmtx rule. A glyph id past the font's last glyph gets the default of VORG, 0 under the vmtx rule, and the top of the line, its ascender, where boxes are centered.

Shaping uses the origin already: in a run shaped with DAEGUN_DIRECTION_TTB, the offsets place each glyph by it. Call this when you set vertical glyphs yourself.

uint32_t glyph = 0;
if (daegun_font_glyph_id(font, 0x65E5, &glyph) != DAEGUN_OK) return 1; /* the ideograph U+65E5 */

double origin = 0.0;
if (daegun_font_vertical_origin(font, glyph, NULL, &origin) != DAEGUN_OK) return 1;
/* Source Han Sans hangs this glyph from a point 880 units above its baseline. */
daegun_font_default_vertical_origin
daegun_status daegun_font_default_vertical_origin(
    const daegun_font *font,
    double *out
);

The vertical origin a font's VORG table gives every glyph it does not list.

A VORG table says where glyphs sit in vertical text: one default height for the font, and a height of its own for each glyph that differs. This writes that default to *out, in font units up from the baseline.

It writes 0 for a font without the table or with one in a version daegun does not read, and for any font with TrueType outlines. So 0 means there is no default, not that the origin is on the baseline. For the origin of a glyph, whatever the font holds, call daegun_font_vertical_origin.

double origin = 0.0;
if (daegun_font_default_vertical_origin(font, &origin) != DAEGUN_OK) return 1;
/* 880 in Source Han Sans. Inter, which has no such table, answers 0. */
daegun_font_ligature_carets
daegun_status daegun_font_ligature_carets(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    int32_t orientation,
    double *out_values,
    uint8_t *out_present,
    size_t out_len,
    size_t *out_count
);

Where the font says a text cursor may sit inside a ligature: one position for each caret its GDEF table lists.

A ligature draws several characters as one glyph, so a cursor moving through the text has to stop inside the glyph. A font can say where: for an ffi ligature, two carets, one after each f. The call gives them in the order the font lists them, in font units. location picks the instance of a variable font, NULL being the default one.

With DAEGUN_HORIZONTAL each is an x in the glyph's own coordinates. With DAEGUN_VERTICAL each is a y, for a ligature set in a vertical line. A vertical caret that the font ties to a point of the outline is measured from the glyph's vertical origin, so it is negative below that origin.

out_values[i] receives caret i, and out_present[i] a byte: 1 for a caret that was resolved, and 0 for one the font lists but that can't be resolved, such as one tied to an outline point the glyph does not have. Its value is then written as 0. Either buffer may be NULL to leave it out.

*out_count is set to the number of carets the font lists for the glyph. That is 0 where the font has no GDEF table, or has one daegun cannot read, or lists none for the glyph, which is DAEGUN_OK and not a failure. Many fonts list none, even for their ligatures. With both buffers NULL the call answers with the count alone. A buffer you pass has room for out_len entries, and one too small answers DAEGUN_INVALID_ARGUMENT with the count set and nothing written.

DAEGUN_INVALID_ARGUMENT also means orientation is neither of the two constants, or the buffers share bytes with each other or with the count. Those leave the count as it was.

daegun_font_caret_positions uses these carets already. Call this when you place carets yourself.

/* Glyph 4 of this font is an ffi ligature. */
double carets[8];
uint8_t present[8];
size_t count = 0;
if (daegun_font_ligature_carets(font, 4, NULL, DAEGUN_HORIZONTAL, carets, present, 8, &count) != DAEGUN_OK)
    return 1;
for (size_t i = 0; i < count; i++) {
    if (present[i]) {
        /* A cursor may sit at x = carets[i] inside the glyph. */
    }
}
/* count is 2: one caret after the first f at x = 300, and one after the second at x = 600. */
daegun_font_glyph_class
daegun_status daegun_font_glyph_class(
    const daegun_font *font,
    uint32_t gid,
    int32_t *out
);

The class a font's GDEF table gives a glyph: base, ligature, mark or component.

Writes one of the DAEGUN_GLYPH_CLASS_ codes to *out: DAEGUN_GLYPH_CLASS_BASE, DAEGUN_GLYPH_CLASS_LIGATURE, DAEGUN_GLYPH_CLASS_MARK or DAEGUN_GLYPH_CLASS_COMPONENT. Use it to tell marks from the letters they sit on, or to find the ligatures in a run.

DAEGUN_ABSENT means the font has no GDEF table, or has one daegun cannot read, or the table gives the glyph no class, and *out is left as it was. Plenty of glyphs have none, Inter's space among them, so don't read it as a base.

The class belongs to the glyph, so it is the same at every location of a variable font.

uint32_t glyph = 0;
if (daegun_font_glyph_id(font, 0x0301, &glyph) != DAEGUN_OK) return 1; /* the combining acute accent */

int32_t kind = -1;
daegun_status status = daegun_font_glyph_class(font, glyph, &kind);
if (status == DAEGUN_OK && kind == DAEGUN_GLYPH_CLASS_MARK) {
    /* A mark: draw it onto the glyph before it. */
} else if (status == DAEGUN_ABSENT) {
    /* The font gives this glyph no class. */
}
daegun_font_mark_attachment_class
daegun_status daegun_font_mark_attachment_class(
    const daegun_font *font,
    uint32_t gid,
    uint32_t *out
);

The mark attachment class a font's GDEF table gives a glyph.

A font can sort its marks into numbered classes, for example marks that sit above a letter and marks that sit below it. Its layout rules use the classes to work on one kind of mark and pass over the rest. The numbers are the font's own and mean nothing in another font.

The class is written to *out and is never 0. A font with the wider 24-bit class tables can use numbers past 65,535.

DAEGUN_ABSENT means the font has no GDEF table, or has one daegun cannot read, or gives the glyph no class, which the table stores as class 0. *out is left as it was.

uint32_t grave = 0, comma = 0;
if (daegun_font_glyph_id(font, 0x0300, &grave) != DAEGUN_OK) return 1; /* combining grave accent */
if (daegun_font_glyph_id(font, 0x0326, &comma) != DAEGUN_OK) return 1; /* combining comma below */

uint32_t above = 0, below = 0;
if (daegun_font_mark_attachment_class(font, grave, &above) != DAEGUN_OK) return 1;
if (daegun_font_mark_attachment_class(font, comma, &below) != DAEGUN_OK) return 1;
/* Source Serif puts the accent in class 1 and the comma in class 2. */
daegun_font_glyph_name
daegun_status daegun_font_glyph_name(
    const daegun_font *font,
    uint32_t gid,
    char *out,
    size_t out_len,
    size_t *out_count
);

A glyph's name, such as A or acutecomb, copied into a buffer of yours.

The name comes from the font's post table, or, where that gives none, from the glyph names a CFF font carries. It is what the designer called the glyph, useful in a debugger, a glyph inspector or an error message. It is not text: for the character a glyph stands for, go by the text you shaped.

out is your buffer, with room for out_len bytes. The name is written with a NUL after it, and *out_count is set to the bytes that takes, the NUL among them. No name is longer than DAEGUN_MAX_GLYPH_NAME bytes, so a buffer of DAEGUN_MAX_GLYPH_NAME + 1 always fits. The name is copied, so there is no handle to free.

A NULL out with an out_len of 0 asks for the count alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT with the count set, and writes nothing into it. A buffer that shares bytes with the count answers DAEGUN_INVALID_ARGUMENT as well, and leaves the count as it was.

DAEGUN_ABSENT means the font does not name the glyph, and leaves the buffer and the count as they were. A font may ship without names: Source Han Sans and Noto Color Emoji name none of their glyphs. A name the font stores as empty, as longer than DAEGUN_MAX_GLYPH_NAME bytes, as bytes that are not UTF-8, or with a NUL inside it, which a C string can't hold, counts as none too.

char name[DAEGUN_MAX_GLYPH_NAME + 1];
size_t count = 0;
daegun_status status = daegun_font_glyph_name(font, 2, name, sizeof name, &count);
if (status == DAEGUN_OK) {
    /* Glyph 2 of Inter is named "A". count is 2: the letter and the NUL. */
} else if (status == DAEGUN_ABSENT) {
    /* The font does not name this glyph. */
}
daegun_font_glyph_names
daegun_status daegun_font_glyph_names(
    const daegun_font *font,
    daegun_str_list **out
);

Every glyph's name, in one list you own.

Writes a daegun_str_list to *out that holds one string per glyph of the font, so string i is the name of glyph i. Read it with daegun_str_list_count and daegun_str_list_at, and free it with daegun_str_list_free. The strings are borrowed from the list and valid until that free.

Each name is what daegun_font_glyph_name gives for the glyph. A glyph the font does not name has an empty string, which no real name is.

The list holds a copy of every name, so for a few glyphs daegun_font_glyph_name is the lighter call. If the call fails, *out is NULL.

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

size_t count = 0;
daegun_str name = { NULL, 0 };
if (daegun_str_list_count(names, &count) == DAEGUN_OK && count > 2
    && daegun_str_list_at(names, 2, &name) == DAEGUN_OK) {
    /* One name a glyph: Inter has 2937, and the name of glyph 2 is "A". */
}
daegun_str_list_free(names);

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_glyphs
const uint32_t *daegun_shaped_run_glyphs(
    const daegun_shaped_run *run,
    size_t *out_count
);

The run's glyph ids, in the order they are drawn.

Returns a borrowed array and sets *out_count to its length. The glyphs are in visual order: from the left as drawn, for right-to-left text too. This array and those of the other daegun_shaped_run_ views line up, so entry i of each describes the same glyph.

The array is valid until the run is freed, or until daegun_font_shape_into shapes into it again. Don't free it. NULL comes back, with the count left as it was, only if run or out_count is NULL.

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);
for (size_t i = 0; i < n; i++) {
    /* glyphs[i] is a glyph id, to hand to daegun_font_prepared_outline or a rasterizer. */
}

daegun_shaped_run_free(run);
daegun_shaped_run_advances
const double *daegun_shaped_run_advances(
    const daegun_shaped_run *run,
    size_t *out_count
);

How far the pen moves after each glyph, in font units.

Returns a borrowed array of one advance per glyph: across the line, or down it in vertical text. Kerning is already in them. For pixels, multiply by the pixel size over the font's units per em, which daegun_font_units_per_em gives.

Valid until the run is freed or shaped into again. NULL, with the count left as it was, only if run or out_count is NULL.

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

size_t n = 0;
const double *advances = daegun_shaped_run_advances(run, &n);
double pen_px = 0.0;
for (size_t i = 0; i < n; i++) pen_px += advances[i] * 16.0 / upem;
/* At 16 px, Inter sets "Wave" about 41.7 pixels wide. */

daegun_shaped_run_free(run);
daegun_shaped_run_offsets
const daegun_offset *daegun_shaped_run_offsets(
    const daegun_shaped_run *run,
    size_t *out_count
);

Each glyph's offset from where its advance puts it, in font units.

Returns a borrowed array of one daegun_offset per glyph. Draw glyph i at the pen plus offsets[i]. Most offsets are zero; marks and vertical text are where they matter.

Valid until the run is freed or shaped into again. NULL, with the count left as it was, only if run or out_count is NULL.

/* An Arabic letter with a vowel mark above it. */
const char *text = "بَ";
daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, text, strlen(text), NULL, NULL, &run) != DAEGUN_OK) return 1;

size_t n = 0;
const daegun_offset *offsets = daegun_shaped_run_offsets(run, &n);
/* Two glyphs in visual order: the mark first, which its offset moves into place over the letter, then
   the letter, whose offset is zero. */

daegun_shaped_run_free(run);
daegun_shaped_run_clusters
const uint32_t *daegun_shaped_run_clusters(
    const daegun_shaped_run *run,
    size_t *out_count
);

For each glyph, the byte offset in the text where its cluster starts.

A cluster is the piece of text a glyph came from, which is how you map a glyph back to the text for selection or hit testing. Glyphs of one cluster share a value: several glyphs may come from one character, and one glyph, such as a ligature, may cover several characters.

With the default cluster level the values rise along a left-to-right run and fall along a right-to-left one. text + clusters[i] is where the text of glyph i begins. A run lent by daegun_bidi_runs_at or by a layout counts from the start of its own piece of the text, so add that run's start.

Returns a borrowed array, valid until the run is freed or shaped into again. NULL, with the count left as it was, only if run or out_count is NULL.

/* EB Garamond draws the ffi of "office" as one ligature glyph. */
daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, "office", 6, NULL, NULL, &run) != DAEGUN_OK) return 1;

size_t n = 0;
const uint32_t *clusters = daegun_shaped_run_clusters(run, &n);
/* Four glyphs for six letters. Their clusters are 0, 1, 4, 5: the ligature covers bytes 1 to 3. */

daegun_shaped_run_free(run);
daegun_shaped_run_unsafe_to_break
const uint8_t *daegun_shaped_run_unsafe_to_break(
    const daegun_shaped_run *run,
    size_t *out_count
);

For each glyph, whether breaking the line before it would change how the text shapes.

Returns a borrowed array of one byte per glyph: 1 where breaking the text where that glyph's cluster starts and shaping the two sides apart could give different glyphs, as before the second letter of a kerned pair, and 0 where a break there is safe. A line breaker that breaks at a 1 shapes both sides again. A break inside a cluster, such as between the letters of a ligature, has no glyph to carry a flag and always needs both sides shaped again.

Valid until the run is freed or shaped into again. NULL, with the count left as it was, only if run or out_count is NULL.

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

size_t n = 0;
const uint8_t *unsafe = daegun_shaped_run_unsafe_to_break(run, &n);
/* Inter kerns each pair of "Wave", so breaking before any glyph but the first would change it. */

daegun_shaped_run_free(run);
daegun_shaped_run_unsafe_to_concat
const uint8_t *daegun_shaped_run_unsafe_to_concat(
    const daegun_shaped_run *run,
    size_t *out_count
);

For each glyph, whether shaping the text on either side of it separately and joining the runs could differ from shaping it whole.

Returns a borrowed array of one byte per glyph, 1 for yes. It is filled only when the options set report_unsafe_to_concat. Otherwise the count is 0.

Valid until the run is freed or shaped into again. NULL, with the count left as it was, only if run or out_count is NULL.

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

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

size_t n = 0;
const uint8_t *unsafe = daegun_shaped_run_unsafe_to_concat(run, &n);
/* n is 4, one flag a glyph. Without the option it would be 0. */

daegun_shaped_run_free(run);
daegun_shaped_run_safe_to_insert_tatweel
const uint8_t *daegun_shaped_run_safe_to_insert_tatweel(
    const daegun_shaped_run *run,
    size_t *out_count
);

For each glyph, whether a tatweel may go before it in the text.

A tatweel is the stroke that stretches an Arabic word to justify a line. Returns a borrowed array of one byte per glyph, 1 where one may be put before that glyph in the text. In a right-to-left run that is on the glyph's right as drawn. It is filled only when the options set report_tatweel_positions. Otherwise the count is 0.

Valid until the run is freed or shaped into again. NULL, with the count left as it was, only if run or out_count is NULL.

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

const char *text = "مرحبا";
daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, text, strlen(text), NULL, &opts, &run) != DAEGUN_OK) return 1;

size_t n = 0;
const uint8_t *tatweel = daegun_shaped_run_safe_to_insert_tatweel(run, &n);
/* Five glyphs, with 1 where a tatweel may go before one: 1, 1, 0, 1, 0. */

daegun_shaped_run_free(run);
daegun_shaped_run_width
daegun_status daegun_shaped_run_width(
    const daegun_shaped_run *run,
    double *out
);

The sum of the run's advances: its width, or its height for vertical text.

In font units, written to *out. Kerning is already in the advances, so this is the length the run takes on its line.

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

double width = 0.0;
if (daegun_shaped_run_width(run, &width) != DAEGUN_OK) return 1;
/* 5339.0 with Inter. */

daegun_shaped_run_free(run);
daegun_shaped_run_complete
daegun_status daegun_shaped_run_complete(
    const daegun_shaped_run *run,
    bool *out
);

Whether shaping ran to its end.

Writes false where shaping stopped short because the font pushed it past daegun's limits, as a hostile font can. The call that shaped the run still answered DAEGUN_OK, and the run holds the glyphs as they stood when shaping stopped. It is true for any ordinary font.

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

bool complete = false;
if (daegun_shaped_run_complete(run, &complete) != DAEGUN_OK) return 1;

daegun_shaped_run_free(run);
daegun_shaped_run_has_broken_syllable
daegun_status daegun_shaped_run_has_broken_syllable(
    const daegun_shaped_run *run,
    bool *out
);

Whether the text held a malformed syllable.

Writes true where a syllable was broken, such as a vowel sign with no letter before it. A dotted circle may then stand in for the missing base, unless the options set suppress_dotted_circle.

Only the models that shape by syllable look for one, DAEGUN_SHAPER_INDIC, DAEGUN_SHAPER_KHMER, DAEGUN_SHAPER_MYANMAR and DAEGUN_SHAPER_UNIVERSAL, so text left to the general model, as Devanagari is in a Latin font, writes false.

/* A Devanagari vowel sign with no letter before it. */
const char *text = "ि";
daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, text, strlen(text), NULL, NULL, &run) != DAEGUN_OK) return 1;

bool broken = false;
if (daegun_shaped_run_has_broken_syllable(run, &broken) != DAEGUN_OK) return 1;
/* broken is true, and the run holds two glyphs: the sign and a dotted circle to carry it. */

daegun_shaped_run_free(run);
daegun_shaped_run_shaper
daegun_status daegun_shaped_run_shaper(
    const daegun_shaped_run *run,
    int32_t *out
);

Which shaping model the run went through.

Writes a DAEGUN_SHAPER_ code to *out, such as DAEGUN_SHAPER_ARABIC. A library newer than your header may write a code you have no constant for, so don't treat an unknown one as an error. daegun_shaper_name turns any code the library knows into text.

const char *text = "مرحبا";
daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, text, strlen(text), NULL, NULL, &run) != DAEGUN_OK) return 1;

int32_t shaper = 0;
if (daegun_shaped_run_shaper(run, &shaper) != DAEGUN_OK) return 1;
/* shaper is DAEGUN_SHAPER_ARABIC. */

daegun_shaped_run_free(run);
daegun_shaper_name
daegun_status daegun_shaper_name(int32_t shaper, daegun_str *out);

A shaping model's name in snake case, such as arabic or myanmar_zawgyi.

Writes a daegun_str that points at a static string, valid for the life of the program, so there is nothing to free. The names are default, dumber, arabic, hangul, hebrew, indic, khmer, myanmar, myanmar_zawgyi, thai and universal.

A code that is none of the DAEGUN_SHAPER_ values this library knows answers DAEGUN_INVALID_ARGUMENT.

daegun_str name;
if (daegun_shaper_name(DAEGUN_SHAPER_MYANMAR_ZAWGYI, &name) != DAEGUN_OK) return 1;
/* name.data is "myanmar_zawgyi" and name.len is 14. */
daegun_shaped_run_copy
daegun_status daegun_shaped_run_copy(
    const daegun_shaped_run *run,
    daegun_shaped_run **out
);

A run of your own that holds a copy of what another run holds.

For a borrowed run you need to keep: one from daegun_bidi_runs_at or from a layout stops being valid when its owner is freed, and the copy lives until you free it with daegun_shaped_run_free.

On failure *out is set to NULL.

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;

const daegun_shaped_run *borrowed = NULL;
if (daegun_bidi_runs_at(runs, 0, &borrowed, NULL, NULL, NULL) != DAEGUN_OK) return 1;
daegun_shaped_run *kept = NULL;
if (daegun_shaped_run_copy(borrowed, &kept) != DAEGUN_OK) return 1;
daegun_bidi_runs_free(runs);

/* `borrowed` is gone with the set. `kept` is still good. */
double width = 0.0;
if (daegun_shaped_run_width(kept, &width) != DAEGUN_OK) return 1;
daegun_shaped_run_free(kept);
daegun_shaped_run_free
void daegun_shaped_run_free(daegun_shaped_run *run);

Frees a run you own.

That is a run from daegun_font_shape, daegun_font_shape_into, daegun_shaped_run_copy, daegun_font_justify or daegun_font_shape_justified. NULL is fine and does nothing, so a cleanup path may free without checking. Every array the run lent you is invalid afterward.

Never pass it a borrowed run, one that daegun_bidi_runs_at or a layout gave you: its owner frees it.

daegun_shaped_run *run = NULL;
daegun_status status = daegun_font_shape(font, "Wave", 4, NULL, NULL, &run);
if (status == DAEGUN_OK) {
    /* read the run */
}
/* Safe either way: a call that fails leaves `run` NULL. */
daegun_shaped_run_free(run);
  • May be NULL: run.
daegun_feature_from_string
daegun_status daegun_feature_from_string(
    const char *text,
    size_t text_len,
    daegun_feature *out
);

Reads a feature from text, as shaping tools and CSS write one.

It understands kern, -liga (off), +smcp (on), aalt=2 or aalt 2, on and off as values, the tag in quotes or not, and [start:end] for a byte range, where either end may be left out, a ; may stand for the :, and [i] means the one byte at i: kern[3:5]=0. The text comes as a pointer and its length in bytes, with no need for a NUL.

A feature read with no range has a start of 0 and an end of UINT32_MAX. A range that is empty and ends at 0, such as kern[:0], comes back as 1 to 1, which is still empty, since an end of 0 would mean the text's end.

Anything else answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was, as does empty text or text that is not UTF-8. The reason is in daegun_last_error.

daegun_feature feature;
if (daegun_feature_from_string("kern[3:5]=0", 11, &feature) != DAEGUN_OK) return 1;
/* The tag is kern, the value 0, over bytes 3 to 5. */
daegun_shape_options_default
daegun_status daegun_shape_options_default(
    daegun_shape_options *out,
    size_t size
);

Fills shaping options with their defaults.

Pass the struct and sizeof it. The call zeroes that many bytes, which is every default, and sets size. Then set the fields you want.

A size below what daegun 2.0 defined answers DAEGUN_INVALID_ARGUMENT, and one larger than this library knows answers DAEGUN_UNSUPPORTED, which means your header is newer than the library. Neither writes anything.

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

daegun_shaped_run *run = NULL;
if (daegun_font_shape(font, "Wave", 4, NULL, &opts, &run) != DAEGUN_OK) return 1;
size_t n = 0;
const uint32_t *clusters = daegun_shaped_run_clusters(run, &n);
/* Forced right to left, the glyphs come back in visual order: clusters 3, 2, 1, 0. */

daegun_shaped_run_free(run);
daegun_cluster_level_is_graphemes
daegun_status daegun_cluster_level_is_graphemes(int32_t level, bool *out);

Whether a cluster spans a whole grapheme at a cluster level.

Writes true for DAEGUN_CLUSTER_MONOTONE_GRAPHEMES and DAEGUN_CLUSTER_GRAPHEMES. Two of the four levels group by grapheme, so the question is not a comparison against one constant.

A code that is none of the DAEGUN_CLUSTER_ values answers DAEGUN_INVALID_ARGUMENT.

bool graphemes = false;
if (daegun_cluster_level_is_graphemes(DAEGUN_CLUSTER_GRAPHEMES, &graphemes) != DAEGUN_OK) return 1;
if (daegun_cluster_level_is_graphemes(DAEGUN_CLUSTER_CHARACTERS, &graphemes) != DAEGUN_OK) return 1;
/* true, then false. */
daegun_cluster_level_is_monotone
daegun_status daegun_cluster_level_is_monotone(int32_t level, bool *out);

Whether clusters stay in text order at a cluster level.

Writes true for DAEGUN_CLUSTER_MONOTONE_GRAPHEMES and DAEGUN_CLUSTER_MONOTONE_CHARACTERS.

A code that is none of the DAEGUN_CLUSTER_ values answers DAEGUN_INVALID_ARGUMENT.

bool monotone = false;
if (daegun_cluster_level_is_monotone(DAEGUN_CLUSTER_MONOTONE_GRAPHEMES, &monotone) != DAEGUN_OK)
    return 1;
if (daegun_cluster_level_is_monotone(DAEGUN_CLUSTER_GRAPHEMES, &monotone) != DAEGUN_OK) return 1;
/* true, then false. */
daegun_font_shape
daegun_status daegun_font_shape(
    const daegun_font *font,
    const char *text,
    size_t text_len,
    const daegun_location *location,
    const daegun_shape_options *opts,
    daegun_shaped_run **out
);

Shapes text into positioned glyphs, applying the font's ligatures, kerning, mark placement and reordering.

The call most text starts from. It works out the script and direction of the text, runs the shaping model for that script, applies the font's substitution and positioning tables and hands back a daegun_shaped_run through out. Read it with the daegun_shaped_run_ calls and free it with daegun_shaped_run_free.

The text is UTF-8 with its length in bytes, so it needs no NUL and may be a slice of a larger buffer. location picks the instance of a variable font, NULL being the default one. NULL for opts means the default options.

A character the font has no glyph for is not a failure. Where the font can draw it another way it does: an accented letter as its letter and its accent, a space character such as an em space with the font's space glyph at that space's width, and a non-breaking hyphen with the font's hyphen. An invisible character such as a zero width joiner goes by ignorables of the options. Anything else becomes not_found_glyph of the options, which is .notdef by default.

DAEGUN_INVALID_ARGUMENT means the text, or the language, before or after of the options, is not UTF-8, or the options hold a code that is none of its constants or a seed_script that is no script. It is also the answer to options whose size is below daegun 2.0's, which is what a struct you zeroed yourself holds: fill it with daegun_shape_options_default. DAEGUN_UNSUPPORTED means their size is larger than this library knows, so your header is newer than the library. daegun_last_error says which. On any failure *out is NULL.

A request with plain options comes from the font's shape cache, so asking again for the same text is as a rule a lookup that hands back the same run: daegun_shape_options says which requests are kept. A very long run is not kept, and is shaped again on every call: one that takes more than an eighth of the list it goes in, or 64 KB where that is more. The budget daegun_font_set_cache_budget sets is one list below 4 MB and is split over 16 lists from there, so at the default of 8 MB a run of more than 64 KB, roughly 1,900 glyphs, is not kept, and a budget of 0 keeps none. Threads may shape on one font at the same time, and none waits for the cache: one that finds it busy shapes the run itself.

It shapes the whole text as one run in one direction. A line feed or a tab gets no special treatment: it is looked up in the font like any character and becomes the not-found glyph where the font has none for it, and nothing breaks the line or moves to a tab stop. Split the text into paragraphs yourself, or leave line breaks and tabs to daegun_font_layout, which is also the call for a paragraph that wraps. For text that may mix directions use daegun_font_shape_bidi.

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

double x = 0.0;
for (size_t i = 0; i < n; i++) {
    /* Draw glyphs[i] at (x + offsets[i].x, offsets[i].y), in font units. */
    x += advances[i];
}
/* With Inter: n is 4, and x ends at 5339.0, the run's width. */

daegun_shaped_run_free(run);
daegun_font_shape_into
daegun_status daegun_font_shape_into(
    const daegun_font *font,
    const char *text,
    size_t text_len,
    const daegun_location *location,
    const daegun_shape_options *opts,
    daegun_shaped_run **run
);

Shapes text as daegun_font_shape does, into a run you already hold, reusing its memory.

For a loop that shapes many strings. The run's arrays keep their room between calls, so shaping one string after another into the same run allocates only when a string needs more room than any before it.

*run is a run of yours from an earlier shaping call, or NULL to get a new one. On DAEGUN_OK it is the shaped run. That is usually the same handle, but it may be a new one where the shape cache still shared the old, so always go on with *run as the call left it. Any other status leaves *run as it was. Free the run once, after the loop, with daegun_shaped_run_free.

Arrays that the run lent you before the call are invalid after it. The call writes into the run, so no other thread may use that run until it returns. It always shapes afresh: it neither reads the shape cache nor adds to it.

DAEGUN_INVALID_ARGUMENT means the text, or the language, before or after of the options, is not UTF-8, the options hold a code that is none of its constants or a seed_script that is no script, or their size is below daegun 2.0's, as in a struct you zeroed yourself. DAEGUN_UNSUPPORTED means their size is larger than this library knows.

const char *words[] = { "one", "two", "three" };
daegun_shaped_run *run = NULL;
for (size_t i = 0; i < 3; i++) {
    if (daegun_font_shape_into(font, words[i], strlen(words[i]), NULL, NULL, &run) != DAEGUN_OK) break;
    size_t n = 0;
    const uint32_t *glyphs = daegun_shaped_run_glyphs(run, &n);
    /* `run` now holds this word's glyphs. The handle is the one the first word got. */
}
daegun_shaped_run_free(run);
daegun_font_shape_bidi
daegun_status daegun_font_shape_bidi(
    const daegun_font *font,
    const char *text,
    size_t text_len,
    const daegun_location *location,
    int32_t base,
    const daegun_shape_options *opts,
    daegun_bidi_runs **out
);

Shapes text that may mix directions, such as Arabic inside English, into runs in the order they are drawn.

It runs the Unicode bidirectional algorithm over the text, cuts each directional run again wherever the script changes, and shapes every piece with its own direction and script. Each piece is shaped with the text around it as context, so letters still join across the cuts. The result is a daegun_bidi_runs, its runs in visual order from the left. Free it with daegun_bidi_runs_free.

base is a DAEGUN_BASE_ code, the direction of the paragraph. NULL for opts means the defaults. The options apply to every run, with these exceptions. Their direction, before and after are not read: each run takes the direction the algorithm gave it, and the text on either side of it as its context, so the text is shaped as if nothing came before or after it. Options that name a script stop the cutting by script, so each directional run stays whole. A seed_script stands in for a run whose text has no script to take, such as digits and punctuation alone, since digits and spaces beside letters take the letters' script. When the options also name a script, the seed script is used for every run.

Each run is shaped as a piece of text of its own, so a feature's start and end count bytes from the start of each run, not of the whole text, and a feature with a range applies at the same offsets in every run. Use features that cover the whole text here.

No line is broken, and text with no paragraph separator in it is treated as a single line. A paragraph ends at a line feed, a carriage return, the two together, or another character Unicode classes as a paragraph separator, such as U+0085 or U+2029. The line separator U+2028 and a vertical tab do not end one. Each paragraph is put in visual order on its own, takes its own direction under DAEGUN_BASE_AUTO, and its runs follow those of the paragraph before, with the separator shaped as a glyph in one of its runs. So give this call one paragraph at a time, or use daegun_font_layout, which does the same work line by line for a paragraph that wraps. Empty text gives a set of 0 runs.

DAEGUN_INVALID_ARGUMENT means the text, or the language, before or after of the options, is not UTF-8, base is none of the DAEGUN_BASE_ codes, the options hold a code that is none of its constants or a seed_script that is no script, or their size is below daegun 2.0's. The fields the call does not read are checked like the rest. DAEGUN_UNSUPPORTED means the size of the options is larger than this library knows. On any failure *out is NULL.

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;
double pen = 0.0;
for (size_t i = 0; i < count; i++) {
    const daegun_shaped_run *run = NULL; /* borrowed from `runs`: don't free it */
    uint8_t level = 0;
    size_t start = 0, end = 0;
    if (daegun_bidi_runs_at(runs, i, &run, &level, &start, &end) != DAEGUN_OK) return 1;
    /* Draw `run` at `pen`. It shows bytes start to end of the text, right to left
       if level is odd. */
    double width = 0.0;
    if (daegun_shaped_run_width(run, &width) != DAEGUN_OK) return 1;
    pen += width;
}

daegun_bidi_runs_free(runs);
daegun_bidi_runs_count
daegun_status daegun_bidi_runs_count(
    const daegun_bidi_runs *runs,
    size_t *out
);

How many runs a set of bidi runs holds.

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. */

daegun_bidi_runs_free(runs);
daegun_bidi_runs_at
daegun_status daegun_bidi_runs_at(
    const daegun_bidi_runs *runs,
    size_t index,
    const daegun_shaped_run **out_run,
    uint8_t *out_level,
    size_t *out_start,
    size_t *out_end
);

One run of a set of bidi runs: its shaped run, its bidi level and the bytes of text it covers.

Runs are indexed in visual order, 0 being the leftmost. Each out may be NULL if you have no use for it.

*out_run is borrowed from the set and valid until daegun_bidi_runs_free. Never pass it to daegun_shaped_run_free. To keep it longer, take a copy with daegun_shaped_run_copy. Its clusters count bytes from the start of this run's own text, so add *out_start to place one in the whole text.

*out_level is the bidi embedding level: odd reads right to left, even left to right. *out_start and *out_end are byte offsets into the text, the end not included.

An index past the last run answers DAEGUN_INVALID_ARGUMENT and writes none of the outs. *out_run is a borrowed pointer, not a handle of yours, so it keeps what it held and is not set to NULL.

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;

/* The second run from the left is the Arabic word. */
const daegun_shaped_run *run = NULL;
uint8_t level = 0;
size_t start = 0, end = 0;
if (daegun_bidi_runs_at(runs, 1, &run, &level, &start, &end) != DAEGUN_OK) return 1;
/* level is 1, so it reads right to left, and it covers bytes 5 to 15 of the text. */

daegun_bidi_runs_free(runs);
daegun_bidi_runs_free
void daegun_bidi_runs_free(daegun_bidi_runs *runs);

Frees a set of bidi runs, and with it every run the set lent.

NULL is fine and does nothing. A run you copied out with daegun_shaped_run_copy is your own and stays.

const char *text = "Read مرحبا aloud";
daegun_bidi_runs *runs = NULL;
daegun_status status =
    daegun_font_shape_bidi(font, text, strlen(text), NULL, DAEGUN_BASE_AUTO, NULL, &runs);
if (status == DAEGUN_OK) {
    /* read the runs */
}
/* Safe either way: a call that fails leaves `runs` NULL. */
daegun_bidi_runs_free(runs);
  • May be NULL: runs.
daegun_font_caret_positions
daegun_status daegun_font_caret_positions(
    const daegun_font *font,
    const char *text,
    size_t text_len,
    const daegun_location *location,
    int32_t orientation,
    double *out,
    size_t out_len,
    size_t *out_count
);

Where the text cursor sits before each byte of a string, for hit testing and for drawing a caret.

Fills out with text_len + 1 positions in font units, measured from the left edge of the text, or from its top with DAEGUN_VERTICAL. Index it with a byte offset: out[i] is the caret before the grapheme that byte i belongs to, a grapheme being a character as a reader sees it, and the last entry is the text's trailing edge. Every byte of a grapheme holds its leading edge, the bytes of a combining mark too, so any offset is safe to index and no caret lands between a letter and its marks.

Horizontal text is shaped the way daegun_font_shape_bidi shapes it with DAEGUN_BASE_AUTO and NULL options, so the carets match what those runs draw, right-to-left parts included. The call takes no base direction and no options of its own: runs you shaped with another base direction or with options may sit elsewhere than these carets say. Vertical text is shaped as one run from top to bottom. Inside a ligature the caret moves through the glyph.

out is your buffer with room for out_len positions. *out_count is set to the number needed whenever the call answers DAEGUN_OK or finds the buffer too small. A NULL buffer with a length of 0 asks for that number alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes no position. Text that is not UTF-8, an orientation that is neither DAEGUN_HORIZONTAL nor DAEGUN_VERTICAL, or a buffer that overlaps the text or *out_count answers the same and writes neither a position nor the count.

const char *text = "Wave";
double carets[5]; /* text_len + 1 always fits */
size_t count = 0;
if (daegun_font_caret_positions(font, text, 4, NULL, DAEGUN_HORIZONTAL, carets, 5, &count) != DAEGUN_OK)
    return 1;
/* count is 5. With Inter, carets[2] sits between "Wa" and "ve", 3034 units from the left. */

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_grapheme_boundaries
daegun_status daegun_grapheme_boundaries(
    const char *text,
    size_t text_len,
    size_t *out,
    size_t out_len,
    size_t *out_count
);

Finds where each grapheme cluster of a text begins: the units a reader sees as single characters.

A grapheme cluster is what a reader takes for one character, though it may be several code points: a letter with its combining accents, a flag made of two regional indicators, emoji joined by a zero width joiner, a Hangul syllable written as separate jamo, a CR LF pair. It is the unit to move a text cursor by and to delete by. The rules are those of UAX #29.

Like every call in this header it needs no font. The text is UTF-8 with its length in bytes, so it needs no NUL and may be a slice of a larger buffer. Every position that comes back is a byte offset where a character starts, so text + offset is where it begins.

The list holds the offsets in ascending order: 0 first, then the start of each later cluster, then text_len last. Cluster i is the bytes from text + out[i] up to text + out[i + 1], and there are count - 1 of them. An empty text, for which text may be NULL, gives the single offset 0.

out is your buffer with room for out_len offsets. *out_count is set to the number the text needs, which is never more than text_len + 1, so a buffer that large always fits. A NULL buffer with a length of 0 asks for that number alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes nothing into it, with the count still set.

Text that is not UTF-8, or a buffer that shares bytes with the text, also answers DAEGUN_INVALID_ARGUMENT. Then nothing is written, the count included.

/* An e with a combining acute accent, then a flag made of two regional indicators. */
const char *text = "e\u0301\U0001F1F0\U0001F1F7";
size_t len = strlen(text);
size_t starts[12]; /* len + 1 always fits, and len is 11 */
size_t count = 0;
if (daegun_grapheme_boundaries(text, len, starts, 12, &count) != DAEGUN_OK) return 1;
/* count is 3: the offsets 0, 3 and 11. That is two clusters, each of them several code points. */

for (size_t i = 0; i + 1 < count; i++) {
    const char *cluster = text + starts[i];
    size_t cluster_len = starts[i + 1] - starts[i];
    /* Cluster i is the cluster_len bytes at cluster. */
}
daegun_word_boundaries
daegun_status daegun_word_boundaries(
    const char *text,
    size_t text_len,
    size_t *out,
    size_t out_len,
    size_t *out_count
);

Finds the word boundaries of a text, as for selecting a word or moving the cursor by one.

The list holds every boundary the rules of UAX #29 find, as byte offsets in ascending order, with 0 first and text_len last. A boundary falls on each side of a word, and of each run of spaces and each punctuation mark between words, so the text between two neighboring offsets is one of those. "Hello, world" gives 0, 5, 6, 7 and 12. An empty text, for which text may be NULL, gives the single offset 0.

Letters and digits hold together, and so does one punctuation mark between two letters or two digits, as the apostrophe in "don't" and the period in "3.14". No word list is used, so text written without spaces is cut finer than its words: a boundary follows every Thai letter, with the marks on it, and every CJK ideograph, while a run of katakana stays whole.

out is your buffer with room for out_len offsets. *out_count is set to the number of boundaries, which is never more than text_len + 1, so a buffer that large always fits. A NULL buffer with a length of 0 asks for that number alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes nothing into it, with the count still set.

Text that is not UTF-8, or a buffer that shares bytes with the text, also answers DAEGUN_INVALID_ARGUMENT. Then nothing is written, the count included.

const char *text = "Hello, world";
size_t at[13]; /* text_len + 1 always fits */
size_t count = 0;
if (daegun_word_boundaries(text, 12, at, 13, &count) != DAEGUN_OK) return 1;
/* count is 5: the offsets 0, 5, 6, 7 and 12, around "Hello", the comma, the space and "world". */

/* The word under a cursor at byte 9 lies between the boundaries on either side of it. */
size_t i = 0;
while (i + 1 < count && at[i + 1] <= 9) i++;
/* It is the at[i + 1] - at[i] bytes at text + at[i]: "world". */
daegun_line_break_opportunities
daegun_status daegun_line_break_opportunities(
    const char *text,
    size_t text_len,
    daegun_word_segmenter segmenter,
    void *user,
    daegun_line_break *out,
    size_t out_len,
    size_t *out_count
);

Finds every place a line of the text may break, and marks the ones where it must.

It applies the Unicode line breaking rules (UAX #14) and fills out with a daegun_line_break for each opportunity, in text order. at is the byte offset the next line would start at, so text + at is its first character. The start of the text is never listed and the end always is, as the last entry. An empty text, for which text may be NULL, gives none.

A break is allowed or mandatory. An allowed one, with mandatory false, is a place a line may end when it has run out of room: after a space, after a hyphen, between two CJK ideographs. 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. A line breaker ends a line at every mandatory break and picks among the allowed ones by width.

Thai, Lao, Khmer and Myanmar are written without spaces between words, so the rules alone find no break inside a stretch of them. Pass a daegun_word_segmenter as segmenter and it is called for each such stretch, with user handed to it, and a line may break at each boundary it reports. With a NULL segmenter, a library built with the dictionaries feature finds the words of those four scripts from its own lists. A library built without it finds none, and such text then breaks only where other text would, as after a space. daegun_has_dictionaries says which library you have. user is yours alone and may be NULL.

out is your buffer with room for out_len breaks. *out_count is set to the number of breaks, and room for text_len + 1 always fits. A NULL buffer with a length of 0 asks for that number alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes nothing into it, with the count still set.

Text that is not UTF-8, or a buffer that shares bytes with the text, also answers DAEGUN_INVALID_ARGUMENT. Then nothing is written, the count included.

const char *text = "A well-known fact.\nNext";
size_t len = strlen(text);
daegun_line_break breaks[24]; /* len + 1 always fits, and len is 23 */
size_t count = 0;
if (daegun_line_break_opportunities(text, len, NULL, NULL, breaks, 24, &count) != DAEGUN_OK) return 1;
for (size_t i = 0; i < count; i++) {
    /* A line may end just before text + breaks[i].at, and must if breaks[i].mandatory. */
}
/* Five breaks. Allowed at 2, 7 and 13: after each space and after the hyphen.
   Mandatory at 19, after the newline, and at 23, the end of the text. */
daegun_has_dictionaries
bool daegun_has_dictionaries(void);

Whether this library was built with the word lists that break Thai, Lao, Khmer and Myanmar text between words.

The lists come with the dictionaries build feature, which is off by default and adds about 1 MB. Building the library with --features capi,dictionaries turns it on.

Where this returns true, daegun_line_break_opportunities and daegun_font_layout break such text between words with no daegun_word_segmenter. Where it returns false they need a segmenter of yours for that, and without one such text breaks only where other text would. The answer is fixed when the library is built.

/* Two Thai words, with no space between them. The second starts at byte 18. */
const char *text = "สวัสดีครับ";
daegun_line_break breaks[31];
size_t count = 0;
if (daegun_line_break_opportunities(text, 30, NULL, NULL, breaks, 31, &count) != DAEGUN_OK) return 1;
if (daegun_has_dictionaries()) {
    /* The word lists found the boundary: count is 2, a break at byte 18 and the end of the text. */
} else {
    /* No word lists and no segmenter: count is 1, the end of the text alone. */
}
daegun_script_runs
daegun_status daegun_script_runs(
    const char *text,
    size_t text_len,
    daegun_script_run *out,
    size_t out_len,
    size_t *out_count
);

Splits a text into runs of one script each.

Fills out with a daegun_script_run for each run, in text order: where it starts, where it ends and its script as a tag. The runs follow one another with no gap and cover the whole text. An empty text, for which text may be NULL, gives none. This is how text is cut before shaping, since each run is shaped by the rules of its own script.

A run ends where a character of another script begins. Most characters with no script of their own go with their neighbors: digits, spaces and punctuation, which are Common (Zyyy), and the combining marks several scripts share, such as accents, which are Inherited (Zinh), join the run around them. So "abc " followed by Greek letters is two runs, the space going with the Latin. A closing bracket takes the script of the run its opening bracket is in, up to 32 brackets deep.

Some shared characters belong to a few scripts only and claim those: the ideographic comma U+3001 after a Latin letter starts a run of its own. Text of characters that claim no script, such as "123", comes back as one run of Zyyy, but U+3001 alone is a run of Hani.

out is your buffer with room for out_len runs. *out_count is set to the number of runs, which is never more than text_len, so a buffer that large always fits. A NULL buffer with a length of 0 asks for that number alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes nothing into it, with the count still set.

Text that is not UTF-8, or a buffer that shares bytes with the text, also answers DAEGUN_INVALID_ARGUMENT. Then nothing is written, the count included.

const char *text = "abc αβγ";
size_t len = strlen(text);

/* Ask how many runs there are, then fetch them. */
size_t count = 0;
if (daegun_script_runs(text, len, NULL, 0, &count) != DAEGUN_OK) return 1;
daegun_script_run *runs = malloc(count * sizeof *runs);
if (!runs) return 1;
if (daegun_script_runs(text, len, runs, count, &count) != DAEGUN_OK) {
    free(runs);
    return 1;
}
/* Two runs: bytes 0 to 4 are Latin, the space with them, and bytes 4 to 10 are Greek. */
free(runs);
daegun_script_name
daegun_status daegun_script_name(daegun_tag script, daegun_str *out);

A script's Unicode name, such as Arabic for the code Arab.

A script is named in this header by its ISO 15924 code, four letters packed into a daegun_tag with DAEGUN_TAG: DAEGUN_TAG('A', 'r', 'a', 'b') is Arabic. The code is read in any case, so arab and ARAB name it too. Zyyy is Common, the script of characters that many scripts share, and Zinh is Inherited, the script of the combining marks that many scripts share, such as accents.

Writes a daegun_str that points at a static string, valid for the life of the program, so there is nothing to free. The name is spelled as the Unicode data files spell it, with an underscore where a name has two words: Old_Italic.

A tag that is the code of no script this library knows answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was. That goes for 0, and for Zzzz, the code for an unknown script.

daegun_str name;
if (daegun_script_name(DAEGUN_TAG('A', 'r', 'a', 'b'), &name) != DAEGUN_OK) return 1;
/* name.data is "Arabic" and name.len is 6. */
daegun_script_direction
daegun_status daegun_script_direction(daegun_tag script, int32_t *out);

Which way a script is written across a line: left to right or right to left.

Writes DAEGUN_SCRIPT_DIRECTION_LEFT_TO_RIGHT or DAEGUN_SCRIPT_DIRECTION_RIGHT_TO_LEFT to *out. script is an ISO 15924 code packed with DAEGUN_TAG, read in any case. A script answers right to left where most of its letters read that way, as those of Arabic and Hebrew do. Common (Zyyy) and Inherited (Zinh) answer left to right.

This is the direction of a script as a whole, not of a piece of text. Text that mixes directions is ordered by the bidirectional algorithm, which daegun_bidi_paragraph_new runs.

A tag that is the code of no script this library knows answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

/* The script of a character, then the way that script is written. */
daegun_tag script = 0;
if (daegun_script(0x05D0, &script) != DAEGUN_OK) return 1; /* the Hebrew letter alef */
int32_t direction = 0;
if (daegun_script_direction(script, &direction) != DAEGUN_OK) return 1;
/* script is DAEGUN_TAG('H', 'e', 'b', 'r') and direction is DAEGUN_SCRIPT_DIRECTION_RIGHT_TO_LEFT. */
daegun_script_opentype_tags
daegun_status daegun_script_opentype_tags(
    daegun_tag script,
    daegun_tag *out,
    size_t out_len,
    size_t *out_count
);

The OpenType script tags a font may file a script under, most specific first.

A font's layout tables file their rules under OpenType script tags, which are not the ISO 15924 codes this header names scripts by. Most scripts have one tag, their code in lowercase, such as latn. A few have a tag of another spelling: Lao is lao with a space, and Hiragana shares kana with Katakana. And some have several, one for each version of their shaping rules, newest first: Devanagari is dev3, dev2, deva, and Myanmar is mym2, mymr. A shaper tries them in that order. Common and Inherited give the one tag DFLT.

out is your buffer with room for out_len tags. *out_count is set to the number of tags, which is never more than 3, so a buffer of 3 always fits. A NULL buffer with a length of 0 asks for that number alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes nothing into it, with the count still set.

A script that is the code of no script this library knows also answers DAEGUN_INVALID_ARGUMENT. Then nothing is written, the count included.

daegun_tag tags[3]; /* 3 always fits */
size_t count = 0;
if (daegun_script_opentype_tags(DAEGUN_TAG('D', 'e', 'v', 'a'), tags, 3, &count) != DAEGUN_OK) return 1;
for (size_t i = 0; i < count; i++) {
    /* Look for tags[i] among the scripts of the font, and stop at the first one it has. */
}
/* count is 3: 'dev3', 'dev2' and 'deva'. */
daegun_script_is_context_dependent
daegun_status daegun_script_is_context_dependent(
    daegun_tag script,
    bool *out
);

Whether a script takes its identity from the text around it, as Common and Inherited do.

Writes true for Zyyy, Common, the script of digits, spaces and punctuation, and for Zinh, Inherited, the script of the combining marks several scripts share, such as accents. A character of either has no script of its own and goes with its neighbors, which is how daegun_script_runs treats it. Every other script writes false.

A tag that is the code of no script this library knows answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

bool depends = false;
if (daegun_script_is_context_dependent(DAEGUN_TAG('Z', 'y', 'y', 'y'), &depends) != DAEGUN_OK) return 1;
/* true: Common takes its script from its neighbors. */
if (daegun_script_is_context_dependent(DAEGUN_TAG('L', 'a', 't', 'n'), &depends) != DAEGUN_OK) return 1;
/* false: Latin is a script of its own. */
daegun_general_category
daegun_status daegun_general_category(uint32_t codepoint, int32_t *out);

A character's Unicode general category: whether it is a letter, a mark, a number, punctuation, a symbol, a separator or something else.

Writes one of the DAEGUN_GC_ codes to *out, such as DAEGUN_GC_UPPERCASE_LETTER for A. codepoint is the character as a Unicode scalar value. A code point that no character is assigned to is not an error: it answers DAEGUN_OK and writes DAEGUN_GC_UNASSIGNED.

DAEGUN_INVALID_ARGUMENT means codepoint is not a scalar value: it is above U+10FFFF, or it is a surrogate, U+D800 to U+DFFF. *out is then left as it was.

int32_t category = 0;
if (daegun_general_category(0x0301, &category) != DAEGUN_OK) return 1;
/* U+0301, the combining acute accent: category is DAEGUN_GC_NONSPACING_MARK. */
bool mark = category >= DAEGUN_GC_SPACING_MARK && category <= DAEGUN_GC_NONSPACING_MARK;
daegun_script
daegun_status daegun_script(uint32_t codepoint, daegun_tag *out);

A character's script, as its ISO 15924 code packed into a tag.

Writes the Script property of the character: DAEGUN_TAG('A', 'r', 'a', 'b') for an Arabic letter, and so on. Two answers are not scripts of their own. Zyyy, Common, is for a character that many scripts share, such as a digit or a space. Zinh, Inherited, is for a combining mark that many scripts share, such as an accent, which takes the script of the letter it sits on. The tag goes to daegun_script_name and the other script calls.

A character that Unicode gives no script, such as an unassigned code point or a private use character, writes 0 and still answers DAEGUN_OK. No script call accepts 0, so test for it first.

DAEGUN_INVALID_ARGUMENT means codepoint is not a Unicode scalar value: it is above U+10FFFF, or it is a surrogate, U+D800 to U+DFFF. *out is then left as it was.

daegun_tag script = 0;
if (daegun_script(0x0628, &script) != DAEGUN_OK) return 1;
/* U+0628, the Arabic letter beh: script is DAEGUN_TAG('A', 'r', 'a', 'b'). */

if (daegun_script('7', &script) != DAEGUN_OK) return 1;
/* A digit belongs to no one script: script is DAEGUN_TAG('Z', 'y', 'y', 'y'), Common. */
daegun_vertical_form
daegun_status daegun_vertical_form(uint32_t codepoint, uint32_t *out);

The presentation form a character takes in vertical text, where Unicode encodes one.

Some punctuation has a second shape for text set down a vertical line, such as a bracket turned to lie along the line. Unicode encodes those shapes as characters of their own, in the Vertical Forms and CJK Compatibility Forms blocks. This writes that character to *out: U+FE12 for the ideographic full stop U+3002, and U+FE35 for the fullwidth left parenthesis U+FF08.

A few dozen characters have one, all of them punctuation. Any other answers DAEGUN_ABSENT and leaves *out as it was. That is an answer, not a failure.

DAEGUN_INVALID_ARGUMENT means codepoint is not a Unicode scalar value: it is above U+10FFFF, or it is a surrogate. *out is left as it was then too.

uint32_t form = 0;
daegun_status status = daegun_vertical_form(0x3002, &form);
/* The ideographic full stop has one: status is DAEGUN_OK and form is 0xFE12. */

status = daegun_vertical_form('a', &form);
/* A Latin letter has none: status is DAEGUN_ABSENT and form is still 0xFE12. */
daegun_vertical_orientation
daegun_status daegun_vertical_orientation(uint32_t codepoint, int32_t *out);

How a character is set in vertical text: upright, or turned on its side.

Writes a DAEGUN_VO_ code to *out, the Vertical_Orientation property of UAX #50. DAEGUN_VO_UPRIGHT is a character that stands upright down the line, as a CJK ideograph does, and DAEGUN_VO_ROTATED one that is turned a quarter clockwise, as a Latin letter is. The two transformed codes are for characters that are drawn differently in vertical text, such as brackets, the ideographic comma and the small kana.

A character stands upright where the code is DAEGUN_VO_UPRIGHT or DAEGUN_VO_TRANSFORMED_UPRIGHT, and where it is DAEGUN_VO_TRANSFORMED_ROTATED and Unicode encodes a vertical form of it, which daegun_vertical_form finds: the fullwidth parentheses have one, the long vowel mark U+30FC none. A library newer than your header may write a code you have no constant for.

DAEGUN_INVALID_ARGUMENT means codepoint is not a Unicode scalar value: it is above U+10FFFF, or it is a surrogate. *out is then left as it was.

int32_t orientation = 0;
if (daegun_vertical_orientation(0x65E5, &orientation) != DAEGUN_OK) return 1;
/* U+65E5, a CJK ideograph, stands upright: orientation is DAEGUN_VO_UPRIGHT. */

if (daegun_vertical_orientation('a', &orientation) != DAEGUN_OK) return 1;
/* A Latin letter is turned on its side: orientation is DAEGUN_VO_ROTATED. */
daegun_bidi_paragraph_new
daegun_status daegun_bidi_paragraph_new(
    const char *text,
    size_t text_len,
    int32_t base,
    daegun_bidi_paragraph **out
);

Resolves a text with the Unicode bidirectional algorithm and hands back the result as a handle.

The text is UTF-8 with its length in bytes. base is a DAEGUN_BASE_ code, the direction the paragraph as a whole reads in: DAEGUN_BASE_LTR, DAEGUN_BASE_RTL, or DAEGUN_BASE_AUTO to take it from the first strongly directional character, such as a letter. Digits, spaces and punctuation are not strong, and a paragraph with no strong character reads left to right. Letters inside a directional isolate, from U+2066, U+2067 or U+2068 to the U+2069 that closes it, are passed over.

A text of several paragraphs is cut at each paragraph separator, and every paragraph is resolved by itself. With DAEGUN_BASE_AUTO each takes its direction from its own first strong character. With the other two codes all of them take the direction you gave.

On DAEGUN_OK, *out is a daegun_bidi_paragraph you own. Read it with the daegun_bidi_paragraph_ calls and free it with daegun_bidi_paragraph_free. It keeps no pointer into your text, which you may free or change afterward, though daegun_bidi_paragraph_visual_runs asks for the same text again. An empty text is fine, and text may then be NULL: it gives a handle with no levels and no paragraphs.

DAEGUN_INVALID_ARGUMENT means the text is not UTF-8, or base is none of the DAEGUN_BASE_ codes. On any failure *out is NULL.

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

uint8_t base = 0;
if (daegun_bidi_paragraph_base_level(paragraph, &base) != DAEGUN_OK) return 1;
size_t n = 0;
const uint8_t *levels = daegun_bidi_paragraph_levels(paragraph, &n);
/* base is 0, as the first letter is Latin. Of the 21 levels, those of the ten bytes of the Arabic
   word, 5 to 14, are 1, and the rest are 0. */

daegun_bidi_paragraph_free(paragraph);
daegun_bidi_paragraph_base_level
daegun_status daegun_bidi_paragraph_base_level(
    const daegun_bidi_paragraph *paragraph,
    uint8_t *out
);

The level of the text's first paragraph: 0 where it reads left to right, 1 where it reads right to left.

Written to *out. It is what DAEGUN_BASE_AUTO worked out from the text, or the direction you asked for. In a text of several paragraphs the others may be at another level, and daegun_bidi_paragraph_paragraphs lists the level of each.

For an empty text it is 1 if you asked for DAEGUN_BASE_RTL and 0 otherwise.

/* A Hebrew word, then an English one. */
const char *text = "שלום world";
daegun_bidi_paragraph *paragraph = NULL;
if (daegun_bidi_paragraph_new(text, strlen(text), DAEGUN_BASE_AUTO, &paragraph) != DAEGUN_OK) return 1;

uint8_t base = 0;
if (daegun_bidi_paragraph_base_level(paragraph, &base) != DAEGUN_OK) return 1;
/* base is 1: the first letter is Hebrew, so the paragraph reads right to left. */

daegun_bidi_paragraph_free(paragraph);
daegun_bidi_paragraph_levels
const uint8_t *daegun_bidi_paragraph_levels(
    const daegun_bidi_paragraph *paragraph,
    size_t *out_count
);

The direction level of every byte of the text.

Returns a borrowed array and sets *out_count to its length, which is the text's length in bytes. Index it with any byte offset: levels[i] is the level of the character that byte i belongs to, and every byte of a multi-byte character holds the same level.

An even level reads left to right and an odd one right to left. Level 0 is left-to-right text in a left-to-right paragraph, level 1 is right-to-left text, and level 2 is left-to-right text inside right-to-left, as a number or a Latin word in a Hebrew sentence. A space or a punctuation mark has no direction of its own, and takes its level from the text around it and from the paragraph.

The array is valid until daegun_bidi_paragraph_free. Do not free it. NULL comes back, with the count left as it was, only if paragraph or out_count is NULL. For an empty text the count is 0 and there is nothing to read.

/* "abc", then a Hebrew word. */
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, the length of the text in bytes. Any byte offset indexes the array:
   byte 6 starts the second Hebrew letter, and its level, 1, is odd. */
bool right_to_left = levels[6] % 2 == 1;

daegun_bidi_paragraph_free(paragraph);
daegun_bidi_paragraph_visual_order
const size_t *daegun_bidi_paragraph_visual_order(
    const daegun_bidi_paragraph *paragraph,
    size_t *out_count
);

Where each character of the text starts, in the order the characters are drawn from left to right.

Returns a borrowed array with one entry for each character, not for each byte. An entry is the byte offset where a character starts: text + order[0] is the leftmost character on the line, text + order[1] the one to its right, and so on. Along left-to-right text the offsets rise. A right-to-left stretch comes out backward, its last character first.

Each paragraph is reordered as one line of its own, and the paragraphs follow one another in text order. Text that you wrap needs every line reordered by itself, which daegun_bidi_paragraph_visual_runs does.

The array is valid until daegun_bidi_paragraph_free. Do not free it. NULL comes back, with the count left as it was, only if paragraph or out_count is NULL.

/* "abc", a space, then a Hebrew word of four letters, two bytes each. */
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 size_t *order = daegun_bidi_paragraph_visual_order(paragraph, &n);
for (size_t i = 0; i < n; i++) {
    /* text + order[i] is the next character to draw, moving right. */
}
/* n is 8, one entry a character: 0, 1, 2, 3, then the Hebrew letters last to first, 10, 8, 6, 4. */

daegun_bidi_paragraph_free(paragraph);
daegun_bidi_paragraph_paragraphs
const daegun_paragraph_run *daegun_bidi_paragraph_paragraphs(
    const daegun_bidi_paragraph *paragraph,
    size_t *out_count
);

The paragraphs the text was cut into, each with its byte range and its level.

Returns a borrowed array of daegun_paragraph_run in text order and sets *out_count to its length. A text with no paragraph separator in it is one paragraph, and an empty text has none.

The level of a paragraph is its base direction, 0 for left to right and 1 for right to left. It is the level daegun_bidi_paragraph_visual_runs reorders a line of that paragraph by.

The array is valid until daegun_bidi_paragraph_free. Do not free it. NULL comes back, with the count left as it was, only if paragraph or out_count is NULL.

/* 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);
/* n is 2. The first paragraph took its direction from the Hebrew, and the second from "abc":
   bytes 0 to 9 at level 1, then bytes 9 to 12 at level 0. */

daegun_bidi_paragraph_free(paragraph);
daegun_bidi_paragraph_free
void daegun_bidi_paragraph_free(daegun_bidi_paragraph *paragraph);

Frees a bidi paragraph.

NULL is fine and does nothing, so a cleanup path may free without checking. Every array the handle lent, from daegun_bidi_paragraph_levels, daegun_bidi_paragraph_visual_order and daegun_bidi_paragraph_paragraphs, is invalid afterward.

Runs that daegun_bidi_paragraph_visual_runs wrote are in your own buffer and stay good.

daegun_bidi_paragraph *paragraph = NULL;
daegun_status status = daegun_bidi_paragraph_new("hello", 5, DAEGUN_BASE_AUTO, &paragraph);
if (status == DAEGUN_OK) {
    /* read the paragraph */
}
/* Safe either way: a call that fails leaves `paragraph` NULL. */
daegun_bidi_paragraph_free(paragraph);
  • May be NULL: paragraph.
daegun_bidi_paragraph_visual_runs
daegun_status daegun_bidi_paragraph_visual_runs(
    const daegun_bidi_paragraph *paragraph,
    const char *text,
    size_t text_len,
    size_t start,
    size_t end,
    daegun_visual_run *out,
    size_t out_len,
    size_t *out_count
);

Cuts one line of the text into runs of a single direction, in the order they are drawn from left to right.

The line is the bytes start to end of the text, end not included: the whole text, or one line of it once you have chosen where to wrap. text must be the text the handle was made from, since the handle keeps the levels and not the text. Each daegun_visual_run written to out is a stretch of the line at one level. Draw them in the order given, from the left, each in its own direction: right to left where its level is odd.

Reordering works a line at a time, which is why the call takes a range: where a piece of text is drawn depends on what else is on its line. The line is reordered by the level of the paragraph that holds start, so keep a line inside one paragraph. Spaces at the end of the line take the level of the paragraph, as the algorithm asks.

out is your buffer with room for out_len runs. *out_count is set to the number of runs, which is never more than end - start, so a buffer that large always fits. A NULL buffer with a length of 0 asks for that number alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes nothing into it, with the count still set.

A range that is empty or reversed, that reaches past the end of the text, or whose start or end falls inside a character has no runs: the call answers DAEGUN_OK with a count of 0. text may be NULL only where text_len is 0, and an empty text has no runs either.

Text that is not UTF-8, or a buffer that shares bytes with the text, also answers DAEGUN_INVALID_ARGUMENT. Then nothing is written, the count included.

/* A Hebrew word, then an English one. The paragraph reads right to left, as its first letter does. */
const char *text = "שלום world";
size_t len = strlen(text);
daegun_bidi_paragraph *paragraph = NULL;
if (daegun_bidi_paragraph_new(text, len, DAEGUN_BASE_AUTO, &paragraph) != DAEGUN_OK) return 1;

daegun_visual_run runs[14]; /* end - start always fits, and len is 14 */
size_t count = 0;
if (daegun_bidi_paragraph_visual_runs(paragraph, text, len, 0, len, runs, 14, &count) != DAEGUN_OK)
    return 1;
/* Two runs, from the left: "world", bytes 9 to 14, at level 2, then the Hebrew word and the space,
   bytes 0 to 9, at level 1. What comes first in the text is drawn on the right. */

daegun_bidi_paragraph_free(paragraph);

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_writing_mode_is_vertical
daegun_status daegun_writing_mode_is_vertical(int32_t mode, bool *out);

Whether a writing mode sets its lines top to bottom.

Writes true for DAEGUN_WRITING_VERTICAL_RL and DAEGUN_WRITING_VERTICAL_LR, and false for DAEGUN_WRITING_HORIZONTAL.

A code that is none of the DAEGUN_WRITING_ values answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

bool vertical = false;
if (daegun_writing_mode_is_vertical(DAEGUN_WRITING_VERTICAL_RL, &vertical) != DAEGUN_OK) return 1;
if (daegun_writing_mode_is_vertical(DAEGUN_WRITING_HORIZONTAL, &vertical) != DAEGUN_OK) return 1;
/* true, then false. */
daegun_layout_options_default
daegun_status daegun_layout_options_default(
    daegun_layout_options *out,
    size_t size
);

Fills layout options with their defaults.

Pass the struct and sizeof it. The call zeroes that many bytes, sets the three defaults that are not zero and sets size: max_inline_size becomes infinity, tab_size 8 and base_direction DAEGUN_BASE_AUTO. Then set the fields you want.

Zero is the default of every other field: DAEGUN_ALIGN_START, DAEGUN_WRITING_HORIZONTAL, DAEGUN_TEXT_ORIENTATION_MIXED, DAEGUN_BREAK_GREEDY, no language, no segmenter, no features, the font's own line height and no limit on the lines.

A size below what daegun 2.0 defined answers DAEGUN_INVALID_ARGUMENT, and one larger than this library knows answers DAEGUN_UNSUPPORTED, which means your header is newer than the library. Neither writes anything.

daegun_layout_options opts;
if (daegun_layout_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
/* Not zero: no wrapping, tab stops 8 spaces apart, and the direction taken from the text. */
opts.max_inline_size = 12000.0;
opts.strategy = DAEGUN_BREAK_OPTIMAL;

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_free(layout);
daegun_font_layout
daegun_status daegun_font_layout(
    const daegun_font *font,
    const char *text,
    size_t text_len,
    const daegun_location *location,
    const daegun_layout_options *opts,
    daegun_layout **out
);

Lays text out in lines: it breaks the text, shapes each line, orders mixed directions and places every run.

It runs the Unicode bidirectional algorithm over the text, ends a line at every hard break, such as a newline, finds where else lines may break, shapes the text and fills each line up to max_inline_size of the options. The result is a daegun_layout. Read it with daegun_layout_info_of, daegun_layout_line_at and daegun_layout_run_at, and free it with daegun_layout_free.

Layout works in font units, as shaping does. Convert a width in pixels to font units going in, and the positions back to pixels coming out: a font unit is the pixel size over the units per em, which daegun_font_units_per_em gives.

The text is UTF-8 with its length in bytes, and may be NULL where the length is 0. Empty text gives a layout of no lines. A hard break at the very end of the text ends its line and starts no empty line after it: "a\n" is one line and "a\n\n" two, the second blank. location picks the instance of a variable font, NULL being the default one. NULL for opts means the defaults of daegun_layout_options, which wrap nothing.

A soft hyphen (U+00AD) is a place a word may break. A line that breaks at one ends in the hyphen of the font: U+2010, or else U+002D, or nothing where the font has neither.

Thai, Lao, Khmer and Myanmar are written without spaces between words. Their lines break between words only with a segmenter in the options, or in a library built with the dictionaries feature, which daegun_has_dictionaries reports. Otherwise such text breaks only where other text would.

Laying out cannot fail on the text or the font. DAEGUN_INVALID_ARGUMENT means the text or the language is not UTF-8, the options hold a code that is none of its constants, or their size is below what daegun 2.0 defined. DAEGUN_UNSUPPORTED means the options are larger than this library knows. daegun_last_error gives the reason. On any failure *out is NULL.

uint16_t upem = 0;
if (daegun_font_units_per_em(font, &upem) != DAEGUN_OK) return 1;
double scale = 16.0 / upem; /* font units to pixels 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 / scale; /* 200 px, in font units */

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;
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;
    for (size_t k = 0; k < line.run_count; k++) {
        daegun_layout_run run; /* run.run is borrowed from the layout: never free it */
        if (daegun_layout_run_at(layout, i, k, &run) != DAEGUN_OK) return 1;
        size_t n = 0;
        const uint32_t *glyphs = daegun_shaped_run_glyphs(run.run, &n);
        const double *advances = daegun_shaped_run_advances(run.run, &n);
        const daegun_offset *offsets = daegun_shaped_run_offsets(run.run, &n);
        double pen = run.offset.x;
        for (size_t g = 0; g < n; g++) {
            double x = (pen + offsets[g].x) * scale;
            double y = (line.baseline - offsets[g].y) * scale;
            /* Draw glyphs[g] with its origin x pixels from the left of the block and y pixels
               down from its top. */
            pen += advances[g];
        }
    }
}
/* With Inter this is two lines, their baselines 15.5 and about 34.9 pixels down. */

daegun_layout_free(layout);
daegun_layout_free
void daegun_layout_free(daegun_layout *layout);

Frees a layout, and with it every run the layout lent.

NULL is fine and does nothing, so a cleanup path may free without checking. The run of every daegun_layout_run read from the layout is invalid afterward. A run you copied out with daegun_shaped_run_copy is your own and stays.

daegun_layout *layout = NULL;
daegun_status status = daegun_font_layout(font, "Wave", 4, NULL, NULL, &layout);
if (status == DAEGUN_OK) {
    /* read the layout */
}
/* Safe either way: a call that fails leaves `layout` NULL. */
daegun_layout_free(layout);
  • May be NULL: layout.
daegun_layout_info_of
daegun_status daegun_layout_info_of(
    const daegun_layout *layout,
    daegun_layout_info *out
);

Reads a layout as a whole into a daegun_layout_info: its line count, its sizes and where it was cut off.

The place to start reading a layout, since line_count is the bound for daegun_layout_line_at. The sizes are in font units, so multiply by the pixel size over the units per em for pixels.

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, NULL, &layout) != DAEGUN_OK) return 1;

daegun_layout_info info;
if (daegun_layout_info_of(layout, &info) != DAEGUN_OK) return 1;
uint16_t upem = 0;
if (daegun_font_units_per_em(font, &upem) != DAEGUN_OK) return 1;
double width_px = info.inline_size * 16.0 / upem;
double height_px = info.block_size * 16.0 / upem;
/* Unwrapped, the sentence is one line: about 344.4 by 19.4 pixels at 16 px. */

daegun_layout_free(layout);
daegun_layout_line_at
daegun_status daegun_layout_line_at(
    const daegun_layout *layout,
    size_t line,
    daegun_layout_line *out
);

Reads one line of a layout into a daegun_layout_line.

Lines are indexed from 0 in the order they are read: top to bottom in horizontal text. The count is line_count of daegun_layout_info.

An index past the last line answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

const char *text = "one\ntwo";
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, 1, &line) != DAEGUN_OK) return 1;
/* The second line covers bytes 4 to 7, "two". With Inter its baseline is 4462 units down from
   the top, one line height of 2478 below the first, and a hard break ends it: the end of the text. */

daegun_layout_free(layout);
daegun_layout_run_at
daegun_status daegun_layout_run_at(
    const daegun_layout *layout,
    size_t line,
    size_t run,
    daegun_layout_run *out
);

Reads one run of a line into a daegun_layout_run.

line is the line's index and run the run's index within that line, in visual order: 0 is the leftmost run of a horizontal line. The count is run_count of the daegun_layout_line.

The run it writes is borrowed. It points into the layout, is valid until daegun_layout_free and must never go to daegun_shaped_run_free. daegun_shaped_run_copy makes one you can keep.

A line past the last line, or a run past the last run of its line, answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

daegun_layout *layout = NULL;
if (daegun_font_layout(font, "Wave", 4, NULL, NULL, &layout) != DAEGUN_OK) return 1;

daegun_layout_run first;
if (daegun_layout_run_at(layout, 0, 0, &first) != DAEGUN_OK) return 1;
/* first.run belongs to the layout. Copy it to keep it longer than the layout. */
daegun_shaped_run *kept = NULL;
if (daegun_shaped_run_copy(first.run, &kept) != DAEGUN_OK) return 1;
daegun_layout_free(layout);

/* `first.run` is gone with the layout. `kept` is still good. */
double width = 0.0;
if (daegun_shaped_run_width(kept, &width) != DAEGUN_OK) return 1;
daegun_shaped_run_free(kept);
daegun_justify_options_default
daegun_status daegun_justify_options_default(
    daegun_justify_options *out,
    size_t size
);

Fills justification options with their defaults, which are all 0.

Pass the struct and sizeof it. The call zeroes that many bytes and sets size. Left at 0, script names no JSTF data and target_width is a width that any text with a width is past, so set both afterward.

A size below what daegun 2.0 defined answers DAEGUN_INVALID_ARGUMENT, and one larger than this library knows answers DAEGUN_UNSUPPORTED, which means your header is newer than the library. Neither writes anything.

daegun_justify_options opts;
if (daegun_justify_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
/* Everything is 0 but the size, so name the script and the width. */
opts.script = DAEGUN_TAG('l', 'a', 't', 'n');
opts.target_width = 6000.0;

daegun_shaped_run *run = NULL;
if (daegun_font_justify(font, "Wave", 4, NULL, DAEGUN_HORIZONTAL, &opts, &run, NULL) != DAEGUN_OK) return 1;
daegun_shaped_run_free(run);
daegun_font_justify
daegun_status daegun_font_justify(
    const daegun_font *font,
    const char *text,
    size_t text_len,
    const daegun_location *location,
    int32_t orientation,
    const daegun_justify_options *opts,
    daegun_shaped_run **out_run,
    daegun_justification *out_info
);

Shapes one line to a target width, trying the font's JSTF priority levels until one fits.

It shapes the whole text as one run with the default shaping options, along orientation: DAEGUN_HORIZONTAL, or DAEGUN_VERTICAL for a line set top to bottom. If that natural width is within tolerance of target_width, the natural run comes back.

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. Where the natural width is not close enough, the call shapes the line again at each level of the script in the options, highest priority first: with the level's shrinkage lookups where the line is too wide, and with its extension lookups where it is too narrow. The first level that lands within the tolerance wins. If none does, you get the shaping that came nearest, which may be the natural one, and best_effort is true.

It changes the line only through the font's own lookups. It adds no space between words and repeats no extender glyph, so a font with no JSTF levels for the script gives the natural run back.

*out_run is a run of your own: read it like any shaped run and free it with daegun_shaped_run_free. out_info receives a daegun_justification, and may be NULL if the run is all you want. The text may be NULL where its length is 0, which gives an empty run. NULL for opts means all zeros, no script and a target width of 0: the natural run comes back, with best_effort true for any text that has a width. location picks the instance of a variable font, NULL being the default one.

DAEGUN_INVALID_ARGUMENT means the text is not UTF-8, orientation is neither DAEGUN_HORIZONTAL nor DAEGUN_VERTICAL, or the size of the options is below what daegun 2.0 defined. DAEGUN_UNSUPPORTED means the options are larger than this library knows. On any failure *out_run is NULL and *out_info is left as it was.

/* `font` is a test font with JSTF priority levels for the arab script. */
const char *text = "Aa الماس";
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 = 8127.0;

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;
if (info.best_effort) {
    /* No level reached the target: info.width is as near as the font gets. */
}
/* The line is 7649 units wide as shaped. The font's first level extends it to 8127 exactly. */

daegun_shaped_run_free(run);
daegun_font_justification_glyphs
daegun_status daegun_font_justification_glyphs(
    const daegun_font *font,
    daegun_tag script,
    uint32_t *out,
    size_t out_len,
    size_t *out_count
);

The glyphs a font's JSTF table lists as extenders for a script, such as the tatweel.

An extender is a glyph a justifier may repeat to widen a line. The tatweel, the stroke that stretches Arabic words, is the usual one. daegun reports the glyphs and leaves the inserting to you. daegun_shaped_run_safe_to_insert_tatweel says where in a run one may go, but only for a run shaped with report_tatweel_positions set in a daegun_shape_options. The runs that daegun_font_justify, daegun_font_shape_justified and a layout give are shaped without it and carry no such flags.

script is an OpenType script tag, such as DAEGUN_TAG('a', 'r', 'a', 'b'). The glyph ids go into out, your buffer with room for out_len of them, as the table stores them: they are not checked against daegun_font_glyph_count. *out_count is set to how many there are, at most 65,535, in two cases: on DAEGUN_OK, and where the buffer is too small. A NULL buffer with a length of 0 asks for that number alone and answers DAEGUN_OK. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes nothing into it, but the count is set, so you can call again with enough room. Any other failure leaves the count as it was. That includes a buffer that shares bytes with *out_count, which answers DAEGUN_INVALID_ARGUMENT as well.

DAEGUN_ABSENT means the font has no JSTF table, the table doesn't list the script, the script has no list of extenders there, or the data is too damaged to read. A list that is there and holds no glyph answers DAEGUN_OK with a count of 0.

uint32_t glyphs[16];
size_t count = 0;
daegun_status status =
    daegun_font_justification_glyphs(font, DAEGUN_TAG('a', 'r', 'a', 'b'), glyphs, 16, &count);
if (status == DAEGUN_ABSENT) {
    /* The font lists no extenders for Arabic. */
} else if (status == DAEGUN_INVALID_ARGUMENT) {
    /* More than 16: `count` says how many, so call again with a buffer that large. */
} else if (status == DAEGUN_OK) {
    for (size_t i = 0; i < count; i++) {
        /* glyphs[i] may be repeated to widen a line. */
    }
}
/* Scheherazade New lists two, glyphs 1313 and 1315. The first is its tatweel. */
daegun_font_justification_priorities
daegun_status daegun_font_justification_priorities(
    const daegun_font *font,
    daegun_tag script,
    daegun_tag language_system,
    daegun_jstf_priorities **out
);

Reads a script's JSTF priority levels for a language system into a handle.

script and language_system are OpenType tags. A language_system of 0 asks for the default levels of the script, and a language system the script does not list gets the default too. The levels come highest priority first in a daegun_jstf_priorities, which you free with daegun_jstf_priorities_free. DAEGUN_OK does not promise a level: a language system the script lists with no levels gives a handle whose daegun_jstf_priorities_count is 0.

DAEGUN_ABSENT means the font has no JSTF table, the table doesn't list the script, the script lists neither the language system nor default levels, or the data is too damaged to read. *out is then NULL, as it is on any failure.

daegun_jstf_priorities *levels = NULL;
daegun_status status =
    daegun_font_justification_priorities(font, DAEGUN_TAG('a', 'r', 'a', 'b'), 0, &levels);
if (status == DAEGUN_ABSENT) {
    /* No JSTF levels for Arabic: this font has no way to adjust such a line. */
} else if (status != DAEGUN_OK) {
    return 1;
}
/* This test font has levels for arab and none for latn. */
daegun_jstf_priorities_free(levels);
daegun_jstf_priorities_count
daegun_status daegun_jstf_priorities_count(
    const daegun_jstf_priorities *priorities,
    size_t *out
);

How many priority levels a set of JSTF priorities holds.

Levels are indexed from 0, the highest priority, in daegun_jstf_priorities_lookups and daegun_font_shape_justified.

daegun_jstf_priorities *levels = NULL;
if (daegun_font_justification_priorities(font, DAEGUN_TAG('a', 'r', 'a', 'b'), 0, &levels) != DAEGUN_OK)
    return 1;

size_t count = 0;
if (daegun_jstf_priorities_count(levels, &count) != DAEGUN_OK) return 1;
for (size_t level = 0; level < count; level++) {
    /* Level 0 has the highest priority, so try it first. */
}
/* count is 2 in this test font. */

daegun_jstf_priorities_free(levels);
daegun_jstf_priorities_free
void daegun_jstf_priorities_free(daegun_jstf_priorities *priorities);

Frees a set of JSTF priorities, and with it every lookup list it lent.

NULL is fine and does nothing, so a cleanup path may free without checking. A run that daegun_font_shape_justified shaped with one of the levels is your own and stays.

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) {
    /* read the levels */
}
/* Safe either way: a call that fails, or finds no levels, leaves `levels` NULL. */
daegun_jstf_priorities_free(levels);
  • May be NULL: priorities.
daegun_jstf_priorities_lookups
daegun_status daegun_jstf_priorities_lookups(
    const daegun_jstf_priorities *priorities,
    size_t level,
    int32_t which,
    const uint16_t **out,
    size_t *out_count
);

One of a priority level's eight lookup lists: the GSUB or GPOS lookups it turns on or off to shrink a line or to extend it.

level indexes the levels from 0, the highest priority, and which is a DAEGUN_JSTF_ code that names the list. On DAEGUN_OK, *out points at the lookup indices, each an index into the GSUB or GPOS lookup list of the font, and *out_count is how many there are.

The array is borrowed from the handle: it is valid until daegun_jstf_priorities_free, and not yours to free.

DAEGUN_ABSENT means the level has no such list. That is not the same as a list that names no lookups, which answers DAEGUN_OK with a count of 0. DAEGUN_INVALID_ARGUMENT means level is past the last level or which is none of the DAEGUN_JSTF_ codes. Both leave *out and *out_count as they were.

daegun_jstf_priorities *levels = NULL;
if (daegun_font_justification_priorities(font, DAEGUN_TAG('a', 'r', 'a', 'b'), 0, &levels) != DAEGUN_OK)
    return 1;

/* The GSUB lookups the second level turns on to extend a line. */
const uint16_t *lookups = NULL;
size_t count = 0;
daegun_status status =
    daegun_jstf_priorities_lookups(levels, 1, DAEGUN_JSTF_EXTENSION_ENABLE_GSUB, &lookups, &count);
if (status == DAEGUN_OK) {
    for (size_t i = 0; i < count; i++) {
        /* lookups[i] is an index into the font's GSUB lookup list. */
    }
}
/* In this test font that is one lookup, index 1. */

daegun_jstf_priorities_free(levels);
daegun_font_shape_justified
daegun_status daegun_font_shape_justified(
    const daegun_font *font,
    const char *text,
    size_t text_len,
    const daegun_location *location,
    int32_t orientation,
    const daegun_jstf_priorities *priorities,
    size_t level,
    int32_t adjustment,
    daegun_shaped_run **out
);

Shapes text with the lookups of one JSTF priority level applied, to shrink the line or to extend it.

The building block under daegun_font_justify, for a justifier of your own that tries the levels itself. It shapes the whole text as one run with the default shaping options, along orientation, and switches lookups as level level of priorities says: its shrinkage lists with DAEGUN_ADJUST_SHRINK, its extension lists with DAEGUN_ADJUST_EXTEND.

A lookup in a disable list is not applied. A lookup in an enable list that the shaping would not apply by itself is applied after the table's other lookups, to every glyph. A lookup named in both lists counts as enabled, and an index the font has no lookup for is passed over.

Read priorities from the same font. A level is a list of lookup indices, which mean something only in the font they came from, and the call does not check: with levels from another font it still answers DAEGUN_OK and switches whichever lookups have those indices.

*out is a run of your own, to free with daegun_shaped_run_free. Compare its width, from daegun_shaped_run_width, with the width you are after. The text may be NULL where its length is 0, and location picks the instance of a variable font, NULL being the default one.

DAEGUN_INVALID_ARGUMENT means the text is not UTF-8, orientation is neither DAEGUN_HORIZONTAL nor DAEGUN_VERTICAL, level is past the last level, or adjustment is neither of the DAEGUN_ADJUST_ codes. On any failure *out is NULL.

daegun_jstf_priorities *levels = NULL;
if (daegun_font_justification_priorities(font, DAEGUN_TAG('a', 'r', 'a', 'b'), 0, &levels) != DAEGUN_OK)
    return 1;
size_t count = 0;
if (daegun_jstf_priorities_count(levels, &count) != DAEGUN_OK) return 1;

/* Shrink the line with each level in turn, and keep the narrowest width. */
const char *text = "Aa الماس";
double narrowest = INFINITY;
for (size_t level = 0; level < count; level++) {
    daegun_shaped_run *run = NULL;
    if (daegun_font_shape_justified(font, text, strlen(text), NULL, DAEGUN_HORIZONTAL, levels, level,
                                    DAEGUN_ADJUST_SHRINK, &run) != DAEGUN_OK)
        return 1;
    double width = 0.0;
    if (daegun_shaped_run_width(run, &width) != DAEGUN_OK) return 1;
    if (width < narrowest) narrowest = width;
    daegun_shaped_run_free(run);
}
/* The line is 7649 units wide as shaped. The second level of this test font brings it to 6744. */

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_font_outline
daegun_status daegun_font_outline(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    const daegun_pen *pen
);

Draws a glyph's outline onto a pen, in font units.

The outline comes as the font draws it at location, neither scaled nor hinted: floats in font units, y up, measured from the glyph's origin. For pixels, multiply by the pixel size over daegun_font_units_per_em, or call daegun_font_prepared_outline, which scales the outline and can hint, stroke or embolden it on the way.

Each contour reaches the pen as a move_to, its lines and curves, and then a close. A font with TrueType outlines draws its curves through quad_to, and one with CFF or CFF2 outlines through curve_to. A glyph with nothing to draw, such as a space, answers DAEGUN_OK and calls nothing.

location picks the instance of a variable font, and NULL is the default instance. To keep the outline, pass the pen daegun_path_as_pen gives. Each call draws the glyph from the font's data again, unless daegun_font_prewarm has put its outline at that location in the outline cache of the font, which is then replayed.

DAEGUN_NO_OUTLINE means there is no such outline: gid is past the last glyph, or the font has no outlines at all, as one that holds only bitmaps. DAEGUN_MALFORMED means the glyph's data doesn't decode, and DAEGUN_LIMIT_EXCEEDED that decoding it would take more work than daegun allows one glyph. The decoder has rarer answers too, such as DAEGUN_UNSUPPORTED for a CFF operator it does not know and DAEGUN_MISSING where data the glyph needs isn't there. daegun_last_error gives the reason.

A glyph is drawn as it is decoded. By the time a call fails, the pen may already have received part of the outline, so throw away what a failed call drew.

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

/* Keep the outline in a path, through the pen that draws into it. */
daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
if (daegun_font_outline(font, gid, NULL, &pen) != DAEGUN_OK) return 1;

daegun_bounds box;
if (daegun_path_bounds(path, &box) != DAEGUN_OK) return 1;
/* Inter's "o" in font units: x from 104 to 1124, y from -24 to 1132. */

/* The same glyph at weight 700. */
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_path_clear(path);
if (daegun_font_outline(font, gid, bold, &pen) != DAEGUN_OK) return 1;
if (daegun_path_bounds(path, &box) != DAEGUN_OK) return 1;
/* Bolder, so wider: x from 81 to 1175. */

daegun_location_free(bold);
daegun_path_free(path);
daegun_font_has_overlap_flag
daegun_status daegun_font_has_overlap_flag(
    const daegun_font *font,
    uint32_t gid,
    bool *out
);

Whether the font flags a glyph as one whose contours or components may overlap.

A TrueType font's glyf table can mark a glyph whose pieces overlap one another. *out is true where the glyph carries the OVERLAP_SIMPLE flag, where a glyph it is built from carries it, or where one of its components carries OVERLAP_COMPOUND. A rasterizer may take that as a cue to antialias the glyph with more care.

It reads a flag and does not look at the outline. False doesn't mean the contours keep apart: a glyph the font left unflagged may overlap all the same. A glyph that CFF, CFF2 or VARC draws is always false, as those carry no such flag, and so is a gid past the last glyph. To merge contours that do overlap, flatten the outline with daegun_path_flatten and hand the result to daegun_contours_resolve_overlaps.

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

bool may_overlap = false;
if (daegun_font_has_overlap_flag(font, gid, &may_overlap) != DAEGUN_OK) return 1;
if (may_overlap) {
    /* Take more care over this glyph: merge its contours, or antialias it more finely. */
}
/* Inter leaves its "o" unflagged, so may_overlap is false. */
daegun_path_free
void daegun_path_free(daegun_path *path);

Frees a path.

That is a path from daegun_path_new or daegun_scene_path_copy. NULL is fine and does nothing, so a cleanup path may free without checking. Afterward the arrays the path lent, and any pen from daegun_path_as_pen, are invalid.

A freed path that holds 64 KiB of memory or less is not handed back to the allocator: daegun keeps it, emptied, as this thread's next daegun_path_new. A loop that makes and frees a path for each glyph therefore reuses one path. daegun_thread_release lets go of the kept one, and a library built with --cfg daegun_no_spares keeps none.

daegun_path *path = daegun_path_new();
daegun_pen pen;
uint32_t gid = 0;
daegun_status status = daegun_font_glyph_id(font, 'o', &gid);
if (status == DAEGUN_OK) status = daegun_path_as_pen(path, &pen);
if (status == DAEGUN_OK) status = daegun_font_outline(font, gid, NULL, &pen);
if (status == DAEGUN_OK) {
    /* read the path */
}
/* One free on the way out, whatever happened. The pen is no good after it. */
daegun_path_free(path);
  • May be NULL: path.
daegun_path_new
daegun_path *daegun_path_new(void);

Makes an empty path.

It never returns NULL, so there is nothing to check: running out of memory ends the process, as it does throughout daegun. Free the path with daegun_path_free.

Where the thread has kept a path it freed earlier, as daegun_path_free describes, this hands that one back, emptied, with the memory it had.

daegun_path *path = daegun_path_new();

bool empty = false;
if (daegun_path_is_empty(path, &empty) != DAEGUN_OK) return 1;
/* A new path holds nothing: empty is true. */

daegun_path_free(path);
daegun_path_move_to
daegun_status daegun_path_move_to(daegun_path *path, float x, float y);

Starts a new contour of a path at a point.

Appends the verb DAEGUN_VERB_MOVE and one point. Every contour begins with one. A contour before it that was not closed stays open in the path, and the calls that read the path decide what that means.

It answers DAEGUN_OK, or DAEGUN_NULL for a NULL path, and nothing else. The point is stored as given and not checked, so a NaN goes in, and it is left to the calls that read the path, such as a stroke, to refuse it. With a path from daegun_path_new, which is never NULL, the status has nothing to tell you. The header leaves it without DAEGUN_NODISCARD, so ignoring it draws no warning.

It changes the path: the path must be with one thread while it runs, and the arrays from daegun_path_verbs and daegun_path_points are invalid after it.

/* Two contours: each move starts one. */
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_move_to(path, 0.0f, 50.0f);
daegun_path_line_to(path, 100.0f, 50.0f);

size_t count = 0;
const uint8_t *verbs = daegun_path_verbs(path, &count);
size_t contours = 0;
for (size_t i = 0; i < count; i++) contours += verbs[i] == DAEGUN_VERB_MOVE;
/* Four verbs, two of them moves. */

daegun_path_free(path);
daegun_path_line_to
daegun_status daegun_path_line_to(daegun_path *path, float x, float y);

Adds a straight line to a path, from where it stands to a point.

Appends the verb DAEGUN_VERB_LINE and one point. The line starts where the last segment ended, or where daegun_path_move_to put the start of the contour. Begin each contour with daegun_path_move_to: this call does not add one for you.

It answers DAEGUN_OK, or DAEGUN_NULL for a NULL path, and nothing else: the point is stored as given, not checked. So with a path that is not NULL the status may be ignored, and the header does not mark it DAEGUN_NODISCARD. The call changes the path: the path must be with one thread while it runs, and the arrays the path lent are invalid after it.

/* A triangle. The close draws its third 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_line_to(path, 50.0f, 80.0f);
daegun_path_close(path);

size_t verbs = 0, points = 0;
daegun_path_verbs(path, &verbs);
daegun_path_points(path, &points);
/* Four verbs and three points: a move, two lines and a close. */

daegun_path_free(path);
daegun_path_quad_to
daegun_status daegun_path_quad_to(
    daegun_path *path,
    float cx,
    float cy,
    float x,
    float y
);

Adds a quadratic curve to a path, from where it stands to a point.

Appends the verb DAEGUN_VERB_QUAD and two points: the control (cx, cy), then the end (x, y). The curve leaves the current point heading for the control and arrives at the end coming from it. It bends toward the control without passing through it. TrueType outlines are made of these curves.

It answers DAEGUN_OK, or DAEGUN_NULL for a NULL path, and nothing else: the points are stored as given, not checked. So with a path that is not NULL the status may be ignored, and the header does not mark it DAEGUN_NODISCARD. The call changes the path: the path must be with one thread while it runs, and the arrays the path lent are invalid after it.

/* An arch from (0, 0) to (100, 0), pulled up toward its control at (50, 100). */
daegun_path *path = daegun_path_new();
daegun_path_move_to(path, 0.0f, 0.0f);
daegun_path_quad_to(path, 50.0f, 100.0f, 100.0f, 0.0f);

daegun_bounds box;
if (daegun_path_bounds(path, &box) != DAEGUN_OK) return 1;
/* The curve rises to y 50, halfway to the control, and never touches it. */

daegun_path_free(path);
daegun_path_curve_to
daegun_status daegun_path_curve_to(
    daegun_path *path,
    float c1x,
    float c1y,
    float c2x,
    float c2y,
    float x,
    float y
);

Adds a cubic curve to a path, from where it stands to a point.

Appends the verb DAEGUN_VERB_CUBIC and three points: the controls (c1x, c1y) and (c2x, c2y), then the end (x, y). The curve leaves the current point heading for the first control and arrives at the end coming from the second. CFF outlines are made of these curves.

It answers DAEGUN_OK, or DAEGUN_NULL for a NULL path, and nothing else: the points are stored as given, not checked. So with a path that is not NULL the status may be ignored, and the header does not mark it DAEGUN_NODISCARD. The call changes the path: the path must be with one thread while it runs, and the arrays the path lent are invalid after it.

/* An arch from (0, 0) to (100, 0), with a control straight above each end. */
daegun_path *path = daegun_path_new();
daegun_path_move_to(path, 0.0f, 0.0f);
daegun_path_curve_to(path, 0.0f, 100.0f, 100.0f, 100.0f, 100.0f, 0.0f);

daegun_bounds box;
if (daegun_path_bounds(path, &box) != DAEGUN_OK) return 1;
/* The curve rises to y 75, three quarters of the way to its controls. */

daegun_path_free(path);
daegun_path_close
daegun_status daegun_path_close(daegun_path *path);

Closes the contour a path is drawing.

Appends the verb DAEGUN_VERB_CLOSE, which takes no point. It joins the contour's last point to its first with a straight line, where the two differ.

A stroke reads the difference. A closed contour has a join at every corner and no ends, and an open one has a cap at each end. A fill does not: daegun_path_replay and daegun_path_flatten treat every contour as closed, whether or not you closed it.

It answers DAEGUN_OK, or DAEGUN_NULL for a NULL path, and nothing else, so with a path that is not NULL the status may be ignored. It changes the path: the path must be with one thread while it runs, and the arrays the path lent are invalid after it.

/* A pen that counts the contours it is drawn: every callback but move_to is left NULL. */
static void count_loop(void *user, float x, float y)
{
    (void)x;
    (void)y;
    ++*(int *)user;
}

int loops = 0;
daegun_pen pen = { 0 };
pen.move_to = count_loop;
pen.user = &loops;
daegun_stroke_style style = { 2.0f, DAEGUN_CAP_BUTT, DAEGUN_JOIN_MITER, 4.0f };

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);
if (daegun_path_stroke(path, &style, 0.1f, &pen) != DAEGUN_OK) return 1;
/* Left open, the two lines stroke as one loop: a bent line with a cap at each end. */

loops = 0;
daegun_path_close(path);
if (daegun_path_stroke(path, &style, 0.1f, &pen) != DAEGUN_OK) return 1;
/* Closed, they are a triangle, which strokes as two loops: its outside and its inside. */

daegun_path_free(path);
daegun_path_clear
daegun_status daegun_path_clear(daegun_path *path);

Empties a path and keeps its memory.

For a loop that draws one outline after another into the same path. The path keeps the room it has grown to, so it allocates again only when an outline needs more room than any before it.

Afterward the path is empty, as a new one is. The arrays it lent are invalid, and a pen from daegun_path_as_pen is still good.

It answers DAEGUN_OK, or DAEGUN_NULL for a NULL path, and nothing else. It changes the path, so the path must be with one thread while it runs.

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

/* One path for every glyph of the run. */
daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
for (size_t i = 0; i < n; i++) {
    daegun_path_clear(path);
    if (daegun_font_outline(font, glyphs[i], NULL, &pen) != DAEGUN_OK) break;
    /* `path` holds glyph i alone, in the memory the glyphs before it left. */
}

daegun_path_free(path);
daegun_shaped_run_free(run);
daegun_path_as_pen
daegun_status daegun_path_as_pen(daegun_path *path, daegun_pen *out);

Fills in a pen that draws into a path.

Hand the pen to anything that draws, such as daegun_font_outline, daegun_font_prepared_outline, daegun_hinted_outline_draw, daegun_path_replay or a stroke, and what it draws is appended to the path, after whatever the path already holds. That is how you keep an outline as a value with no callbacks of your own. Call daegun_path_clear first where you want the new outline alone.

The pen borrows the path: its user is the path, and its five callbacks are daegun's own. It is a plain struct with nothing to free. You may copy it and use it as often as you like, until the path is freed.

A call that draws through the pen changes the path, so for as long as that call runs the path must be with one thread, and the arrays the path lent are invalid after it.

The pen may be handed to a call that reads this very path. daegun_path_replay and the stroke calls read the path as it was when they began, and what they draw lands after it.

This call itself changes nothing in the path. The only failure is a NULL pointer, which leaves *out as it was.

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

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

/* Whatever draws onto the pen now draws into the path: here the glyph at 16 pixels to the em. */
if (daegun_font_prepared_outline(font, gid, NULL, 16.0f, NULL, &pen, NULL) != DAEGUN_OK) return 1;

daegun_bounds box;
if (daegun_path_bounds(path, &box) != DAEGUN_OK) return 1;
/* In pixels now: Inter's "o" is just under 8 wide at this size. */

daegun_path_free(path);
daegun_path_is_empty
daegun_status daegun_path_is_empty(const daegun_path *path, bool *out);

Whether nothing has been drawn into a path.

Writes true to *out for a path with no verbs: a new one, a cleared one, or one that only a glyph with no outline, such as a space, was drawn into. A path that holds nothing but a daegun_path_close is not empty, though it has no points.

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

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

bool empty = false;
if (daegun_path_is_empty(path, &empty) != DAEGUN_OK) return 1;
/* A space draws nothing, so the path is still empty and there is nothing to fill. */

daegun_path_free(path);
daegun_path_cost
daegun_status daegun_path_cost(const daegun_path *path, size_t *out);

How many bytes of outline a path holds.

Writes one byte for each verb plus eight for each point to *out, which is the size of what daegun_path_verbs and daegun_path_points lend. It counts what the path holds, not the memory set aside for it, which may be more. It is a number to budget a cache of paths by.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'o', &gid) != DAEGUN_OK) return 1;
daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
if (daegun_font_outline(font, gid, NULL, &pen) != DAEGUN_OK) return 1;

size_t cost = 0;
if (daegun_path_cost(path, &cost) != DAEGUN_OK) return 1;
/* Inter's "o" is 28 verbs and 50 points: 28 + 50 * 8 = 428 bytes. */

daegun_path_free(path);
daegun_path_bounds
daegun_status daegun_path_bounds(
    const daegun_path *path,
    daegun_bounds *out
);

The smallest box that holds everything a path draws.

Writes a daegun_bounds to *out, in the path's own units, y up. The box is tight: it follows each curve to its extremes, so a control point the curve only bends toward is left outside. A point set by daegun_path_move_to counts even where nothing is drawn from it.

DAEGUN_ABSENT means the path has no points, so there is no box: an empty path, or one that holds nothing but closes. *out is then left as it was.

daegun_path *path = daegun_path_new();
daegun_bounds box = { 0 };

daegun_status status = daegun_path_bounds(path, &box);
/* status is DAEGUN_ABSENT: nothing is drawn yet, so there is no box. */

daegun_path_move_to(path, 10.0f, 20.0f);
daegun_path_line_to(path, 110.0f, 20.0f);
daegun_path_quad_to(path, 60.0f, 120.0f, 10.0f, 20.0f);
status = daegun_path_bounds(path, &box);
if (status != DAEGUN_OK) return 1;
/* From (10, 20) to (110, 70): up to the top of the curve, not to its control at y 120. */

daegun_path_free(path);
daegun_path_verbs
const uint8_t *daegun_path_verbs(
    const daegun_path *path,
    size_t *out_count
);

A path's verbs, a byte each, in the order they were drawn.

Returns a borrowed array and sets *out_count to its length. Each byte is one of the DAEGUN_VERB_ values, and takes its points off the front of what daegun_path_points has left: one for a move or a line, two for a quadratic curve, three for a cubic, none for a close. Read the two arrays together.

The array is valid until the path is drawn into, cleared or freed. Don't free it. An empty path gives a count of 0, with a pointer that is not NULL and must not be read. NULL comes back, with the count left as it was, only if path or out_count is NULL.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'o', &gid) != DAEGUN_OK) return 1;
daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
if (daegun_font_outline(font, gid, NULL, &pen) != DAEGUN_OK) return 1;

size_t count = 0;
const uint8_t *verbs = daegun_path_verbs(path, &count);
size_t contours = 0, quads = 0, cubics = 0;
for (size_t i = 0; i < count; i++) {
    contours += verbs[i] == DAEGUN_VERB_MOVE;
    quads += verbs[i] == DAEGUN_VERB_QUAD;
    cubics += verbs[i] == DAEGUN_VERB_CUBIC;
}
/* Inter's "o" is 2 contours and 24 quadratic curves. No cubics: its outlines are TrueType. */

daegun_path_free(path);
daegun_path_points
const daegun_point *daegun_path_points(
    const daegun_path *path,
    size_t *out_count
);

All of a path's points in one array, in the order its verbs take them.

Returns a borrowed array of daegun_point and sets *out_count to its length. The points belong to the verbs that daegun_path_verbs lends, in order: a move or a line takes one, a quadratic curve its control and then its end, a cubic its two controls and then its end, and a close none. They are in the units the path was drawn in, y up.

The array is valid until the path is drawn into, cleared or freed. Don't free it. An empty path gives a count of 0, with a pointer that is not NULL and must not be read. NULL comes back, with the count left as it was, only if path or out_count is NULL.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'o', &gid) != DAEGUN_OK) return 1;
daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
if (daegun_font_outline(font, gid, NULL, &pen) != DAEGUN_OK) return 1;

size_t verb_count = 0, point_count = 0;
const uint8_t *verbs = daegun_path_verbs(path, &verb_count);
const daegun_point *points = daegun_path_points(path, &point_count);

/* How many points each verb takes. */
static const size_t takes[] = {
    [DAEGUN_VERB_MOVE] = 1, [DAEGUN_VERB_LINE] = 1, [DAEGUN_VERB_QUAD] = 2,
    [DAEGUN_VERB_CUBIC] = 3, [DAEGUN_VERB_CLOSE] = 0,
};
size_t at = 0;
for (size_t i = 0; i < verb_count; i++) {
    if (verbs[i] == DAEGUN_VERB_MOVE) {
        /* A contour starts at (points[at].x, points[at].y). */
    }
    at += takes[verbs[i]];
}
/* The verbs take every point between them: `at` ends at point_count, 50 for Inter's "o". */

daegun_path_free(path);
daegun_path_replay
daegun_status daegun_path_replay(
    const daegun_path *path,
    const double *transform,
    const daegun_pen *pen
);

Draws a path onto a pen again, through a transform if you give one.

The pen receives the path verb by verb, curves as curves: a move as move_to, a quadratic as quad_to, a cubic as curve_to. Every contour reaches the pen closed, as a fill reads it: one you started with a move and left open gets its close before the next contour starts, or at the end. Segments with no move before them, at the start of the path or after a close, are passed on as they are, with no move_to and no close added.

transform is six doubles, [a, b, c, d, dx, dy]. A point (x, y) arrives as (a * x + c * y + dx, b * x + d * y + dy), worked out in doubles. So [s, 0, 0, s, 0, 0] scales by s, and [1, 0, 0, 1, dx, dy] moves. NULL means no transform: the points arrive as they are.

The pen may draw into this same path, as the one from daegun_path_as_pen does. daegun replays a copy it takes when the call begins, so the path is replayed as it was at that moment and what is drawn lands after it.

There is nothing here to fail but a NULL path or pen. Nothing is checked on the way through, so a point that is not a finite number is passed on to the pen, not refused.

The call only reads the path, so threads may replay one path at the same time, each onto its own pen. That stops being true where the pen draws into this path: then the call changes it, and the path must be with one thread.

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

daegun_path *glyph = daegun_path_new();
daegun_path *placed = daegun_path_new();
daegun_pen into_glyph, into_placed;
if (daegun_path_as_pen(glyph, &into_glyph) != DAEGUN_OK) return 1;
if (daegun_path_as_pen(placed, &into_placed) != DAEGUN_OK) return 1;
if (daegun_font_outline(font, gid, NULL, &into_glyph) != DAEGUN_OK) return 1;

/* From font units with y up to a canvas of pixels with y down: scale to 16 px, flip y,
   and put the glyph's origin at (10, 20). */
double s = 16.0 / upem;
const double transform[6] = { s, 0.0, 0.0, -s, 10.0, 20.0 };
if (daegun_path_replay(glyph, transform, &into_placed) != DAEGUN_OK) return 1;

daegun_bounds box;
if (daegun_path_bounds(placed, &box) != DAEGUN_OK) return 1;
/* Inter's "I" now stands on the baseline at y 20, and its top is at y 8.36, about 11.6 pixels up. */

daegun_path_free(placed);
daegun_path_free(glyph);
daegun_path_stroke
daegun_status daegun_path_stroke(
    const daegun_path *path,
    const daegun_stroke_style *style,
    float tolerance,
    const daegun_pen *pen
);

Strokes a path: draws onto a pen the shape a line of a given width leaves along it, as contours to fill.

The pen receives closed contours made of move_to, line_to and close alone, curves and round joins flattened into short lines. An open contour of the path becomes one loop around it, with a cap at each end. A closed contour becomes two loops, one along each side. An open contour that is a single point, a daegun_path_move_to with nothing after it, becomes a dot with round or square caps and nothing with butt caps. Closed, such a point draws nothing. The loops may overlap themselves and one another, so fill them with the nonzero winding rule, or use daegun_path_stroke_simplified for a filler that has another rule.

style is required: there are no defaults behind a NULL. Its width is in the path's units, with its sign ignored, and a width of 0 answers DAEGUN_OK and draws nothing.

tolerance is how far the flattened lines may sit from the true curves, in the path's units: smaller is smoother and draws more points. A tolerance that is not above zero, or NaN, means 0.1. No curve or arc is cut into more than 256 lines, however small the tolerance.

DAEGUN_INVALID_ARGUMENT means the style is wrong: a cap or join that is none of its constants, or a width that is infinite or NaN. DAEGUN_OVERFLOW means a point is not a finite number: one of the path's own, or one the stroke would have to draw, as happens where a wide stroke or a long miter reaches past what a float holds. daegun_last_error says which. Each is found before anything is drawn, so the pen receives nothing from a call that fails.

Each point goes to the pen as it is worked out and nothing is held back, so a stroke of any size draws: there is no limit on the points.

The pen may draw into this same path, as daegun_path_replay allows: the path is stroked as it was when the call began. The call otherwise only reads the path, so threads may stroke one path at the same time.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'o', &gid) != DAEGUN_OK) return 1;
daegun_path *glyph = daegun_path_new();
daegun_path *outlined = daegun_path_new();
daegun_pen into_glyph, into_outlined;
if (daegun_path_as_pen(glyph, &into_glyph) != DAEGUN_OK) return 1;
if (daegun_path_as_pen(outlined, &into_outlined) != DAEGUN_OK) return 1;
if (daegun_font_outline(font, gid, NULL, &into_glyph) != DAEGUN_OK) return 1;

/* A line 40 font units wide along the glyph's outline, with round corners. */
daegun_stroke_style style = { 40.0f, DAEGUN_CAP_BUTT, DAEGUN_JOIN_ROUND, 0.0f };
if (daegun_path_stroke(glyph, &style, 0.1f, &into_outlined) != DAEGUN_OK) return 1;

daegun_bounds box, inked;
if (daegun_path_bounds(glyph, &box) != DAEGUN_OK) return 1;
if (daegun_path_bounds(outlined, &inked) != DAEGUN_OK) return 1;
/* Half the width lies outside the outline, so the ink is 20 units larger on every side. */

daegun_path_free(outlined);
daegun_path_free(glyph);
daegun_path_stroke_simplified
daegun_status daegun_path_stroke_simplified(
    const daegun_path *path,
    const daegun_stroke_style *style,
    float tolerance,
    const daegun_pen *pen
);

Strokes a path as daegun_path_stroke does, with the overlaps of the stroke merged into one boundary.

The loops of a stroke overlap: where the path crosses itself, where two of its contours run into each other, and at a corner too tight for its inner side to be trimmed. The nonzero winding rule hides that. The even-odd rule turns each overlap into a hole, and a rasterizer that sums coverage counts it twice. This call resolves the overlaps first, so the pen receives the boundary of the stroked shape alone, made of move_to, line_to and close. Where the loops meet too closely to call, they reach the pen unresolved, as daegun_path_stroke draws them.

The style, the tolerance and the pen are as daegun_path_stroke takes them, and it fails as that call does: DAEGUN_INVALID_ARGUMENT for a cap or join that is none of its constants or a width that is not finite, and DAEGUN_OVERFLOW for a point that is not finite.

It has one failure of its own. The whole stroke is held in memory to be resolved, so it has a size limit: a stroke of more than DAEGUN_MAX_FLATTEN_POINTS points answers DAEGUN_LIMIT_EXCEEDED. The pen receives nothing from a call that fails.

The pen may draw into this same path: the path is stroked as it was when the call began.

/* Two lines that cross, making a plus. */
daegun_path *path = daegun_path_new();
daegun_path_move_to(path, 0.0f, 50.0f);
daegun_path_line_to(path, 100.0f, 50.0f);
daegun_path_move_to(path, 50.0f, 0.0f);
daegun_path_line_to(path, 50.0f, 100.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 = { 10.0f, DAEGUN_CAP_BUTT, DAEGUN_JOIN_MITER, 4.0f };
if (daegun_path_stroke_simplified(path, &style, 0.1f, &pen) != DAEGUN_OK) return 1;

size_t verb_count = 0, point_count = 0;
const uint8_t *verbs = daegun_path_verbs(stroked, &verb_count);
daegun_path_points(stroked, &point_count);
size_t loops = 0;
for (size_t i = 0; i < verb_count; i++) loops += verbs[i] == DAEGUN_VERB_MOVE;
/* One loop of 12 corners: the outline of the plus. daegun_path_stroke would draw two
   rectangles of 4 corners each, overlapping in the middle. */

daegun_path_free(stroked);
daegun_path_free(path);
daegun_max_area_for
float daegun_max_area_for(float px, float units_per_em);

The max_area to hand daegun_path_flatten for a path in font units that will be drawn at a pixel size.

It returns 6 * units_per_em / px. A larger px gives a smaller area, so the curves of a glyph are cut into more lines the larger it is drawn. units_per_em is what daegun_font_units_per_em gives, as a float.

There is no status to check, and the call reads no font: the answer comes from the two numbers alone. A px of zero or below, or one so small that the area overflows, returns FLT_MAX, the coarsest there is: daegun_path_flatten then draws every curve as one line from its start to its end. A px that is NaN returns NaN, which daegun_path_flatten reads the other way, as the finest.

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

float max_area = daegun_max_area_for(32.0f, (float)upem);
/* Inter has 2048 units to the em, so at 32 px the area is 6 * 2048 / 32 = 384. */
daegun_path_flatten
daegun_status daegun_path_flatten(
    const daegun_path *path,
    float max_area,
    daegun_contours **out
);

Turns a path into closed polygons, cutting each curve into straight lines.

For a rasterizer that walks straight edges. On DAEGUN_OK, *out is a new daegun_contours, which you free with daegun_contours_free. Each contour is one closed polygon in the path's own units. An open contour of the path is closed, a contour left with fewer than three points is dropped, and no contour repeats its first point at its end. An empty path gives contours with a count of 0.

max_area says how flat is flat enough. A curve is halved, and each half again, until twice the area of the triangle between a piece's two ends and the point halfway along it is no more than max_area, in the path's units squared. daegun_max_area_for gives the value for a path in font units drawn at a pixel size. A max_area that is not finite and above zero is read as 0, the finest: a curve is then halved for as long as a piece of it still bends, down to 4,096 lines, the most any curve becomes.

DAEGUN_INVALID_ARGUMENT means the path holds a point that is not finite or that lies past FLT_MAX / 16. DAEGUN_LIMIT_EXCEEDED means the polygons would keep more than DAEGUN_MAX_FLATTEN_POINTS points, or that flattening read more than twice that many. Either way *out is NULL.

The path is only read, so threads may flatten one path at the same time. Contours freed on a thread are reused by that thread's next flatten, handle and point lists both, so flattening glyph after glyph and freeing each allocates only where a glyph needs more room than the one before it left. The exception is contours holding more than 64 KiB, which are let go when freed.

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

/* The glyph's outline in font units, kept as a path. */
daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
if (daegun_font_outline(font, gid, NULL, &pen) != DAEGUN_OK) return 1;

/* Flat enough to draw at 32 px. */
daegun_contours *contours = NULL;
float max_area = daegun_max_area_for(32.0f, (float)upem);
if (daegun_path_flatten(path, max_area, &contours) != DAEGUN_OK) return 1;

size_t count = 0;
if (daegun_contours_count(contours, &count) != DAEGUN_OK) return 1;
for (size_t i = 0; i < count; i++) {
    size_t n = 0;
    const daegun_point *points = daegun_contours_points(contours, i, &n);
    /* A closed polygon of n points in font units: points[n - 1] joins points[0]. */
}
/* Inter's W is one contour, and for this size it flattens to 34 points. */

daegun_contours_free(contours);
daegun_path_free(path);
daegun_contours_new
daegun_status daegun_contours_new(
    const daegun_point *points,
    const size_t *lengths,
    size_t count,
    daegun_contours **out
);

Makes contours from points of your own.

For polygons that did not come from daegun_path_flatten and that you want to pass to daegun_contours_resolve_overlaps. points holds every contour's points end to end, and lengths holds count lengths: contour i is the next lengths[i] points. The points are copied, so your arrays need not outlive the call. On DAEGUN_OK, *out is a new daegun_contours to free with daegun_contours_free.

Nothing is checked or tidied. A contour of fewer than three points, or one that repeats its first point at its end, is kept as you gave it, where daegun_path_flatten would have dropped or trimmed it.

lengths may be NULL where count is 0, which makes a handle with no contours, and points may be NULL where the lengths add up to 0. DAEGUN_INVALID_ARGUMENT means the lengths add up to more than a size_t holds. On any failure *out is NULL.

/* Two squares 100 units wide that overlap, each counterclockwise. */
const daegun_point points[] = {
    { 0.0f, 0.0f }, { 100.0f, 0.0f }, { 100.0f, 100.0f }, { 0.0f, 100.0f },
    { 50.0f, 50.0f }, { 150.0f, 50.0f }, { 150.0f, 150.0f }, { 50.0f, 150.0f },
};
const size_t lengths[] = { 4, 4 };

daegun_contours *squares = NULL;
if (daegun_contours_new(points, lengths, 2, &squares) != DAEGUN_OK) return 1;

daegun_contours *merged = NULL;
if (daegun_contours_resolve_overlaps(squares, &merged) != DAEGUN_OK) return 1;
size_t n = 0;
const daegun_point *outline = daegun_contours_points(merged, 0, &n);
/* One polygon of 8 points: the two squares as a single shape. */

daegun_contours_free(merged);
daegun_contours_free(squares);
daegun_contours_count
daegun_status daegun_contours_count(
    const daegun_contours *contours,
    size_t *out
);

How many contours a set of contours holds.

Written to *out. daegun_contours_points takes an index below it. The count is 0 for a path that drew nothing.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'o', &gid) != DAEGUN_OK) return 1;
daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
if (daegun_font_outline(font, gid, NULL, &pen) != DAEGUN_OK) return 1;

daegun_contours *contours = NULL;
if (daegun_path_flatten(path, 384.0f, &contours) != DAEGUN_OK) return 1;
size_t count = 0;
if (daegun_contours_count(contours, &count) != DAEGUN_OK) return 1;
/* count is 2: the outside of the o, and the hole in it. */

daegun_contours_free(contours);
daegun_path_free(path);
daegun_contours_points
const daegun_point *daegun_contours_points(
    const daegun_contours *contours,
    size_t index,
    size_t *out_count
);

One contour's points.

Returns a borrowed array of daegun_point and sets *out_count to its length. The polygon is closed without saying so: the last point joins the first. Contours from daegun_path_flatten hold at least three points and never repeat the first at the end.

The array is valid until the contours are freed with daegun_contours_free. Don't free it. NULL comes back, with the count left as it was, for an index past the last contour, or if contours or out_count is NULL.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'o', &gid) != DAEGUN_OK) return 1;
daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
if (daegun_font_outline(font, gid, NULL, &pen) != DAEGUN_OK) return 1;
daegun_contours *contours = NULL;
if (daegun_path_flatten(path, 384.0f, &contours) != DAEGUN_OK) return 1;

double twice_area[2] = { 0.0, 0.0 };
for (size_t i = 0; i < 2; i++) {
    size_t n = 0;
    const daegun_point *points = daegun_contours_points(contours, i, &n);
    if (!points) return 1;
    for (size_t j = 0; j < n; j++) {
        daegun_point a = points[j], b = points[(j + 1) % n]; /* the last edge runs back to the first point */
        twice_area[i] += (double)a.x * b.y - (double)b.x * a.y;
    }
}
/* With y up, a clockwise polygon has a negative area. Inter draws the outside of its o
   clockwise and the hole the other way. */

daegun_contours_free(contours);
daegun_path_free(path);
daegun_contours_free
void daegun_contours_free(daegun_contours *contours);

Frees contours.

That is contours from daegun_path_flatten, daegun_contours_new or daegun_contours_resolve_overlaps. NULL is fine and does nothing, so a cleanup path may free without checking. Every array daegun_contours_points lent from them is invalid afterward.

The thread keeps the freed handle for the next contours it makes, and daegun_path_flatten fills its point lists again, unless they hold more than 64 KiB. daegun_thread_release lets go of what a thread keeps.

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, 100.0f);
daegun_path_close(path);

daegun_contours *contours = NULL;
daegun_status status = daegun_path_flatten(path, 1.0f, &contours);
if (status == DAEGUN_OK) {
    /* read the contours */
}
/* Safe either way: a call that fails leaves `contours` NULL. */
daegun_contours_free(contours);
daegun_path_free(path);
  • May be NULL: contours.
daegun_contours_resolve_overlaps
daegun_status daegun_contours_resolve_overlaps(
    const daegun_contours *contours,
    daegun_contours **out
);

Merges contours that overlap into the boundary of the area they cover together.

A rasterizer that sums the coverage of every edge counts an area twice where two contours overlap, where a nonzero fill paints it once. This call reads the contours as a nonzero fill does and gives back new ones that cover the same area with nothing covered twice. The filled side is on the left of every edge: an outer boundary runs counterclockwise and a hole clockwise, whichever way the input was wound. *out is a new daegun_contours to free with daegun_contours_free, and the input is left as it is.

DAEGUN_ABSENT is an answer, not a failure: keep the contours you have. *out is then NULL. It comes when no point is covered twice, which is so for contours that lie apart, for an outline with its holes wound the other way, and for a lone clockwise contour, which is not rewound for you. It also comes when the contours meet in a way too close to call, as can happen where a corner of one lies exactly on an edge of another, when untangling them would take more work than their number of edges allows, as no font needs, and when a point is not finite.

Three things need it. An embolden from daegun_font_prepared_outline does, as it draws a stroke over the edge of the outline. So does a stroke wide enough to run into itself. And so does a glyph whose own outline crosses itself, as Inter's W does.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'W', &gid) != DAEGUN_OK) return 1;
daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
if (daegun_font_outline(font, gid, NULL, &pen) != DAEGUN_OK) return 1;
daegun_contours *contours = NULL;
if (daegun_path_flatten(path, 384.0f, &contours) != DAEGUN_OK) return 1;

daegun_contours *merged = NULL;
daegun_status status = daegun_contours_resolve_overlaps(contours, &merged);
if (status != DAEGUN_OK && status != DAEGUN_ABSENT) return 1;
/* DAEGUN_ABSENT: nothing to merge, so rasterize the contours as they are. */
const daegun_contours *fill = status == DAEGUN_OK ? merged : contours;

size_t n = 0;
const daegun_point *points = daegun_contours_points(fill, 0, &n);
/* Inter's W is one contour that crosses itself where its strokes meet, so here `merged` is
   its boundary: 31 points, down from 34, and counterclockwise now. */

daegun_contours_free(merged);
daegun_contours_free(contours);
daegun_path_free(path);
daegun_font_quads
daegun_status daegun_font_quads(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    daegun_quads **out
);

A glyph's outline as quadratic curves in font units, for a renderer that evaluates curves in a GPU shader.

Every piece of the outline becomes a daegun_quad. A quadratic, as TrueType outlines are made of, passes through as it is. A straight line becomes a curve with its control at the midpoint. A cubic, as CFF and CFF2 outlines are made of, is split until each piece lies within 1/4096 of an em of it, into 256 pieces at most. Every contour is closed. The curves are in font units, y up, at location, NULL being the default instance.

The curves come wound clockwise, as daegun_quads_normalize_winding leaves them. For a glyph the font draws the other way, which is the convention of CFF and CFF2 outlines, that means each curve is turned around where it sits in the list, so curve i ends where curve i - 1 starts.

On DAEGUN_OK, *out is a new daegun_quads to free with daegun_quads_free. DAEGUN_NO_OUTLINE means the glyph draws nothing, such as a space, gid is past the font's last glyph, or the font has no outlines at all, as one that holds only bitmaps. DAEGUN_OVERFLOW means a point is not finite or lies past FLT_MAX / 16. A glyph that does not decode answers the decoder's status, DAEGUN_MALFORMED for broken glyph data. On any failure *out is NULL.

Quads freed on a thread are reused by that thread's next, list and all, so asking for glyph after glyph and freeing each allocates only when a glyph has more curves than any before it. The exception is a list holding more than 64 KiB, which is let go when freed.

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

daegun_quads *quads = NULL;
daegun_status status = daegun_font_quads(font, gid, NULL, &quads);
if (status == DAEGUN_NO_OUTLINE) {
    /* A space, or another glyph with nothing to draw: skip it. */
} else if (status != DAEGUN_OK) {
    return 1;
}

size_t n = 0;
const daegun_quad *curves = daegun_quads_data(quads, &n);
for (size_t i = 0; i < n; i++) {
    /* Hand curves[i].start, .control and .end to the shader, in font units. */
}
/* Inter's W: 32 curves, its 16 quadratics and a curve for each of its 16 straight sides. */

daegun_quads_free(quads);
daegun_path_quads
daegun_status daegun_path_quads(
    const daegun_path *path,
    float tolerance,
    daegun_quads **out
);

A path as quadratic curves, in its own units.

The same conversion as daegun_font_quads, for a path you built or kept. A line becomes a curve with its control at the midpoint, a quadratic passes through, and a cubic is split until each piece lies within tolerance of it, in the path's units, or into 256 pieces. An open contour is closed with a line back to its start.

The curves come in the order the path was drawn and are not rewound. Call daegun_quads_normalize_winding on the result if you need them clockwise.

DAEGUN_INVALID_ARGUMENT means tolerance is not finite and above zero. DAEGUN_NO_OUTLINE means the path draws nothing: it is empty, or holds moves alone. DAEGUN_OVERFLOW means a point is not finite or lies past FLT_MAX / 16. On any failure *out is NULL. On DAEGUN_OK it is a new daegun_quads to free with daegun_quads_free.

/* An arch: one cubic, left open. */
daegun_path *path = daegun_path_new();
daegun_path_move_to(path, 0.0f, 0.0f);
daegun_path_curve_to(path, 0.0f, 100.0f, 100.0f, 100.0f, 100.0f, 0.0f);

daegun_quads *quads = NULL;
if (daegun_path_quads(path, 1.0f, &quads) != DAEGUN_OK) return 1;
size_t n = 0;
const daegun_quad *curves = daegun_quads_data(quads, &n);
/* 5 curves: the cubic takes 4 quadratics to stay within 1 unit, and the last is the line
   that closes the arch, from (100, 0) back to (0, 0). */

daegun_quads_free(quads);
daegun_path_free(path);
daegun_quads_normalize_winding
daegun_status daegun_quads_normalize_winding(daegun_quads *quads);

Rewinds curves in place so that they run clockwise.

It adds up the area the curves enclose, signed. Where the total is positive, which is counterclockwise with y up, every curve swaps its start and its end. Otherwise nothing changes. Clockwise is the convention of TrueType outlines and what daegun_font_quads already gives, so this is for curves from daegun_path_quads.

A rewound curve keeps its place in the list. The list itself is not reversed, so after a rewind curve i ends where curve i - 1 starts. The call works on any list of curves: they need not join end to start.

It takes the handle as non-const. It needs the quads to itself until it returns, and an array that daegun_quads_data lent before it is no longer valid: ask for the data again.

/* A square drawn counterclockwise. */
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, 100.0f, 100.0f);
daegun_path_line_to(path, 0.0f, 100.0f);
daegun_path_close(path);

daegun_quads *quads = NULL;
if (daegun_path_quads(path, 0.25f, &quads) != DAEGUN_OK) return 1;
if (daegun_quads_normalize_winding(quads) != DAEGUN_OK) return 1;

/* Read the curves after rewinding, not before. */
size_t n = 0;
const daegun_quad *curves = daegun_quads_data(quads, &n);
/* Four curves, clockwise now. The first ran from (0, 0) to (100, 0) and runs back, and the
   second ends where the first starts. */

daegun_quads_free(quads);
daegun_path_free(path);
daegun_quads_data
const daegun_quad *daegun_quads_data(
    const daegun_quads *quads,
    size_t *out_count
);

The curves a list of quads holds.

Returns a borrowed array of daegun_quad and sets *out_count to its length. The array is valid until the quads are freed with daegun_quads_free or rewound with daegun_quads_normalize_winding. Don't free it. NULL comes back, with the count left as it was, only if quads or out_count is NULL.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'o', &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);
float top = curves[0].start.y;
for (size_t i = 0; i < n; i++) {
    if (curves[i].end.y > top) top = curves[i].end.y;
}
/* Inter's o is 24 curves, and the highest point any of them ends on is 1132 units up. */

daegun_quads_free(quads);
daegun_quads_free
void daegun_quads_free(daegun_quads *quads);

Frees a list of quads.

That is quads from daegun_font_quads or daegun_path_quads. NULL is fine and does nothing. The array daegun_quads_data lent from them is invalid afterward.

The thread keeps the freed handle and the room its list holds for the next quads it makes, unless that room is more than 64 KiB.

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

daegun_quads *quads = NULL;
daegun_status status = daegun_font_quads(font, gid, NULL, &quads);
if (status == DAEGUN_OK) {
    /* read the curves */
}
/* Safe either way: a call that fails leaves `quads` NULL. */
daegun_quads_free(quads);
  • May be NULL: quads.
daegun_hint_mode_may_autohint
daegun_status daegun_hint_mode_may_autohint(int32_t mode, bool *out);

Whether the autohinter may take a glyph under a hint mode.

Writes true for DAEGUN_HINT_AUTO and DAEGUN_HINT_AUTO_FORCE, and false for DAEGUN_HINT_NONE and DAEGUN_HINT_FONT. Two of the four modes let it, so the question is not a comparison against one constant.

A code that is none of the DAEGUN_HINT_ values answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

bool may = false;
if (daegun_hint_mode_may_autohint(DAEGUN_HINT_AUTO, &may) != DAEGUN_OK) return 1;
if (daegun_hint_mode_may_autohint(DAEGUN_HINT_FONT, &may) != DAEGUN_OK) return 1;
/* true, then false. */
daegun_font_hinted_outline
daegun_status daegun_font_hinted_outline(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    float px,
    int32_t mode,
    daegun_hinted_outline **out
);

A glyph hinted at a pixel size, as points in pixels.

The glyph's outline at location is scaled to px pixels to the em and fitted to the pixel grid by the hinter that mode names, a DAEGUN_HINT_ code. On DAEGUN_OK, *out is a new daegun_hinted_outline to free with daegun_hinted_outline_free. Its points are in pixels from the glyph's origin, y up. It carries no advance: daegun_font_prepared_outline gives that, and draws the hinted outline too.

DAEGUN_ABSENT means no hinter takes the glyph, and *out is NULL. Draw it unhinted then. It comes for DAEGUN_HINT_NONE. It comes for a px outside what the hinters take: they hold the size in 64ths of a pixel, from half a pixel to a little under 65,535.5. It comes for a glyph too large to hint at that size, for one that draws nothing, such as a space, and for one a VARC table draws. It comes for a glyph the hinter would leave where scaling puts it, as a font's own hints leave a simple TrueType glyph that has no instructions. And it comes for a glyph that does not decode, or a gid past the font's last glyph: this call never answers the decoder's status.

DAEGUN_INVALID_ARGUMENT means px is not finite and above zero, or mode is none of the DAEGUN_HINT_ codes. *out is NULL then too.

A thread keeps the hinting state of the sizes it last used, so hinting many glyphs of one font at one size runs the font program and the CVT program, or fits the autohinter's zones, once and not for every glyph.

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

daegun_hinted_outline *hinted = NULL;
daegun_status status = daegun_font_hinted_outline(font, gid, NULL, 16.0f, DAEGUN_HINT_AUTO, &hinted);
if (status == DAEGUN_ABSENT) {
    /* No hinter takes this glyph: draw it unhinted. */
} else if (status != DAEGUN_OK) {
    return 1;
}

size_t n = 0;
const daegun_point *points = daegun_hinted_outline_points(hinted, &n);
float top = 0.0f;
for (size_t i = 0; i < n; i++) {
    if (points[i].y > top) top = points[i].y;
}
/* Unhinted, Inter's H is 11.64 px tall at 16 px. Hinted, its top sits on a pixel edge:
   top is 12. */

daegun_hinted_outline_free(hinted);
daegun_hinted_outline_points
const daegun_point *daegun_hinted_outline_points(
    const daegun_hinted_outline *outline,
    size_t *out_count
);

The hinted outline's points, in pixels.

Returns a borrowed array of daegun_point, y up, measured from the glyph's origin, and sets *out_count to its length. The array holds every contour's points one after another, on-curve points and control points alike. daegun_hinted_outline_kinds says which each one is, at the same index, and daegun_hinted_outline_contours where each contour ends.

Hinters work in 64ths of a pixel, so every coordinate is a whole number of 64ths.

The array is valid until the outline is freed with daegun_hinted_outline_free. NULL comes back, with the count left as it was, only if outline or out_count is NULL.

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;
const daegun_point *points = daegun_hinted_outline_points(hinted, &n);
float left = points[0].x, right = points[0].x;
for (size_t i = 1; i < n; i++) {
    if (points[i].x < left) left = points[i].x;
    if (points[i].x > right) right = points[i].x;
}
/* The H spans x from 1.40625 to 10.484375 px: 90 and 671 64ths. The autohinter fits y and
   leaves x as scaled. */

daegun_hinted_outline_free(hinted);
daegun_hinted_outline_kinds
const uint8_t *daegun_hinted_outline_kinds(
    const daegun_hinted_outline *outline,
    size_t *out_count
);

What each point of the hinted outline is: on the curve, or a control point.

Returns a borrowed array of one byte per point, in step with daegun_hinted_outline_points, and sets *out_count to its length. Each byte is DAEGUN_POINT_ON_CURVE, DAEGUN_POINT_QUADRATIC or DAEGUN_POINT_CUBIC.

A glyph with TrueType outlines has on-curve points and quadratic controls. A CFF or CFF2 glyph has on-curve points and cubic controls, two between one on-curve point and the next, and that holds under the autohinter too.

The array is valid until the outline is freed with daegun_hinted_outline_free. NULL comes back, with the count left as it was, only if outline or out_count is NULL.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'o', &gid) != DAEGUN_OK) return 1;
daegun_hinted_outline *hinted = NULL;
if (daegun_font_hinted_outline(font, gid, NULL, 16.0f, DAEGUN_HINT_FONT, &hinted) != DAEGUN_OK) return 1;

size_t n = 0;
const uint8_t *kinds = daegun_hinted_outline_kinds(hinted, &n);
size_t on = 0, cubic = 0;
for (size_t i = 0; i < n; i++) {
    if (kinds[i] == DAEGUN_POINT_ON_CURVE) on++;
    if (kinds[i] == DAEGUN_POINT_CUBIC) cubic++;
}
/* Source Serif is a CFF2 font. Its o is 8 cubic curves: 8 points on the curve and 16 controls,
   each on-curve point followed by two controls. */

daegun_hinted_outline_free(hinted);
daegun_hinted_outline_contours
const size_t *daegun_hinted_outline_contours(
    const daegun_hinted_outline *outline,
    size_t *out_count
);

Where each contour of the hinted outline ends.

Returns a borrowed array of one size_t per contour and sets *out_count to its length. Each entry is the index of that contour's last point in the arrays of daegun_hinted_outline_points and daegun_hinted_outline_kinds. The first contour starts at index 0, and each later one starts right after the end of the one before it. Every contour is closed: its last point joins its first.

The array is valid until the outline is freed with daegun_hinted_outline_free. NULL comes back, with the count left as it was, only if outline or out_count is NULL.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'o', &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, count = 0;
const daegun_point *points = daegun_hinted_outline_points(hinted, &n);
const size_t *ends = daegun_hinted_outline_contours(hinted, &count);
size_t first = 0;
for (size_t c = 0; c < count; c++) {
    /* Contour c is points[first] to points[ends[c]], both included. */
    first = ends[c] + 1;
}
/* Inter's o has two contours of 24 points each: they end at points 23 and 47. */

daegun_hinted_outline_free(hinted);
daegun_hinted_outline_draw
daegun_status daegun_hinted_outline_draw(
    const daegun_hinted_outline *outline,
    const daegun_pen *pen
);

Draws the hinted outline onto a pen, in pixels.

The pen gets each contour as a move, then lines and curves, then a close. The curves of a glyph with TrueType outlines reach quad_to, and those of a CFF or CFF2 glyph reach curve_to. Coordinates are pixels from the glyph's origin, y up.

The pen is a daegun_pen of your own, or one from daegun_path_as_pen, which keeps the drawing as a daegun_path. A NULL callback skips its event. The callbacks run on your thread, before the call returns.

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;

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

daegun_bounds box;
if (daegun_path_bounds(path, &box) != DAEGUN_OK) return 1;
/* The path holds the hinted H in pixels. Its box runs from the baseline to 12 px up. */

daegun_path_free(path);
daegun_hinted_outline_free(hinted);
daegun_hinted_outline_free
void daegun_hinted_outline_free(daegun_hinted_outline *outline);

Frees a hinted outline.

NULL is fine and does nothing, so a cleanup path may free without checking. The three arrays the outline lent are invalid afterward. The thread keeps the freed handle for the next hinted outline it makes.

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

daegun_hinted_outline *hinted = NULL;
daegun_status status = daegun_font_hinted_outline(font, gid, NULL, 16.0f, DAEGUN_HINT_AUTO, &hinted);
if (status == DAEGUN_OK) {
    /* read or draw the outline */
}
/* Safe either way: any other status leaves `hinted` NULL. */
daegun_hinted_outline_free(hinted);
  • May be NULL: outline.
daegun_font_cff_hints
daegun_status daegun_font_cff_hints(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    daegun_cff_hints **out
);

A CFF or CFF2 glyph's stem hints and hint masks, as the font states them.

They are read out of the glyph's charstring, in font units. A CFF2 font's are blended at location, as its outline is, so a stem is as wide as the instance draws it. NULL is the default instance.

On DAEGUN_OK, *out is a new daegun_cff_hints to free with daegun_cff_hints_free. A CFF glyph with no hints at all, such as a space, answers DAEGUN_OK too, with no stems and no masks.

DAEGUN_ABSENT means the glyph is not a CFF or CFF2 glyph, which is so for every glyph of a font with TrueType outlines, or that its charstring does not decode, which is also what a gid past the font's last glyph gets. *out is then NULL.

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

daegun_cff_hints *hints = NULL;
daegun_status status = daegun_font_cff_hints(font, gid, NULL, &hints);
if (status == DAEGUN_ABSENT) {
    /* Not a CFF glyph: a font with TrueType outlines has no such hints. */
} else if (status != DAEGUN_OK) {
    return 1;
}

size_t n = 0;
const daegun_cff_stem *stems = daegun_cff_hints_stems(hints, &n);
for (size_t i = 0; i < n; i++) {
    /* stems[i].min to stems[i].max: x positions if stems[i].vertical, else y positions. */
}
/* STIX Two Math's H: 5 stems, three horizontal and then two vertical. */

daegun_cff_hints_free(hints);
daegun_cff_hints_stems
const daegun_cff_stem *daegun_cff_hints_stems(
    const daegun_cff_hints *hints,
    size_t *out_count
);

The glyph's stem hints, in the order its charstring declares them.

Returns a borrowed array of daegun_cff_stem and sets *out_count to its length, which is 0 for a glyph with no stems. A mask's bits follow the order of this array.

The array is valid until the hints are freed with daegun_cff_hints_free. Don't free it. NULL comes back, with the count left as it was, only if hints or out_count is NULL.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'A', &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);
size_t edges = 0;
for (size_t i = 0; i < n; i++) {
    if (stems[i].max < stems[i].min) edges++; /* an edge hint: one edge, no stem */
}
/* STIX Two Math's A has 6 stems, and one is an edge hint for the top of the letter, at
   y 662: a horizontal stem from 662 back to 642. */

daegun_cff_hints_free(hints);
daegun_cff_hints_mask_count
daegun_status daegun_cff_hints_mask_count(
    const daegun_cff_hints *hints,
    size_t *out
);

How many hint masks the glyph's charstring sets.

Written to *out. It is 0 for a glyph whose charstring sets none. daegun_cff_hints_mask_at takes an index below it.

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 count = 0;
if (daegun_cff_hints_mask_count(hints, &count) != DAEGUN_OK) return 1;
/* STIX Two Math's E sets 5 masks. Its H sets none. */

daegun_cff_hints_free(hints);
daegun_cff_hints_mask_at
daegun_status daegun_cff_hints_mask_at(
    const daegun_cff_hints *hints,
    size_t index,
    daegun_cff_mask *out
);

One hint mask of the glyph.

Fills *out with a daegun_cff_mask. Masks are indexed in the order the charstring sets them, which is the order they take effect in. The mask's bits point into the hints and stay valid until daegun_cff_hints_free.

An index past the last mask answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

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 count = 0;
if (daegun_cff_hints_mask_count(hints, &count) != DAEGUN_OK) return 1;
for (size_t i = 0; i < count; i++) {
    daegun_cff_mask mask;
    if (daegun_cff_hints_mask_at(hints, i, &mask) != DAEGUN_OK) return 1;
    /* From point mask.point on, the stems set in mask.bits are in force. */
}
/* STIX Two Math's E switches masks at points 0, 20, 24, 26 and 34. */

daegun_cff_hints_free(hints);
daegun_cff_hints_free
void daegun_cff_hints_free(daegun_cff_hints *hints);

Frees CFF hints.

NULL is fine and does nothing, so a cleanup path may free without checking. The stems daegun_cff_hints_stems lent and the bits of every mask read from the hints are invalid afterward.

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

daegun_cff_hints *hints = NULL;
daegun_status status = daegun_font_cff_hints(font, gid, NULL, &hints);
if (status == DAEGUN_OK) {
    /* read the stems and the masks */
}
/* Safe either way: any other status leaves `hints` NULL. */
daegun_cff_hints_free(hints);
  • May be NULL: hints.
daegun_outline_options_default
daegun_status daegun_outline_options_default(
    daegun_outline_options *out,
    size_t size
);

Fills outline options with their defaults.

Pass the struct and sizeof it. The call zeroes that many bytes, which is every default, and sets size. Then set the fields you want.

A size below what daegun 2.0 defined answers DAEGUN_INVALID_ARGUMENT, and one larger than this library knows answers DAEGUN_UNSUPPORTED, which means your header is newer than the library. Neither writes anything.

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;
/* Everything is off. Ask for a lean to the right. */
opts.has_oblique = true;
opts.oblique = 0.2f;

daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
if (daegun_font_prepared_outline(font, gid, NULL, 32.0f, &opts, &pen, NULL) != DAEGUN_OK) return 1;
daegun_bounds box;
if (daegun_path_bounds(path, &box) != DAEGUN_OK) return 1;
/* Upright, the H reaches 20.96875 px to the right. Leaning, its top right corner sits 0.2
   times its height further on, at 25.625 px. */

daegun_path_free(path);
daegun_font_prepared_outline
daegun_status daegun_font_prepared_outline(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    float px,
    const daegun_outline_options *opts,
    const daegun_pen *pen,
    daegun_prepared_glyph *out
);

Draws a glyph's outline onto your pen in pixels, ready to rasterize: scaled to a size, and hinted, leaned, transformed, stroked or emboldened as the options say.

The call a rasterizer of your own is built on. You hand it a daegun_pen, five callbacks and a pointer of yours, and it calls them with the glyph's contours: a move, then lines and curves, then a close for each. Coordinates are in pixels at px pixels to the em, y up, measured from the glyph's origin on the baseline.

location picks the instance of a variable font, NULL being the default one. opts is a daegun_outline_options, and NULL means the defaults: the outline as the font has it, scaled and nothing else. The options apply in a fixed order: hinting at px, then the oblique and the transform, then a stroke or an embolden. A glyph the chosen hinter does not take is drawn unhinted, which is not a failure.

out receives a daegun_prepared_glyph: the advances in pixels, and whether a hinter ran. It may be NULL if you have no use for it. A glyph that draws nothing, such as a space, answers DAEGUN_OK, makes no pen call and still reports its advance.

Which callbacks are called depends on the glyph. TrueType curves reach quad_to and CFF curves reach curve_to. A stroke reaches the pen as lines alone, and so do the contours an embolden adds around the outline.

DAEGUN_INVALID_ARGUMENT means one of these: px is not finite and above zero; a transform, a stroke width, an embolden or an oblique that the options turn on is not finite; the hinting code is none of its constants, or, with has_stroke set, the cap or the join is; or their size is below what daegun 2.0 defined. DAEGUN_UNSUPPORTED means the options are larger than this library knows. DAEGUN_OVERFLOW means an advance, a width or a point would pass FLT_MAX once scaled. Anything else is the status of the decoder: DAEGUN_MALFORMED for glyph data that does not decode, and DAEGUN_NO_OUTLINE for a gid past the font's last glyph or a font with no outlines at all, as one that holds only bitmaps. In every one of these cases nothing is drawn, and *out is left as it was.

The callbacks run on the calling thread before the call returns, and no lock is held while one runs. Threads may prepare glyphs of one font at the same time.

/* A pen of your own. These callbacks only measure what they are handed, where a rasterizer's
   would add edges to its scanlines. */
typedef struct { int contours; float x_max, y_max; } extent;

static void reach(extent *e, float x, float y)
{
    if (x > e->x_max) e->x_max = x;
    if (y > e->y_max) e->y_max = y;
}
static void on_move(void *user, float x, float y) { reach(user, x, y); }
static void on_line(void *user, float x, float y) { reach(user, x, y); }
static void on_quad(void *user, float cx, float cy, float x, float y)
{
    reach(user, cx, cy);
    reach(user, x, y);
}
static void on_cubic(void *user, float c1x, float c1y, float c2x, float c2y, float x, float y)
{
    reach(user, c1x, c1y);
    reach(user, c2x, c2y);
    reach(user, x, y);
}
static void on_close(void *user) { ((extent *)user)->contours++; }

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

extent seen = { 0, 0.0f, 0.0f };
daegun_pen pen = { on_move, on_line, on_quad, on_cubic, on_close, &seen };
daegun_prepared_glyph glyph;
if (daegun_font_prepared_outline(font, gid, NULL, 32.0f, NULL, &pen, &glyph) != DAEGUN_OK) return 1;

/* The callbacks were handed Inter's W at 32 px, in pixels: one contour, whose points reach
   30.72 px right of the origin and 23.28 px above the baseline. The next glyph starts
   glyph.advance_width further on, 31.53 px. */

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_font_bitmap
daegun_status daegun_font_bitmap(
    const daegun_font *font,
    uint32_t gid,
    uint16_t ppem,
    daegun_bitmap **out
);

A glyph's picture from the font's bitmap strikes, taken from the strike nearest the size asked for.

The glyph is looked for in the sbix table, then CBDT, then EBDT, then bdat, and the first that has it answers. The picture comes back through out as a daegun_bitmap. Read it with daegun_bitmap_info_of and free it with daegun_bitmap_free.

ppem is the size you mean to draw at, in pixels per em. A font holds a strike for each of a few sizes, and the call takes the smallest strike at or above ppem, or the largest below it where none is that large. A strike that lacks the glyph hands over to the next nearest, so a glyph with a picture in any strike of the table is found. The size of the strike that answered is the ppem of the daegun_bitmap_info: scale the picture by your size over it. Asking for 65535 takes the largest strike that holds the glyph.

DAEGUN_ABSENT means no strike holds a picture of the glyph, and *out is then NULL. That is the answer for a font with none of these tables, as an outline font has none, for a glyph id past the font's glyphs, and for a glyph the strikes leave out. A picture daegun can't hand over counts as none too, such as one that sbix stores as anything but a PNG, or a strike of raw 32-bit color pixels. The next nearest strike is tried in its place.

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

daegun_bitmap *bitmap = NULL;
daegun_status status = daegun_font_bitmap(font, gid, 32, &bitmap);
if (status == DAEGUN_OK) {
    daegun_bitmap_info info;
    if (daegun_bitmap_info_of(bitmap, &info) != DAEGUN_OK) return 1;
    /* The picture comes from a strike at 109 pixels per em, not the 32 asked for. To show it at
       32 px, scale it by 32 / 109. */
    double scale = 32.0 / info.ppem;
    /* Its top left corner on a surface whose y runs down, with the glyph's origin at (ox, oy). */
    double ox = 10.0, oy = 40.0;
    double x = ox + info.left * scale, y = oy - info.top * scale;
} else if (status == DAEGUN_ABSENT) {
    /* No picture of this glyph: draw its outline. */
} else {
    return 1;
}
daegun_bitmap_free(bitmap);
daegun_bitmap_free
void daegun_bitmap_free(daegun_bitmap *bitmap);

Frees a bitmap.

NULL is fine and does nothing, so a cleanup path may free without checking. The data that daegun_bitmap_info_of lent from the bitmap is invalid afterward.

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

daegun_bitmap *bitmap = NULL;
daegun_status status = daegun_font_bitmap(font, gid, 64, &bitmap);
if (status == DAEGUN_OK) {
    /* read the bitmap */
}
/* Safe either way: a call that finds no bitmap leaves `bitmap` NULL. */
daegun_bitmap_free(bitmap);
  • May be NULL: bitmap.
daegun_bitmap_info_of
daegun_status daegun_bitmap_info_of(
    const daegun_bitmap *bitmap,
    daegun_bitmap_info *out
);

Reads a bitmap: its format, its strike's size, where it sits and its bytes.

Fills *out with a daegun_bitmap_info. Nothing is copied: its data points into the bitmap and is valid until daegun_bitmap_free. The only way the call fails is a NULL pointer.

/* Glyph 19 of this sample font is one of its sbix pictures. */
daegun_bitmap *bitmap = NULL;
if (daegun_font_bitmap(font, 19, 64, &bitmap) != DAEGUN_OK) return 1;

daegun_bitmap_info info;
if (daegun_bitmap_info_of(bitmap, &info) != DAEGUN_OK) return 1;
const uint8_t *png = info.data; /* borrowed: good until daegun_bitmap_free */
size_t png_len = info.data_len;
/* A PNG file of 2516 bytes from the strike at 109 pixels per em. Its top left corner sits 4 pixels
   right of the glyph's origin and 101 above it. */

daegun_bitmap_free(bitmap);
daegun_font_colr_layers
daegun_status daegun_font_colr_layers(
    const daegun_font *font,
    uint32_t gid,
    uint16_t palette,
    daegun_colr_layer *out,
    size_t out_len,
    size_t *out_count
);

A COLR version 0 glyph's layers, each a glyph and its color in the palette asked for.

Fills out with one daegun_colr_layer for each layer, back to front, so drawing them in order builds the glyph. palette is the index of one of the font's CPAL palettes. An index past the font's palettes reads palette 0, the default.

A layer that names a glyph the font lacks, or a color past the palette's entries, draws nothing and is left out of the list. A layer whose glyph has no outline is still listed, though daegun_font_color_scene leaves it out.

out is your buffer with room for out_len layers. *out_count is set to the number of layers whenever the call answers DAEGUN_OK or finds the buffer too small. A NULL out with an out_len of 0 asks for that number alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes no layer. A buffer that shares bytes with out_count answers the same and writes nothing at all, the count included. The count is never more than 65,535, as COLR counts a glyph's layers in 16 bits.

DAEGUN_ABSENT means the glyph has no version 0 layers to draw, and the count is left as it was. That is the answer where the font has no COLR table or no CPAL table beside it, where daegun does not read one of the two (a table cut short of its header, or of a version above 1), where the glyph is no color glyph, and where every one of its layers is left out. A glyph that COLR version 1 describes answers it too, unless the font also gives it layers: read that kind with daegun_font_paint_graph, or take either kind with daegun_font_color_scene.

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

/* Ask for the count, then for the layers. */
size_t count = 0;
daegun_status status = daegun_font_colr_layers(font, gid, 0, NULL, 0, &count);
if (status == DAEGUN_ABSENT) {
    /* No layers: draw the glyph's outline in the text's color. */
    return 0;
}
if (status != DAEGUN_OK) return 1;
daegun_colr_layer *layers = malloc(count * sizeof *layers);
if (!layers) return 1;
if (daegun_font_colr_layers(font, gid, 0, layers, count, &count) != DAEGUN_OK) {
    free(layers);
    return 1;
}
/* Bungee Tint's A is 2 layers. The first fills the A's own outline with 201, 9, 0, and the second
   fills glyph 1054 with 255, 149, 128 over it. */
free(layers);
daegun_font_palettes
daegun_status daegun_font_palettes(
    const daegun_font *font,
    daegun_palette *out,
    size_t out_len,
    size_t *out_count
);

The font's color palettes.

Fills out with one daegun_palette for each palette of the font's CPAL table, in order, so entry i has an index of i. A font with no CPAL table has none, and neither has one whose CPAL daegun doesn't read: a table cut short of its header, or of a version above 1. That is no failure. The call answers DAEGUN_OK with a count of 0.

out is your buffer with room for out_len palettes. *out_count is set to the number of palettes whenever the call answers DAEGUN_OK or finds the buffer too small. A NULL out with an out_len of 0 asks for that number alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes no palette. A buffer that shares bytes with out_count answers the same and writes nothing at all, the count included. The count is never more than 65,535.

daegun_palette palettes[16];
size_t count = 0;
daegun_status status = daegun_font_palettes(font, palettes, 16, &count);
if (status == DAEGUN_INVALID_ARGUMENT) {
    /* More than 16 palettes: `count` says how many, so make that much room and call again. */
} else if (status != DAEGUN_OK) {
    return 1;
}
for (size_t i = 0; i < count; i++) {
    /* Offer palettes[i].index as a choice. */
}
/* Bungee Tint has 8 palettes. A font with no color tables, such as Inter, has 0. */
daegun_font_palette_colors
daegun_status daegun_font_palette_colors(
    const daegun_font *font,
    uint16_t palette,
    daegun_rgba *out,
    size_t out_len,
    size_t *out_count
);

One palette's colors, in entry order.

Fills out with the colors of a palette: out[i] is the color a layer or a paint means by entry i. It is what a color picker shows for the palette. Every palette of a font has the same number of entries. A font with no CPAL table, or one whose CPAL daegun doesn't read, has no colors: the call answers DAEGUN_OK with a count of 0.

A palette past the font's palettes reads palette 0, the default, as drawing does. So an index never makes the call fail: compare it with the count from daegun_font_palettes to know whether a palette exists.

out is your buffer with room for out_len colors. *out_count is set to the number of colors whenever the call answers DAEGUN_OK or finds the buffer too small. A NULL out with an out_len of 0 asks for that number alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes no color. A buffer that shares bytes with out_count answers the same and writes nothing at all, the count included. The count is never more than 65,535.

daegun_rgba colors[8];
size_t count = 0;
if (daegun_font_palette_colors(font, 1, colors, 8, &count) != DAEGUN_OK) return 1;
/* Each palette of Bungee Tint holds 2 colors. Palette 1 is white, 255, 255, 255, and 232, 232, 231. */

/* The font has palettes 0 to 7, so palette 8 reads as palette 0, whose first color is 201, 9, 0. */
if (daegun_font_palette_colors(font, 8, colors, 8, &count) != DAEGUN_OK) return 1;
daegun_font_palette_entry_labels
daegun_status daegun_font_palette_entry_labels(
    const daegun_font *font,
    uint16_t *out_name_ids,
    uint8_t *out_named,
    size_t out_len,
    size_t *out_count
);

The name each palette entry goes by, as an ID in the font's name table, so a picker can label the colors.

A font may name the entries of its palettes, saying what each color is for, so that someone choosing colors of their own sees what each one changes. A label belongs to an entry, not to one palette: entry i has the same label in every palette.

The call fills two buffers that line up. out_name_ids[i] receives the name ID of entry i, to read with daegun_font_name, and out_named[i] receives 1 where the font names that entry and 0 where it leaves it unnamed. An unnamed entry has its ID written as 0, so go by the byte. Either buffer may be NULL, whatever out_len is, to leave that half out. out_len is the room in each buffer you pass.

*out_count is set to the number of entries whenever the call answers DAEGUN_OK or finds the buffers too small. That is the number of colors in a palette, or 0 where the font has no entry labels: no CPAL table, one daegun doesn't read, a CPAL of version 0, or one of version 1 without the array of entry labels. A font that has the array but names no entry gives the full count, every byte 0. The count is never more than 65,535. With both buffers NULL the call answers with the count alone. Buffers too small answer DAEGUN_INVALID_ARGUMENT and write no label. Buffers that share bytes with each other or with out_count answer the same and write nothing at all, the count included.

uint16_t name_ids[32];
uint8_t named[32];
size_t count = 0;
if (daegun_font_palette_entry_labels(font, name_ids, named, 32, &count) != DAEGUN_OK) return 1;
for (size_t i = 0; i < count; i++) {
    if (named[i]) {
        /* Label entry i of every palette with the name whose ID is name_ids[i]. */
    }
}
/* This font has 14 colors to a palette and labels none of them, so count is 0. */
daegun_scene_options_default
daegun_status daegun_scene_options_default(
    daegun_scene_options *out,
    size_t size
);

Fills scene options with their defaults: palette 0 and opaque black text.

Pass the struct and sizeof it. The call zeroes that many bytes, sets foreground to opaque black (0, 0, 0, 255) and sets size. Then set the fields you want. Always start here: a struct you zero yourself is not the default, as daegun_scene_options explains.

A size below what daegun 2.0 defined answers DAEGUN_INVALID_ARGUMENT, and one larger than this library knows answers DAEGUN_UNSUPPORTED, which means your header is newer than the library. Neither writes anything.

daegun_scene_options opts;
if (daegun_scene_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
/* Now palette 0 and opaque black text. Draw with red text instead. */
opts.foreground = (daegun_rgba){ 255, 0, 0, 255 };

/* Glyph 154 of the COLR test font fills with the text's color. */
daegun_scene *scene = NULL;
if (daegun_font_color_scene(font, 154, NULL, &opts, &scene) != DAEGUN_OK) return 1;
size_t n = 0;
const daegun_scene_op *ops = daegun_scene_ops(scene, &n);
/* Its one fill, ops[1], is red. With NULL options it is black. */

daegun_scene_free(scene);
daegun_font_color_scene
daegun_status daegun_font_color_scene(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    const daegun_scene_options *opts,
    daegun_scene **out
);

A color glyph as a scene to draw: fills, clips and layers in drawing order, in font units.

A color glyph has more than one color in it, so it comes back as a daegun_scene through out, not as one outline. The scene is made from the glyph's COLR version 1 paint graph if it has one, and otherwise from its COLR version 0 layers. Walk it with daegun_scene_ops: each daegun_scene_op fills a path with a color or a gradient, or pushes or pops a clip or a layer. Free it with daegun_scene_free.

Everything is in font units, y up, from the glyph's origin. To draw at a pixel size, scale by that size over the font's units per em, which daegun_font_units_per_em gives, and flip y if your rows run down. Each glyph's outline is held once as a path, however many ops name it, and an op's transform places it. A version 0 glyph gives a fill for each layer that draws, back to front, each a solid color. A version 1 glyph that has a clip box is drawn inside it: its ops sit between a clip to that box and its pop.

location picks the instance of a variable font, NULL being the default one. NULL for opts means the default daegun_scene_options: palette 0 and opaque black text.

DAEGUN_ABSENT means the glyph has no color description: the font has no COLR table it can draw, which takes a CPAL table beside it, or COLR lists neither a paint graph nor layers for this glyph, as for a glyph id past the font's last. Version 0 layers that all name a glyph or a palette entry the font does not have count as none. A font that colors its glyphs with bitmaps, as Noto Color Emoji does, has no scenes either: daegun_font_bitmap reads those. One more case answers it. A version 1 glyph with no clip box whose paint has no bounds, a fill that no outline and no clip box contains, is one the OpenType spec says not to draw. Its version 0 layers are drawn if it has them, and without them it is absent.

A color glyph that draws nothing is not absent. It answers DAEGUN_OK with a scene of 0 ops: a glyph whose only gradient is ill-formed, its stops all at one offset under repeat or reflect, for one, or whose layers name glyphs with no outline. A layer or paint whose glyph has no outline, or whose outline fails to decode, is left out and the rest is drawn.

A scene's clips and layers nest at most 128 deep, so a renderer can keep a stack of that size. daegun follows a paint graph 64 paints down and leaves out what lies deeper, and one paint opens at most two levels. Pushes and pops always pair up.

DAEGUN_LIMIT_EXCEEDED means the scene's outlines are more than a font of this size may ask for. daegun adds up, for every glyph the scene names, the points its outline holds and the work that decoding it took, drawn or not, each glyph once however many layers name it. The call fails where that sum passes 16 for each byte of the font's glyf, CFF, CFF2 and VARC tables together, or passes 1,048,576 where that is the larger number. The limit is there because a few bytes of a font can decode into a great many points, and layers may name any glyph.

Options whose size is below daegun 2.0's, as in a struct you zeroed yourself, answer DAEGUN_INVALID_ARGUMENT, and options larger than this library knows answer DAEGUN_UNSUPPORTED. On any failure, and on DAEGUN_ABSENT, *out is NULL. Each call builds the scene anew, so keep the handle while you draw from it. For pixels with no renderer of your own, daegun_rasterizer_color_glyph draws the same scene.

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

daegun_scene *scene = NULL;
daegun_status status = daegun_font_color_scene(font, gid, NULL, NULL, &scene);
if (status == DAEGUN_ABSENT) {
    /* Not a color glyph: draw its outline in the text's color. */
    return 1;
}
if (status != DAEGUN_OK) return 1;

size_t n = 0;
const daegun_scene_op *ops = daegun_scene_ops(scene, &n);
for (size_t i = 0; i < n; i++) {
    if (ops[i].kind != DAEGUN_OP_FILL) continue; /* a clip or a layer: daegun_scene_op shows those */
    daegun_path_view path;
    if (daegun_scene_path_at(scene, ops[i].path, &path) != DAEGUN_OK) return 1;
    /* Fill `path`, placed by ops[i].transform, with ops[i].color, or with gradient
       ops[i].gradient where ops[i].has_gradient is set. */
}
/* Bungee Tint's A is two solid fills, back to front: a red shape, then a lighter one over it. */

daegun_scene_free(scene);
daegun_scene_free
void daegun_scene_free(daegun_scene *scene);

Frees a scene.

NULL is fine and does nothing, so a cleanup path may free without checking. Every array the scene lent you, and every daegun_path_view into it, is invalid afterward. What you made from it is your own and stays: a path from daegun_scene_path_copy and a ramp from daegun_scene_ramp.

The thread that frees a scene keeps its memory for the next scene it builds, unless that memory is more than 64 KiB, so making and freeing scenes in a loop does not allocate each time. daegun_thread_release lets go of it.

daegun_scene *scene = NULL;
daegun_status status = daegun_font_color_scene(font, 2, NULL, NULL, &scene);
if (status == DAEGUN_OK) {
    /* draw the scene */
}
/* Safe either way: a call that fails, or finds no color glyph, leaves `scene` NULL. */
daegun_scene_free(scene);
  • May be NULL: scene.
daegun_scene_ops
const daegun_scene_op *daegun_scene_ops(
    const daegun_scene *scene,
    size_t *out_count
);

The scene's ops, in the order to draw them.

Returns a borrowed array of daegun_scene_op and sets *out_count to its length. Draw them first to last: a later fill goes over an earlier one.

A count of 0 is a glyph that draws nothing. The array is valid until daegun_scene_free. Don't free it. NULL comes back, with the count left as it was, only if scene or out_count is NULL.

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

size_t n = 0;
const daegun_scene_op *ops = daegun_scene_ops(scene, &n);
for (size_t i = 0; i < n; i++) {
    /* ops[i].kind is a DAEGUN_OP_ code: carry it out, in this order. */
}
/* Glyph 84 of the COLR test font composites one paint onto another, which takes six ops: a layer
   pushed, a fill, a second layer pushed with DAEGUN_COMPOSITE_DEST_OVER, a fill, and two pops. */

daegun_scene_free(scene);
daegun_scene_shapes
const daegun_clip_shape *daegun_scene_shapes(
    const daegun_scene *scene,
    size_t *out_count
);

Every clip shape of the scene, in one array.

Returns a borrowed array of daegun_clip_shape and sets *out_count to its length. Each daegun_scene_op whose kind is DAEGUN_OP_PUSH_CLIP owns the entries from its shapes_start up to, and not including, its shapes_end. A scene with no clips gives a count of 0.

Valid until daegun_scene_free. NULL, with the count left as it was, only if scene or out_count is NULL.

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

size_t n = 0, count = 0;
const daegun_scene_op *ops = daegun_scene_ops(scene, &n);
const daegun_clip_shape *shapes = daegun_scene_shapes(scene, &count);
for (size_t i = 0; i < n; i++) {
    if (ops[i].kind != DAEGUN_OP_PUSH_CLIP) continue;
    for (size_t s = ops[i].shapes_start; s < ops[i].shapes_end; s++) {
        /* shapes[s] is one shape of this clip. */
    }
}
/* Glyph 8 of the COLR test font has one clip of one shape: the rectangle of its clip box. */

daegun_scene_free(scene);
daegun_scene_gradients
const daegun_gradient *daegun_scene_gradients(
    const daegun_scene *scene,
    size_t *out_count
);

Every gradient of the scene, in one array.

Returns a borrowed array of daegun_gradient and sets *out_count to its length. A daegun_scene_op that fills with a gradient indexes this array with its gradient. A scene whose fills are all solid colors gives a count of 0.

Valid until daegun_scene_free. NULL, with the count left as it was, only if scene or out_count is NULL.

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

size_t n = 0, count = 0;
const daegun_scene_op *ops = daegun_scene_ops(scene, &n);
const daegun_gradient *gradients = daegun_scene_gradients(scene, &count);
const daegun_gradient *found = NULL;
for (size_t i = 0; i < n; i++) {
    if (ops[i].kind != DAEGUN_OP_FILL || !ops[i].has_gradient) continue;
    found = &gradients[ops[i].gradient]; /* what this fill paints with */
}
/* Glyph 156 of the COLR test font has one gradient, a radial one: from a point at (166, 768)
   out to a circle of radius 256 around it, reflected past that. */

daegun_scene_free(scene);
daegun_scene_stops
const daegun_stop *daegun_scene_stops(
    const daegun_scene *scene,
    size_t *out_count
);

The stops of every gradient of the scene, in one array.

Returns a borrowed array of daegun_stop and sets *out_count to its length. The stops lie gradient after gradient: each daegun_gradient owns stops_count entries from its stops_start. A scene with no gradients gives a count of 0.

Valid until daegun_scene_free. NULL, with the count left as it was, only if scene or out_count is NULL.

daegun_scene *scene = NULL;
if (daegun_font_color_scene(font, 180, 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);
for (size_t g = 0; g < count; g++) {
    const daegun_stop *own = stops + gradients[g].stops_start;
    for (size_t i = 0; i < gradients[g].stops_count; i++) {
        /* own[i] is stop i of gradient g. */
    }
}
/* Glyph 180 of the COLR test font has 5 gradients of 2 stops each, so 10 stops. The third
   gradient's stops begin at index 4. */

daegun_scene_free(scene);
daegun_scene_path_count
daegun_status daegun_scene_path_count(
    const daegun_scene *scene,
    size_t *out
);

How many paths the scene holds.

Writes the count to *out. Paths are numbered from 0 to one less than it: that number is the path of a daegun_scene_op and of a daegun_clip_shape, and what daegun_scene_path_at and daegun_scene_path_copy take.

A glyph's outline is held once however many ops fill it, so there may be fewer paths than fills. A scene may also hold a path that no op names, left from a paint that turned out to draw nothing.

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

size_t paths = 0;
if (daegun_scene_path_count(scene, &paths) != DAEGUN_OK) return 1;
/* 1 path: the glyph's two fills draw the same outline, each placed by its own transform. */

daegun_scene_free(scene);
daegun_scene_path_at
daegun_status daegun_scene_path_at(
    const daegun_scene *scene,
    size_t path,
    daegun_path_view *out
);

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

Fills *out, a daegun_path_view, with pointers into the scene. They are borrowed and valid until daegun_scene_free, and nothing is copied. path is the index an op or a clip shape names, below what daegun_scene_path_count gives.

An index past the last path answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

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

size_t n = 0;
const daegun_scene_op *ops = daegun_scene_ops(scene, &n);
/* ops[1] is this glyph's fill. */
daegun_path_view path;
if (daegun_scene_path_at(scene, ops[1].path, &path) != DAEGUN_OK) return 1;
/* A rectangle: a move, three lines and a close over four points, the first at (100, 250). */

daegun_scene_free(scene);
daegun_scene_path_copy
daegun_status daegun_scene_path_copy(
    const daegun_scene *scene,
    size_t path,
    daegun_path **out
);

A path of your own that holds a copy of one of the scene's paths.

For the calls that take a daegun_path, such as daegun_path_bounds, daegun_path_flatten, daegun_path_stroke and daegun_rasterizer_path, and for a path you need after the scene is gone. The copy comes back through out, in font units as the scene holds it, with no transform applied. It is yours: free it with daegun_path_free.

An index past the last path answers DAEGUN_INVALID_ARGUMENT. On failure *out is NULL.

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

daegun_path *path = NULL;
if (daegun_scene_path_copy(scene, 1, &path) != DAEGUN_OK) return 1;
daegun_scene_free(scene);

/* The copy outlives the scene. */
daegun_bounds box;
if (daegun_path_bounds(path, &box) != DAEGUN_OK) return 1;
/* The rectangle this glyph fills: x from 100 to 900, y from 250 to 950. */
daegun_path_free(path);
daegun_font_colr_clip_box
daegun_status daegun_font_colr_clip_box(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    daegun_bounds *out
);

A COLR version 1 glyph's clip box: the box that everything the glyph draws stays inside, in font units.

Writes a daegun_bounds to *out, y up. A font may give a color glyph a clip box so that a renderer can size a surface for it without walking its paints. The scene daegun_font_color_scene makes for the glyph is clipped to the same box, so nothing it draws shows outside it.

location picks the instance of a variable font, NULL being the default one. Where the box varies, each edge moves by its delta, and the result is rounded outward to whole units, not to the nearest: the minimums down and the maximums up, so the rounded box still holds all that the exact one would.

DAEGUN_ABSENT means the glyph has no clip box, and *out is left as it was. That is the answer for a glyph of a font with no COLR version 1 clip list, such as a font of version 0 layers alone, for a glyph the list does not cover, and for every glyph of a font whose COLR daegun doesn't draw, as one with no CPAL table beside it. A clip box is optional, so a color glyph may well have none.

daegun_bounds box;
daegun_status status = daegun_font_colr_clip_box(font, 160, NULL, &box);
if (status == DAEGUN_OK) {
    /* Everything the glyph draws lies inside the box, so it sizes the surface. */
    double width = box.x_max - box.x_min, height = box.y_max - box.y_min;
} else if (status == DAEGUN_ABSENT) {
    /* The glyph has no clip box. */
}
/* Glyph 160 of the COLR test font: from 250 to 750, across and up. */
daegun_scene_ramp
daegun_status daegun_scene_ramp(
    const daegun_scene *scene,
    size_t gradient,
    const double to_device[ 6],
    int32_t interpolation,
    daegun_ramp **out
);

Makes one gradient of a scene ready to sample at your pixels.

gradient is an index into the gradients that daegun_scene_gradients lends, the same number a fill op of the scene holds in its gradient. The ramp comes back through out. Sample it with daegun_ramp_at and free it with daegun_ramp_free. It keeps nothing of the scene, so the scene may be freed first.

to_device is six numbers [a, b, c, d, e, f] that take a point of the scene to one of your pixels: x' = a*x + c*y + e and y' = b*x + d*y + f. A scene is in font units with y up. So for a glyph drawn at size pixels per em, with its origin at pixel (ox, oy) of a surface whose y runs down, it is [s, 0, 0, -s, ox, oy] where s is size over the units per em. It is one matrix for the whole scene, the same that takes its paths to your pixels after each op's own transform. The gradient's own transform, which takes its shape into the scene, is applied first, so leave it out of yours.

interpolation is DAEGUN_INTERPOLATE_LINEAR_LIGHT or DAEGUN_INTERPOLATE_SRGB: how the ramp mixes the colors between two stops.

DAEGUN_INVALID_ARGUMENT means gradient is past the last gradient of the scene, or interpolation is neither code. *out is then NULL, and daegun_last_error says which. A transform that can't be undone is no failure: where it flattens the plane, or holds a value that is not finite, the ramp is made and paints nothing at any pixel.

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

/* Font units to pixels at 100 px per em, on a surface whose y runs down, the origin at (0, 100). */
uint16_t upem = 0;
if (daegun_font_units_per_em(font, &upem) != DAEGUN_OK) return 1;
double s = 100.0 / upem;
const double to_device[6] = { s, 0.0, 0.0, -s, 0.0, 100.0 };

size_t count = 0;
daegun_scene_gradients(scene, &count);
for (size_t i = 0; i < count; i++) {
    daegun_ramp *ramp = NULL;
    if (daegun_scene_ramp(scene, i, to_device, DAEGUN_INTERPOLATE_LINEAR_LIGHT, &ramp) != DAEGUN_OK) break;
    /* Fill with it: daegun_ramp_at(ramp, x, y, &color) for each pixel a fill with gradient i covers. */
    daegun_ramp_free(ramp);
}
/* This glyph has one gradient. */
daegun_scene_free(scene);
daegun_ramp_at
daegun_status daegun_ramp_at(
    const daegun_ramp *ramp,
    double x,
    double y,
    daegun_rgba *out
);

The color a gradient paints at one pixel.

Writes the color of pixel (x, y) to *out, as sRGB with straight alpha. The pixel is sampled at its center, the point (x + 0.5, y + 0.5) of your pixel grid, so pass whole pixel positions as they are. To sample at an exact point, pass that point less 0.5 each way.

DAEGUN_ABSENT means the gradient paints nothing there, and *out is left as it was. Treat it as a transparent pixel. A radial gradient paints nothing outside the cone its two circles span. Some gradients paint nothing anywhere: one whose transform can't be undone, a radial one whose two circles are the same, and under DAEGUN_EXTEND_REPEAT or DAEGUN_EXTEND_REFLECT a sweep whose two angles are equal.

The call only reads the ramp, so threads may sample one ramp at the same time, a row each.

daegun_scene *scene = NULL;
if (daegun_font_color_scene(font, 96, NULL, NULL, &scene) != DAEGUN_OK) return 1;
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;

/* One row of pixels, transparent where the gradient paints nothing. */
daegun_rgba row[100];
for (int x = 0; x < 100; x++) {
    daegun_rgba transparent = { 0, 0, 0, 0 };
    row[x] = transparent;
    daegun_status status = daegun_ramp_at(ramp, x, 50, &row[x]);
    if (status != DAEGUN_OK && status != DAEGUN_ABSENT) return 1;
}
/* This gradient is radial, between a small circle and a larger one, and paints only inside the cone
   they span. Pixel 10 lies outside it and stays transparent. Pixel 20 is the first stop's green. */

daegun_ramp_free(ramp);
daegun_scene_free(scene);
daegun_ramp_free
void daegun_ramp_free(daegun_ramp *ramp);

Frees a ramp.

NULL is fine and does nothing, so a cleanup path may free without checking.

daegun_scene *scene = NULL;
if (daegun_font_color_scene(font, 8, NULL, NULL, &scene) != DAEGUN_OK) return 1;
const double to_device[6] = { 1.0, 0.0, 0.0, 1.0, 0.0, 0.0 };

daegun_ramp *ramp = NULL;
daegun_status status = daegun_scene_ramp(scene, 0, to_device, DAEGUN_INTERPOLATE_LINEAR_LIGHT, &ramp);
if (status == DAEGUN_OK) {
    /* sample the ramp */
}
/* Safe either way: a call that fails leaves `ramp` NULL. */
daegun_ramp_free(ramp);
daegun_scene_free(scene);
  • May be NULL: ramp.
daegun_blend
daegun_status daegun_blend(
    int32_t mode,
    const float backdrop[ 3],
    const float source[ 3],
    float out[ 3]
);

A blend mode's function of a backdrop color and a source color.

This is the function B(Cb, Cs) of the W3C Compositing and Blending specification, worked on red, green and blue. mode is a DAEGUN_COMPOSITE_ code. backdrop and source are three floats each, straight and 0 to 1, and the answer is three floats written to out. No alpha takes part: daegun_composite is the whole operation and uses this function inside it.

Only the blend modes blend: DAEGUN_COMPOSITE_SCREEN to DAEGUN_COMPOSITE_HSL_LUMINOSITY, codes 13 to 27. The Porter-Duff modes before them, DAEGUN_COMPOSITE_CLEAR to DAEGUN_COMPOSITE_PLUS, combine by alpha alone, so for them the answer is the source as it came.

DAEGUN_INVALID_ARGUMENT means mode is none of the DAEGUN_COMPOSITE_ codes, and out is left as it was. out may be the same array as either color.

const float gray[3] = { 0.5f, 0.5f, 0.5f }, orange[3] = { 1.0f, 0.5f, 0.0f };
float out[3];
if (daegun_blend(DAEGUN_COMPOSITE_MULTIPLY, gray, orange, out) != DAEGUN_OK) return 1;
/* Multiply is the product of the two, channel by channel: 0.5, 0.25, 0. */

if (daegun_blend(DAEGUN_COMPOSITE_SRC_OVER, gray, orange, out) != DAEGUN_OK) return 1;
/* A Porter-Duff mode doesn't blend, so the answer is the source: 1, 0.5, 0. */
daegun_composite
daegun_status daegun_composite(
    int32_t mode,
    const float source[ 3],
    float source_alpha,
    const float backdrop[ 3],
    float backdrop_alpha,
    float out[ 3],
    float *out_alpha
);

Composites one source pixel onto one backdrop pixel under a mode.

mode is a DAEGUN_COMPOSITE_ code. source and backdrop are colors as three floats each, red, green and blue, straight and 0 to 1, with the alpha of each beside it. The color is written to out and its alpha to *out_alpha.

The source first blends with the backdrop where the two overlap: Cs' = (1 - ab)*Cs + ab*B(Cb, Cs). Here Cs and Cb are the source and backdrop colors, ab is the backdrop's alpha, and B is the mode's blend function, the one daegun_blend computes. Then two factors of the mode, Fa and Fb, say how much of each is kept: the color is as*Fa*Cs' + ab*Fb*Cb and the alpha as*Fa + ab*Fb, as being the source's alpha. A blend mode takes the factors of DAEGUN_COMPOSITE_SRC_OVER, 1 and 1 - as.

The result is premultiplied: each float in out is already multiplied by the alpha in *out_alpha. Divide by that alpha for a straight color, unless it is 0, where there is no color to recover.

No color space is converted, so the answer is in the space of what you pass. daegun's own renderer passes linear light: each sRGB byte decoded, then composited, then encoded back.

Both alphas are held to 0 to 1 on the way in, and each channel and the alpha of the result on the way out. The colors are not checked, so keep them within 0 to 1 and every input finite: an infinity, a value near float's largest or a NaN alpha answers NaN, whatever the mode.

DAEGUN_INVALID_ARGUMENT means mode is none of the DAEGUN_COMPOSITE_ codes. Nothing is written then.

const float red[3] = { 1.0f, 0.0f, 0.0f }, blue[3] = { 0.0f, 0.0f, 1.0f };
float out[3], alpha = 0.0f;
/* Red at half strength over blue at half strength. */
if (daegun_composite(DAEGUN_COMPOSITE_SRC_OVER, red, 0.5f, blue, 0.5f, out, &alpha) != DAEGUN_OK) return 1;
/* out is 0.5, 0, 0.25 and alpha is 0.75: the color comes back multiplied by its alpha. */

/* Divided by the alpha it is the straight color: two parts red to one part blue. */
float straight[3] = { 0.0f, 0.0f, 0.0f };
if (alpha > 0.0f) {
    for (int i = 0; i < 3; i++) straight[i] = out[i] / alpha;
}
daegun_font_paint_graph
daegun_status daegun_font_paint_graph(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    uint16_t palette,
    daegun_paint_graph **out
);

A COLR version 1 glyph's paint graph: the paints the glyph is drawn with, as the font states them.

The graph comes back through out as a daegun_paint_graph. Read its paints with daegun_paint_graph_nodes and the stops of its gradients with daegun_paint_graph_stops, and free it with daegun_paint_graph_free.

location picks the instance of a variable font, NULL being the default one, and the values a variable font moves along its axes are read there. palette is the index of the CPAL palette the colors are read from. An index past the font's palettes reads palette 0, the default.

The graph is the font's description, not a drawing. A DAEGUN_PAINT_COLR_GLYPH carries the other glyph's paints below it, a color that asks for the text's color is flagged and not filled in, and no outline is read. For fills ready to draw, use daegun_font_color_scene.

DAEGUN_ABSENT means the glyph has no version 1 paints, and *out is then NULL. That is the answer where the font has no COLR table or no CPAL table beside it, where daegun does not read one of the two (a table cut short of its header, or of a version above 1), where its COLR is version 0, and where the glyph is not one of its color glyphs. The layers of a version 0 glyph come from daegun_font_colr_layers.

/* Glyph 169, with its colors read from palette 1. */
daegun_paint_graph *graph = NULL;
daegun_status status = daegun_font_paint_graph(font, 169, NULL, 1, &graph);
if (status == DAEGUN_OK) {
    size_t count = 0;
    const daegun_paint_node *nodes = daegun_paint_graph_nodes(graph, &count);
    /* 17 paints: a layers paint, and below it 8 outlines with a solid color inside each. The first
       color, nodes[2].color, is 42, 41, 74 in this palette. */
} else if (status == DAEGUN_ABSENT) {
    /* No version 1 paints: try daegun_font_colr_layers, or draw the outline. */
} else {
    return 1;
}
daegun_paint_graph_free(graph);
daegun_paint_graph_nodes
const daegun_paint_node *daegun_paint_graph_nodes(
    const daegun_paint_graph *graph,
    size_t *out_count
);

The graph's paints, the root first.

Returns a borrowed array of daegun_paint_node and sets *out_count to its length. Paint 0 is the root, and the paints come in the order a visitor meets them, each followed by everything below it. A paint's end is the index one past the last paint below it, which is how you step over its children, as daegun_paint_node shows. A graph always has at least its root.

The array is valid until daegun_paint_graph_free. Don't free it. NULL comes back, with the count left as it was, only if graph or out_count is NULL.

/* Goes through nodes[at] and all the paints below it, and says how many levels deep they nest. */
static int depth_of(const daegun_paint_node *nodes, size_t at)
{
    int deepest = 0;
    for (size_t child = at + 1; child < nodes[at].end; child = nodes[child].end) {
        int below = depth_of(nodes, child);
        if (below > deepest) deepest = below;
    }
    return deepest + 1;
}

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);
int depth = depth_of(nodes, 0);
/* Glyph 84 has 6 paints, nested 4 deep: a composite, a scale, an outline and a solid color. */

daegun_paint_graph_free(graph);
daegun_paint_graph_stops
const daegun_color_stop *daegun_paint_graph_stops(
    const daegun_paint_graph *graph,
    size_t *out_count
);

Every gradient stop of the graph, in one array.

Returns a borrowed array of daegun_color_stop and sets *out_count to its length. A gradient paint owns stops_count of them, from index stops_start, in the font's order. A graph with no gradient has a count of 0, and then there is nothing to read at the pointer.

The array is valid until daegun_paint_graph_free. Don't free it. NULL comes back, with the count left as it was, only if graph or out_count is NULL.

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

size_t count = 0, stop_count = 0;
const daegun_paint_node *nodes = daegun_paint_graph_nodes(graph, &count);
const daegun_color_stop *stops = daegun_paint_graph_stops(graph, &stop_count);
for (size_t i = 0; i < count; i++) {
    const daegun_color_stop *own = stops + nodes[i].stops_start;
    for (size_t s = 0; s < nodes[i].stops_count; s++) {
        /* own[s] is stop s of the gradient nodes[i]. */
    }
}
/* Glyph 8's gradient, nodes[1], has 2 stops: red at offset 0 and blue at offset 1. */

daegun_paint_graph_free(graph);
daegun_paint_graph_free
void daegun_paint_graph_free(daegun_paint_graph *graph);

Frees a paint graph.

NULL is fine and does nothing, so a cleanup path may free without checking. The arrays that daegun_paint_graph_nodes and daegun_paint_graph_stops lent are invalid afterward.

daegun_paint_graph *graph = NULL;
daegun_status status = daegun_font_paint_graph(font, 8, NULL, 0, &graph);
if (status == DAEGUN_OK) {
    /* read the graph */
}
/* Safe either way: a call that finds no graph leaves `graph` NULL. */
daegun_paint_graph_free(graph);
  • May be NULL: graph.
daegun_font_visit_paint_graph
daegun_status daegun_font_visit_paint_graph(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    uint16_t palette,
    const daegun_paint_visitor *visitor
);

Walks a COLR version 1 glyph's paints and calls you back for each one, with no graph built.

It goes through the paints daegun_font_paint_graph would hold, in the same order. For each paint the enter of the daegun_paint_visitor runs, then the walk goes through that paint's children, then leave runs. There is no handle to free afterward, which suits a renderer that draws as it walks.

location and palette mean what they do for daegun_font_paint_graph: NULL is the default instance, and a palette past the font's reads palette 0.

The callbacks run on the calling thread, before this call returns. Each paint, and the stops of a gradient, are valid only inside the enter they are handed to. The walk always runs to its end: a callback has no way to stop it.

DAEGUN_ABSENT means the glyph has no version 1 paints, in the cases daegun_font_paint_graph lists, and no callback runs.

/* Counts the outlines a color glyph is built from. */
static void DAEGUN_CALLBACK on_enter(void *user, const daegun_paint_node *node,
                                     const daegun_color_stop *stops, size_t stops_count)
{
    (void)stops;
    (void)stops_count;
    if (node->kind == DAEGUN_PAINT_GLYPH) ++*(size_t *)user;
}

size_t outlines = 0;
daegun_paint_visitor visitor = { on_enter, NULL, &outlines };
daegun_status status = daegun_font_visit_paint_graph(font, 169, NULL, 0, &visitor);
if (status == DAEGUN_ABSENT) {
    /* No version 1 paints for this glyph, and on_enter never ran. */
} else if (status != DAEGUN_OK) {
    return 1;
}
/* Glyph 169 fills 8 outlines. */

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_font_math_constants
daegun_status daegun_font_math_constants(
    const daegun_font *font,
    const daegun_location *location,
    daegun_math_constants *out
);

Reads the font's math constants at a location: the distances and percentages that place scripts, fractions, limits, bars and roots in a formula.

Fills *out, a daegun_math_constants, with one field for each constant of the OpenType MATH table. Distances are in font units. A height is measured up from the baseline, and a shift or a drop downward is a positive number. The struct says what each field is for.

location picks the instance of a variable font, NULL being the default one, which works for any font. Away from the default, each distance has the variation delta the font gives for that location added to it. The sum is not rounded, so it may carry a fraction.

DAEGUN_ABSENT means the font has no constants to give: it has no MATH table, the table holds no constants, or the table ends before the last of them. A text font such as Inter answers it. *out is then left as it was.

Nothing is cached. Each call reads all 56 values from the table, so ask once for a formula and keep the struct.

daegun_math_constants constants;
daegun_status status = daegun_font_math_constants(font, NULL, &constants);
if (status == DAEGUN_ABSENT) {
    /* Not a math font: there are no constants to set a formula with. */
    return 1;
}
if (status != DAEGUN_OK) return 1;
uint16_t upem = 0;
if (daegun_font_units_per_em(font, &upem) != DAEGUN_OK) return 1;

/* A fraction bar at 20 px: how thick to draw it, and how far above the baseline its middle goes. */
double thickness = constants.fraction_rule_thickness * 20.0 / upem;
double height = constants.axis_height * 20.0 / upem;
/* STIX Two Math gives 68 and 258 font units, so a bar 1.36 px thick, 5.16 px up. */
daegun_font_math_italics_correction
daegun_status daegun_font_math_italics_correction(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    double *out
);

Reads a glyph's italic correction at a location, in font units: the room to leave after a slanted glyph so that what follows clears its overhanging top.

A slanted glyph leans past the end of its advance. The italic correction is by how much, and a math layout uses it in three places. Where a slanted glyph is followed by an upright one, such as an operator or a delimiter, the correction is added to its advance. A superscript on the glyph is set further right than a subscript by the correction, so that both follow the slant. And on a big operator such as an integral, the upper limit moves right by half the correction and the lower limit left by half.

DAEGUN_ABSENT means the font gives this glyph no correction, as for an upright glyph, or for any glyph of a font with no MATH table. *out is then left as it was, so preset it to 0 and you can use it either way.

location picks the instance of a variable font, NULL being the default one. Away from the default, the correction has its variation delta added and is not rounded.

uint32_t integral = 0, letter = 0;
if (daegun_font_glyph_id(font, 0x222B, &integral) != DAEGUN_OK) return 1; /* the integral sign */
if (daegun_font_glyph_id(font, 'A', &letter) != DAEGUN_OK) return 1;

/* Preset 0, which stays where the font gives the glyph no correction. */
double leaning = 0.0, upright = 0.0;
daegun_status status = daegun_font_math_italics_correction(font, integral, NULL, &leaning);
if (status != DAEGUN_OK && status != DAEGUN_ABSENT) return 1;
/* The integral sign leans to the right, and STIX Two Math gives it a correction of 230 units. */

status = daegun_font_math_italics_correction(font, letter, NULL, &upright);
/* An upright A has none: the status is DAEGUN_ABSENT and `upright` is still 0. */
daegun_font_math_top_accent_attachment
daegun_status daegun_font_math_top_accent_attachment(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    double *out
);

Reads where an accent centers over a glyph at a location: an x position in font units from the glyph's origin.

To set an accent such as a hat or a tilde over a base in a formula, line up two attachment points: ask for the base's and for the accent's own, and move the accent right by the difference. The point is not always the middle of the glyph. Over a slanted letter the accent belongs further right, above where the top of the letter is.

*out receives the font's own value where its MATH table gives the glyph one. Otherwise it receives half the glyph's horizontal advance at that location, the middle of the glyph. So there is always an answer, for a font with no MATH table too. A glyph id the font does not have receives 0, as its advance is 0.

location picks the instance of a variable font, NULL being the default one. The value from the table has its variation delta added, unrounded, and the fallback uses the advance at that location.

uint32_t base = 0, hat = 0;
if (daegun_font_glyph_id(font, 'A', &base) != DAEGUN_OK) return 1;
if (daegun_font_glyph_id(font, 0x0302, &hat) != DAEGUN_OK) return 1; /* the combining circumflex */

/* Put a circumflex over an A: move the accent so that its attachment point lands on the base's. */
double base_x = 0.0, hat_x = 0.0;
if (daegun_font_math_top_accent_attachment(font, base, NULL, &base_x) != DAEGUN_OK) return 1;
if (daegun_font_math_top_accent_attachment(font, hat, NULL, &hat_x) != DAEGUN_OK) return 1;
double shift = base_x - hat_x;
/* STIX Two Math gives 360 for the A and -230 for the accent, which is drawn left of its origin.
   So the accent is drawn 590 units right of the A's origin. */
daegun_font_math_is_extended_shape
daegun_status daegun_font_math_is_extended_shape(
    const daegun_font *font,
    uint32_t gid,
    bool *out
);

Reads whether the font marks a glyph as an extended shape: a glyph drawn tall to match the formula beside it, such as a large parenthesis, where scripts are placed by the height of what is drawn and not at the usual shift.

A superscript on an ordinary letter is raised by a fixed amount, superscript_shift_up of the daegun_math_constants. Beside a tall parenthesis that would leave it stranded halfway up. Where the glyph is an extended shape, a layout works from the ink box instead: the box around everything drawn in the sub-expression the glyph belongs to, such as a fraction and its parentheses. The baseline of a superscript goes no more than superscript_baseline_drop_max below the top of that box, and the baseline of a subscript at least subscript_baseline_drop_min below its bottom.

*out receives false for a glyph the font does not mark, and for every glyph of a font with no MATH table. The mark belongs to the glyph and is the same at every location, so the call takes none.

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

bool tall = false, plain = true;
if (daegun_font_math_is_extended_shape(font, paren, &tall) != DAEGUN_OK) return 1;
if (daegun_font_math_is_extended_shape(font, letter, &plain) != DAEGUN_OK) return 1;
/* STIX Two Math marks its parenthesis, and not a letter: tall is true and plain is false. */
daegun_font_math_min_connector_overlap
daegun_status daegun_font_math_min_connector_overlap(
    const daegun_font *font,
    double *out
);

Reads the least overlap the font allows where two parts of an assembled glyph join, in font units.

When a glyph is built from the parts of a daegun_glyph_assembly, each part is laid a little over the one before it, so that their strokes merge with no seam. This is the smallest overlap the font allows at such a join. Pulling the parts apart, down to this overlap, is how a build reaches the sizes between one count of repeated pieces and the next.

It is one number for the whole font: the same for every glyph, in both directions and at every location, so the call takes neither a glyph nor a location.

DAEGUN_ABSENT means the font has no MATH table, or a MATH table with nothing in it about stretching glyphs. *out is then left as it was.

double overlap = 0.0;
daegun_status status = daegun_font_math_min_connector_overlap(font, &overlap);
if (status == DAEGUN_ABSENT) {
    /* Not a math font: it has no glyphs to assemble. */
    return 1;
}
if (status != DAEGUN_OK) return 1;
/* STIX Two Math wants the parts of a glyph to overlap by at least 100 units. */
daegun_font_math_kern
daegun_status daegun_font_math_kern(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    int32_t corner,
    double height,
    double *out
);

Reads the kern at one corner of a glyph for a script that meets it at a given height, in font units.

Ordinary kerning moves two glyphs along a line. A subscript or superscript sits diagonally from its base, so how close it may come depends on how high it sits: a subscript can slide in under the arm of a V, and one set higher cannot. A math font therefore cuts each corner of a glyph into bands of height and gives a kern for each band.

corner is one of the four DAEGUN_MATH_KERN_ codes, such as DAEGUN_MATH_KERN_TOP_RIGHT. height is where the other glyph meets that corner: a y position in font units, measured up from this glyph's own baseline, so it is negative below the baseline. *out receives the kern of the band the height falls in. A negative kern moves the script closer.

The font lists the heights that divide the bands. A height below the first takes the first kern, one at or above the last takes the last kern, and a height equal to a listed one belongs to the band above it. The comparison is exact, with nothing rounded. An infinite height is fine: -INFINITY takes the first kern and INFINITY the last.

To kern a base and its script, add two answers: the base at the corner the script sits at, and the script at its own facing corner. For a superscript after its base those are DAEGUN_MATH_KERN_TOP_RIGHT of the base and DAEGUN_MATH_KERN_BOTTOM_LEFT of the superscript, each asked at the same level, measured from that glyph's own baseline. The OpenType specification takes the sum at two levels, the bottom of the superscript and the top of the base, and kerns by the smaller. For a subscript the corners are DAEGUN_MATH_KERN_BOTTOM_RIGHT of the base and DAEGUN_MATH_KERN_TOP_LEFT of the subscript, and the levels are the top of the subscript and the bottom of the base.

Where the font has no kern, *out receives 0 and the call still answers DAEGUN_OK: a font with no MATH table, a glyph it lists no kerns for, or a corner it leaves out.

DAEGUN_INVALID_ARGUMENT means corner is none of the four codes, or height is not a number (NaN). *out is left as it was, and daegun_last_error says which of the two it was.

location picks the instance of a variable font, NULL being the default one. Away from the default, the dividing heights and the kerns each have their variation delta added, so a band may begin at another height there.

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

/* STIX Two Math divides the top right corner of its A at heights 252 and 352. A superscript
   that meets it below 252 stays put. Higher up, where the A slopes away, it moves in. */
int32_t corner = DAEGUN_MATH_KERN_TOP_RIGHT;
double low = 0.0, middle = 0.0, high = 0.0;
if (daegun_font_math_kern(font, a, NULL, corner, 100.0, &low) != DAEGUN_OK) return 1;
if (daegun_font_math_kern(font, a, NULL, corner, 300.0, &middle) != DAEGUN_OK) return 1;
if (daegun_font_math_kern(font, a, NULL, corner, 400.0, &high) != DAEGUN_OK) return 1;
/* low is 0, middle is -18 and high is -66. */

/* A height that is not a number is refused: the status is DAEGUN_INVALID_ARGUMENT, and
   `kept` is still 7. */
double kept = 7.0;
daegun_status status = daegun_font_math_kern(font, a, NULL, corner, NAN, &kept);
daegun_font_math_glyph_variants
daegun_status daegun_font_math_glyph_variants(
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    int32_t orientation,
    daegun_math_construction **out
);

Reads how a glyph stretches in one direction: its ready-made sizes, and the parts to build it at any size.

A formula needs glyphs that grow: a parenthesis as tall as the fraction inside it, a brace as wide as the terms under it. A math font offers two ways to get one. A variant is a ready-made drawing of the glyph at one size, a glyph in its own right. An assembly is a set of parts, such as the two hooks of a parenthesis and a straight piece that repeats, joined to reach any size. The daegun_math_construction that comes back through out holds both.

orientation is the direction to stretch in: DAEGUN_VERTICAL for what grows taller, such as delimiters, roots and integrals, and DAEGUN_HORIZONTAL for what grows wider, such as arrows, braces over a formula and wide accents. The font lists the two directions separately.

To use the result, go through the sizes that daegun_math_construction_variants lends, in order, and take the first whose advance covers the size you need. They come as the font lists them, which daegun does not sort: STIX Two Math lists the glyph itself first, then each larger size. If none is large enough, ask daegun_math_construction_assembly for the parts and build the glyph from them: daegun_glyph_assembly says how.

DAEGUN_ABSENT means the font does not stretch this glyph in that direction. That is the answer for every glyph of a font with no MATH table. DAEGUN_INVALID_ARGUMENT means orientation is neither DAEGUN_HORIZONTAL nor DAEGUN_VERTICAL. On either, and on any other failure, *out is NULL.

On DAEGUN_OK the construction is yours: free it with daegun_math_construction_free. Every call reads the table and makes a new one, so keep it if you need it again.

location picks the instance of a variable font, NULL being the default one. Sizes are in font units and are the same at every location. The one value that follows the location is the assembly's italics_correction.

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

daegun_math_construction *stretch = NULL;
daegun_status status = daegun_font_math_glyph_variants(font, paren, NULL, DAEGUN_VERTICAL, &stretch);
if (status == DAEGUN_ABSENT) {
    /* The font does not stretch it: draw the glyph as it is. */
    return 1;
}
if (status != DAEGUN_OK) return 1;

/* A parenthesis for a formula 2000 units tall: the first ready-made size that covers it. */
size_t count = 0;
const daegun_math_variant *variants = daegun_math_construction_variants(stretch, &count);
size_t fit = 0;
while (fit < count && variants[fit].advance < 2000.0) fit++;
if (fit < count) {
    /* Draw variants[fit].glyph in place of the parenthesis. */
} else {
    /* Taller than every size: build it from daegun_math_construction_assembly. */
}
/* STIX Two Math draws 13 sizes, and the sixth, 2145 units tall, is the pick. */

daegun_math_construction_free(stretch);
daegun_math_construction_variants
const daegun_math_variant *daegun_math_construction_variants(
    const daegun_math_construction *construction,
    size_t *out_count
);

A construction's ready-made sizes, in the order the font lists them.

Returns a borrowed array of daegun_math_variant and sets *out_count to its length. Each entry is a glyph and how much it covers along the stretch, in font units. Take the first whose advance covers the size you need. daegun does not sort them: STIX Two Math lists the glyph itself first, then each larger size. A count of 0 means the font gives this glyph parts alone, and then there is nothing to read.

The array is valid until the construction is freed. Don't free it. NULL comes back, with the count left as it was, only if construction or out_count is NULL.

/* A brace over a formula stretches sideways, so its sizes are widths. */
uint32_t brace = 0;
if (daegun_font_glyph_id(font, 0x23DE, &brace) != DAEGUN_OK) return 1;
daegun_math_construction *stretch = NULL;
if (daegun_font_math_glyph_variants(font, brace, NULL, DAEGUN_HORIZONTAL, &stretch) != DAEGUN_OK) return 1;

/* To span terms 1600 units wide, take the first size that is wide enough. */
size_t count = 0;
const daegun_math_variant *variants = daegun_math_construction_variants(stretch, &count);
size_t fit = 0;
while (fit < count && variants[fit].advance < 1600.0) fit++;
/* STIX Two Math draws six widths, and the fourth, 1771 units wide, is the first past 1600. */

daegun_math_construction_free(stretch);
daegun_math_construction_assembly
daegun_status daegun_math_construction_assembly(
    const daegun_math_construction *construction,
    daegun_glyph_assembly *out
);

Reads the parts a construction gives for building the glyph at any size.

Fills *out, a daegun_glyph_assembly: the italic correction of the built glyph, and the parts in the order they are laid. The struct says how to join them.

The parts array is borrowed. It points into the construction and is valid until the construction goes to daegun_math_construction_free. Don't free it.

DAEGUN_ABSENT means the font gives this glyph ready-made sizes only, so there are no parts and the largest size is as far as it goes. *out is then left as it was.

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;
daegun_glyph_assembly assembly;
if (daegun_math_construction_assembly(stretch, &assembly) != DAEGUN_OK) {
    daegun_math_construction_free(stretch); /* DAEGUN_ABSENT: sizes only, no parts */
    return 1;
}

/* A parenthesis 5000 units tall is past every ready-made size. Count the extenders it takes:
   the tallest build is every advance added up, less the least overlap at each join. */
unsigned repeats = 0;
double tallest = 0.0;
for (; repeats < 16; repeats++) {
    unsigned laid = 0;
    double length = 0.0;
    for (size_t i = 0; i < assembly.parts_len; i++) {
        unsigned times = assembly.parts[i].extender ? repeats : 1;
        laid += times;
        length += assembly.parts[i].full_advance * times;
    }
    tallest = laid ? length - overlap * (laid - 1) : 0.0;
    if (tallest >= 5000.0) break;
}
/* With STIX Two Math it takes three, which reach as far as 5902 units. */

daegun_math_construction_free(stretch);
daegun_math_construction_free
void daegun_math_construction_free(daegun_math_construction *construction);

Frees a construction.

That is a daegun_math_construction from daegun_font_math_glyph_variants. NULL is fine and does nothing, so a cleanup path may free without checking. The array of sizes and the parts of any assembly read from it are invalid afterward.

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

daegun_math_construction *stretch = NULL;
daegun_status status = daegun_font_math_glyph_variants(font, paren, NULL, DAEGUN_VERTICAL, &stretch);
if (status == DAEGUN_OK) {
    /* read the sizes and the parts */
}
/* Safe either way: a call that does not answer DAEGUN_OK leaves `stretch` NULL. */
daegun_math_construction_free(stretch);
  • May be NULL: construction.

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_font_subset
daegun_status daegun_font_subset(
    const daegun_font *font,
    const uint32_t *gids,
    size_t gids_len,
    const daegun_location *location,
    daegun_subset **out
);

Builds a smaller font file that holds the glyphs you name and every glyph they reach, pinned to one location.

For when you already hold glyph ids. daegun_font_subset_text takes the text itself, and is the one to use for a web font. gids is an array of gids_len glyph ids. It may be NULL where gids_len is 0, which gives glyph 0 and whatever it reaches, in most fonts glyph 0 alone. On DAEGUN_OK, *out is a daegun_subset of yours: daegun_subset_bytes lends its font file, daegun_subset_renumbered says where each glyph went, and daegun_subset_free frees it.

What it keeps. The glyphs you pass and every glyph they reach: every glyph the font's substitutions (GSUB) can turn them into under any feature of any script, on by default or not, the size variants and assembly parts a MATH table gives them, the layers of a color glyph and the parts a composite glyph is built from, and also the glyphs Apple's morx can turn them into, the base and accent of a CFF seac glyph, the glyphs a bitmap glyph copies or is built from, and the parts of a VARC glyph. daegun_font_glyph_closure gives the same set without building the font, and says how far each step reaches. Glyph 0, .notdef, is always kept. An id past the font's last glyph is ignored, and a repeated one counts once.

Pinned to a location. The subset is a static font. A variable font's outlines, advances and kerning are worked out at location and its variation tables are left out, so pass the location you will draw at. NULL is the default instance. A font that is not variable gives the same subset at any location.

Its tables. Those that name glyphs are rewritten for the glyphs kept, those that name none, such as cvt , fpgm, prep and gasp, are copied as they are, and the variation tables and DSIG, which signs the source's bytes, are left out. A font with TrueType outlines also loses every table daegun doesn't know, SVG color glyphs among them. A font with CFF or CFF2 outlines keeps such tables as they are.

Its cmap. The subset's cmap, the map from characters to glyphs, keeps every character the source maps to a glyph the subset keeps. That includes the characters of glyphs the closure brought in: asking for the glyph of a in Inter also keeps ª, whose glyph a feature reaches from it. Variation sequences go the same way: each one whose glyph the subset keeps stays, and one that takes its base's default glyph stays while the base is mapped.

Renumbering. In a font with TrueType outlines the kept glyphs are packed together: they stay in their order and take the ids 0, 1, 2 and so on, so a glyph's id in the subset is rarely its id in the source. A font with CFF or CFF2 outlines is left in place by this call: each kept glyph keeps its id, the dropped ones are emptied, and the glyph count stays what it was. That file is larger than the one daegun_font_subset_text makes, which packs CFF glyphs too. daegun_subset_renumbered is right in both cases.

Failures. DAEGUN_MISSING: the font lacks a table the subsetter needs, such as a glyf with no loca, or a variable font with no hmtx. DAEGUN_MALFORMED: a table does not hold together, such as a maxp that counts no glyphs, or a CFF table whose glyph count differs from the one in maxp. DAEGUN_UNSUPPORTED: a table is in a form the subsetter can't write, such as a CFF charset of an unknown format. DAEGUN_LIMIT_EXCEEDED: the font asks for more work than daegun allows, as a hostile one does with glyph data that overlaps so the same bytes would be copied again and again, or with substitutions that keep reaching more glyphs. A variable font goes through the instancer first, at the default location too, and its failures come back as these statuses. Each of them sets *out to NULL and leaves its reason in daegun_last_error.

Each call builds the file anew, and nothing of the result is cached. The font does keep what it read at location, such as a variable font's instance there, so a later subset or glyph closure at that location is faster.

/* The glyphs of "Wave", one per character. */
uint32_t glyphs[4];
size_t count = 0;
if (daegun_font_glyph_ids(font, "Wave", 4, glyphs, NULL, 4, &count) != DAEGUN_OK) return 1;

daegun_subset *subset = NULL;
if (daegun_font_subset(font, glyphs, count, NULL, &subset) != DAEGUN_OK) return 1;

size_t size = 0;
const uint8_t *file = daegun_subset_bytes(subset, &size);
/* A font file of 4,192 bytes, where Inter is 879,708. */

/* The W was glyph 459 in Inter. In the subset it is glyph 1. */
uint32_t w = 0;
if (daegun_subset_renumbered(subset, glyphs[0], &w) != DAEGUN_OK) return 1;

/* The file opens like any font. It holds 17 glyphs: the four asked for, .notdef and the forms
   Inter's features reach from them. */
daegun_font *small = NULL;
if (daegun_font_open(file, size, &small) != DAEGUN_OK) return 1;
uint32_t held = 0;
if (daegun_font_glyph_count(small, &held) != DAEGUN_OK) return 1;
daegun_font_free(small);

daegun_subset_free(subset);
  • May be NULL: gids where gids_len is 0, location.
  • Answers: DAEGUN_OK, DAEGUN_NULL, or the failure its text names.
daegun_font_subset_text
daegun_status daegun_font_subset_text(
    const daegun_font *font,
    const char *text,
    size_t text_len,
    const daegun_location *location,
    daegun_subset **out
);

Builds a smaller font file that can draw one piece of text: the glyphs its characters map to and every glyph those reach, pinned to one location.

The call for a web font or an embedded one. Pass the text a page shows and get back a font file that holds what the text needs and little else. It looks up the glyphs of the characters and then keeps what daegun_font_subset would keep for them, so ligatures, the joined forms of Arabic, accents built from parts and color layers all survive, and the subset shapes the text as the source font does.

The text is UTF-8 with its length in bytes, so it needs no NUL, and it may be NULL where text_len is 0. location is where the subset is pinned, as in daegun_font_subset, NULL being the default instance. On DAEGUN_OK, *out is a daegun_subset to read with daegun_subset_bytes and free with daegun_subset_free.

The characters it looks up are the text's own and the ones shaping can turn them into or draw them with, such as the parts a letter breaks into, the single character a letter and its accent make together, a Hangul syllable its jamo make, the halves Thai's SARA AM splits into, a bracket's mirror image, the vertical forms of punctuation, the dotted circle that carries a stray mark, the space a joiner or a missing space is drawn with, the digits a figure space takes its width from, the hyphen a non-breaking hyphen falls back to, and, in a font with no Arabic rules of its own, the presentation forms Arabic shaping falls back to. A variation sequence in the text keeps the glyph the font gives it.

So a character the font has no glyph for can still add glyphs: a letter the font lacks adds the parts it breaks into, and a joiner or a variation selector the font lacks adds the space glyph shaping draws it with. Text that maps to nothing gives .notdef and whatever it reaches, in most fonts .notdef alone.

Its cmap holds those characters and no others, where daegun_font_subset keeps every character of every kept glyph. A glyph the closure brought in, such as a ligature or an alternate, is in the font but has no character of its own in the map.

Renumbering. The kept glyphs are packed together as daegun_font_subset packs them, and here a font with CFF or CFF2 outlines is packed too, so the glyph count falls to what is kept. The exception is a CFF or CFF2 font that carries a table daegun has no way to renumber, such as a BASE that names glyphs or a table it doesn't know: that font keeps its glyph ids in place. daegun_subset_renumbered is right in both cases.

DAEGUN_INVALID_ARGUMENT means the text is not UTF-8. The other failures are those of daegun_font_subset, DAEGUN_MALFORMED, DAEGUN_UNSUPPORTED, DAEGUN_LIMIT_EXCEEDED and DAEGUN_MISSING, the last of which also comes for a font with no cmap table, which has no characters to look up. Any of them sets *out to NULL and leaves its reason in daegun_last_error.

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

size_t size = 0;
const uint8_t *file = daegun_subset_bytes(subset, &size);
/* Inter is 879,708 bytes. The subset is 9,824: fwrite(file, 1, size, out) writes it out. */

/* Opened again, it maps the 16 different characters of the text and no others. */
daegun_font *small = NULL;
if (daegun_font_open(file, size, &small) != DAEGUN_OK) return 1;
size_t mapped = 0;
if (daegun_font_coverage(small, NULL, NULL, 0, &mapped) != DAEGUN_OK) return 1;
daegun_font_free(small);

daegun_subset_free(subset);
daegun_subset_bytes
const uint8_t *daegun_subset_bytes(
    const daegun_subset *subset,
    size_t *out_count
);

The subset's font file: a borrowed pointer to its bytes, with their count.

Returns the bytes of a complete font file and sets *out_count to how many there are. Write them to disk, send them, or open them with daegun_font_open, which takes a copy.

The bytes are borrowed from the subset. They stay valid until daegun_subset_free, and you never free them yourself: copy them if you need them longer. NULL comes back, with the count left as it was, only if subset or out_count is NULL.

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

size_t size = 0;
const uint8_t *file = daegun_subset_bytes(subset, &size);
/* Keep a copy if the bytes must outlive the subset. */
uint8_t *kept = malloc(size);
if (!kept) return 1;
memcpy(kept, file, size);
daegun_subset_free(subset);

/* `file` is gone with the subset. `kept` is still a font file, of 3,900 bytes. */
free(kept);
daegun_subset_renumbered
daegun_status daegun_subset_renumbered(
    const daegun_subset *subset,
    uint32_t old,
    uint32_t *out
);

The id a glyph of the source font has in the subset.

A subset packs the glyphs it keeps, so their ids change. The kept glyphs stay in their order and take the ids 0, 1, 2 and so on: a kept glyph's new id is the number of kept glyphs with a lower id. Glyph 0, .notdef, is always kept and stays glyph 0. The new id is written to *out.

Two kinds of subset are not packed: daegun_font_subset of a font with CFF or CFF2 outlines, and daegun_font_subset_text of such a font when it carries a table daegun can't renumber, such as a BASE that names glyphs or a table it doesn't know. There a kept glyph answers its own id.

DAEGUN_ABSENT means the subset dropped the glyph, or the source font never had that id. It is an answer, not a failure, and it leaves *out as it was.

Use it to carry glyph ids from the source into the subset: the glyphs of a run shaped with the source font, a glyph you cached, a table of your own keyed by glyph.

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

/* Shaped with Inter, "Wave" is glyphs 459, 507, 980 and 614. */
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);

uint32_t moved[4] = { 0 };
for (size_t i = 0; i < n && i < 4; i++) {
    if (daegun_subset_renumbered(subset, glyphs[i], &moved[i]) != DAEGUN_OK) return 1;
}
/* In the subset they are glyphs 1, 2, 5 and 4. */

/* A glyph the text has no use for was dropped. */
uint32_t x = 0, gone = 0;
if (daegun_font_glyph_id(font, 'x', &x) != DAEGUN_OK) return 1;
daegun_status status = daegun_subset_renumbered(subset, x, &gone);
/* status is DAEGUN_ABSENT, and `gone` is still 0. */
if (status != DAEGUN_ABSENT || gone != 0) return 1;

daegun_shaped_run_free(run);
daegun_subset_free(subset);
daegun_subset_free
void daegun_subset_free(daegun_subset *subset);

Frees a subset, and with it the bytes it lent.

NULL is fine and does nothing, so a cleanup path may free without checking. The pointer daegun_subset_bytes gave is invalid afterward. A font you opened from those bytes with daegun_font_open holds its own copy and stays good.

daegun_subset *subset = NULL;
daegun_status status = daegun_font_subset_text(font, "Wave", 4, NULL, &subset);
if (status == DAEGUN_OK) {
    /* read the subset */
}
/* Safe either way: a call that fails leaves `subset` NULL. */
daegun_subset_free(subset);
  • May be NULL: subset.
daegun_font_glyph_closure
daegun_status daegun_font_glyph_closure(
    const daegun_font *font,
    const uint32_t *gids,
    size_t gids_len,
    const daegun_location *location,
    uint32_t *out,
    size_t out_len,
    size_t *out_count
);

The glyphs a subset of these glyphs would hold: the ones you name and every glyph they reach.

Fills out with glyph ids sorted from low to high, each once, in the source font's numbering. It is the set daegun_font_subset keeps, found without writing a font. Use it to see what a subset will hold, or to gather glyphs for a glyph atlas or a subsetter of your own.

One glyph reaches another when drawing or shaping can lead from the first to the second: the glyphs the font's substitutions (GSUB) can turn it into under any feature, the size variants and assembly parts MATH gives it, the layers of a color glyph, the parts a composite glyph is built from, and beyond those the glyphs Apple's morx can turn it into, the base and accent of a CFF seac glyph, the glyphs a bitmap glyph copies or is built from (sbix, EBDT), the parts of a VARC glyph, and the glyphs bsln and fmtx name.

Substitutions are followed from the glyphs you name until nothing new comes. Then the MATH variants, color layers and parts of all of those are added, with their own parts and layers in turn, but a glyph that comes in that way is not run through GSUB again. So Inter's é brings in its e as a part, but not the e's superscript and subscript forms, which asking for the e itself would.

Glyph 0, .notdef, is always in the list. An id past the font's last glyph is left out, and a repeat counts once. gids may be NULL where gids_len is 0, which gives glyph 0 and whatever it reaches, in most fonts glyph 0 alone. location is the one you would subset at, NULL being the default instance.

out is your buffer with room for out_len ids, and *out_count is set to the number of glyphs in the closure. That is never more than the font's glyph count, so room for what daegun_font_glyph_count answers always fits. A NULL out with an out_len of 0 asks for the count alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT with the count set, and writes nothing into it. Buffers that share bytes, out with gids or either with the count, answer DAEGUN_INVALID_ARGUMENT too, and leave the count as it was.

A font that cannot be read, or a closure that cannot be finished, answers a failure and leaves both the count and the buffer as they were: DAEGUN_MISSING for a glyf with no loca, DAEGUN_MALFORMED for a maxp that counts no glyphs, DAEGUN_LIMIT_EXCEEDED for substitutions that lead past the work daegun allows. The failures daegun_font_subset meets while writing the file do not come up here, so a font may give a closure and still fail to subset. For a variable font, or one with CFF2 outlines, the call first builds the font at location as a subset does, so the instancer's failures come here too, such as DAEGUN_MISSING for a variable font with no hmtx.

uint32_t e_acute = 0;
if (daegun_font_glyph_id(font, 0xE9, &e_acute) != DAEGUN_OK) return 1; /* é */

/* Ask how many glyphs the closure holds, then fetch them. */
size_t count = 0;
if (daegun_font_glyph_closure(font, &e_acute, 1, NULL, NULL, 0, &count) != DAEGUN_OK) return 1;
uint32_t *closure = malloc(count * sizeof *closure);
if (!closure) return 1;
if (daegun_font_glyph_closure(font, &e_acute, 1, NULL, closure, count, &count) != DAEGUN_OK) return 1;
/* Inter builds its é from an e and an acute accent, so count is 4: .notdef, the e, the é and
   the accent, in the order of their ids. */
free(closure);
daegun_font_base_script
daegun_status daegun_font_base_script(
    const daegun_font *font,
    daegun_tag script,
    const daegun_location *location,
    int32_t orientation,
    daegun_base_script **out
);

A script's baselines from the font's BASE table: where each named baseline lies, and which one the script's glyphs sit on.

Scripts sit on different lines. Latin letters stand on the roman baseline, Chinese and Japanese characters fill a box whose bottom edge lies below it, and Devanagari hangs from a line near the top. A font's BASE table records where those lines are, so that text mixing scripts or sizes can be lined up on one of them. On DAEGUN_OK, *out is a daegun_base_script that holds each baseline the font gives the script, as a daegun_baseline, and names the one its glyphs sit on. Free it with daegun_base_script_free.

script is an OpenType script tag, such as DAEGUN_TAG('l', 'a', 't', 'n') or DAEGUN_TAG('h', 'a', 'n', 'i'), the kind daegun_font_script_tags lists. orientation picks the direction of the line: positions are y values for DAEGUN_HORIZONTAL and x values for DAEGUN_VERTICAL. They are in font units at location, NULL being the default instance, and in a variable font whose BASE varies they move with it.

A script the table has no record for gets the baselines of DFLT, the default script, where the table has that. DAEGUN_ABSENT means there is nothing to give: the font has no BASE table, the table holds nothing for that orientation, neither the script nor DFLT has a record there, or the record found has no baseline values. It is an answer, not a failure. A record whose values list no baseline answers DAEGUN_OK, and its baselines come with a count of 0. Plenty of fonts have no BASE at all, and Inter is one.

DAEGUN_INVALID_ARGUMENT means orientation is neither DAEGUN_HORIZONTAL nor DAEGUN_VERTICAL. Any status but DAEGUN_OK leaves *out NULL.

daegun_tag hani = DAEGUN_TAG('h', 'a', 'n', 'i');
daegun_base_script *han = NULL;
daegun_status status = daegun_font_base_script(font, hani, NULL, DAEGUN_HORIZONTAL, &han);
if (status == DAEGUN_OK) {
    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);
    /* Han characters sit on the ideographic baseline, ideo. Source Han Sans puts it 120 units
       below the roman one: of its four baselines, ideo is at -120 and romn at 0. */
    if (count != 4 || baselines[2].tag != sits_on || baselines[2].position != -120.0) return 1;
} else if (status == DAEGUN_ABSENT) {
    /* The font gives this script no baselines. */
} else {
    return 1;
}
/* Safe either way: `han` is NULL unless the call answered DAEGUN_OK. */
daegun_base_script_free(han);
daegun_base_script_default_baseline
daegun_status daegun_base_script_default_baseline(
    const daegun_base_script *script,
    daegun_tag *out
);

The tag of the baseline the script's glyphs sit on.

Writes a baseline tag to *out, such as DAEGUN_TAG('r', 'o', 'm', 'n') for Latin or DAEGUN_TAG('i', 'd', 'e', 'o') for Han. Its position is in the array daegun_base_script_baselines lends, under the same tag.

DAEGUN_ABSENT means the table names no default baseline for the script. *out is then left as it was.

daegun_tag latn = DAEGUN_TAG('l', 'a', 't', 'n');
daegun_base_script *latin = NULL;
if (daegun_font_base_script(font, latn, NULL, DAEGUN_HORIZONTAL, &latin) != DAEGUN_OK) return 1;

daegun_tag sits_on = 0;
daegun_status status = daegun_base_script_default_baseline(latin, &sits_on);
if (status == DAEGUN_ABSENT) {
    /* The table names none: `sits_on` is still 0. */
} else if (status != DAEGUN_OK) {
    return 1;
}
/* Latin letters in Source Han Sans sit on the roman baseline, romn. */

daegun_base_script_free(latin);
daegun_base_script_baselines
const daegun_baseline *daegun_base_script_baselines(
    const daegun_base_script *script,
    size_t *out_count
);

The script's baselines, each with its tag and position, in tag order.

Returns a borrowed array of daegun_baseline and sets *out_count to its length. The entries are sorted by tag, each tag once. A position is a y value where the baselines were asked for with DAEGUN_HORIZONTAL and an x value with DAEGUN_VERTICAL, in font units.

The array is valid until daegun_base_script_free, and you never free it yourself. NULL comes back, with the count left as it was, only if script or out_count is NULL.

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

size_t count = 0;
const daegun_baseline *baselines = daegun_base_script_baselines(han, &count);
/* Find the roman baseline among them. */
const daegun_baseline *roman = NULL;
for (size_t i = 0; i < count; i++) {
    if (baselines[i].tag == DAEGUN_TAG('r', 'o', 'm', 'n')) roman = &baselines[i];
}
/* Source Han Sans gives Han four baselines, the roman one at 0. */
if (!roman || roman->position != 0.0) return 1;

daegun_base_script_free(han);
daegun_base_script_free
void daegun_base_script_free(daegun_base_script *script);

Frees a script's baselines, and with them the array they lent.

NULL is fine and does nothing, so a cleanup path may free without checking. The array daegun_base_script_baselines gave is invalid afterward.

daegun_tag latn = DAEGUN_TAG('l', 'a', 't', 'n');
daegun_base_script *script = NULL;
daegun_status status = daegun_font_base_script(font, latn, NULL, DAEGUN_HORIZONTAL, &script);
if (status == DAEGUN_OK) {
    /* read the baselines */
}
/* Safe either way. Inter has no BASE table, so the call answered DAEGUN_ABSENT and `script`
   is NULL. */
daegun_base_script_free(script);
  • May be NULL: script.
daegun_font_base_extents
daegun_status daegun_font_base_extents(
    const daegun_font *font,
    daegun_tag script,
    const daegun_location *location,
    int32_t orientation,
    daegun_tag language_system,
    daegun_tag feature,
    daegun_extents *out
);

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

Besides baselines, BASE can record the lowest and highest points a script's glyphs reach, so a layout can give lines of that script the room they need. The call fills a daegun_extents. Its min and max are y values for DAEGUN_HORIZONTAL and x values for DAEGUN_VERTICAL, in font units at location, NULL being the default instance. Either side may be missing, which its has_min or has_max says.

script is an OpenType script tag, and a script with no record takes those of DFLT, as in daegun_font_base_script. language_system is an OpenType language system tag such as DAEGUN_TAG('T', 'R', 'K', ' '), the kind daegun_font_language_system_tags lists, not a BCP 47 language. With one the script has extents for, you get those. With 0, or one it has no record for, you get the script's default extents.

feature is a feature tag, or 0 for none. Where the extents chosen hold a record for that feature, as for one that swaps in taller glyphs, its values replace both sides, and a side the feature's record leaves out comes back with its has_min or has_max false, not the value it replaced. Otherwise they stand.

DAEGUN_ABSENT means the font states no extents here: it has no BASE table, the table holds nothing for that orientation, neither the script nor DFLT has a record there, or the record found has no extents. A font can give a script baselines and no extents, as Source Han Sans does, and then daegun_font_base_script answers while this call does not. DAEGUN_INVALID_ARGUMENT means orientation is neither DAEGUN_HORIZONTAL nor DAEGUN_VERTICAL. Both leave *out as it was.

daegun_tag hani = DAEGUN_TAG('h', 'a', 'n', 'i');
daegun_extents extents;
daegun_status status = daegun_font_base_extents(font, hani, NULL, DAEGUN_HORIZONTAL, 0, 0, &extents);
if (status == DAEGUN_OK) {
    /* extents.min where extents.has_min, extents.max where extents.has_max: the lowest and
       highest y, in font units. */
} else if (status == DAEGUN_ABSENT) {
    /* No extents for the script: go by the font's own line metrics. */
    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;
} else {
    return 1;
}
/* Source Han Sans gives Han baselines and no extents, so status is DAEGUN_ABSENT. */
daegun_font_has_glyph_free_base
daegun_status daegun_font_has_glyph_free_base(
    const daegun_font *font,
    bool *out
);

Whether the font has a BASE table that names no glyph, so the table stays valid when glyphs are renumbered.

A coordinate in BASE is usually a plain number, but the format lets one be tied to a contour point of a glyph, named by its id. A table with such a coordinate goes wrong once the glyphs are renumbered, as a subset renumbers them. The call writes true to *out when the font has a BASE table and every coordinate in it, baselines and extents alike, is a plain number, or a number with a device or variation adjustment. It writes false for a font with no BASE table, and for one with a coordinate in a format daegun doesn't know or a table too tangled to read within its budget.

daegun's own subsets go by it. A subset of a font with TrueType outlines carries BASE over only when this is true, and a CFF font whose BASE names glyphs is subset with its glyph ids left in place. Ask it yourself before copying BASE into a font whose glyphs you have renumbered.

bool glyph_free = false;
if (daegun_font_has_glyph_free_base(font, &glyph_free) != DAEGUN_OK) return 1;
if (glyph_free) {
    /* BASE can go as it is into a font whose glyphs were renumbered. */
}
/* True for Source Han Sans. False for Inter, which has no BASE table. */
daegun_font_script_tags
daegun_status daegun_font_script_tags(
    const daegun_font *font,
    daegun_tag *out,
    size_t out_len,
    size_t *out_count
);

The OpenType script tags the font's layout tables have rules for.

A font's substitution table GSUB and its positioning table GPOS group their rules by script, each named by an OpenType script tag: latn for Latin, arab for Arabic, deva and dev2 for the older and newer ways of shaping Devanagari, DFLT for rules that apply whatever the script. This reads both tables and writes their scripts together into out, sorted and each once. Tags sort as the numbers they are, so DFLT comes before the lowercase tags.

You don't need these to shape text: daegun_font_shape picks the script from the text. They are for showing what a font supports, and for the calls that take a script tag: daegun_font_language_system_tags, daegun_font_feature_tags and daegun_font_base_script.

The count is 0 for a font with neither table, such as one shaped by Apple's morx, and a table too damaged for shaping to use adds nothing. A script in the list means the font has rules for it, not that it has glyphs for its characters: daegun_font_has_glyph answers that.

out is your buffer with room for out_len tags, and *out_count is set to the number of scripts. A NULL out with an out_len of 0 asks for the count alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT with the count set, and writes nothing into it. A buffer that shares bytes with the count answers DAEGUN_INVALID_ARGUMENT too, and leaves the count as it was.

/* Ask how many scripts there are, then fetch them. */
size_t count = 0;
if (daegun_font_script_tags(font, NULL, 0, &count) != DAEGUN_OK) return 1;
daegun_tag *scripts = malloc(count * sizeof *scripts);
if (!scripts) return 1;
if (daegun_font_script_tags(font, scripts, count, &count) != DAEGUN_OK) return 1;
/* Inter has rules for four scripts: DFLT, cyrl, grek and latn, in that order. */
free(scripts);
daegun_font_language_system_tags
daegun_status daegun_font_language_system_tags(
    const daegun_font *font,
    daegun_tag script,
    daegun_tag *out,
    size_t out_len,
    size_t *out_count
);

The OpenType language system tags the font's layout tables have for one script.

Within a script a font can keep different rules for different languages. Turkish tells a dotted i from a dotless one, so an fi ligature that swallows the dot must not form. Serbian italics use other letter shapes than Russian ones. Each such set of rules is a language system, and this writes the tags of the ones GSUB and GPOS have for script into out, sorted and each once.

An OpenType language system tag is not a BCP 47 language tag. BCP 47 is what the web and operating systems write: tr, ro, sr-Latn. OpenType has its own list of tags in capitals, most of them three letters and a space: TRK for Turkish, ROM for Romanian, SRB for Serbian. The language of a daegun_shape_options takes the BCP 47 form, and shaping finds the font's language system for you. This call and daegun_font_feature_tags deal in the OpenType tags as the font stores them, the space included, so write DAEGUN_TAG('T', 'R', 'K', ' ').

A script's default language system, the one used when no language is asked for or the language has no rules of its own, has no tag and is not in the list. A font that also tags a record dflt lists that tag, and that record serves as the default. So a count of 0 means the script has its default alone, or that the font has no such script. script must be one the font lists: a script it doesn't have, 0 among them, gives a count of 0, with no falling back to DFLT.

out is your buffer with room for out_len tags, and *out_count is set to the number of language systems. A NULL out with an out_len of 0 asks for the count alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT with the count set, and writes nothing into it. A buffer that shares bytes with the count answers DAEGUN_INVALID_ARGUMENT too, and leaves the count as it was.

daegun_tag latn = DAEGUN_TAG('l', 'a', 't', 'n');
daegun_tag languages[32];
size_t count = 0;
if (daegun_font_language_system_tags(font, latn, languages, 32, &count) != DAEGUN_OK) return 1;
/* Inter keeps Latin rules of their own for three languages: CAT, MOL and ROM, which are
   Catalan, Moldavian and Romanian. */

/* Its Cyrillic has the default language system and no other. */
daegun_tag cyrl = DAEGUN_TAG('c', 'y', 'r', 'l');
if (daegun_font_language_system_tags(font, cyrl, languages, 32, &count) != DAEGUN_OK) return 1;
daegun_font_feature_tags
daegun_status daegun_font_feature_tags(
    const daegun_font *font,
    daegun_tag script,
    daegun_tag language_system,
    daegun_tag *out,
    size_t out_len,
    size_t *out_count
);

The OpenType features the font offers a script and language system.

A feature is a named set of rules in GSUB or GPOS, with a four-letter tag: kern for kerning, liga for ligatures, smcp for small caps, ss01 for the first stylistic set. This writes the features both tables hold for one script and language system into out, sorted and each once. Use it to build a feature picker, or to check that a feature is there before you turn it on with a daegun_feature.

script is an OpenType script tag, one that daegun_font_script_tags lists. A script the font does not have gives a count of 0. A script of 0 stands for the script shaping falls back to when the font has no rules for the text's own script: the first the table has of DFLT, dflt and latn. Each of the two tables is read by itself, so each falls back on its own.

language_system is an OpenType language system tag such as DAEGUN_TAG('R', 'O', 'M', ' '), as daegun_font_language_system_tags lists them, not a BCP 47 language. 0, or a tag the script has no record for, gives the features of the script's default language system. Where a font tags a record dflt, that record is taken as the default.

The list holds the features that are on by default and the optional ones alike, the language system's required feature among them, and does not say which are which. The count is 0 for a font with neither table.

out is your buffer with room for out_len tags, and *out_count is set to the number of features. A NULL out with an out_len of 0 asks for the count alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT with the count set, and writes nothing into it. A buffer that shares bytes with the count answers DAEGUN_INVALID_ARGUMENT too, and leaves the count as it was.

daegun_tag latn = DAEGUN_TAG('l', 'a', 't', 'n');
/* What Inter offers Latin text in its default language system: ask for the count, then the tags. */
size_t count = 0;
if (daegun_font_feature_tags(font, latn, 0, NULL, 0, &count) != DAEGUN_OK) return 1;
daegun_tag *features = malloc(count * sizeof *features);
if (!features) return 1;
if (daegun_font_feature_tags(font, latn, 0, features, count, &count) != DAEGUN_OK) return 1;

bool has_tnum = false, has_smcp = false;
for (size_t i = 0; i < count; i++) {
    if (features[i] == DAEGUN_TAG('t', 'n', 'u', 'm')) has_tnum = true;
    if (features[i] == DAEGUN_TAG('s', 'm', 'c', 'p')) has_smcp = true;
}
/* 42 features. Tabular figures are among them, and small caps are not. */
if (!has_tnum || has_smcp) return 1;
free(features);

/* Romanian has one feature more: locl, the forms a language prefers. */
size_t romanian = 0;
daegun_tag rom = DAEGUN_TAG('R', 'O', 'M', ' ');
if (daegun_font_feature_tags(font, latn, rom, NULL, 0, &romanian) != DAEGUN_OK) return 1;

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_table_map_build
daegun_status daegun_table_map_build(
    const daegun_table_map *map,
    daegun_blob **out
);

Writes the tables of a table map out as a font file.

The call a font tool comes to raw.h for: take the tables out of a font, change or drop some, and build a file again. The file opens with its 12-byte header and a directory of 16 bytes a table, in tag order as the spec sorts it. Each table follows at an offset that is a multiple of four, padded with zero bytes up to the next, and its directory entry holds its checksum. Where the map has a head of 12 bytes or more, head's checkSumAdjustment, the 4 bytes at its offset 8, is set so the 32-bit words of the whole file sum to 0xB1B0AFBA, as the spec asks, and head's own checksum is taken with that field as 0. The header starts with OTTO where the map holds a CFF or CFF2 table, and with 00 01 00 00 otherwise. So a map with both glyf and CFF outlines builds an OTTO file, and a font opened from it reads the CFF alone: daegun_font_table finds no glyf or loca in it.

The tables go in as the map holds them. No tag and no byte is checked, so whether the file opens as a font is up to what you put in. An empty map builds a blob of 0 bytes and answers DAEGUN_OK, and that is no font: daegun_font_open refuses it.

The file comes back in a daegun_blob of your own. daegun_blob_data lends its bytes and daegun_blob_free frees them. They are a copy, so the map may be changed or freed while you keep the blob. daegun_font_open copies them again, so the blob may go as soon as the font is open.

DAEGUN_INVALID_ARGUMENT is for what a font's directory can't state: more than 65,535 tables, a table of 4 GiB or more, or one that would start 4 GiB or more into the file. The reason is in daegun_last_error, and on any failure *out is NULL. The map is only read, so several threads may build from one map at once, as long as none changes it.

/* Every table Inter stores, less GPOS, as a new font file. */
daegun_tag tags[64];
size_t count = 0;
if (daegun_font_table_tags(font, tags, 64, &count) != DAEGUN_OK) return 1;
daegun_table_map *map = daegun_table_map_new();
for (size_t i = 0; i < count; i++) {
    daegun_bytes table;
    if (daegun_font_table(font, tags[i], &table) != DAEGUN_OK) continue;
    if (daegun_table_map_set(map, tags[i], table.data, table.len) != DAEGUN_OK) return 1;
}
if (daegun_table_map_remove(map, DAEGUN_TAG('G', 'P', 'O', 'S')) != DAEGUN_OK) return 1;

daegun_blob *file = NULL;
if (daegun_table_map_build(map, &file) != DAEGUN_OK) return 1;
daegun_table_map_free(map);
size_t size = 0;
const uint8_t *bytes = daegun_blob_data(file, &size);
/* The file's 32-bit words sum to 0xB1B0AFBA, as head's checkSumAdjustment makes them. */

/* Open it as any other font. The blob may go once it is open. */
daegun_font *rebuilt = NULL;
if (daegun_font_open(bytes, size, &rebuilt) != DAEGUN_OK) return 1;
daegun_blob_free(file);
daegun_shaped_run *run = NULL;
double width = 0.0;
if (daegun_font_shape(rebuilt, "Wave", 4, NULL, NULL, &run) != DAEGUN_OK) return 1;
if (daegun_shaped_run_width(run, &width) != DAEGUN_OK) return 1;
/* 5513 units: kerning lived in GPOS, and Inter kerns "Wave" to 5339. */
daegun_shaped_run_free(run);
daegun_font_free(rebuilt);
daegun_parse_loca
daegun_status daegun_parse_loca(
    const uint8_t *loca,
    size_t loca_len,
    int16_t format,
    size_t num_glyphs,
    size_t *out,
    size_t out_len,
    size_t *out_count
);

Reads loca: where each glyph's data starts and ends in glyf, as byte offsets.

The loca table says where in glyf each glyph lies. It holds an offset for every glyph and one more for the end, so glyph g takes bytes out[g] up to out[g + 1] of glyf, and a glyph whose two offsets are equal, such as a space, has no outline. The offsets go into your buffer as size_t, the form daegun_outline_glyf_bytes takes.

format is head's indexToLocFormat, the int16 at byte 50 of head. 0 is the short form, where loca stores each offset halved in 16 bits and the call doubles it back. Any other value reads the long form of 32-bit offsets, the one the spec numbers 1. num_glyphs is the font's glyph count, as daegun_font_glyph_count gives it.

The call answers num_glyphs + 1 offsets, so room for that many always suffices. Past 65,535 glyphs it answers no more than the entries loca holds, or 65,536 where it holds fewer, so a wrong count cannot ask for an answer bigger than the table. An entry past the end of loca reads 0. Nothing in loca can make the call fail.

out is your buffer with room for out_len offsets, and a NULL buffer with a length of 0 asks for the count alone. *out_count is set to the count whenever the call answers DAEGUN_OK or finds the buffer too small. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes no offset. A buffer that overlaps loca or the count answers the same and writes neither an offset nor the count.

daegun_bytes head, loca;
if (daegun_font_table(font, DAEGUN_TAG('h', 'e', 'a', 'd'), &head) != DAEGUN_OK) return 1;
if (daegun_font_table(font, DAEGUN_TAG('l', 'o', 'c', 'a'), &loca) != DAEGUN_OK) return 1;
int16_t format = 0;
if (daegun_read_i16_be(head.data, head.len, 50, &format) != DAEGUN_OK) return 1;
uint32_t glyphs = 0;
if (daegun_font_glyph_count(font, &glyphs) != DAEGUN_OK) return 1;

size_t *offsets = malloc(((size_t)glyphs + 1) * sizeof *offsets);
size_t count = 0;
if (!offsets) return 1;
if (daegun_parse_loca(loca.data, loca.len, format, glyphs, offsets, (size_t)glyphs + 1, &count) != DAEGUN_OK)
    return 1;
/* Inter is in the long form, format 1: 2938 offsets for its 2937 glyphs. A space has no outline, so
   its glyph starts and ends at one offset. */
uint32_t space = 0;
if (daegun_font_glyph_id(font, ' ', &space) != DAEGUN_OK) return 1;
free(offsets);
daegun_outline_glyf_bytes
daegun_status daegun_outline_glyf_bytes(
    const uint8_t *glyf,
    size_t glyf_len,
    bool extended,
    const size_t *loca,
    size_t loca_len,
    uint32_t gid,
    const daegun_pen *pen
);

Draws a glyph onto a pen straight from glyf bytes and the offsets loca gives, with no font open.

For a tool that holds the tables but no font, or has changed glyf and wants to see the result. loca is the offsets daegun_parse_loca reads, loca_len of them, and gid the glyph to draw. A composite glyph, one built of other glyphs placed and transformed, is drawn with its components resolved.

The outline reaches the pen as daegun_font_outline would send it: in font units, y up, through move_to, line_to, quad_to and close. It is the glyph as glyf stores it, with no variation applied, so a variable font's glyph comes out in its default design.

extended is for the bytes of GLYF, the draft table for fonts past 65,535 glyphs. Its composites may name a component in 24 bits, and its points may be cubic controls, which reach the pen through curve_to. Pass false for glyf.

DAEGUN_NO_OUTLINE means gid is past the glyphs the offsets reach: gid + 1 is not below loca_len. A glyph whose range is empty, runs backward or runs past the end of glyf draws nothing and answers DAEGUN_OK. DAEGUN_MALFORMED is for a glyph that doesn't decode: its header or points are cut short, a composite holds itself or names a glyph the offsets don't reach or a point its component lacks, or the outline holds more points or contours than one can. DAEGUN_LIMIT_EXCEEDED is for a composite that asks for more work than daegun allows one glyph. The reason is in daegun_last_error. A failure may come after the pen has had part of the outline.

The pen is handled as daegun_pen says: its callbacks run on the calling thread before the call returns, and nothing of it is kept.

daegun_bytes head, loca, glyf;
if (daegun_font_table(font, DAEGUN_TAG('h', 'e', 'a', 'd'), &head) != DAEGUN_OK) return 1;
if (daegun_font_table(font, DAEGUN_TAG('l', 'o', 'c', 'a'), &loca) != DAEGUN_OK) return 1;
if (daegun_font_table(font, DAEGUN_TAG('g', 'l', 'y', 'f'), &glyf) != DAEGUN_OK) return 1;
int16_t format = 0;
uint32_t glyphs = 0;
if (daegun_read_i16_be(head.data, head.len, 50, &format) != DAEGUN_OK) return 1;
if (daegun_font_glyph_count(font, &glyphs) != DAEGUN_OK) return 1;
size_t *offsets = malloc(((size_t)glyphs + 1) * sizeof *offsets);
size_t count = 0;
if (!offsets) return 1;
if (daegun_parse_loca(loca.data, loca.len, format, glyphs, offsets, (size_t)glyphs + 1, &count) != DAEGUN_OK)
    return 1;

/* Draw Inter's A into a path. */
uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'A', &gid) != DAEGUN_OK) return 1;
daegun_path *path = daegun_path_new();
daegun_pen pen;
if (daegun_path_as_pen(path, &pen) != DAEGUN_OK) return 1;
if (daegun_outline_glyf_bytes(glyf.data, glyf.len, false, offsets, count, gid, &pen) != DAEGUN_OK) return 1;
daegun_bounds box;
if (daegun_path_bounds(path, &box) != DAEGUN_OK) return 1;
/* It spans 52 to 1361 across and 0 to 1490 up, the outline daegun_font_outline draws. */
daegun_path_free(path);
free(offsets);
  • May be NULL: glyf where glyf_len is 0, loca where loca_len is 0.
  • Answers: DAEGUN_OK, DAEGUN_NULL, or the failure its text names.
daegun_read_u16_be
daegun_status daegun_read_u16_be(
    const uint8_t *data,
    size_t len,
    size_t off,
    uint16_t *out
);

Reads the big-endian unsigned 16-bit number at byte off of some bytes.

The five daegun_read_ calls read a number at off, big-endian, which is how fonts store numbers, and write it to *out. A read never goes past len bytes. One that would, wherever off lies, up to SIZE_MAX, answers DAEGUN_INVALID_ARGUMENT, leaves *out as it was and puts the reason in daegun_last_error. So an offset read from a font may be passed as it is, without checking it first.

data may be NULL with a len of 0. Every read of no bytes runs past the end.

daegun_bytes head;
if (daegun_font_table(font, DAEGUN_TAG('h', 'e', 'a', 'd'), &head) != DAEGUN_OK) return 1;
uint16_t upem = 0;
if (daegun_read_u16_be(head.data, head.len, 18, &upem) != DAEGUN_OK) return 1;
/* head keeps the units per em at byte 18: 2048 for Inter. */

uint16_t past = 7;
daegun_status status = daegun_read_u16_be(head.data, head.len, head.len - 1, &past);
/* One byte from the end there is no room for 2: DAEGUN_INVALID_ARGUMENT, and past is still 7. */
daegun_read_i16_be
daegun_status daegun_read_i16_be(
    const uint8_t *data,
    size_t len,
    size_t off,
    int16_t *out
);

Reads the big-endian signed 16-bit number at byte off of some bytes.

The two bytes are read as two's complement, as fonts store an int16 or FWORD: FF FE is -2. A read that would run past len bytes answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

daegun_bytes hhea;
if (daegun_font_table(font, DAEGUN_TAG('h', 'h', 'e', 'a'), &hhea) != DAEGUN_OK) return 1;
int16_t descender = 0;
if (daegun_read_i16_be(hhea.data, hhea.len, 6, &descender) != DAEGUN_OK) return 1;
/* hhea keeps the descender at byte 6. Inter stores FE 12 there, which reads as -494. */
daegun_read_u24_be
daegun_status daegun_read_u24_be(
    const uint8_t *data,
    size_t len,
    size_t off,
    uint32_t *out
);

Reads the big-endian unsigned 24-bit number at byte off of some bytes, into a uint32_t.

Three bytes, for the fields fonts keep in 24 bits: glyph ids past 65,535, as Coverage tables of formats 3 and 4 store them, and Offset24 fields. A read that would run past len bytes answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

daegun_read_offset24 reads the same three bytes to the same number. It differs only in its out, a size_t, ready to add to a position.

/* A Coverage table of format 3, whose count and glyphs are 24-bit: two glyphs, 65536 and 65541. */
static const uint8_t coverage[11] = { 0, 3, 0, 0, 2, 1, 0, 0, 1, 0, 5 };
uint32_t count = 0, first = 0;
if (daegun_read_u24_be(coverage, sizeof coverage, 2, &count) != DAEGUN_OK) return 1;
if (daegun_read_u24_be(coverage, sizeof coverage, 5, &first) != DAEGUN_OK) return 1;
/* count is 2 and first is 65536, more than 16 bits hold. */
daegun_read_u32_be
daegun_status daegun_read_u32_be(
    const uint8_t *data,
    size_t len,
    size_t off,
    uint32_t *out
);

Reads the big-endian unsigned 32-bit number at byte off of some bytes.

For a uint32, an Offset32, a tag or a Fixed read as its raw bits. A read that would run past len bytes answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

daegun_bytes head;
if (daegun_font_table(font, DAEGUN_TAG('h', 'e', 'a', 'd'), &head) != DAEGUN_OK) return 1;
uint32_t magic = 0;
if (daegun_read_u32_be(head.data, head.len, 12, &magic) != DAEGUN_OK) return 1;
/* Every head holds the magic number 0x5F0F3CF5 at byte 12. */
daegun_read_offset24
daegun_status daegun_read_offset24(
    const uint8_t *data,
    size_t len,
    size_t off,
    size_t *out
);

Reads the big-endian 24-bit offset at byte off of some bytes, into a size_t.

It reads the same three bytes to the same number as daegun_read_u24_be. Only the out differs: a size_t, so the offset adds to a position with no cast. A read that would run past len bytes answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

daegun_bytes colr;
if (daegun_font_table(font, DAEGUN_TAG('C', 'O', 'L', 'R'), &colr) != DAEGUN_OK) return 1;
/* COLR keeps its ClipList's offset at byte 22. Byte 9 of the list holds the first clip's Offset24 to
   its box, counted from the list's start. */
uint32_t list = 0;
if (daegun_read_u32_be(colr.data, colr.len, 22, &list) != DAEGUN_OK) return 1;
size_t box = 0;
if (daegun_read_offset24(colr.data, colr.len, (size_t)list + 9, &box) != DAEGUN_OK) return 1;
/* The box starts at list + box in COLR: 96 bytes into the list, in this font. */
daegun_write_u16_be
daegun_status daegun_write_u16_be(
    uint8_t *data,
    size_t len,
    size_t off,
    uint16_t value
);

Writes an unsigned 16-bit number big-endian at byte off of a buffer.

The four daegun_write_ calls store a number as fonts do, most significant byte first. A write that would run past len bytes, wherever off lies, answers DAEGUN_INVALID_ARGUMENT, writes nothing at all and puts the reason in daegun_last_error. data may be NULL with a len of 0, and every write of it runs past the end.

/* A Coverage table of format 1 that lists glyphs 3 and 7: its format, its count, then the glyphs. */
uint8_t coverage[8];
const uint16_t fields[4] = { 1, 2, 3, 7 };
for (size_t i = 0; i < 4; i++) {
    if (daegun_write_u16_be(coverage, sizeof coverage, 2 * i, fields[i]) != DAEGUN_OK) return 1;
}
uint32_t index = 0;
if (daegun_coverage_index(coverage, sizeof coverage, 7, &index) != DAEGUN_OK) return 1;
/* index is 1. A write one byte from the end is refused and leaves the byte there as it was. */
daegun_status status = daegun_write_u16_be(coverage, sizeof coverage, 7, 0xFFFF);
daegun_write_i16_be
daegun_status daegun_write_i16_be(
    uint8_t *data,
    size_t len,
    size_t off,
    int16_t value
);

Writes a signed 16-bit number big-endian, in two's complement, at byte off of a buffer.

A write that would run past len bytes answers DAEGUN_INVALID_ARGUMENT and writes nothing.

uint8_t field[2];
if (daegun_write_i16_be(field, sizeof field, 0, -40) != DAEGUN_OK) return 1;
/* The bytes are FF D8. */
daegun_write_u32_be
daegun_status daegun_write_u32_be(
    uint8_t *data,
    size_t len,
    size_t off,
    uint32_t value
);

Writes an unsigned 32-bit number big-endian at byte off of a buffer.

A write that would run past len bytes answers DAEGUN_INVALID_ARGUMENT and writes nothing, not even the bytes that would fit.

/* The start of a font file's header: its version, 00 01 00 00 for TrueType outlines, and 3 tables. */
uint8_t header[12] = { 0 };
if (daegun_write_u32_be(header, sizeof header, 0, 0x00010000) != DAEGUN_OK) return 1;
if (daegun_write_u16_be(header, sizeof header, 4, 3) != DAEGUN_OK) return 1;
daegun_write_offset24
daegun_status daegun_write_offset24(
    uint8_t *data,
    size_t len,
    size_t off,
    size_t value
);

Writes an offset of up to 24 bits big-endian in the three bytes at byte off of a buffer.

DAEGUN_INVALID_ARGUMENT, writing nothing, where the three bytes would run past len, or where value is 0x1000000 or more and so needs more than 24 bits. The reason is in daegun_last_error.

uint8_t field[3] = { 0 };
if (daegun_write_offset24(field, sizeof field, 0, 0x123456) != DAEGUN_OK) return 1;
/* The bytes are 12 34 56. An offset past 24 bits doesn't fit, and is refused with nothing written. */
daegun_status status = daegun_write_offset24(field, sizeof field, 0, 0x1000000);
daegun_records_fit
bool daegun_records_fit(
    size_t start,
    size_t count,
    size_t stride,
    size_t len
);

Whether count records of stride bytes each, from byte start on, lie within len bytes.

The check a table reader makes before it walks an array the font describes. A count and a start read from a font are not to be trusted, and start + count * stride can overflow size_t and wrap round to a small number that looks in range. This call does both the product and the sum with overflow checked, and answers false where either overflows. Once it answers true, record i of the count lies at start + i * stride, inside the data, and reading the records needs no more bounds checks.

A count of 0 fits wherever start is at most len.

/* A font file's directory: numTables at byte 4, then that many records of 16 bytes from byte 12. */
uint16_t tables = 0;
if (daegun_read_u16_be(data, len, 4, &tables) != DAEGUN_OK) return 1;
if (!daegun_records_fit(12, tables, 16, len)) return 1;
/* Inter's 19 records fit. A count of SIZE_MAX / 16 + 1 does not, though times 16 it wraps to 0 in size_t
   and 12 + count * 16 comes to 12. */
size_t hostile = SIZE_MAX / 16 + 1;
bool fits = daegun_records_fit(12, hostile, 16, len);
daegun_bytes_window
const uint8_t *daegun_bytes_window(
    const uint8_t *data,
    size_t len,
    size_t off,
    size_t n
);

A pointer to the n bytes at off of some bytes, or NULL where they do not all lie within len.

One bounds check, with off + n checked for overflow, after which the n bytes from the pointer may be indexed directly, as a record of fixed fields is read. The pointer is borrowed from data: nothing is copied, and it is valid for as long as data is.

A window of 0 bytes is fine at any off up to len, and points at data + off. NULL data gives NULL.

/* The first record of a font file's directory: 16 bytes from byte 12, a tag, a checksum, an offset and a
   length. After the one check, read them in place. */
const uint8_t *record = daegun_bytes_window(data, len, 12, 16);
if (!record) return 1;
/* record[0] to record[3] are the tag: GDEF, the first table of Inter. */

/* 16 bytes from 8 before the end don't fit, so there is no window. */
const uint8_t *past = daegun_bytes_window(data, len, len - 8, 16);
daegun_search_records
daegun_status daegun_search_records(
    size_t count,
    uint32_t target,
    bool (*key_at)(void *user, size_t index, uint32_t *out_key),
    void *user,
    size_t *out_index,
    bool *out_found
);

A binary search of records sorted by a 32-bit key, with the reading of each key left to you.

Many tables end in an array of records sorted by a key, such as a glyph id or a tag, and finding one is a binary search. key_at reads the keys. It is handed user, as you passed it, and the index of a record below count. It writes that record's key to *out_key and returns true, or returns false where the record doesn't read, as where it would lie past the end of the data.

On DAEGUN_OK, *out_found says whether a record's key equals target. If one does, *out_index is that record. If none does, it is where target would go to keep the order: the first record with a larger key, or count after them all. A count of 0 calls nothing and answers not found, at 0.

The records must be sorted by key, smallest first. The search reads one key at each step of halving, about log2(count) of them, so it cannot tell when the records are out of order and answers from what it read. Where several records hold the target key, it stops at the first of them it reads, which need not be the first in the array.

The first time key_at returns false the search stops and answers DAEGUN_ABSENT, leaving both outs as they were.

key_at runs on the calling thread, only during this call, and nothing of it is kept afterward. It must return normally: a longjmp or a C++ exception out of it, or ending the thread inside it, is undefined behavior. Declare a C++ one noexcept, and mark it DAEGUN_CALLBACK where your build changes the default calling convention, as /Gv and /Gz do under MSVC.

/* A font file's directory, sorted by tag: record i is 16 bytes at 12 + 16 * i, its tag first. */
struct directory { const uint8_t *data; size_t len; };

static bool tag_at(void *user, size_t index, uint32_t *out_key)
{
    const struct directory *dir = user;
    return daegun_read_u32_be(dir->data, dir->len, 12 + 16 * index, out_key) == DAEGUN_OK;
}
uint16_t tables = 0;
if (daegun_read_u16_be(data, len, 4, &tables) != DAEGUN_OK) return 1;
struct directory dir = { data, len };
size_t index = 0;
bool found = false;
if (daegun_search_records(tables, DAEGUN_TAG('h', 'e', 'a', 'd'), tag_at, &dir, &index, &found) != DAEGUN_OK)
    return 1;
/* found is true and index is 12: head is the 13th table of Inter's directory. */
daegun_ot_round
int32_t daegun_ot_round(double value);

Rounds as the OpenType spec is written: floor(value + 0.5), so a half always goes up.

Ties go toward positive infinity: 0.5 rounds to 1, -0.5 to 0, 1.5 to 2 and -1.5 to -1. C's round takes ties away from zero instead and gives -1 and -2 for the last pair, so it lands one unit off wherever a value below zero falls on a half. This is the rounding gvar points and cvar deltas are compiled with, so use it to match the numbers a font was built from.

A value below the range of int32_t answers INT32_MIN, one above it INT32_MAX, and NaN answers 0.

int32_t a = daegun_ot_round(0.5), b = daegun_ot_round(-0.5);
int32_t c = daegun_ot_round(1.5), d = daegun_ot_round(-1.5);
/* 1, 0, 2 and -1. C's round() gives -1.0 for -0.5 and -2.0 for -1.5. */
daegun_coverage_index
daegun_status daegun_coverage_index(
    const uint8_t *data,
    size_t len,
    uint32_t glyph,
    uint32_t *out
);

A glyph's index in a Coverage table: its place in the list of glyphs the table covers.

A Coverage table lists the glyphs a GSUB or GPOS subtable applies to, and a glyph's index in it picks that glyph's row in the subtable's own arrays. data starts at the Coverage table itself, so pass the table's bytes from its offset on. It reads formats 1 and 2, a sorted list of glyphs and a list of ranges, and formats 3 and 4, the same with 24-bit glyph ids.

DAEGUN_ABSENT means the table does not cover the glyph, and leaves *out as it was. The same comes back for bytes that are no Coverage table: too short to hold the header, or a format other than 1 to 4. A table cut short answers from the records that fit.

It searches by halving, as the records are meant to be sorted by glyph, so a table with its glyphs out of order may miss one it lists. In a range, the index is the range's start index plus the glyph's distance into it, and it may pass 65,535.

daegun_bytes gpos;
if (daegun_font_table(font, DAEGUN_TAG('G', 'P', 'O', 'S'), &gpos) != DAEGUN_OK) return 1;
/* The Coverage of the first lookup's first subtable. GPOS names its LookupList at byte 8, the list its
   first Lookup at byte 2, the Lookup its first subtable at byte 6, and the subtable its Coverage at byte 2,
   each an Offset16 from the start of the table it is read in. */
static const size_t field[4] = { 8, 2, 6, 2 };
size_t at = 0;
for (size_t i = 0; i < 4; i++) {
    uint16_t offset = 0;
    if (daegun_read_u16_be(gpos.data, gpos.len, at + field[i], &offset) != DAEGUN_OK) return 1;
    at += offset;
}
uint32_t gid = 0, index = 0;
if (daegun_font_glyph_id(font, 'B', &gid) != DAEGUN_OK) return 1;
if (daegun_coverage_index(gpos.data + at, gpos.len - at, gid, &index) != DAEGUN_OK) return 1;
/* Inter's B is at index 62. A lowercase a is not covered: DAEGUN_ABSENT. */
if (daegun_font_glyph_id(font, 'a', &gid) != DAEGUN_OK) return 1;
daegun_status status = daegun_coverage_index(gpos.data + at, gpos.len - at, gid, &index);
daegun_coverage_glyphs
daegun_status daegun_coverage_glyphs(
    const uint8_t *data,
    size_t len,
    size_t off,
    uint32_t *out,
    size_t out_len,
    size_t *out_count
);

Every glyph a Coverage table covers, in the order the table lists them.

Unlike daegun_coverage_index, this takes the bytes the table sits in and its offset off there. A range comes out glyph by glyph: one range of format 2 can give 65,536 glyphs, and one of format 4 16,777,216, so ask for the count first. The glyphs come in table order, which for a well-made table is ascending. The list of a format 1 or 3 table is given as stored, without checking its order.

out is your buffer with room for out_len glyphs, and a NULL buffer with a length of 0 asks for the count alone. *out_count is set to it whenever the call answers DAEGUN_OK or finds the buffer too small. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes no glyph. A buffer that overlaps data or the count answers the same and sets neither.

DAEGUN_MALFORMED where the table doesn't parse: it is cut short, off lies past the data, or its ranges end before they start, overlap or go backward. DAEGUN_UNSUPPORTED for a format other than 1 to 4. Neither sets the count, and the reason is in daegun_last_error.

daegun_bytes gpos;
if (daegun_font_table(font, DAEGUN_TAG('G', 'P', 'O', 'S'), &gpos) != DAEGUN_OK) return 1;
/* The Coverage of the first lookup's first subtable, found as daegun_coverage_index shows. */
static const size_t field[4] = { 8, 2, 6, 2 };
size_t at = 0;
for (size_t i = 0; i < 4; i++) {
    uint16_t offset = 0;
    if (daegun_read_u16_be(gpos.data, gpos.len, at + field[i], &offset) != DAEGUN_OK) return 1;
    at += offset;
}
size_t count = 0;
if (daegun_coverage_glyphs(gpos.data, gpos.len, at, NULL, 0, &count) != DAEGUN_OK) return 1;
uint32_t *glyphs = malloc(count * sizeof *glyphs);
if (!glyphs) return 1;
if (daegun_coverage_glyphs(gpos.data, gpos.len, at, glyphs, count, &count) != DAEGUN_OK) return 1;
/* 621 glyphs from the 15 ranges the table stores, glyph 2, Inter's A, first. */
free(glyphs);
daegun_aat_lookup_parse
daegun_status daegun_aat_lookup_parse(
    const uint8_t *data,
    size_t len,
    uint32_t num_glyphs,
    daegun_aat_lookup **out
);

Reads an AAT lookup table from bytes, keeping a copy of them.

data starts at the lookup table, so pass the bytes from its offset on. Where its size is not known, pass them to the end of the table that holds it. num_glyphs is the font's glyph count: a format 0 table stores a value for every glyph and says nothing of its own length, so this is where its array ends.

The handle copies all len bytes, so data may be freed or reused as soon as the call returns. Free the handle with daegun_aat_lookup_free.

Only the format is checked here. DAEGUN_MALFORMED means the bytes are too short to name one, under 2 of them, and DAEGUN_UNSUPPORTED that it is none of 0, 2, 4, 6, 8 and 10. A table cut short after its format parses, and the values it lost read as absent. On failure *out is NULL, with the reason in daegun_last_error.

/* The body of TestMORXOne's one subtable, a lookup, as daegun_aat_lookup 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_lookup *lookup = NULL;
daegun_status status = daegun_aat_lookup_parse(morx.data + body, morx.len - body, glyphs, &lookup);
if (status != DAEGUN_OK) {
    fprintf(stderr, "%s\n", daegun_last_error().data);
    return 1;
}
/* The lookup holds its own copy: the font's bytes are no longer needed. */
daegun_aat_lookup_free(lookup);
daegun_aat_lookup_value
daegun_status daegun_aat_lookup_value(
    const daegun_aat_lookup *lookup,
    uint32_t glyph,
    uint16_t *out
);

The value a lookup maps a glyph to.

DAEGUN_ABSENT where the lookup maps nothing to the glyph, leaving *out as it was: no range or entry holds it, it is past a format 0 table's num_glyphs, its value lies past the bytes, the table's units are smaller than its format needs, or in format 10 its unit is not 1, 2, 4 or 8 bytes or its value is wider than 16 bits.

Each call parses the handle's copy again. It parsed once already, when the handle was made, so the DAEGUN_MALFORMED or DAEGUN_UNSUPPORTED a parse can answer does not come back here.

/* A format 8 table: from glyph 5 on, two glyphs, mapped to 50 and 60. */
static const uint8_t bytes[10] = { 0, 8, 0, 5, 0, 2, 0, 50, 0, 60 };
daegun_aat_lookup *lookup = NULL;
if (daegun_aat_lookup_parse(bytes, sizeof bytes, 100, &lookup) != DAEGUN_OK) return 1;
uint16_t value = 0;
if (daegun_aat_lookup_value(lookup, 6, &value) != DAEGUN_OK) return 1;
/* value is 60. Glyph 7 is past the array: DAEGUN_ABSENT, and value keeps its 60. */
daegun_status status = daegun_aat_lookup_value(lookup, 7, &value);
daegun_aat_lookup_free(lookup);
daegun_aat_lookup_entries
daegun_status daegun_aat_lookup_entries(
    const daegun_aat_lookup *lookup,
    daegun_glyph_value *out,
    size_t out_len,
    size_t *out_count
);

Every glyph a lookup maps, with its value, in glyph order.

Fills your buffer with daegun_glyph_value pairs. Each glyph comes once, in ascending order, even where the ranges of the table overlap, with the value daegun_aat_lookup_value answers for it. A glyph whose value does not read is left out, and so is glyph 0xFFFF in formats 2, 4 and 6. There are never more than 65,536: a glyph past 65,535, which a format 0 table given a larger num_glyphs can map, is not listed.

out has room for out_len pairs, and a NULL buffer with a length of 0 asks for the count alone. *out_count is set whenever the call answers DAEGUN_OK or finds the buffer too small. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes no pair. A buffer that overlaps the count answers the same and sets neither.

The copy is parsed again on each call, and it parsed when the handle was made, so the DAEGUN_MALFORMED or DAEGUN_UNSUPPORTED of a parse does not come back here.

/* The lookup in TestMORXOne's one subtable, as daegun_aat_lookup 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_lookup *lookup = NULL;
if (daegun_aat_lookup_parse(morx.data + body, morx.len - body, glyphs, &lookup) != DAEGUN_OK) return 1;

daegun_glyph_value pairs[16];
size_t count = 0;
if (daegun_aat_lookup_entries(lookup, pairs, 16, &count) != DAEGUN_OK) return 1;
/* Two pairs: glyph 2 becomes 5 and glyph 4 becomes 7. */
daegun_aat_lookup_free(lookup);
daegun_aat_lookup_free
void daegun_aat_lookup_free(daegun_aat_lookup *lookup);

Frees a lookup.

NULL is fine and does nothing, so a cleanup path may free without checking. A freed lookup whose copy takes 64 KiB or less is kept, emptied, for this thread's next daegun_aat_lookup_parse, so a loop that parses and frees one allocates once. daegun_thread_release lets go of it.

static const uint8_t bytes[10] = { 0, 8, 0, 5, 0, 2, 0, 50, 0, 60 };
daegun_aat_lookup *lookup = NULL;
daegun_status status = daegun_aat_lookup_parse(bytes, sizeof bytes, 100, &lookup);
if (status == DAEGUN_OK) {
    /* read the lookup */
}
/* Safe either way: a parse that fails leaves `lookup` NULL. */
daegun_aat_lookup_free(lookup);
  • May be NULL: lookup.
daegun_aat_state_table_parse
daegun_status daegun_aat_state_table_parse(
    const uint8_t *data,
    size_t len,
    size_t extra_words,
    uint32_t num_glyphs,
    daegun_aat_state_table **out
);

Reads an extended AAT state table from bytes, keeping a copy of them.

data starts at the state table, which in a morx subtable is the body after the subtable's 12-byte header. It opens with the class count and the offsets of the class table, the state array and the entry table, each 32 bits and counted from data. Pass the bytes to the end of the subtable, or of morx: the parts are found by their offsets.

extra_words is how many 16-bit words each entry holds after its new state and flags. The subtable's type decides it and the table doesn't say: 0 for rearrangement, 1 for ligature, 2 for contextual and insertion, and 1 for the state tables of kerx. With the wrong number the entries read wrong. More than 2 is taken too: the entries are found at that size, and daegun_aat_entry holds the first two words. num_glyphs is the font's glyph count, which bounds a class table of format 0.

The handle copies all len bytes, so data may go as soon as the call returns. Free the handle with daegun_aat_state_table_free.

DAEGUN_MALFORMED where the header is cut short, names no classes or more than 65,535, or points past the data, or where the class table is under 2 bytes. DAEGUN_UNSUPPORTED for a class table in a format other than 0, 2, 4, 6, 8 and 10. DAEGUN_INVALID_ARGUMENT for an extra_words so large that an entry's size overflows. On failure *out is NULL, with the reason in daegun_last_error.

/* The test font's ligature subtable, 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;
daegun_status status = daegun_aat_state_table_parse(morx.data + body, morx.len - body, 1, glyphs, &table);
if (status != DAEGUN_OK) {
    fprintf(stderr, "%s\n", daegun_last_error().data);
    return 1;
}
/* The table holds its own copy: the font's bytes are no longer needed. */
daegun_aat_state_table_free(table);
daegun_aat_state_table_class
daegun_status daegun_aat_state_table_class(
    const daegun_aat_state_table *table,
    uint32_t glyph,
    uint16_t *out
);

The class a state table puts a glyph in.

Glyph 0xFFFF is always DAEGUN_AAT_CLASS_DELETED_GLYPH. A glyph the class table does not list, which includes one past a format 0 table's num_glyphs, is class 1, out of bounds, which every table predefines and this header has no constant for. Any other glyph gets the class the table stores.

That class is not checked against the table's class count. For one at or past it, daegun_aat_state_table_entry finds no entry, and daegun's own shaper reads it as class 1.

There is always a class, so the call answers DAEGUN_OK. It parses the handle's copy again, which parsed once already, so the DAEGUN_MALFORMED or DAEGUN_UNSUPPORTED of a parse does not come back.

/* The test font's ligature subtable, 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;

uint16_t listed = 0, unlisted = 0, deleted = 0;
if (daegun_aat_state_table_class(table, 4, &listed) != DAEGUN_OK) return 1;
if (daegun_aat_state_table_class(table, 0, &unlisted) != DAEGUN_OK) return 1;
if (daegun_aat_state_table_class(table, 0xFFFF, &deleted) != DAEGUN_OK) return 1;
/* Glyph 4 is class 6, glyph 0 is listed nowhere and so class 1, and 0xFFFF is the deleted glyph's 2. */
daegun_aat_state_table_free(table);
daegun_aat_state_table_entry
daegun_status daegun_aat_state_table_entry(
    const daegun_aat_state_table *table,
    uint16_t state,
    uint16_t class_id,
    daegun_aat_entry *out
);

The entry a state table names for a state and a class.

The cell at row state, column class_id of the state array holds the index of an entry. Each entry is 4 bytes plus 2 for each of the extra words the parse was given, and is read into *out, with the words the table lacks set to 0.

DAEGUN_ABSENT where class_id is not below the table's class count, or where the cell or its entry lies past the end of the data, and *out is then left as it was. The table does not record how many states it has: a state past the last is read from whatever bytes follow the state array, and only answers DAEGUN_ABSENT where those run out. So ask only for the states that entries name, from DAEGUN_AAT_STATE_START_OF_TEXT on.

It parses the handle's copy again, which parsed once already, so the DAEGUN_MALFORMED or DAEGUN_UNSUPPORTED of a parse does not come back here.

/* The test font's ligature subtable, 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;

uint16_t class_id = 0;
daegun_aat_entry entry;
if (daegun_aat_state_table_class(table, 2, &class_id) != DAEGUN_OK) return 1;
if (daegun_aat_state_table_entry(table, DAEGUN_AAT_STATE_START_OF_TEXT, class_id, &entry) != DAEGUN_OK)
    return 1;
/* Glyph 2, class 4, at the start: stay in state 0 and add it to the components, flags 0x8000. The table
   has 7 classes, so class 7 has no entry. */
daegun_status status = daegun_aat_state_table_entry(table, 0, 7, &entry);
daegun_aat_state_table_free(table);
daegun_aat_state_table_free
void daegun_aat_state_table_free(daegun_aat_state_table *table);

Frees a state table.

NULL is fine and does nothing, so a cleanup path may free without checking. A freed table whose copy takes 64 KiB or less is kept, emptied, for this thread's next daegun_aat_state_table_parse. daegun_thread_release lets go of it.

daegun_bytes morx;
if (daegun_font_table(font, DAEGUN_TAG('m', 'o', 'r', 'x'), &morx) != DAEGUN_OK) return 1;
/* Its state table starts at byte 60 of morx, and the font has 7 glyphs. */
daegun_aat_state_table *table = NULL;
daegun_status status = daegun_aat_state_table_parse(morx.data + 60, morx.len - 60, 1, 7, &table);
if (status == DAEGUN_OK) {
    /* read the table */
}
/* Safe either way: a parse that fails leaves `table` NULL. */
daegun_aat_state_table_free(table);
  • May be NULL: table.
daegun_ankr_version
daegun_status daegun_ankr_version(
    const uint8_t *data,
    size_t len,
    uint16_t *out
);

The version an ankr table opens with.

Reads the big-endian 16-bit number at the start of data, and nothing past it. daegun_ankr_parse does not check the version, so a tool that wants to refuse one it doesn't know asks here first.

DAEGUN_INVALID_ARGUMENT for data under 2 bytes, leaving *out as it was.

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,
};
uint16_t version = 9;
if (daegun_ankr_version(bytes, sizeof bytes, &version) != DAEGUN_OK) return 1;
/* version is 0. One byte holds no version: DAEGUN_INVALID_ARGUMENT, and version stays 0. */
daegun_status status = daegun_ankr_version(bytes, 1, &version);
daegun_ankr_control_point
daegun_status daegun_ankr_control_point(
    const uint8_t *data,
    size_t len,
    size_t at,
    int16_t *out_x,
    int16_t *out_y
);

Reads one point, an x and a y, from the 4 bytes at byte at, with no table around it.

A point is stored as two big-endian int16, x then y, in font units, both in the glyph data of ankr and as a control point in kerx. This reads one at any offset of any bytes you hold, with no handle and no parse, for a tool that walks a table itself. daegun_ankr_anchor_point is the other way in: it finds a glyph's point by its index, through a parsed table.

DAEGUN_INVALID_ARGUMENT where the 4 bytes would run past the end of data, wherever at lies, leaving both outs as they were.

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,
};
/* Glyph 1's first point, in the ankr built by hand for daegun_ankr: the glyph data starts at 20, glyph 1's
   points at 0 in it, and its first point follows the 4-byte count. */
int16_t x = 0, y = 0;
if (daegun_ankr_control_point(bytes, sizeof bytes, 20 + 0 + 4, &x, &y) != DAEGUN_OK) return 1;
/* (10, 20). */
daegun_ankr_parse
daegun_status daegun_ankr_parse(
    const uint8_t *data,
    size_t len,
    uint32_t num_glyphs,
    daegun_ankr **out
);

Reads an ankr table from bytes, keeping a copy of them.

data is the whole table, and num_glyphs the font's glyph count, which bounds a lookup of format 0. The handle copies all len bytes, so data may go as soon as the call returns. Free it with daegun_ankr_free.

DAEGUN_MALFORMED where the 12-byte header is cut short, its lookup lies past the end, or that lookup is under 2 bytes. DAEGUN_UNSUPPORTED for a lookup in a format other than 0, 2, 4, 6, 8 and 10. The version and the offset of the glyph data are not checked: a glyph whose points lie past the data reads as having none. On failure *out is NULL, with the reason in daegun_last_error.

/* The ankr built by hand for daegun_ankr. */
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;
daegun_status status = daegun_ankr_parse(bytes, sizeof bytes, 3, &ankr);
if (status != DAEGUN_OK) {
    fprintf(stderr, "%s\n", daegun_last_error().data);
    return 1;
}
/* The handle holds its own copy, so bytes of yours could go now. */
daegun_ankr_free(ankr);
daegun_ankr_point_count
daegun_status daegun_ankr_point_count(
    const daegun_ankr *ankr,
    uint32_t glyph,
    uint32_t *out
);

How many anchor points a glyph has in an ankr table.

The count the table states for the glyph, cut to the points its data really holds and to 65,536, the most a 16-bit index can name, so daegun_ankr_anchor_point reads every index below it. 0 for a glyph the lookup does not list or whose points lie past the data.

There is always a count, so the call answers DAEGUN_OK. It parses the handle's copy again, which parsed once already, so the DAEGUN_MALFORMED or DAEGUN_UNSUPPORTED of a parse does not come back.

/* The ankr built by hand for daegun_ankr. */
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 one = 9, zero = 9;
if (daegun_ankr_point_count(ankr, 1, &one) != DAEGUN_OK) return 1;
if (daegun_ankr_point_count(ankr, 0, &zero) != DAEGUN_OK) return 1;
/* Glyph 1 has 2 points and glyph 0 none. */
daegun_ankr_free(ankr);
daegun_ankr_anchor_point
daegun_status daegun_ankr_anchor_point(
    const daegun_ankr *ankr,
    uint32_t glyph,
    uint16_t index,
    int16_t *out_x,
    int16_t *out_y
);

A glyph's anchor point, by its index, from an ankr table.

Writes the point's x and y, in font units, y up. index counts from 0 in the glyph's list.

DAEGUN_ABSENT where the glyph has no point at that index: the lookup does not list the glyph, index is not below the count the table states, or the point lies past the data. Both outs are then left as they were. Where a kerx attachment names a point a glyph lacks, daegun's shaper takes it as (0, 0).

It parses the handle's copy again, which parsed once already, so the DAEGUN_MALFORMED or DAEGUN_UNSUPPORTED of a parse does not come back here.

/* The ankr built by hand for daegun_ankr. */
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;
int16_t x = 0, y = 0;
if (daegun_ankr_anchor_point(ankr, 1, 1, &x, &y) != DAEGUN_OK) return 1;
/* Glyph 1's second point is (-30, 40). It has no third: DAEGUN_ABSENT, and x and y keep their values. */
daegun_status status = daegun_ankr_anchor_point(ankr, 1, 2, &x, &y);
daegun_ankr_free(ankr);
daegun_ankr_free
void daegun_ankr_free(daegun_ankr *ankr);

Frees an ankr handle.

NULL is fine and does nothing, so a cleanup path may free without checking. A freed handle whose copy takes 64 KiB or less is kept, emptied, for this thread's next daegun_ankr_parse. daegun_thread_release lets go of it.

static const uint8_t bytes[12] = { 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 12 };
daegun_ankr *ankr = NULL;
daegun_status status = daegun_ankr_parse(bytes, sizeof bytes, 3, &ankr);
if (status == DAEGUN_OK) {
    /* read the table */
}
/* Safe either way: this parse fails, as the lookup lies at the very end, and leaves `ankr` NULL. */
daegun_ankr_free(ankr);
  • May be NULL: ankr.
daegun_ivs_parse
daegun_status daegun_ivs_parse(
    const uint8_t *data,
    size_t len,
    size_t base,
    daegun_ivs **out
);

Reads the item variation store that starts at an offset in a table.

data and len are the bytes that hold the store, usually a whole table from daegun_font_table, and base is the byte in them where the store starts. The table says where that is: HVAR and VVAR keep the offset as a uint32 at byte 4, MVAR as a uint16 at byte 10, and GDEF, from version 1.3 on, as a uint32 at byte 14. The store's own offsets count from base, so bytes that begin at the store work too, with a base of 0.

On DAEGUN_OK, *out is a store of your own, to free with daegun_ivs_free. It is decoded in full during the call and keeps no pointer into data, so the bytes may be freed or changed as soon as the call returns.

Only the store's header of eight bytes has to be there. DAEGUN_MALFORMED means base is at or past the end of the bytes, which is always so for NULL with a len of 0, or that the header is cut short. DAEGUN_UNSUPPORTED means the store's format, its first two bytes, is not 1, and it is also the answer where a single byte is left at base. On either, *out is NULL and daegun_last_error has the reason.

Past the header nothing fails the parse. A region list that does not fit in the bytes leaves the store with no regions and an axis count of 0. A subtable that can not be read is kept as an empty one with no rows, so the outer indices of the others stay right, and a row that runs past the end is all zeros.

A store is also held to two limits, which guard against a font that points many subtables at the same bytes: a million rows in all, and four values for each byte from base to the end of the bytes, or 65,536 where that is more, a subtable spending one for each delta and each region it names. A subtable that would take the store past either is kept as an empty one too.

The format is the only check on base itself, so a wrong offset that lands on the bytes 0, 1 parses into a store of nonsense. A base of 0 with a whole HVAR table does exactly that, since the version HVAR opens with begins with those two bytes.

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 store as a uint32 at byte 4. */
uint32_t store_at = 0;
if (daegun_read_u32_be(hvar.data, hvar.len, 4, &store_at) != DAEGUN_OK) return 1;

/* The whole table goes in, with that offset as the base. */
daegun_ivs *ivs = NULL;
daegun_status status = daegun_ivs_parse(hvar.data, hvar.len, store_at, &ivs);
if (status != DAEGUN_OK) {
    /* DAEGUN_MALFORMED or DAEGUN_UNSUPPORTED. daegun_last_error() says why. */
    return 1;
}
size_t subtables = 0;
if (daegun_ivs_ivd_count(ivs, &subtables) != DAEGUN_OK) return 1;
/* Inter's HVAR store starts at byte 20 and holds 10 subtables. */

daegun_ivs_free(ivs);
daegun_ivs_axis_count
daegun_status daegun_ivs_axis_count(const daegun_ivs *ivs, size_t *out);

How many axes each region of the store spans.

Writes the count to *out. Every region daegun_ivs_region lends has this many entries, and daegun_ivs_region_scalars reads this many normalized coordinates.

The number is the one the store states. In a well-formed font it equals the number of axes the font declares, which daegun_font_axes gives, but nothing here checks the two against each other. A store whose region list could not be read reports 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 axes = 0, font_axes = 0;
if (daegun_ivs_axis_count(ivs, &axes) != DAEGUN_OK) return 1;
if (daegun_font_axes(font, NULL, 0, &font_axes) != DAEGUN_OK) return 1;
/* Both are 2: the store's regions span Inter's two axes, opsz and wght. */

daegun_ivs_free(ivs);
daegun_ivs_region_count
daegun_status daegun_ivs_region_count(const daegun_ivs *ivs, size_t *out);

How many regions the store defines.

Writes the count to *out. Regions are numbered from 0, which is how daegun_ivs_region takes one and how a subtable names the regions of its columns. It is also the room daegun_ivs_region_scalars needs in its buffer: one scalar for each region.

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;
/* Inter's HVAR store defines 5 regions, so a buffer of 5 doubles holds a location's scalars. */
double scalars[5];
size_t count = 0;
if (daegun_ivs_region_scalars(ivs, NULL, 0, scalars, 5, &count) != DAEGUN_OK) return 1;

daegun_ivs_free(ivs);
daegun_ivs_region
const daegun_region_axis *daegun_ivs_region(
    const daegun_ivs *ivs,
    size_t region,
    size_t *out_count
);

One region of the store: for each axis, where the region starts, peaks and ends.

Returns a borrowed array of daegun_region_axis and sets *out_count to its length, which is the store's axis count for every region. Entry j is the region's span on axis j of the font, in normalized coordinates.

The array is valid until daegun_ivs_free. Don't free it. NULL comes back, with the count left as it was, for a region at or past daegun_ivs_region_count, or if ivs or out_count is NULL.

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 axes = 0;
const daegun_region_axis *region = daegun_ivs_region(ivs, 2, &axes);
if (!region) return 1;
/* Region 2 of Inter's HVAR store spans 2 axes. On opsz, axis 0, it is 0, 0, 0: the axis takes no
   part. On wght, axis 1, it starts at 0 and peaks and ends at 1: the region counts more and more
   as the weight goes from the default to the heaviest. */

/* There are 5 regions, so there is no region 5. */
size_t untouched = 77;
const daegun_region_axis *past = daegun_ivs_region(ivs, 5, &untouched);
/* past is NULL, and untouched is still 77. */

daegun_ivs_free(ivs);
daegun_ivs_ivd_count
daegun_status daegun_ivs_ivd_count(const daegun_ivs *ivs, size_t *out);

How many item variation data subtables the store holds.

Writes the count to *out. A subtable is what the outer index of an item's delta picks, so the valid outer indices run from 0 to one below this count. A subtable the parse could not read is still counted, as one with no rows.

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 subtables = 0, total = 0;
if (daegun_ivs_ivd_count(ivs, &subtables) != DAEGUN_OK) return 1;
for (size_t i = 0; i < subtables; i++) {
    size_t rows = 0;
    if (daegun_ivs_ivd_rows(ivs, i, &rows) != DAEGUN_OK) return 1;
    total += rows;
}
/* Inter's HVAR store has 10 subtables with 821 rows between them, which its 2937 glyphs share. */

daegun_ivs_free(ivs);
daegun_ivs_ivd_rows
daegun_status daegun_ivs_ivd_rows(
    const daegun_ivs *ivs,
    size_t ivd,
    size_t *out
);

How many rows of deltas one subtable of the store holds.

Writes the row count of subtable ivd to *out. A row is one item's deltas and is what the inner index picks, so the valid inner indices of the subtable run from 0 to one below this count.

A subtable at or past daegun_ivs_ivd_count answers DAEGUN_INVALID_ARGUMENT and leaves *out as it was.

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 rows = 0;
if (daegun_ivs_ivd_rows(ivs, 3, &rows) != DAEGUN_OK) return 1;
/* Subtable 3 of Inter's HVAR store holds 148 rows, so its inner indices run from 0 to 147. */

/* The store has 10 subtables, so there is no subtable 10. */
daegun_status status = daegun_ivs_ivd_rows(ivs, 10, &rows);
/* status is DAEGUN_INVALID_ARGUMENT, and rows still holds 148. */

daegun_ivs_free(ivs);
daegun_ivs_ivd_region_indices
const size_t *daegun_ivs_ivd_region_indices(
    const daegun_ivs *ivs,
    size_t ivd,
    size_t *out_count
);

Which regions the columns of a subtable belong to.

A subtable does not hold a delta for every region of the store, only for the regions it lists. Returns a borrowed array of region numbers and sets *out_count to its length: column k of every row in subtable ivd is the delta for region indices[k]. The order is the subtable's own and need not be ascending.

The array is valid until daegun_ivs_free. Don't free it. NULL comes back, with the count left as it was, for a subtable at or past daegun_ivs_ivd_count, or if ivs or out_count is NULL.

The numbers are the ones the font states and are not checked against daegun_ivs_region_count. daegun_ivs_delta reads the scalar at that number in the array you pass and counts 0 for a number past its length. So with the scalars daegun_ivs_region_scalars gives, a column whose region does not exist adds nothing.

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 columns = 0;
const size_t *indices = daegun_ivs_ivd_region_indices(ivs, 0, &columns);
if (!indices) return 1;
/* Subtable 0 of Inter's HVAR store has 2 columns, for regions 2 and 4 of the store's 5. Each of
   its rows holds 2 deltas. */

daegun_ivs_free(ivs);
daegun_ivs_ivd_row
const int32_t *daegun_ivs_ivd_row(
    const daegun_ivs *ivs,
    size_t ivd,
    size_t row,
    size_t *out_count
);

One row of a subtable: an item's deltas, one for each region the subtable lists.

ivd is the outer index and row the inner index. Returns a borrowed array of deltas and sets *out_count to its length, which is the count daegun_ivs_ivd_region_indices gives for the same subtable. Delta k is how much the item changes where region indices[k] counts in full, in the item's own units: font units for an advance or a metric.

These are the numbers as stored, with no location applied. daegun_ivs_delta does the weighting and the sum for a location.

The array is valid until daegun_ivs_free. Don't free it. NULL comes back, with the count left as it was, for a subtable at or past daegun_ivs_ivd_count, for a row at or past that subtable's daegun_ivs_ivd_rows, or if ivs or out_count is NULL.

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;

/* Inter's advance map sends the letter A to subtable 3, row 46. */
size_t columns = 0, count = 0;
const size_t *indices = daegun_ivs_ivd_region_indices(ivs, 3, &columns);
const int32_t *row = daegun_ivs_ivd_row(ivs, 3, 46, &count);
if (!indices || !row) return 1;
for (size_t k = 0; k < count; k++) {
    /* row[k] is the A's delta for region indices[k]. */
}
/* The row is 215, -75, -103, -17, 12, and its first column is region 2, the heavy side of the
   weight axis. So at the heaviest weight the A is 215 units wider than at the default. */

daegun_ivs_free(ivs);
daegun_ivs_region_scalars
daegun_status daegun_ivs_region_scalars(
    const daegun_ivs *ivs,
    const double *location,
    size_t location_len,
    double *out,
    size_t out_len,
    size_t *out_count
);

Works out how much each region of the store counts at a location.

location is the location's normalized coordinates, one for each axis in the order of the font's axes, each from -1 to 1: what daegun_location_normalized lends. The result is one scalar for each region, from 0, where the location lies outside the region, to 1, where it sits at the region's peak. Work them out once for a location and hand them to every daegun_ivs_delta you read there.

A coordinate is used as given, not clamped to -1 to 1, so 1.5 lies past a region that peaks and ends at 1, which counts 0 there.

Fewer coordinates than the store has axes is fine: an axis with no coordinate sits at 0, its default. So NULL with a location_len of 0 is the default location, which is also what daegun_location_normalized lends there, an array of no coordinates. Coordinates past the axis count are not read.

out is your buffer with room for out_len doubles, and daegun_ivs_region_count is how many it needs. *out_count is set to that number whenever the call answers DAEGUN_OK or finds the buffer too small. A NULL buffer with a length of 0 asks for the number alone. A buffer too small answers DAEGUN_INVALID_ARGUMENT and writes nothing into it. The buffer, the count and location must share no byte: where any two of them do, the call answers the same and writes neither a scalar nor the count.

The scalars are worked out in 16.16 fixed point, as all of daegun's variation math is, so each one is a whole number of 65536ths.

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;

/* The location to read at, weight 700, as normalized coordinates. */
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;
size_t axes = 0;
const double *normalized = daegun_location_normalized(bold, &axes);

/* Ask how many scalars there are, then fetch them. */
size_t count = 0;
if (daegun_ivs_region_scalars(ivs, normalized, axes, NULL, 0, &count) != DAEGUN_OK) return 1;
double *scalars = calloc(count, sizeof *scalars);
if (!scalars) return 1;
if (daegun_ivs_region_scalars(ivs, normalized, axes, scalars, count, &count) != DAEGUN_OK) return 1;
/* Inter's HVAR store has 5 regions. At weight 700 only region 2 counts, the one that rises along
   the weight axis: its scalar is about 0.54, the normalized weight itself. The other four are 0. */

free(scalars);
daegun_location_free(bold);
daegun_ivs_free(ivs);
daegun_ivs_delta
daegun_status daegun_ivs_delta(
    const daegun_ivs *ivs,
    size_t outer,
    size_t inner,
    const double *scalars,
    size_t scalars_len,
    double *out
);

An item's delta at a location: its row of deltas, each weighted by the scalar of its region, summed.

outer picks the subtable and inner the row, as a daegun_delta_set_index_map or the table that owns the store gives them. scalars are the location's region scalars from daegun_ivs_region_scalars. The call multiplies each delta of the row by the scalar of its region and writes the sum to *out: what the location adds to the item's default value.

The result is in the item's own units, font units for an advance or a metric, and it is not rounded to a whole unit. The sum is worked out in 16.16 fixed point, so it is a whole number of 65536ths of a unit. daegun's own advances round the delta to the nearest whole unit before adding it, a half going up, which is what daegun_ot_round does, and never go below 0. Scalars of your own are rounded to whole 65536ths first and not clamped.

An index out of range is not a failure. An outer at or past daegun_ivs_ivd_count, or an inner at or past that subtable's daegun_ivs_ivd_rows, writes 0. A region with no scalar counts as 0 too, so scalars shorter than daegun_ivs_region_count, or NULL with a scalars_len of 0, drops those regions from the sum.

/* How much wider is Inter's A at weight 700? HVAR holds an advance delta for each glyph. */
daegun_bytes hvar = { NULL, 0 };
if (daegun_font_table(font, DAEGUN_TAG('H', 'V', 'A', 'R'), &hvar) != DAEGUN_OK) return 1;
/* Two uint32 offsets in HVAR's header: its store at byte 4, and its advance map at byte 8. */
uint32_t store_at = 0, map_at = 0;
if (daegun_read_u32_be(hvar.data, hvar.len, 4, &store_at) != DAEGUN_OK) return 1;
if (daegun_read_u32_be(hvar.data, hvar.len, 8, &map_at) != DAEGUN_OK) return 1;
daegun_ivs *ivs = NULL;
daegun_delta_set_index_map *map = NULL;
if (daegun_ivs_parse(hvar.data, hvar.len, store_at, &ivs) != DAEGUN_OK) return 1;
if (daegun_delta_set_index_map_parse(hvar.data, hvar.len, map_at, &map) != DAEGUN_OK) return 1;

/* The location as normalized coordinates, and the scalar of each region there. */
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;
size_t axes = 0, regions = 0, count = 0;
const double *normalized = daegun_location_normalized(bold, &axes);
if (daegun_ivs_region_count(ivs, &regions) != DAEGUN_OK) return 1;
double *scalars = calloc(regions, sizeof *scalars);
if (!scalars) return 1;
if (daegun_ivs_region_scalars(ivs, normalized, axes, scalars, regions, &count) != DAEGUN_OK) return 1;

/* The glyph's row in the store, then its delta. */
uint32_t glyph = 0;
if (daegun_font_glyph_id(font, 'A', &glyph) != DAEGUN_OK) return 1;
size_t outer = 0, inner = 0;
if (daegun_delta_set_index_map_lookup(map, glyph, &outer, &inner) != DAEGUN_OK) return 1;
double delta = 0.0;
if (daegun_ivs_delta(ivs, outer, inner, scalars, count, &delta) != DAEGUN_OK) return 1;
/* delta is about 116.11 font units. Rounded, it is the 116 units between the A's advance of 1413
   at the default and its advance of 1529 at weight 700. */

free(scalars);
daegun_location_free(bold);
daegun_delta_set_index_map_free(map);
daegun_ivs_free(ivs);
daegun_ivs_free
void daegun_ivs_free(daegun_ivs *ivs);

Frees an item variation store.

NULL is fine and does nothing, so a cleanup path may free without checking. Every array the store lent, from daegun_ivs_region, daegun_ivs_ivd_region_indices and daegun_ivs_ivd_row, is invalid afterward.

Scalars and deltas you already hold are plain numbers and stay good. So does a daegun_delta_set_index_map read beside the store: no handle depends on another.

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;
daegun_status status = daegun_ivs_parse(hvar.data, hvar.len, store_at, &ivs);
if (status == DAEGUN_OK) {
    /* read the store */
}
/* Safe either way: a parse that fails leaves `ivs` NULL. */
daegun_ivs_free(ivs);
  • May be NULL: ivs.
daegun_delta_set_index_map_parse
daegun_status daegun_delta_set_index_map_parse(
    const uint8_t *data,
    size_t len,
    size_t base,
    daegun_delta_set_index_map **out
);

Reads the delta-set index map that starts at an offset in a table.

data and len are the bytes that hold the map, usually a whole table from daegun_font_table, and base is the byte in them where the map starts. HVAR and VVAR keep the offset of their advance map as a uint32 at byte 8. A 0 there means the table has no map: parse nothing, and read each glyph with an outer index of 0 and its glyph id as the inner index.

On DAEGUN_OK, *out is a map of your own, to free with daegun_delta_set_index_map_free. Its entries are decoded during the call and it keeps no pointer into data, so the bytes may go as soon as the call returns.

The whole map is checked before anything is handed out. DAEGUN_MALFORMED means base is at or past the end of the bytes, which is always so for NULL with a len of 0, or that the map's header or its entries run past the end. DAEGUN_UNSUPPORTED means its format, the first byte, is neither 0 nor 1. On either, *out is NULL and daegun_last_error has the reason. A map of no entries parses, and daegun_delta_set_index_map_lookup says what it answers.

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 || map_at == 0) return 1;

daegun_delta_set_index_map *map = NULL;
daegun_status status = daegun_delta_set_index_map_parse(hvar.data, hvar.len, map_at, &map);
if (status != DAEGUN_OK) {
    /* DAEGUN_MALFORMED or DAEGUN_UNSUPPORTED. daegun_last_error() says why. */
    return 1;
}
size_t entries = 0;
if (daegun_delta_set_index_map_count(map, &entries) != DAEGUN_OK) return 1;
/* Inter's advance map starts at byte 5361 of HVAR and has 2937 entries, one for each glyph. */

daegun_delta_set_index_map_free(map);
daegun_delta_set_index_map_count
daegun_status daegun_delta_set_index_map_count(
    const daegun_delta_set_index_map *map,
    size_t *out
);

How many entries the map holds.

Writes the count to *out. Entry i belongs to item i, a glyph id in HVAR and VVAR.

The count may be lower than the number of items. Every item from the last entry on shares that entry, which is how a font keeps a long run of glyphs with the same deltas short. A count of 0 is an empty map, which daegun_delta_set_index_map_lookup reads as no map at all.

/* VVAR, for vertical advances, keeps the offset of its advance map at byte 8, as HVAR does. */
daegun_bytes vvar = { NULL, 0 };
if (daegun_font_table(font, DAEGUN_TAG('V', 'V', 'A', 'R'), &vvar) != DAEGUN_OK) return 1;
uint32_t map_at = 0;
if (daegun_read_u32_be(vvar.data, vvar.len, 8, &map_at) != DAEGUN_OK || map_at == 0) return 1;
daegun_delta_set_index_map *map = NULL;
if (daegun_delta_set_index_map_parse(vvar.data, vvar.len, map_at, &map) != DAEGUN_OK) return 1;

size_t entries = 0;
if (daegun_delta_set_index_map_count(map, &entries) != DAEGUN_OK) return 1;
/* Source Han Sans has 17944 glyphs and a map of 1 entry: every glyph shares one row of deltas. */

daegun_delta_set_index_map_free(map);
daegun_delta_set_index_map_lookup
daegun_status daegun_delta_set_index_map_lookup(
    const daegun_delta_set_index_map *map,
    size_t index,
    size_t *out_outer,
    size_t *out_inner
);

An item's outer and inner index: which subtable and which row of the store hold its deltas.

Writes entry index of the map to *out_outer and *out_inner, the two numbers daegun_ivs_delta takes. In HVAR and VVAR index is a glyph id.

An index at or past daegun_delta_set_index_map_count is not an error: it takes the last entry of the map. An empty map answers an outer index of 0 and index itself as the inner index, which is how a table with no map at all is read. For an index past 4,294,967,295 that inner index is 4,294,967,295, which names no row.

daegun_bytes hvar = { NULL, 0 };
if (daegun_font_table(font, DAEGUN_TAG('H', 'V', 'A', 'R'), &hvar) != DAEGUN_OK) return 1;
uint32_t map_at = 0;
if (daegun_read_u32_be(hvar.data, hvar.len, 8, &map_at) != DAEGUN_OK || map_at == 0) return 1;
daegun_delta_set_index_map *map = NULL;
if (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;
size_t outer = 0, inner = 0;
if (daegun_delta_set_index_map_lookup(map, glyph, &outer, &inner) != DAEGUN_OK) return 1;
/* Inter's A is glyph 2, and its advance deltas are row 46 of subtable 3. */

/* The map has 2937 entries. An index past them takes the last one, entry 2936. */
size_t last_outer = 0, last_inner = 0;
if (daegun_delta_set_index_map_lookup(map, 2936, &last_outer, &last_inner) != DAEGUN_OK) return 1;
if (daegun_delta_set_index_map_lookup(map, 5000, &outer, &inner) != DAEGUN_OK) return 1;
/* Both answer row 302 of subtable 1. */

daegun_delta_set_index_map_free(map);
daegun_delta_set_index_map_free
void daegun_delta_set_index_map_free(daegun_delta_set_index_map *map);

Frees a delta-set index map.

NULL is fine and does nothing, so a cleanup path may free without checking. The indices the map gave you are plain numbers and stay good, as does the store they point into.

daegun_bytes hvar = { NULL, 0 };
if (daegun_font_table(font, DAEGUN_TAG('H', 'V', 'A', 'R'), &hvar) != DAEGUN_OK) return 1;
uint32_t map_at = 0;
if (daegun_read_u32_be(hvar.data, hvar.len, 8, &map_at) != DAEGUN_OK) return 1;

/* `map` stays NULL for a table with no map, and for a map that fails to parse. */
daegun_delta_set_index_map *map = NULL;
daegun_status status = DAEGUN_OK;
if (map_at != 0) status = daegun_delta_set_index_map_parse(hvar.data, hvar.len, map_at, &map);
if (map) {
    /* read the map */
}
/* Safe either way. */
daegun_delta_set_index_map_free(map);
  • May be NULL: map.
daegun_feature_variations_parse
daegun_status daegun_feature_variations_parse(
    const uint8_t *layout,
    size_t len,
    daegun_feature_variations **out
);

Finds the FeatureVariations table of a GSUB or GPOS table and makes a handle to read it.

layout and len are a whole GSUB or GPOS table, as daegun_font_table gives it. A layout table of version 1.1 or later keeps the offset of its FeatureVariations as a uint32 at byte 10, and the call reads it from there.

DAEGUN_ABSENT means the table names none: it is shorter than 14 bytes, which NULL with a len of 0 is, its major version is not 1, its minor version is 0, or the offset is 0. *out is then NULL. A font that does not vary its features answers this, so treat it as an answer, not a failure.

On DAEGUN_OK, *out is a handle of your own, to free with daegun_feature_variations_free. It keeps a copy of the whole layout table, so the bytes may go as soon as the call returns.

The call reads the header and nothing else. An offset that points past the end still gives a handle, and daegun_feature_variations_find then finds no record in it. A table cut short gives one too, and a record cut off there doesn't hold.

daegun_bytes gsub = { NULL, 0 };
if (daegun_font_table(font, DAEGUN_TAG('G', 'S', 'U', 'B'), &gsub) != DAEGUN_OK) return 1;

daegun_feature_variations *variations = NULL;
daegun_status status = daegun_feature_variations_parse(gsub.data, gsub.len, &variations);
if (status == DAEGUN_ABSENT) {
    /* The font swaps no features across its design space. Inter is one of these: its GSUB is
       version 1.0. */
} else if (status == DAEGUN_OK) {
    /* Ask which record applies at a location, with daegun_feature_variations_find. */
}

daegun_feature_variations_free(variations);
daegun_feature_variations_at
daegun_status daegun_feature_variations_at(
    const uint8_t *layout,
    size_t len,
    size_t at,
    daegun_feature_variations **out
);

Makes a handle for a FeatureVariations table at an offset you already know.

layout and len are the bytes the table lies in, and at is the byte in them where it starts. Use it where daegun_feature_variations_parse can not find the table for you: for bytes that are a FeatureVariations table alone, with an at of 0, or for a layout table whose header you read yourself. No header is read, so no version is asked for.

The call checks nothing and always gives a handle, to free with daegun_feature_variations_free. The handle keeps a copy of all len bytes, so they may go as soon as the call returns. Every read made through it later is checked against the length, so an at past the end does no harm: daegun_feature_variations_find finds no record there, and daegun_feature_variations_substitute no substitute. One that is wrong but inside the bytes reads whatever lies there.

The offsets daegun_feature_variations_substitute answers count from the start of layout, not from at.

/* A FeatureVariations table alone, with no layout table around it, written out by hand. Its one
   record swaps feature 3 where axis 0 is from 0.5 to 1.0. */
static const uint8_t table[] = {
    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, 0, 0x20, 0, 0x40, 0,    /* its condition: axis 0, 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_at(table, sizeof table, 0, &variations) != DAEGUN_OK) return 1;

const int32_t coords[] = { 12288 }; /* axis 0 at 0.75 */
uint32_t record = 0;
size_t alternate = 0;
if (daegun_feature_variations_find(variations, coords, 1, NULL, &record) != DAEGUN_OK) return 1;
if (daegun_feature_variations_substitute(variations, record, 3, &alternate) != DAEGUN_OK) return 1;
/* record is 0, and alternate is 42, counted from the start of the bytes. */

daegun_feature_variations_free(variations);
daegun_feature_variations_find
daegun_status daegun_feature_variations_find(
    const daegun_feature_variations *variations,
    const int32_t *coords,
    size_t coords_len,
    const daegun_ivs *store,
    uint32_t *out
);

Which record of a FeatureVariations table applies at a location.

Writes to *out the index of the first record whose conditions all hold. Records are tried in the table's order and the first match wins. Hand the index to daegun_feature_variations_substitute.

coords are the location's normalized coordinates as F2DOT14 integers, where 16384 is 1.0 and -16384 is -1.0: one for each axis, in the order of the font's axes. They are not the doubles daegun_location_normalized lends. To convert those, multiply each by 16384 and round, which is what daegun's own shaping does. An axis with no coordinate sits at 0, so NULL with a coords_len of 0 is the default location.

The plain kind of condition is a range on one axis, and it holds where the coordinate of that axis lies in the range, both ends included. Conditions may also be joined by and, or and not. One kind tests whether a value that itself varies is above 0, and store is the item variation store its delta is read from, which is GDEF's. With a NULL store, or at the default location, that value is tested as it is, with no delta added. A record with no condition set holds everywhere. A condition that can't be read, or of a format past 5, never holds.

DAEGUN_ABSENT means no record applies, and *out is left as it was: at this location the features stand as the layout table has them. A table that can not be read answers the same. So does one that runs out the budget of a search, which is twice the size of the layout table in bytes plus 65,536 conditions read. No table whose parts do not overlap comes near that.

/* 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;

/* A location's normalized coordinates, turned into F2DOT14 integers. */
const daegun_coord at[] = { { DAEGUN_TAG('w', 'g', 'h', 't'), 700.0 } };
daegun_location *bold = NULL;
if (daegun_font_location(font, at, 1, &bold) != DAEGUN_OK) return 1;
size_t axes = 0;
const double *normalized = daegun_location_normalized(bold, &axes);
int32_t coords[16];
if (!normalized || axes > 16) return 1;
for (size_t i = 0; i < axes; i++) coords[i] = (int32_t)lround(normalized[i] * 16384.0);

uint32_t record = 0;
daegun_status status = daegun_feature_variations_find(variations, coords, axes, NULL, &record);
/* Inter's weight 700 is 8848 on axis 1, inside the range of 8192 to 16384: status is DAEGUN_OK and
   record is 0. */

/* The default location needs no coordinates. No record applies there. */
status = daegun_feature_variations_find(variations, NULL, 0, NULL, &record);
/* status is DAEGUN_ABSENT. */

daegun_location_free(bold);
daegun_feature_variations_free(variations);
daegun_feature_variations_substitute
daegun_status daegun_feature_variations_substitute(
    const daegun_feature_variations *variations,
    uint32_t variation,
    uint16_t feature,
    size_t *out
);

The feature table a record puts in place of one of the layout table's features.

variation is a record index that daegun_feature_variations_find answered, and feature is a feature's index in the feature list of the layout table, not its tag. Where the record swaps that feature, by the first of its substitutions that names it, *out receives the byte offset of the alternate feature table, counted from the start of the layout table the handle was made from. A feature table there reads as any other: a uint16 offset to its parameters, a uint16 count of lookups, then that many uint16 lookup indices.

An *out of 0 with DAEGUN_OK is a substitution too. The record names no table for the feature, which stands for an empty feature: at this location the feature applies no lookups.

DAEGUN_ABSENT means the record leaves the feature alone, so it keeps the table the feature list gives it. *out is left as it was. A record or a table that can not be read answers the same.

The call reads record variation where it would lie and does not check the index against the number of records the table states. Pass only an index that daegun_feature_variations_find answered: one past the last record may read bytes that are no record and answer an offset that means nothing.

/* 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;
const int32_t coords[] = { 0, 12288 }; /* axis 1 at 0.75 */
uint32_t record = 0;
if (daegun_feature_variations_find(variations, coords, 2, NULL, &record) != DAEGUN_OK) return 1;

size_t alternate = 0;
daegun_status status = daegun_feature_variations_substitute(variations, record, 3, &alternate);
if (status == DAEGUN_OK && alternate != 0) {
    /* Feature 3 is swapped. Read the lookups of the feature table that takes its place. */
    uint16_t lookups = 0, first = 0;
    if (daegun_read_u16_be(gsub, sizeof gsub, alternate + 2, &lookups) != DAEGUN_OK) return 1;
    if (daegun_read_u16_be(gsub, sizeof gsub, alternate + 4, &first) != DAEGUN_OK) return 1;
    /* alternate is 56, and the feature table there applies 1 lookup, number 5. */
}

/* The record does not name feature 2, which keeps its own table. */
status = daegun_feature_variations_substitute(variations, record, 2, &alternate);
/* status is DAEGUN_ABSENT, and alternate still holds 56. */

daegun_feature_variations_free(variations);
daegun_feature_variations_free
void daegun_feature_variations_free(daegun_feature_variations *variations);

Frees a FeatureVariations handle, and with it the copy of the layout table it kept.

NULL is fine and does nothing, so a cleanup path may free without checking. The record indices and offsets the handle answered are plain numbers and stay good.

A freed handle whose copy takes 64 KiB or less is kept, emptied, for this thread's next daegun_feature_variations_parse or daegun_feature_variations_at. daegun_thread_release lets go of it.

daegun_bytes gsub = { NULL, 0 };
if (daegun_font_table(font, DAEGUN_TAG('G', 'S', 'U', 'B'), &gsub) != DAEGUN_OK) return 1;

daegun_feature_variations *variations = NULL;
daegun_status status = daegun_feature_variations_parse(gsub.data, gsub.len, &variations);
if (status == DAEGUN_OK) {
    /* read the records */
}
/* Safe either way: a table with no FeatureVariations leaves `variations` NULL. */
daegun_feature_variations_free(variations);
  • May be NULL: 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_grayscale
daegun_status daegun_subpixel_layout_grayscale(daegun_subpixel_layout **out);

The plain layout: one sample and one byte of coverage for each pixel.

Each byte is the share of its pixel the glyph covers, from 0 for none to 255 for all, before any gamma is applied. It suits any display in any rotation. It draws exactly what a NULL layout in the options draws, so you need it only where you want a handle to hand around. Free it with daegun_subpixel_layout_free.

It is the one layout daegun_rasterizer_glyph_into, daegun_rasterizer_color_glyph and daegun_rasterizer_color_glyph_into accept.

daegun_subpixel_layout *gray = NULL;
if (daegun_subpixel_layout_grayscale(&gray) != DAEGUN_OK) return 1;
uint8_t channels = 0, across = 0, down = 0;
if (daegun_subpixel_layout_channels(gray, &channels) != DAEGUN_OK) return 1;
if (daegun_subpixel_layout_oversample(gray, &across, &down) != DAEGUN_OK) return 1;
/* One channel, one sample a pixel. */
daegun_subpixel_layout_free(gray);
daegun_subpixel_layout_horizontal
daegun_status daegun_subpixel_layout_horizontal(
    int32_t order,
    daegun_subpixel_layout **out
);

The layout for a display whose stripes sit side by side: three samples across each pixel, filtered to soften color fringes.

This is the layout for an LCD in its usual rotation. The glyph is drawn at three samples across each pixel and one down, so each sample is the coverage of one stripe. order is a DAEGUN_STRIPES_ code saying which stripe is on the left.

Each channel is a weighted sum of five samples centered on its own stripe, with the weights 8, 77, 86, 77 and 8 out of 256. That evens out the color of an edge, for slightly softer edges than daegun_subpixel_layout_unfiltered gives. The filter reaches two samples past the pixel on each side, so the image is one pixel wider on the left and one on the right than the glyph's own box, and no taller. Each pixel is three bytes: red, green, blue.

An order that is neither DAEGUN_STRIPES_RGB nor DAEGUN_STRIPES_BGR answers DAEGUN_INVALID_ARGUMENT, with *out set to NULL. Free the layout with daegun_subpixel_layout_free.

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;
/* Inter's g at 20 px is 10 by 17 pixels in gray, from 1 pixel right of the origin. Here it is 12 by 17
   from the origin itself, three bytes a pixel. */
daegun_rasterizer_free(rasterizer);
daegun_subpixel_layout_free(lcd);
daegun_subpixel_layout_vertical
daegun_status daegun_subpixel_layout_vertical(
    int32_t order,
    daegun_subpixel_layout **out
);

The layout for a display whose stripes are stacked: three samples down each pixel, through the same filter as daegun_subpixel_layout_horizontal.

A panel turned a quarter turn, as a tablet held upright may be, has the three stripes of each pixel one above the other. The glyph is then drawn at one sample across each pixel and three down. order says which stripe is on top: red for DAEGUN_STRIPES_RGB, blue for DAEGUN_STRIPES_BGR.

The five weights run down in place of across, so the image is one pixel taller at the top and one at the bottom than the glyph's own box, and no wider. Each pixel is three bytes: red, green, blue.

An order that is neither code answers DAEGUN_INVALID_ARGUMENT, with *out set to NULL.

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

daegun_raster_options opts;
if (daegun_raster_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.layout = stacked;
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;
/* The gray g is 10 by 17 with its top 12 pixels up. This one is 10 by 19, its top 13 up. */
daegun_rasterizer_free(rasterizer);
daegun_subpixel_layout_free(stacked);
daegun_subpixel_layout_unfiltered
daegun_status daegun_subpixel_layout_unfiltered(
    int32_t order,
    int32_t orientation,
    daegun_subpixel_layout **out
);

A stripe layout with no filter: three samples for each pixel, and each channel is its own stripe's sample and nothing else.

orientation picks the direction: DAEGUN_HORIZONTAL for stripes side by side, with three samples across each pixel, and DAEGUN_VERTICAL for stacked ones, with three down. order is a DAEGUN_STRIPES_ code, as for daegun_subpixel_layout_horizontal.

What it gives up is the filter. Edges are as sharp as the stripes allow, and nothing evens out the color, so an edge that falls inside a pixel shows as a fringe of color. Nothing reaches past the pixel either, so the image is the size of the gray one, at three bytes a pixel.

Use it when you filter the samples yourself. With DAEGUN_STRIPES_RGB and DAEGUN_HORIZONTAL, a row of the image is the glyph's coverage at three times the resolution across, one byte a sample from left to right.

An order or an orientation that is none of its codes answers DAEGUN_INVALID_ARGUMENT, with *out set to NULL.

daegun_subpixel_layout *raw = NULL;
if (daegun_subpixel_layout_unfiltered(DAEGUN_STRIPES_RGB, DAEGUN_HORIZONTAL, &raw) != DAEGUN_OK) return 1;

/* Red reads the first of the pixel's three samples alone: weights 1, 0, 0. */
size_t n = 0;
const float *red = daegun_subpixel_layout_weights(raw, 0, &n);
daegun_subpixel_layout_free(raw);
daegun_subpixel_layout_from_weights
daegun_status daegun_subpixel_layout_from_weights(
    uint8_t oversample_x,
    uint8_t oversample_y,
    uint8_t taps_x,
    uint8_t taps_y,
    int8_t origin_x,
    int8_t origin_y,
    const float *weights,
    size_t weights_len,
    daegun_subpixel_layout **out
);

A layout from a filter you state yourself: the samples for each pixel, the size and place of the window, and the weights of each of three channels.

oversample_x and oversample_y are how many samples the glyph is drawn at for each pixel, across and down, each from 1 to DAEGUN_MAX_OVERSAMPLE. taps_x and taps_y are the size of the window of samples every channel reads, each from 1 to DAEGUN_MAX_TAPS. origin_x and origin_y are where the window starts, in samples from the first sample of the pixel, its top left one: a negative number starts it that many samples to the left or above, a positive one to the right or below. Any origin is taken, but one far from the pixel makes every image larger by its pad.

weights holds 3 * taps_x * taps_y floats: the weights of the first channel, then the second, then the third, which come out as the three bytes of a pixel in that order. Within a channel the top row of the window comes first, each row from the left. A channel of a pixel is the sum, over its window, of the coverage of each sample, 0 to 255, times its weight, rounded and kept within 0 to 255.

Nothing normalizes the weights: they are used as given. Make each channel sum to 1 for a fully covered window to come out as 255. A weight may be negative, as in a filter that sharpens, and a sum below 0 comes out as 0.

The layout always has three channels, even from three equal sets of weights. DAEGUN_INVALID_ARGUMENT comes for an oversample of 0 or past DAEGUN_MAX_OVERSAMPLE, taps of 0 or past DAEGUN_MAX_TAPS, a weights_len other than 3 * taps_x * taps_y, which includes a NULL list with a length of 0, or a weight that is NaN or infinite. *out is then NULL, and daegun_last_error says which.

/* RGB stripes side by side through a three-tap filter in place of the built-in five: three samples
   across a pixel, and a window of five that starts one sample left of the pixel. */
const float weights[15] = {
    0.25f, 0.5f, 0.25f, 0.0f, 0.0f, /* red */
    0.0f, 0.25f, 0.5f, 0.25f, 0.0f, /* green */
    0.0f, 0.0f, 0.25f, 0.5f, 0.25f, /* blue */
};
daegun_subpixel_layout *layout = NULL;
if (daegun_subpixel_layout_from_weights(3, 1, 5, 1, -1, 0, weights, 15, &layout) != DAEGUN_OK) return 1;

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'g', &gid) != DAEGUN_OK) return 1;
daegun_raster_options opts;
if (daegun_raster_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.layout = layout;
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;
/* 12 by 17 pixels, three bytes each. */

/* A list of the wrong length is refused, and the out is set to NULL. */
daegun_subpixel_layout *refused = NULL;
daegun_status status = daegun_subpixel_layout_from_weights(3, 1, 5, 1, -1, 0, weights, 14, &refused);
daegun_subpixel_layout_free(refused);
daegun_rasterizer_free(rasterizer);
daegun_subpixel_layout_free(layout);
daegun_subpixel_layout_free
void daegun_subpixel_layout_free(daegun_subpixel_layout *layout);

Frees a layout.

NULL is fine and does nothing. Free a layout only once no options that point at it go to another call: the options hold its address, not a copy. The weights daegun_subpixel_layout_weights lent are invalid afterward.

daegun_subpixel_layout *lcd = NULL;
daegun_status status = daegun_subpixel_layout_horizontal(DAEGUN_STRIPES_RGB, &lcd);
/* Safe either way: a call that fails leaves lcd NULL. */
daegun_subpixel_layout_free(lcd);
  • May be NULL: layout.
daegun_subpixel_layout_is_grayscale
daegun_status daegun_subpixel_layout_is_grayscale(
    const daegun_subpixel_layout *layout,
    bool *out
);

Whether the layout has one channel: a single byte of coverage for each pixel.

True for daegun_subpixel_layout_grayscale alone. Every other layout has three channels, one from daegun_subpixel_layout_from_weights too, even with three equal sets of weights.

daegun_rasterizer_glyph_into, daegun_rasterizer_color_glyph and daegun_rasterizer_color_glyph_into refuse options whose layout is not grayscale, so ask before you take one of those paths.

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

bool one = false, other = true;
if (daegun_subpixel_layout_is_grayscale(gray, &one) != DAEGUN_OK) return 1;
if (daegun_subpixel_layout_is_grayscale(lcd, &other) != DAEGUN_OK) return 1;
/* true, then false. */
daegun_subpixel_layout_free(lcd);
daegun_subpixel_layout_free(gray);
daegun_subpixel_layout_channels
daegun_status daegun_subpixel_layout_channels(
    const daegun_subpixel_layout *layout,
    uint8_t *out
);

How many bytes each pixel of an image drawn with this layout has: 1 for grayscale, 3 for any other layout.

It is the channels of the daegun_image that daegun_rasterizer_glyph lends with this layout. A row of an image width pixels wide holds width * channels bytes, and an atlas for these glyphs needs that many bytes a pixel. It is also how many channels daegun_subpixel_layout_weights answers for.

daegun_subpixel_layout *lcd = NULL;
if (daegun_subpixel_layout_horizontal(DAEGUN_STRIPES_RGB, &lcd) != DAEGUN_OK) return 1;
uint8_t channels = 0;
if (daegun_subpixel_layout_channels(lcd, &channels) != DAEGUN_OK) return 1;

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'g', &gid) != 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;
/* The bytes this glyph takes in an atlas: 12 by 17 pixels, 3 bytes each. */
size_t bytes = (size_t)image.width * image.height * channels;
daegun_rasterizer_free(rasterizer);
daegun_subpixel_layout_free(lcd);
daegun_subpixel_layout_oversample
daegun_status daegun_subpixel_layout_oversample(
    const daegun_subpixel_layout *layout,
    uint8_t *out_x,
    uint8_t *out_y
);

How many samples the glyph is drawn at for each pixel, across and down.

1 and 1 for grayscale. A stripe layout takes three one way and one the other: 3 across and 1 down for stripes side by side, 1 and 3 for stacked ones. A layout from daegun_subpixel_layout_from_weights has what it was given, at most DAEGUN_MAX_OVERSAMPLE each way.

A rasterizer of your own scales the outline by these two factors before it samples, so a glyph 10 pixels wide spans 30 samples at 3 across. daegun's rasterizer does that by itself, and the images it lends are in whole pixels whatever the oversampling. Both outs are required.

daegun_subpixel_layout *lcd = NULL;
if (daegun_subpixel_layout_horizontal(DAEGUN_STRIPES_RGB, &lcd) != DAEGUN_OK) return 1;
uint8_t across = 0, down = 0;
if (daegun_subpixel_layout_oversample(lcd, &across, &down) != DAEGUN_OK) return 1;
/* 3 across and 1 down: a glyph box of 10 by 17 pixels spans 30 by 17 samples. */
daegun_subpixel_layout_free(lcd);
daegun_subpixel_layout_taps
daegun_status daegun_subpixel_layout_taps(
    const daegun_subpixel_layout *layout,
    uint8_t *out_x,
    uint8_t *out_y
);

The size of the filter's window: how many samples each channel reads, across and down.

1 and 1 for grayscale, where a pixel is its one sample. 7 and 1 for daegun_subpixel_layout_horizontal: the three samples of the pixel and two more on each side, which is the room a five-tap filter around each stripe takes. 1 and 7 for daegun_subpixel_layout_vertical, and 3 one way for daegun_subpixel_layout_unfiltered. Neither number is above DAEGUN_MAX_TAPS.

Every channel has taps_x * taps_y weights, the count daegun_subpixel_layout_weights sets. All channels share the one window, and a channel that reads fewer samples has zeros for the rest. Both outs are required.

daegun_subpixel_layout *lcd = NULL;
if (daegun_subpixel_layout_horizontal(DAEGUN_STRIPES_RGB, &lcd) != DAEGUN_OK) return 1;
uint8_t across = 0, down = 0;
if (daegun_subpixel_layout_taps(lcd, &across, &down) != DAEGUN_OK) return 1;

/* 7 by 1, so each channel has 7 weights. */
size_t n = 0;
const float *red = daegun_subpixel_layout_weights(lcd, 0, &n);
daegun_subpixel_layout_free(lcd);
daegun_subpixel_layout_origin
daegun_status daegun_subpixel_layout_origin(
    const daegun_subpixel_layout *layout,
    int8_t *out_x,
    int8_t *out_y
);

Where the filter's window starts, in samples from the first sample of the pixel, across and down.

The first sample of a pixel is its top left one. 0 and 0 start the window there, as in grayscale and daegun_subpixel_layout_unfiltered. A negative number starts it before the pixel: -2 and 0 for daegun_subpixel_layout_horizontal is two samples to the left, and 0 and -2 for daegun_subpixel_layout_vertical two samples above. A positive number starts it to the right or below.

So for the pixel in column x, counting sample columns from the first sample of the first pixel, the window covers taps_x columns from x * oversample_x + origin_x, and likewise down. A window that reaches past its own pixel gives the pixels beside the glyph's box some of its coverage, and daegun_subpixel_layout_pad is the room for those. Both outs are required.

daegun_subpixel_layout *lcd = NULL;
if (daegun_subpixel_layout_horizontal(DAEGUN_STRIPES_RGB, &lcd) != DAEGUN_OK) return 1;
int8_t origin_x = 0, origin_y = 0;
uint8_t over_x = 0, over_y = 0;
if (daegun_subpixel_layout_origin(lcd, &origin_x, &origin_y) != DAEGUN_OK) return 1;
if (daegun_subpixel_layout_oversample(lcd, &over_x, &over_y) != DAEGUN_OK) return 1;

/* Two samples left of the pixel's first: the pixel in column 4 reads sample columns from 10 on. */
int first = 4 * over_x + origin_x;
daegun_subpixel_layout_free(lcd);
daegun_subpixel_layout_pad
daegun_status daegun_subpixel_layout_pad(
    const daegun_subpixel_layout *layout,
    size_t *out_x,
    size_t *out_y
);

How many whole pixels an image needs on each side of the glyph's own box so the filter's window has room, across and down.

Both numbers are in pixels, not samples. The first goes on the left and again on the right, the second at the top and again at the bottom, so an image is 2 * pad_x pixels wider and 2 * pad_y taller than the glyph's own box. 0 and 0 for grayscale and daegun_subpixel_layout_unfiltered, 1 and 0 for daegun_subpixel_layout_horizontal, 0 and 1 for daegun_subpixel_layout_vertical.

daegun_rasterizer_glyph adds it by itself: the image it lends is already that much larger, its left and top moved out to match, so size an atlas cell from the image's own width and height. Read the pad to budget cells before you draw, or in a rasterizer of your own.

It is how far the window reaches past the pixel, in samples, on the side where it reaches farther, divided by the samples a pixel and rounded up. The same pad goes on both sides, also where the window reaches out on one side only. Both outs are required.

daegun_subpixel_layout *lcd = NULL;
if (daegun_subpixel_layout_horizontal(DAEGUN_STRIPES_RGB, &lcd) != DAEGUN_OK) return 1;
size_t pad_x = 0, pad_y = 0;
if (daegun_subpixel_layout_pad(lcd, &pad_x, &pad_y) != DAEGUN_OK) return 1;

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'g', &gid) != DAEGUN_OK) return 1;
daegun_rasterizer *rasterizer = daegun_rasterizer_new();
daegun_image gray, image;
if (daegun_rasterizer_glyph(rasterizer, font, gid, NULL, 20.0f, NULL, &gray) != DAEGUN_OK) return 1;
daegun_raster_options opts;
if (daegun_raster_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
opts.layout = lcd;
if (daegun_rasterizer_glyph(rasterizer, font, gid, NULL, 20.0f, &opts, &image) != DAEGUN_OK) return 1;
/* 1 and 0: 12 by 17 pixels where the gray image is 10 by 17. */
daegun_rasterizer_free(rasterizer);
daegun_subpixel_layout_free(lcd);
daegun_subpixel_layout_weights
const float *daegun_subpixel_layout_weights(
    const daegun_subpixel_layout *layout,
    size_t channel,
    size_t *out_count
);

One channel's filter weights, row by row.

Returns a borrowed array of taps_x * taps_y floats, the top row of the window first and each row from the left, and sets *out_count to that number, which is at most DAEGUN_MAX_WEIGHTS. channel counts from 0: grayscale has channel 0 alone, and every other layout 0, 1 and 2, which in the stripe layouts are red, green and blue.

In the layouts daegun builds each channel sums to 1, so a fully covered window comes out as 255. daegun_subpixel_layout_horizontal and daegun_subpixel_layout_vertical hold 8, 77, 86, 77 and 8 out of 256 around the sample of each stripe. A layout from daegun_subpixel_layout_from_weights gives back the weights you gave it.

The array is valid until the layout is freed. NULL comes back, with the count left as it was, for a channel at or past daegun_subpixel_layout_channels, and for a NULL layout or count. The count is set only when an array comes back.

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

size_t n = 0;
const float *red = daegun_subpixel_layout_weights(lcd, 0, &n);
/* Seven taps from two samples left of the pixel: in 256ths, 8, 77, 86, 77, 8 around the red stripe,
   the pixel's first sample, then 0, 0. */
const float *blue = daegun_subpixel_layout_weights(lcd, 2, &n);
/* Blue has the same filter two samples to the right. There is no fourth channel. */
size_t kept = 99;
const float *none = daegun_subpixel_layout_weights(lcd, 3, &kept);
daegun_subpixel_layout_free(lcd);
daegun_subpixel_layout_key
daegun_status daegun_subpixel_layout_key(
    const daegun_subpixel_layout *layout,
    uint64_t *out
);

The layout's identity as a 64-bit number, to go in a cache key.

It is a hash of everything that defines the layout: the oversampling, the taps, the origin, the number of channels and the bits of every weight. Two layouts built from the same parameters have the same key, a layout from daegun_subpixel_layout_from_weights with the parameters of a stripe layout included, and two that differ in any of them have different keys, short of a collision in 64 bits. Put it in the key of any cache or atlas of glyphs drawn through a layout, beside the font, the glyph and the size, so an image drawn for one layout is never served for another.

The font's raster cache, DAEGUN_CACHE_RASTER, files each image under this key with the other options.

The hash reads the parameters as they were given, not what they do. The same filter written another way, a window one tap wider with a zero weight added or a weight of -0.0 in place of 0.0, gets a key of its own. That costs a cache a second copy, never a wrong image.

daegun_subpixel_layout *rgb = NULL, *again = NULL, *bgr = NULL;
if (daegun_subpixel_layout_horizontal(DAEGUN_STRIPES_RGB, &rgb) != DAEGUN_OK) return 1;
if (daegun_subpixel_layout_horizontal(DAEGUN_STRIPES_RGB, &again) != DAEGUN_OK) return 1;
if (daegun_subpixel_layout_horizontal(DAEGUN_STRIPES_BGR, &bgr) != DAEGUN_OK) return 1;

uint64_t a = 0, b = 0, c = 0;
if (daegun_subpixel_layout_key(rgb, &a) != DAEGUN_OK) return 1;
if (daegun_subpixel_layout_key(again, &b) != DAEGUN_OK) return 1;
if (daegun_subpixel_layout_key(bgr, &c) != DAEGUN_OK) return 1;
/* Built twice, the same key. Another stripe order, another key. */
daegun_subpixel_layout_free(bgr);
daegun_subpixel_layout_free(again);
daegun_subpixel_layout_free(rgb);
daegun_shelf_packer_free
void daegun_shelf_packer_free(daegun_shelf_packer *packer);

Frees a packer.

NULL is fine and does nothing. The rectangles it handed out are plain values and stay yours.

daegun_shelf_packer *packer = daegun_shelf_packer_new(256, 256);
daegun_rect r;
daegun_status status = daegun_shelf_packer_insert(packer, 8, 8, &r);
daegun_shelf_packer_free(packer);
/* r is a copy, and still says where the rectangle went. */
  • May be NULL: packer.
daegun_shelf_packer_new
daegun_shelf_packer *daegun_shelf_packer_new(size_t width, size_t height);

An empty packer for an atlas of this width and height, in pixels.

The two numbers are all it takes. There is no padding or gutter to set, and the size cannot change later: a larger atlas is a new packer. It never returns NULL. A size of 0 either way gives a packer that never has room. Free it with daegun_shelf_packer_free.

/* A 1024 by 1024 atlas. Its pixels are yours to allocate: one byte each for grayscale glyphs. */
daegun_shelf_packer *packer = daegun_shelf_packer_new(1024, 1024);
uint8_t *atlas = calloc(1024 * 1024, 1);
if (!atlas) return 1;

daegun_rect first;
if (daegun_shelf_packer_insert(packer, 12, 17, &first) != DAEGUN_OK) return 1;
/* The first rectangle goes at 0, 0. */
free(atlas);
daegun_shelf_packer_free(packer);
daegun_shelf_packer_insert
daegun_status daegun_shelf_packer_insert(
    daegun_shelf_packer *packer,
    size_t w,
    size_t h,
    daegun_rect *out
);

Finds room for a rectangle of this width and height and takes it.

On DAEGUN_OK, *out is where the rectangle goes, with the w and h you passed.

It looks at every open shelf for one that is at least h tall and has w left across. Among those it takes the shortest, the one opened first where two are equally short, and puts the rectangle at the top of that shelf, right after what is already on it. A rectangle shorter than its shelf leaves the strip under it unused. Where no shelf will do, it opens a new one right below the last, as tall as the rectangle, and puts the rectangle at its left end.

DAEGUN_ABSENT is an answer, not a failure, and comes in three cases: w or h is 0, the rectangle is wider or taller than the whole atlas, or the atlas is full for it, which means no open shelf can take it and a new shelf of its height would end below the bottom. It changes nothing and leaves *out as it was, so a smaller rectangle may still fit afterward. A glyph with nothing to draw, such as a space, has an image 0 by 0 and gets DAEGUN_ABSENT too, so skip it before you insert.

daegun_shelf_packer *packer = daegun_shelf_packer_new(64, 32);
daegun_rect r;
/* The first rectangle opens a shelf 10 tall at the top left corner. */
if (daegun_shelf_packer_insert(packer, 20, 10, &r) != DAEGUN_OK) return 1;
/* A taller one can't go on that shelf, so it opens the next shelf below, at y 10. */
if (daegun_shelf_packer_insert(packer, 30, 12, &r) != DAEGUN_OK) return 1;
/* A shorter one fits both shelves and takes the shorter, right of what is there: x 20, y 0. */
if (daegun_shelf_packer_insert(packer, 20, 8, &r) != DAEGUN_OK) return 1;

/* Full for this one: no shelf has 50 left across, and a new shelf 12 tall would end below the atlas. */
daegun_status status = daegun_shelf_packer_insert(packer, 50, 12, &r);
/* A smaller one still fits after that, at x 40, y 0. */
if (daegun_shelf_packer_insert(packer, 24, 10, &r) != DAEGUN_OK) return 1;
daegun_shelf_packer_free(packer);
daegun_shelf_packer_reset
daegun_status daegun_shelf_packer_reset(daegun_shelf_packer *packer);

Empties the atlas, keeping its size.

It forgets every rectangle and every shelf, so the next daegun_shelf_packer_insert starts again at the top left corner. Every rectangle it handed out before may be handed out again, so forget which glyph was where, and clear the pixels if your renderer needs them clear. This is how you reuse a full atlas, as no call frees a single rectangle.

daegun_shelf_packer *packer = daegun_shelf_packer_new(64, 64);
daegun_rect r;
if (daegun_shelf_packer_insert(packer, 64, 64, &r) != DAEGUN_OK) return 1;
/* Full now: even 1 by 1 answers DAEGUN_ABSENT. */

if (daegun_shelf_packer_reset(packer) != DAEGUN_OK) return 1;
/* Empty again, and the same size: the next rectangle starts at the top left corner. */
if (daegun_shelf_packer_insert(packer, 10, 10, &r) != DAEGUN_OK) return 1;
daegun_shelf_packer_free(packer);
daegun_rasterizer_free
void daegun_rasterizer_free(daegun_rasterizer *rasterizer);

Frees a rasterizer, and with it every buffer it kept and what it learned of each glyph.

NULL is fine and does nothing. An image it lent is invalid afterward, so copy what you keep first. The fonts it drew from are yours and stay as they are.

daegun_rasterizer *rasterizer = daegun_rasterizer_new();
uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'g', &gid) != DAEGUN_OK) return 1;
daegun_image image;
daegun_status status = daegun_rasterizer_glyph(rasterizer, font, gid, NULL, 20.0f, NULL, &image);
/* Copy what you keep before the free: image.pixels points into the rasterizer. */
uint8_t kept[170];
if (status == DAEGUN_OK && image.pixels_len <= sizeof kept) memcpy(kept, image.pixels, image.pixels_len);
daegun_rasterizer_free(rasterizer);
  • May be NULL: rasterizer.
daegun_rasterizer_new
daegun_rasterizer *daegun_rasterizer_new(void);

A new rasterizer, with nothing drawn and nothing learned yet.

It takes no settings: what to draw and how goes to each call, the how in a daegun_raster_options. Make one and keep it, as its buffers and what it has learned of each glyph are what make later draws cheap. It never returns NULL. Free it with daegun_rasterizer_free.

daegun_rasterizer *rasterizer = daegun_rasterizer_new();
const char letters[] = "abc";
for (size_t i = 0; i < 3; i++) {
    uint32_t gid = 0;
    if (daegun_font_glyph_id(font, (uint32_t)letters[i], &gid) != DAEGUN_OK) return 1;
    daegun_image image;
    if (daegun_rasterizer_glyph(rasterizer, font, gid, NULL, 16.0f, NULL, &image) != DAEGUN_OK) return 1;
    /* Use the image here: the next draw takes its place. */
}
daegun_rasterizer_free(rasterizer);
daegun_rasterizer_set_cache_budget
daegun_status daegun_rasterizer_set_cache_budget(
    daegun_rasterizer *rasterizer,
    size_t bytes
);

Sets how many bytes of learned glyph outlines the rasterizer may keep.

This budget is not for drawn images. The first time a rasterizer draws a glyph of a font at a location, it decodes the outline in font units and works out whether its contours overlap, removing the overlaps where it can. It keeps both, so every later draw of that glyph, at any size, skips the decoding and the overlap work. That is what the budget holds, across every font the rasterizer has drawn from.

The default is 4 MiB, room for several thousand glyphs. Past the budget the glyphs drawn least recently are let go, whichever font they belong to, and a lower budget applies at once. A budget of 0 keeps nothing: each draw learns its glyph again, and the pixels are the same either way.

Drawn images are kept by another cache, which belongs to the font: DAEGUN_CACHE_RASTER. It is off, at a budget of 0, until daegun_font_set_cache_budget gives it one, and a budget of 0 set later empties it and turns it off again. With a budget, daegun_rasterizer_glyph, daegun_rasterizer_color_glyph and daegun_rasterizer_distance_field keep each image they draw, under the glyph, the location, the size and every option that changes the pixels, and lend it again for the same request in place of drawing, whichever rasterizer asks. The _into calls and daegun_rasterizer_path do not use it.

daegun_rasterizer *rasterizer = daegun_rasterizer_new();
/* A megabyte for the outlines it learns. */
if (daegun_rasterizer_set_cache_budget(rasterizer, 1 << 20) != DAEGUN_OK) return 1;

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'g', &gid) != DAEGUN_OK) return 1;
daegun_image image;
if (daegun_rasterizer_glyph(rasterizer, font, gid, NULL, 20.0f, NULL, &image) != DAEGUN_OK) return 1;
uint8_t kept[170];
memcpy(kept, image.pixels, sizeof kept);

/* A budget of 0 changes the work, never the pixels. */
if (daegun_rasterizer_set_cache_budget(rasterizer, 0) != DAEGUN_OK) return 1;
if (daegun_rasterizer_glyph(rasterizer, font, gid, NULL, 20.0f, NULL, &image) != DAEGUN_OK) return 1;
daegun_rasterizer_free(rasterizer);
daegun_raster_options_default
daegun_status daegun_raster_options_default(
    daegun_raster_options *out,
    size_t size
);

Fills raster options with their defaults.

Pass the struct and sizeof it. The call zeroes that many bytes, which is every default, and sets size. Field by field: outline NULL, the outline as the font holds it. layout NULL, grayscale. offset 0 and 0, the origin on a pixel corner. gamma DAEGUN_GAMMA_LINEAR, coverage as it is. text transparent black and contrast 0, neither read under that gamma. darken false.

A size below what daegun 2.0 defined answers DAEGUN_INVALID_ARGUMENT, and one larger than this library knows answers DAEGUN_UNSUPPORTED, which means your header is newer than the library. Neither writes anything.

daegun_raster_options opts;
if (daegun_raster_options_default(&opts, sizeof opts) != DAEGUN_OK) return 1;
/* Every field but size is 0 or NULL. */
opts.offset[0] = 0.5f;

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, 20.0f, &opts, &image) != DAEGUN_OK) return 1;
/* Moved half a pixel right, the g spills into an eleventh column. */
daegun_rasterizer_free(rasterizer);
daegun_rasterizer_glyph
daegun_status daegun_rasterizer_glyph(
    daegun_rasterizer *rasterizer,
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    float px,
    const daegun_raster_options *opts,
    daegun_image *out
);

Draws one glyph at a pixel size and lends the image: a byte of coverage for each pixel, placed from the glyph's origin.

The call most drawing starts from. font and gid say what to draw, the glyph id coming from daegun_font_glyph_id or from a shaped run. location picks the instance of a variable font, NULL being the default one. px is the size in pixels to the em. opts say how, and NULL gives plain coverage: no hinting, the origin on a pixel corner, one byte a pixel.

On DAEGUN_OK the call fills *out, a daegun_image holding only the pixels the glyph touches. Its left and top say where they go, measured from the glyph's origin, the point on the baseline where the pen stands: the left edge is left pixels right of the origin and the top edge top pixels above it, top counting up. Its width and height are in pixels, and its rows come top first, stride bytes apart, which here is always width * channels. Each pixel is channels bytes: one byte of coverage, from 0 where the glyph covers none of the pixel to 255 where it covers all of it, or three, red, green, blue, under a subpixel layout, whose image grows on each side by daegun_subpixel_layout_pad. pixels points at the first byte of the top row, and pixels_len is stride * height. How far the pen moves afterward is not here: that is the glyph's advance, which shaping gives.

The image is BORROWED from the rasterizer: its pixels are valid until the rasterizer's next call, one that fails included, or its free. Copy what you keep.

A glyph with no outline, such as a space, is not an error: it answers DAEGUN_OK with a 0 by 0 image and a pixels_len of 0. The failures leave *out as it was. DAEGUN_NO_OUTLINE is the answer for a glyph id at or past the count of the font, and for any glyph of a font with no outlines, such as an emoji font made of bitmaps. DAEGUN_INVALID_ARGUMENT comes for a px that is 0, negative or not finite, for options that hold a code that is none of its constants, an offset that is not finite or outline options that daegun_font_prepared_outline refuses, and for options, or their daegun_outline_options, whose size is below daegun 2.0's, as a struct you zeroed yourself has. DAEGUN_UNSUPPORTED means such a size is larger than this library knows.

DAEGUN_LIMIT_EXCEEDED comes for an image wider or taller than DAEGUN_MAX_SIDE pixels or lying more than 2^31 pixels from the origin, for one whose drawing would hold more than DAEGUN_MAX_DRAW_BYTES bytes, and for an outline so tangled that resolving its overlaps would take more than 2^27 passes over a pixel, plus 512 for each point and 8 for each pixel. daegun_rasterizer_glyph_into draws a glyph of any size. Options whose transform, stroke or embolden take a point or an advance past the range of a float answer DAEGUN_INVALID_ARGUMENT or DAEGUN_OVERFLOW, by where it is caught. A font whose outline data does not decode answers what the decoder found, such as DAEGUN_MALFORMED.

The first draw of a glyph decodes its outline and works out where its contours overlap. The rasterizer keeps both, under the budget of daegun_rasterizer_set_cache_budget, so later draws of that glyph at any size start from there. The image is not kept unless the font's DAEGUN_CACHE_RASTER has a budget. With one, a call with the same glyph, location, size and options is lent the image from that cache in place of drawing it again.

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, 20.0f, NULL, &image) != DAEGUN_OK) return 1;
/* Inter's g at 20 px is 10 by 17 pixels, one byte each. Its left edge is 1 pixel right of the origin
   and its top edge 12 pixels above the baseline, so its last 5 rows hang below the line. */

/* Copy it to a canvas whose rows run down, with the pen at column 4 of the baseline on row 16. */
static uint8_t canvas[24][24];
int pen_x = 4, baseline_y = 16;
for (uint32_t y = 0; y < image.height; y++) {
    const uint8_t *row = image.pixels + y * image.stride; /* 0 is empty, 255 fully covered */
    memcpy(&canvas[baseline_y - image.top + (int)y][pen_x + image.left], row, image.width);
}
daegun_rasterizer_free(rasterizer);
daegun_rasterizer_glyph_into
daegun_status daegun_rasterizer_glyph_into(
    daegun_rasterizer *rasterizer,
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    float px,
    const daegun_raster_options *opts,
    const daegun_target *target
);

Draws a glyph as daegun_rasterizer_glyph does, straight into pixels you own, one byte of coverage each, whatever their size.

The daegun_target names a rectangle of your pixels and where it lies from the origin of the glyph: a left of -ox and a top of oy put the origin at column ox of row oy, rows counted down from the top. Every pixel of the rectangle is written, the coverage of the glyph where it falls inside and 0 everywhere else. What the pixels held is replaced, not added to or blended with, so a target is a place for one glyph: to set several into one canvas, give each its own cell of it, or combine lent images yourself. The part of the glyph outside the rectangle is cut off. Bytes of a row past its width are left alone.

The options apply as they do in daegun_rasterizer_glyph, the offset, darkening and gamma included, except that a layout other than grayscale answers DAEGUN_INVALID_ARGUMENT. So does a target whose pixels do not hold its rows: a stride below width, or a pixels_len below (height - 1) * stride + width. A width or height of 0 is fine, and nothing is written.

The other statuses are those of daegun_rasterizer_glyph, without the limits on size: the outline is placed and cut to the target once, then worked out a band of rows at a time, so DAEGUN_MAX_SIDE and DAEGUN_MAX_DRAW_BYTES do not apply and no image is held. A failure leaves the pixels as they were, but for the DAEGUN_LIMIT_EXCEEDED of an outline too tangled for its overlaps to be resolved, which can stop partway with some rows written.

The outline is placed in double precision where daegun_rasterizer_glyph uses single, so a byte can differ from the lent image's by one level. The call keeps what it learns of the glyph as that call does, but never reads or fills the font's DAEGUN_CACHE_RASTER.

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

/* A canvas 64 pixels wide. The glyph gets a cell 16 by 24 from column 8, with its origin at column 2
   of the cell's row 16. Bytes outside the cell are left alone. */
static uint8_t canvas[24][64];
daegun_target cell = {
    .left = -2, .top = 16, .width = 16, .height = 24,
    .stride = sizeof canvas[0], .pixels = &canvas[0][8], .pixels_len = sizeof canvas - 8,
};
daegun_rasterizer *rasterizer = daegun_rasterizer_new();
if (daegun_rasterizer_glyph_into(rasterizer, font, gid, NULL, 20.0f, NULL, &cell) != DAEGUN_OK) return 1;
daegun_rasterizer_free(rasterizer);
daegun_rasterizer_color_glyph
daegun_status daegun_rasterizer_color_glyph(
    daegun_rasterizer *rasterizer,
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    float px,
    const daegun_raster_options *opts,
    const daegun_scene_options *scene,
    daegun_image *out
);

Draws a color glyph from the font's COLR table and lends it as RGBA pixels.

A COLR glyph is a small picture: shapes filled with colors and gradients, stacked and blended. Both versions of the table are drawn, the layers of version 0 and the paint graph of version 1, as daegun_font_color_scene gives them. The call draws the glyph at px pixels to the em and fills *out with a daegun_image placed by left and top from the origin, as daegun_rasterizer_glyph places one. The image is the box of what the glyph paints, cut to its clip box where the font gives it one.

A pixel is four bytes, in the order red, green, blue, alpha. The colors are sRGB levels already multiplied by the alpha, so no color byte is above its alpha byte, and a pixel the glyph leaves empty is four zeros. The layers are blended in linear light, then encoded. The result is ready for a source-over blend of premultiplied pixels: out = src + dst * (255 - alpha) / 255 on each byte. The image is BORROWED until the rasterizer's next call or its free.

scene is a daegun_scene_options: which palette of the font to take colors from, and the foreground color, the color of the text, which a glyph may ask for in place of a palette entry. NULL is palette 0 and opaque black.

DAEGUN_ABSENT means the font has no color description for the glyph: an ordinary glyph, which daegun_rasterizer_glyph draws, a glyph id past the count of the font, or any glyph of a font whose color is bitmaps, with no COLR table. *out is left as it was. A color glyph that paints nothing, such as the space of a color font, answers DAEGUN_OK with a 0 by 0 image of 4 channels.

Of the options, the offset and the outline's transform and oblique apply. A layout other than grayscale, hinting, a stroke or an embolden above 0 answers DAEGUN_INVALID_ARGUMENT, as does a px that is not finite and above 0, checked for every glyph before its color is looked up, a transform or oblique that is not finite, options holding a code that is none of its constants, and options or scene options whose size is below daegun 2.0's. DAEGUN_UNSUPPORTED means a size larger than this library knows. darken, text and contrast are not read, nor is the gamma, though its code is checked.

DAEGUN_LIMIT_EXCEEDED comes for an image past DAEGUN_MAX_SIDE or DAEGUN_MAX_DRAW_BYTES, where every layer the glyph stacks counts toward the bytes, for a glyph whose composing would pass over each pixel more than 1,024 times on top of a fixed allowance, far more than a real font asks for, and where daegun_font_color_scene answers it. daegun_rasterizer_color_glyph_into draws one of any size. With a budget on the font's DAEGUN_CACHE_RASTER, the image is kept there under the glyph, location, size, options, palette and foreground, and lent again for the same request.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'A', &gid) != DAEGUN_OK) return 1;
daegun_rasterizer *rasterizer = daegun_rasterizer_new();
daegun_image image;
daegun_status status = daegun_rasterizer_color_glyph(rasterizer, font, gid, NULL, 16.0f, NULL, NULL, &image);
if (status == DAEGUN_OK) {
    for (uint32_t y = 0; y < image.height; y++) {
        for (uint32_t x = 0; x < image.width; x++) {
            const uint8_t *rgba = image.pixels + y * image.stride + 4 * x;
            /* rgba[0], rgba[1], rgba[2]: sRGB red, green, blue, already multiplied by rgba[3], the alpha. */
        }
    }
    /* Bungee Tint's A at 16 px is 11 by 12 pixels, and the fourth pixel of row 1 is an opaque red:
       201, 9, 0, 255. */
} else if (status == DAEGUN_ABSENT) {
    /* Not a color glyph: draw its outline with daegun_rasterizer_glyph. */
} else {
    return 1;
}
daegun_rasterizer_free(rasterizer);
daegun_rasterizer_color_glyph_into
daegun_status daegun_rasterizer_color_glyph_into(
    daegun_rasterizer *rasterizer,
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    float px,
    const daegun_raster_options *opts,
    const daegun_scene_options *scene,
    const daegun_target *target
);

Draws a color glyph as daegun_rasterizer_color_glyph does, straight into RGBA pixels you own, whatever their size.

The daegun_target is read as four bytes a pixel, red, green, blue and alpha, premultiplied sRGB as in the lent image. Its left and top say where its rectangle lies from the origin of the glyph: a left of -ox and a top of oy put the origin at column ox of row oy.

On DAEGUN_OK every pixel of the rectangle is written, the picture where it falls inside and four zeros, fully transparent, everywhere else. What the pixels held is replaced, not blended with, so draw into a buffer of its own and composite that. DAEGUN_ABSENT means the font has no color description for the glyph, and the pixels are left as they were. A width or height of 0 is fine: nothing is written, and the answer still says whether the glyph has color.

DAEGUN_INVALID_ARGUMENT comes for a target whose pixels do not hold its rows, a stride below width * 4 or a pixels_len below (height - 1) * stride + width * 4, checked before the glyph is looked up, and for the options and sizes daegun_rasterizer_color_glyph refuses. Its limits on the size of an image do not apply here, as the picture is worked out a band of rows at a time. A failure that comes while the bands are drawn, such as the DAEGUN_LIMIT_EXCEEDED of a glyph too heavy to compose, can leave some rows written. The call never reads or fills the font's DAEGUN_CACHE_RASTER.

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

/* 16 by 16 pixels of RGBA, with the glyph's origin at column 2 of row 14. */
static uint8_t pixels[16][16 * 4];
daegun_target target = {
    .left = -2, .top = 14, .width = 16, .height = 16,
    .stride = sizeof pixels[0], .pixels = &pixels[0][0], .pixels_len = sizeof pixels,
};
daegun_rasterizer *rasterizer = daegun_rasterizer_new();
daegun_status status =
    daegun_rasterizer_color_glyph_into(rasterizer, font, gid, NULL, 16.0f, NULL, NULL, &target);
if (status == DAEGUN_OK) {
    /* pixels holds the picture, transparent where the glyph paints nothing. */
} else if (status == DAEGUN_ABSENT) {
    /* Not a color glyph, and pixels is untouched: draw its outline with daegun_rasterizer_glyph_into. */
} else {
    return 1;
}
daegun_rasterizer_free(rasterizer);
daegun_rasterizer_path
daegun_status daegun_rasterizer_path(
    daegun_rasterizer *rasterizer,
    const daegun_path *path,
    int32_t rule,
    const double *transform,
    daegun_image *out
);

Fills a daegun_path you built and lends its coverage, a byte for each pixel.

The path is read in pixels with y up, and the image comes back placed from the origin of the path, point (0, 0): its left is how far right of the origin its left edge lies and its top how far above. One unit of the path is one pixel unless you pass a transform.

transform is six doubles [a, b, c, d, dx, dy], applied to every point first: x = a * px + c * py + dx and y = b * px + d * py + dy. NULL is no transform. A path in font units is drawn at a pixel size by { s, 0, 0, s, 0, 0 }, with s the size over the units per em of the font.

rule says what counts as inside. Under DAEGUN_FILL_NONZERO a place that two contours wound the same way both cover is filled, and filled once: its coverage is that of the two shapes joined, not their sum. Under DAEGUN_FILL_EVENODD it is a hole, and two contours wound opposite ways leave a hole under either rule. A contour left open is closed with a straight line. An empty path, or one whose contours have fewer than three distinct points, answers DAEGUN_OK with a 0 by 0 image.

The image is one byte a pixel, rows top first, stride equal to width, and BORROWED until the rasterizer's next call or its free. This call takes no options, and nothing is cached.

DAEGUN_INVALID_ARGUMENT comes for a rule that is none of the DAEGUN_FILL_ codes and for a point that is not finite once transformed. DAEGUN_LIMIT_EXCEEDED comes for an image past DAEGUN_MAX_SIDE on a side or lying more than 2^31 pixels from the origin, for a draw that would hold more than DAEGUN_MAX_DRAW_BYTES bytes, the points of the path counted in, and for a path so tangled that resolving its overlaps would take more than 2^27 passes over a pixel, plus 512 for each point and 8 for each pixel. *out is then left as it was. daegun_rasterizer_path_into draws an image past the limits on size.

/* A rectangle 4 pixels wide and 3 tall, with y up. */
daegun_path *path = daegun_path_new();
daegun_path_move_to(path, 0.0f, 0.0f);
daegun_path_line_to(path, 4.0f, 0.0f);
daegun_path_line_to(path, 4.0f, 3.0f);
daegun_path_line_to(path, 0.0f, 3.0f);
daegun_path_close(path);

daegun_rasterizer *rasterizer = daegun_rasterizer_new();
daegun_image image;
if (daegun_rasterizer_path(rasterizer, path, DAEGUN_FILL_NONZERO, NULL, &image) != DAEGUN_OK) return 1;
/* 4 by 3 pixels, each 255, the top edge 3 pixels above the path's origin. */

/* Moved half a pixel right and up, it covers half of each pixel along its edges and a quarter of
   each corner: the top row reads 64, 128, 128, 128, 64. */
const double moved[6] = { 1.0, 0.0, 0.0, 1.0, 0.5, 0.5 };
if (daegun_rasterizer_path(rasterizer, path, DAEGUN_FILL_NONZERO, moved, &image) != DAEGUN_OK) return 1;
daegun_rasterizer_free(rasterizer);
daegun_path_free(path);
daegun_rasterizer_path_into
daegun_status daegun_rasterizer_path_into(
    daegun_rasterizer *rasterizer,
    const daegun_path *path,
    int32_t rule,
    const double *transform,
    const daegun_target *target
);

Fills a daegun_path as daegun_rasterizer_path does, straight into pixels you own, one byte each, whatever their size.

The daegun_target names a rectangle of your pixels and where it lies from the origin of the path: a left of -ox and a top of oy put the origin at column ox of row oy, counting rows down from the top. transform and rule mean what they mean in daegun_rasterizer_path.

Every pixel of the rectangle is written: the coverage of the path where it falls inside, and 0 elsewhere. What the pixels held is replaced, not added to. The part of the path outside the rectangle is cut off, and it may reach as far out as it likes: the path is cut to the target first, then worked out a band of rows at a time, so neither DAEGUN_MAX_SIDE nor DAEGUN_MAX_DRAW_BYTES applies. Bytes of a row past its width are left alone. A width or height of 0 is fine, and nothing is written.

DAEGUN_INVALID_ARGUMENT comes for a rule that is none of the DAEGUN_FILL_ codes, for a target whose pixels do not hold its rows, a stride below width or a pixels_len below (height - 1) * stride + width, and for a point that is not finite once transformed. Those leave the pixels as they were. DAEGUN_LIMIT_EXCEEDED comes for a path too tangled for its overlaps to be resolved within the work the call allows, and can leave some rows written.

/* A triangle with its corners at (1, 1), (7, 1) and (4, 5), in pixels with y up. */
daegun_path *path = daegun_path_new();
daegun_path_move_to(path, 1.0f, 1.0f);
daegun_path_line_to(path, 7.0f, 1.0f);
daegun_path_line_to(path, 4.0f, 5.0f);
daegun_path_close(path);

/* 8 by 6 pixels with the path's origin at the bottom left corner: column 0 of row 6. */
static uint8_t pixels[6][8];
daegun_target target = {
    .left = 0, .top = 6, .width = 8, .height = 6,
    .stride = sizeof pixels[0], .pixels = &pixels[0][0], .pixels_len = sizeof pixels,
};
daegun_rasterizer *rasterizer = daegun_rasterizer_new();
if (daegun_rasterizer_path_into(rasterizer, path, DAEGUN_FILL_NONZERO, NULL, &target) != DAEGUN_OK) return 1;
/* The top row, above the triangle's tip, is all 0, and the row its base stands on is 255 in the middle. */
daegun_rasterizer_free(rasterizer);
daegun_path_free(path);
daegun_rasterizer_distance_field
daegun_status daegun_rasterizer_distance_field(
    daegun_rasterizer *rasterizer,
    const daegun_font *font,
    uint32_t gid,
    const daegun_location *location,
    float px,
    int32_t field,
    float spread,
    daegun_image *out
);

Draws a glyph as a distance field: an image whose every pixel holds how far its center is from the glyph's outline.

A distance field is what a GPU text renderer keeps in its atlas in place of coverage. A shader reads the distance, smoothly interpolated between pixels, and turns it into an edge at whatever size the text is drawn, so one image serves many sizes, and outlines and glows come from the same data. field picks the kind: DAEGUN_FIELD_SDF is one byte a pixel, and DAEGUN_FIELD_MSDF three, whose median is the distance, which keeps corners sharp when the image is scaled up.

The distance d is measured in pixels from the center of each pixel to the nearest point of the outline, positive inside the glyph and negative outside, and stored as the byte 127.5 + 127.5 * d / spread, rounded and kept within 0 to 255. So the outline lies where the value crosses from 127 to 128, a pixel spread pixels or more inside reads 255, and one spread or more outside reads 0. The image reaches spread pixels past the outline on every side, and its left and top place it from the glyph's origin as those of daegun_rasterizer_glyph do.

The glyph is drawn as the font holds it, at px pixels to the em with its origin on a pixel corner: the call takes no options, so no hinting, offset or transform. spread is in pixels of this image, so it scales with the image when a shader draws it at another size. The image is BORROWED until the rasterizer's next call or its free. With a budget on the font's DAEGUN_CACHE_RASTER it is kept there under the glyph, location, size, kind and spread.

A glyph with no outline answers DAEGUN_OK with a 0 by 0 image. DAEGUN_INVALID_ARGUMENT comes for a field that is neither code and for a px or a spread that is not finite and above 0. DAEGUN_NO_OUTLINE comes for a glyph id past the count of the font and for a font with no outlines. DAEGUN_LIMIT_EXCEEDED comes for an image past DAEGUN_MAX_SIDE on a side, for one whose working memory would pass DAEGUN_MAX_DRAW_BYTES, which a DAEGUN_FIELD_MSDF field reaches at a far smaller size, and for an outline whose pieces cross or touch each other more than 64 times a piece, as a crafted glyph can. A failure leaves *out as it was.

uint32_t gid = 0;
if (daegun_font_glyph_id(font, 'I', &gid) != DAEGUN_OK) return 1;
daegun_rasterizer *rasterizer = daegun_rasterizer_new();
daegun_image field;
if (daegun_rasterizer_distance_field(rasterizer, font, gid, NULL, 128.0f, DAEGUN_FIELD_SDF, 4.0f, &field)
    != DAEGUN_OK)
    return 1;
/* One byte a pixel. Across the middle of Inter's I it climbs from 8, well outside the stem, through
   104 and 135 on either side of its edge, to 255 inside it. */
const uint8_t *row = field.pixels + (field.height / 2) * field.stride;
int left = field.left, top = field.top;
uint32_t width = field.width, height = field.height;

/* The field reaches 4 pixels past the glyph's coverage on every side. */
daegun_image coverage;
if (daegun_rasterizer_glyph(rasterizer, font, gid, NULL, 128.0f, NULL, &coverage) != DAEGUN_OK) return 1;
daegun_rasterizer_free(rasterizer);

Type to search.