summaryrefslogtreecommitdiff
path: root/VP-fontwork.lua
blob: 4029227966530cea521b3b16606fad210c5e2cac (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
function put_extra_glyph(width, data)
    local idx = width .. "-" .. data
    if not extra_glyphs_file then extra_glyphs_file = Output "extra-glyphs.xml" end
    if extra_glyphs[idx] then return end
    extra_glyphs_file:write('  <Symbol Width="' .. width .. '" Data="' .. data .. '" Text="Unknown" />\n')
    extra_glyphs[idx] = true
end

function resolve_font(font)
    local r = {}
    
    for k, v in pairs(font) do
        local idx = v.Width .. "-" .. v.Data
        local g = glyphes[idx]
        if not g then
            put_extra_glyph(v.Width, v.Data)
            r[k] = "<??>"
        else
            r[k] = g.attr.Text
        end
    end
    
    return r
end

function extract_font(fname, h)
    local n_glyphes = h:readU32()
    local height = h:readU32()
    local widths = {}
    
    for i = 1, n_glyphes do
        widths[i] = h:readU8()
    end
    
    local o
    local r = {}
    
    if dump_glyph then
        dump_mkdir(fname)
    end
    
    for i = 1, n_glyphes do
        if dump_mode and dump_glyph then
            o = Output(fname .. string.format("/%03i-%02i.glyph", i, widths[i]))
            o:copyfrom(h, height * 2)
            o:destroy()
            h:seek(-height * 2, SEEK_CUR)
            o = Output(fname .. string.format("/%03i-%02i.raw", i, widths[i]))
            local bits
            for j = 1, height do
                bits = h:readU16()
                for k = 1, height do -- should be widths[i]
                    bits = shl(bits, 1)
                    local bit = andB(bits, 65536) ~= 0
                    o:writeU8(bit and 0xff or 0)
                end
            end
            o:destroy()
            h:seek(-height * 2, SEEK_CUR)
        end
        local b = Buffer(true)
        b:copyfrom(h, height * 2)
        if widths[i] ~= 0 then
            r[i] = { Data = Base64Encode(b), Width = widths[i] }
        else
            -- Verify this is only padding
            local Data = Base64Encode(b)
            if Data ~= "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" then
                error("Font not consistant.")
            end
        end
        b:destroy()
    end
    
    return r
end

function add_glyph(font, char)
    local idx = font.idx
    font.ilookup[idx] = char
    font.clookup[char] = idx
    font.idx = font.idx + 1
    return idx
end

function load_glyphes()
    local tglyphes = xml.LoadHandle(Input "VP-database.xml")[1]
    glyphes = {}
    for k, v in ipairs(tglyphes) do
        glyphes[v.attr.Width .. "-" .. v.attr.Data] = v
        glyphes[v.attr.Text] = v
    end
end