-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFontLibrary.Font.cs
More file actions
296 lines (240 loc) · 11.6 KB
/
Copy pathFontLibrary.Font.cs
File metadata and controls
296 lines (240 loc) · 11.6 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
using System;
using SharpFont;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace FNT
{
public partial class FontLibrary
{
private partial class Font : IFont
{
public char? DefaultCharacter
{
get { return _defaultChar; }
set
{
if (value == null)
{
_defaultChar = null;
_defaultGlyph = null;
return;
}
var c = value.Value;
if (!TryGetGlyph(c, out var glyph))
throw new Exception($"Invalid character '{c}'");
_defaultChar = c;
_defaultGlyph = glyph;
}
}
public int TabSpaces { get; set; }
public int Size { get; }
public int LineHeight { get; }
public Font(int size, byte[] fontBytes, GraphicsDevice graphicsDevice)
{
Size = size;
this.fontBytes = fontBytes;
this.graphicsDevice = graphicsDevice;
face = new Face(_lib, fontBytes, 0);
face.SetCharSize(0, Size, 0, 96);
LineHeight = face.Size.Metrics.NominalHeight;
ascender = (int)face.Size.Metrics.Ascender;
face.LoadGlyph(face.GetCharIndex(32), LoadFlags.Default, LoadTarget.Normal);
advanceSpace = (int)face.Glyph.Metrics.HorizontalAdvance;
}
public void PreheatCache(IEnumerable<char> chars)
{
foreach (var c in chars)
TryGetGlyph(c, out _);
}
public IText MakeText(string text)
{
// Heavily modified from https://gist.github.com/suzusime/b644eedffba87001427291d79f36a955
if (text == null)
throw new ArgumentNullException(nameof(text));
var set = new HashSet<Texture2D>();
var result = new List<RenderGlyph>();
float maxWidth = 0, maxHeight = 0;
if (text.Length > 0)
{
int currLineWidth = 0, currLineHeight = LineHeight;
bool firstInLine = true;
float underrun = 0, overrun = 0;
var pen = new Vector2();
for (int i = 0; i < text.Length; i++)
{
#region Load character
char c = text[i];
switch (c)
{
case ' ':
pen.X += advanceSpace;
continue;
case '\t':
pen.X += advanceSpace * TabSpaces;
continue;
case '\r': // ignore
continue;
case '\n':
firstInLine = true;
underrun = overrun = 0;
pen.X = 0;
pen.Y += LineHeight;
maxWidth = Math.Max(maxWidth, currLineWidth);
maxHeight = Math.Max(maxHeight, currLineHeight);
continue;
}
if (!TryGetGlyph(c, out var glyph))
{
if (_defaultGlyph == null)
throw new Exception($"Invalid character '{c}'");
glyph = _defaultGlyph.Value;
}
float gAdvanceX = glyph.Advance;
float gBearingX = glyph.BearingX;
float gWidth = glyph.Width;
#endregion
#region Underrun
// Negative bearing would cause clipping of the first character
// at the left boundary, if not accounted for.
// A positive bearing would cause empty space.
underrun += -(gBearingX);
if (pen.X == 0)
pen.X += underrun;
if (firstInLine && underrun <= 0)
{
underrun = 0;
firstInLine = false;
}
#endregion
var texture = GetTexturePageForGlyph(glyph, out var bounds);
int x = (int)Math.Round(pen.X + glyph.BitmapLeft);
int y = (int)Math.Round(pen.Y + ascender - glyph.BearingY);
result.Add(new RenderGlyph(texture, bounds, new Vector2(x, y)));
set.Add(texture);
currLineWidth = x + glyph.Width;
currLineHeight = Math.Max(currLineHeight, y + glyph.Height);
#region Overrun
// Accumulate overrun, which could cause clipping at the right side of characters near
// the end of the string (typically affects fonts with slanted characters)
// Overrun will be added at the end of the line
if (gBearingX + gWidth > 0 || gAdvanceX > 0)
{
overrun -= Math.Max(gBearingX + gWidth, gAdvanceX);
if (overrun < 0) overrun = 0;
}
overrun += (gBearingX == 0 && gWidth == 0 ? 0 : gBearingX + gWidth - gAdvanceX);
#endregion
pen.X += gAdvanceX;
#region Kerning (for next character)
// Calculate kern for the NEXT character (if any)
// The kern value adjusts the origin of the next character (positive or negative).
if (i < text.Length - 1)
{
char cNext = text[i + 1];
if (TryGetGlyph(cNext, out var next))
{
int kern = GetKerning(glyph, next);
// sanity check for some fonts that have kern way out of whack
if (kern > gAdvanceX * 5 || kern < -(gAdvanceX * 5))
kern = 0;
pen.X += kern;
}
}
#endregion
}
maxWidth = Math.Max(maxWidth, currLineWidth);
maxHeight = Math.Max(maxHeight, currLineHeight);
if (set.Count > 1)
result.Sort((a, b) => a.Texture != b.Texture ? 1 : 0);
}
return new TextImpl(text, result, maxWidth, maxHeight);
}
#region Implementation
private Texture2D GetTexturePageForGlyph(GlyphInfo glyph, out Rectangle bounds)
{
if (!texturesByChar.TryGetValue(glyph.Character, out var texture))
{
var page = FindPage(glyph.Width, glyph.Height, out var packX, out var packY);
page.RenderGlyph(glyph.Width, glyph.Height, glyph.BufferData, packX, packY);
boundsByChar[glyph.Character] = bounds = new Rectangle(packX, packY, glyph.Width, glyph.Height);
return texturesByChar[glyph.Character] = texture = page.Texture;
}
bounds = boundsByChar[glyph.Character];
return texture;
}
private GlyphPage FindPage(int width, int height, out int packX, out int packY)
{
foreach (var page in pages)
{
if (page.Pack(width, height, out var rect))
{
packX = rect.X;
packY = rect.Y;
return page;
}
}
// none found, make a new page
{
var result = new GlyphPage(graphicsDevice, TextureSize);
pages.Add(result);
if (!result.Pack(width, height, out var rect))
throw new Exception("Failed to pack item even in new page");
packX = rect.X;
packY = rect.Y;
return result;
}
}
private bool TryGetGlyph(char c, out GlyphInfo glyph)
{
if (glyphs.TryGetValue(c, out glyph))
return true;
var glyphIndex = face.GetCharIndex(c);
if (glyphIndex == 0)
return false;
byte[] bufferData;
face.LoadGlyph(glyphIndex, LoadFlags.Default, LoadTarget.Normal);
if (face.Glyph.Metrics.Width == 0)
{
bufferData = new byte[0];
}
else
{
face.Glyph.RenderGlyph(RenderMode.Normal);
bufferData = face.Glyph.Bitmap.BufferData;
}
glyphs[c] = glyph = new GlyphInfo(c, glyphIndex, face.Glyph.BitmapLeft, face.Glyph.Metrics, bufferData);
return true;
}
private int GetKerning(GlyphInfo l, GlyphInfo r)
{
if (!face.HasKerning)
return 0;
if (!kerning.TryGetValue(l.Character, out var subKerning))
kerning[l.Character] = subKerning = new Dictionary<char, int>();
if (!subKerning.TryGetValue(r.Character, out var kern))
subKerning[r.Character] = kern = (int) face.GetKerning(l.Index, r.Index, KerningMode.Default).X;
return kern;
}
public void Dispose()
{
foreach (var page in pages)
page.Dispose();
}
#endregion
private static int TextureSize = 1024;
private GlyphInfo? _defaultGlyph;
private char? _defaultChar;
private readonly GraphicsDevice graphicsDevice;
private readonly byte[] fontBytes;
private readonly int ascender;
private readonly int advanceSpace;
private readonly Face face;
private readonly List<GlyphPage> pages = new List<GlyphPage>();
private readonly Dictionary<char, GlyphInfo> glyphs = new Dictionary<char, GlyphInfo>();
private readonly Dictionary<char, Rectangle> boundsByChar = new Dictionary<char, Rectangle>();
private readonly Dictionary<char, Texture2D> texturesByChar = new Dictionary<char, Texture2D>();
private readonly Dictionary<char, Dictionary<char, int>> kerning = new Dictionary<char, Dictionary<char, int>>();
}
}
}