comparison semiconginev2/text/font.nim @ 1234:841e12f33c47

add: text & font rendering, not tested yet
author sam <sam@basx.dev>
date Sat, 20 Jul 2024 00:03:57 +0700
parents
children 176383220123
comparison
equal deleted inserted replaced
1233:1cf698973dca 1234:841e12f33c47
1 {.emit: "#define STBTT_STATIC".}
2 {.emit: "#define STB_TRUETYPE_IMPLEMENTATION".}
3 {.emit: "#include \"" & currentSourcePath.parentDir() & "/stb_truetype.h\"".}
4
5 type stbtt_fontinfo {.importc, incompleteStruct.} = object
6
7 proc stbtt_InitFont(info: ptr stbtt_fontinfo, data: ptr char, offset: cint): cint {.importc, nodecl.}
8 proc stbtt_ScaleForPixelHeight(info: ptr stbtt_fontinfo, pixels: cfloat): cfloat {.importc, nodecl.}
9
10 proc stbtt_GetCodepointBitmap(info: ptr stbtt_fontinfo, scale_x: cfloat, scale_y: cfloat, codepoint: cint, width, height, xoff, yoff: ptr cint): cstring {.importc, nodecl.}
11 # proc stbtt_GetCodepointBitmapBox(info: ptr stbtt_fontinfo, codepoint: cint, scale_x, scale_y: cfloat, ix0, iy0, ix1, iy1: ptr cint) {.importc, nodecl.}
12
13 proc stbtt_GetCodepointHMetrics(info: ptr stbtt_fontinfo, codepoint: cint, advance, leftBearing: ptr cint) {.importc, nodecl.}
14 proc stbtt_GetCodepointKernAdvance(info: ptr stbtt_fontinfo, ch1, ch2: cint): cint {.importc, nodecl.}
15 proc stbtt_FindGlyphIndex(info: ptr stbtt_fontinfo, codepoint: cint): cint {.importc, nodecl.}
16
17 proc stbtt_GetFontVMetrics(info: ptr stbtt_fontinfo, ascent, descent, lineGap: ptr cint) {.importc, nodecl.}
18
19 proc ReadTrueType*(stream: Stream, name: string, codePoints: seq[Rune], lineHeightPixels: float32): Font =
20 var
21 indata = stream.readAll()
22 fontinfo: stbtt_fontinfo
23 if stbtt_InitFont(addr fontinfo, addr indata[0], 0) == 0:
24 raise newException(Exception, "An error occured while loading PNG file")
25
26 result.name = name
27 result.fontscale = float32(stbtt_ScaleForPixelHeight(addr fontinfo, cfloat(lineHeightPixels)))
28
29 var ascent, descent, lineGap: cint
30 stbtt_GetFontVMetrics(addr fontinfo, addr ascent, addr descent, addr lineGap)
31
32 result.lineHeight = float32(ascent - descent) * result.fontscale
33 result.lineAdvance = float32(ascent - descent + lineGap) * result.fontscale
34
35 # ensure all codepoints are available in the font
36 for codePoint in codePoints:
37 if stbtt_FindGlyphIndex(addr fontinfo, cint(codePoint)) == 0:
38 warn &"Loading font {name}: Codepoint '{codePoint}' ({cint(codePoint)}) has no glyph"
39
40 var
41 topOffsets: Table[Rune, int]
42 images: seq[Image[Gray]]
43 let empty_image = Image[Gray](width: 1, height: 1, data: @[[0'u8]])
44
45 for codePoint in codePoints:
46 var
47 width, height: cint
48 offX, offY: cint
49 let
50 data = stbtt_GetCodepointBitmap(
51 addr fontinfo,
52 result.fontscale,
53 result.fontscale,
54 cint(codePoint),
55 addr width, addr height,
56 addr offX, addr offY
57 )
58 topOffsets[codePoint] = offY
59
60 if char(codePoint) in UppercaseLetters:
61 result.capHeight = float32(height)
62 if codePoint == Rune('x'):
63 result.xHeight = float32(height)
64
65 if width > 0 and height > 0:
66 var bitmap = newSeq[Gray](width * height)
67 for i in 0 ..< width * height:
68 bitmap[i] = [data[i].uint8]
69 images.add Image[Gray](width: width.uint32, height: height.uint32, data: bitmap)
70 else:
71 images.add empty_image
72
73 nativeFree(data)
74
75 let packed = Pack(images)
76
77 result.fontAtlas = packed.atlas
78
79 let w = float32(packed.atlas.width)
80 let h = float32(packed.atlas.height)
81 for i in 0 ..< codePoints.len:
82 let
83 codePoint = codePoints[i]
84 image = images[i]
85 coord = (x: float32(packed.coords[i].x), y: float32(packed.coords[i].y))
86 iw = float32(image.width)
87 ih = float32(image.height)
88 # horizontal spaces:
89 var advance, leftBearing: cint
90 stbtt_GetCodepointHMetrics(addr fontinfo, cint(codePoint), addr advance, addr leftBearing)
91
92 result.glyphs[codePoint] = GlyphInfo(
93 dimension: NewVec2f(float32(image.width), float32(image.height)),
94 uvs: [
95 NewVec2f((coord.x + 0.5) / w, (coord.y + ih - 0.5) / h),
96 NewVec2f((coord.x + 0.5) / w, (coord.y + 0.5) / h),
97 NewVec2f((coord.x + iw - 0.5) / w, (coord.y + 0.5) / h),
98 NewVec2f((coord.x + iw - 0.5) / w, (coord.y + ih - 0.5) / h),
99 ],
100 topOffset: float32(topOffsets[codePoint]),
101 leftOffset: float32(leftBearing) * result.fontscale,
102 advance: float32(advance) * result.fontscale,
103 )
104
105 for codePointAfter in codePoints:
106 result.kerning[(codePoint, codePointAfter)] = float32(stbtt_GetCodepointKernAdvance(
107 addr fontinfo,
108 cint(codePoint),
109 cint(codePointAfter)
110 )) * result.fontscale
111
112 func TextWidth*(text: seq[Rune], font: FontObj): float32 =
113 var currentWidth = 0'f32
114 var lineWidths: seq[float32]
115 for i in 0 ..< text.len:
116 if text[i] == NEWLINE:
117 lineWidths.add currentWidth
118 currentWidth = 0'f32
119 else:
120 if not (i == text.len - 1 and text[i].isWhiteSpace):
121 currentWidth += font.glyphs[text[i]].advance
122 if i < text.len - 1:
123 currentWidth += font.kerning[(text[i], text[i + 1])]
124 lineWidths.add currentWidth
125 return lineWidths.max
126
127 func WordWrapped*(text: seq[Rune], font: FontObj, maxWidth: float32): seq[Rune] =
128 var remaining: seq[seq[Rune]] = @[@[]]
129 for c in text:
130 if c == SPACE:
131 remaining.add newSeq[Rune]()
132 else:
133 remaining[^1].add c
134 remaining.reverse()
135
136 var currentLine: seq[Rune]
137
138 while remaining.len > 0:
139 var currentWord = remaining.pop()
140 assert not (SPACE in currentWord)
141
142 if currentWord.len == 0:
143 currentLine.add SPACE
144 else:
145 assert currentWord[^1] != SPACE
146 # if this is the first word of the line and it is too long we need to
147 # split by character
148 if currentLine.len == 0 and (SPACE & currentWord).TextWidth(font) > maxWidth:
149 var subWord = @[currentWord[0]]
150 for c in currentWord[1 .. ^1]:
151 if (subWord & c).TextWidth(font) > maxWidth:
152 break
153 subWord.add c
154 result.add subWord & NEWLINE
155 remaining.add currentWord[subWord.len .. ^1] # process rest of the word in next iteration
156 else:
157 if (currentLine & SPACE & currentWord).TextWidth(font) <= maxWidth:
158 if currentLine.len == 0:
159 currentLine = currentWord
160 else:
161 currentLine = currentLine & SPACE & currentWord
162 else:
163 result.add currentLine & NEWLINE
164 remaining.add currentWord
165 currentLine = @[]
166 if currentLine.len > 0 and currentLine != @[SPACE]:
167 result.add currentLine
168
169 return result
170