summaryrefslogtreecommitdiff
path: root/libraries/daguerre/source/psf.cpp
blob: 81f722a8b8ec9cd2a87668804d3dd1c757f3c69b (plain) (blame)
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
43
44
45
46
47
48
49
50
51
#include <daguerre/psf.hpp>

namespace daguerre {

  //TODO: this assumes the font is in psf2 format, and has a unicode table
  std::optional<fixed_font<bool>> try_load_psf(FILE *input) {

    uint32_t header[8];
    if (fread(header, 4, 8, input) != 8)
      return {};

    const uint32_t glyphs_start = header[2];
    const uint32_t glyph_count = header[4];
    const uint32_t glyph_length = header[5];
    const uint32_t height = header[6];
    const uint32_t width = header[7];

    fixed_font<bool> font(width, height);

    const uint32_t unicode_start = glyphs_start + glyph_count * glyph_length;
    fseek(input, unicode_start, SEEK_SET);

    uint32_t indices[128];

    for (uint32_t index = 0; index < glyph_count; ++index) {
      uint8_t ch;
      fread(&ch, 1, 1, input);
      if (ch < 128)
        indices[ch] = index;
      do
        if (fread(&ch, 1, 1, input) != 1)
          return {};
      while (ch != 0xff);
    }

    for (uint8_t ch = 0; ch < 128; ++ch) {
      fseek(input, glyphs_start + glyph_length * indices[ch], SEEK_SET);
      for (unsigned h = 0; h < height; ++h)
        for (unsigned wb = 0; wb < width; wb += 8) {
          uint8_t byte;
          fread(&byte, 1, 1, input);
          for (unsigned x = 0; x < 8 && wb + x < width; ++x)
            font.glyphs[ch].at(wb + x, h) = (byte >> (7 - x)) & 1;
        }
    }

    return font;

  }

}