summaryrefslogtreecommitdiff
path: root/font/font.h
blob: 9d37e646f888954ebbc0bbd8c4826b498393eb9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#pragma once

#include <assert.h>
#include <stdint.h>

static const unsigned char FontGlyphStart     = 32;  // Space.
static const unsigned char FontGlyphEnd       = 127; // One past tilde.
static const unsigned int  FontAtlasNumGlyphs = FontGlyphEnd - FontGlyphStart;

/// Font atlas header.
typedef struct FontHeader {
  uint16_t glyph_width;
  uint16_t glyph_height;
  uint16_t num_glyphs;
} FontHeader;

/// Font atlas.
///
/// Pixels are stored in "glyph-major" order. First the rows of the first glyph,
/// followed by the rows of the second glyph, etc. Thus, pixels should be viewed
/// as a linear array, not a 2d array. This arrangement allows an application to
/// render glyphs by scanning atlas memory linearly.
typedef struct FontAtlas {
  FontHeader    header;
  unsigned char pixels[1];
} FontAtlas;

/// Load a font atlas from a file.
FontAtlas* LoadFontAtlas(const char* path);

/// Get the glyph into the atlas.
static inline const unsigned char* FontGetGlyph(
    const FontAtlas* atlas, unsigned char c) {
  assert(atlas);
  unsigned index = c - FontGlyphStart;
  if (index >= FontAtlasNumGlyphs) {
    index = '?' - FontGlyphStart;
  }
  assert(index < FontAtlasNumGlyphs);
  return atlas->pixels +
         index * (atlas->header.glyph_width * atlas->header.glyph_height);
}