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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
#[cfg(feature = "image")]
mod image_impl;
#[cfg(feature = "rusttype")]
pub mod rusttype_provider;
#[cfg(not(feature = "unicode-normalization"))]
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
#[cfg(feature = "unicode-normalization")]
use alloc::string::String;
use alloc::vec::Vec;
use hashbrown::HashMap;
pub trait FontProvider {
fn pixel_type(&self) -> PixelType;
fn single_glyph(&self, character: char) -> Glyph;
fn glyphs(&self, string: &str, glyphs: &mut Vec<Glyph>);
fn line_height(&self) -> f32;
fn metrics(&self, glyph: Glyph) -> Metrics;
fn rasterize(&self, glpyh: Glyph) -> Result<Vec<u8>, CacheError>;
fn kerning(&self, _a: Glyph, _b: Glyph) -> f32 {
0.0
}
}
pub trait Texture {
fn width(&self) -> u32;
fn height(&self) -> u32;
fn put_rect(&mut self, pixel: PixelType, data: &[u8], gpu: &TextureGlyph);
}
pub struct FontCache<T: Texture> {
glyph_buffer: Vec<Glyph>,
cache: Cache<T>,
}
struct Cache<T: Texture> {
font: Box<dyn FontProvider>,
texture: T,
map: HashMap<Glyph, TextureGlyph>,
h_cursor: u32,
v_cursor: u32,
current_line_height: u32,
}
impl<T: Texture> FontCache<T> {
pub fn new(font: Box<dyn FontProvider>, texture: T) -> Self {
FontCache {
glyph_buffer: Vec::new(),
cache: Cache {
font,
texture,
map: HashMap::new(),
h_cursor: 0,
v_cursor: 0,
current_line_height: 0,
},
}
}
pub fn clear(&mut self) {
self.cache.clear();
}
pub fn render_glyph(&mut self, key: Glyph) -> Result<(Metrics, TextureGlyph), CacheError> {
self.cache.render_glyph(key)
}
pub fn render_string<'a>(
&'a mut self,
string: &str,
) -> impl 'a + Iterator<Item = Result<(Metrics, TextureGlyph), CacheError>> {
#[cfg(feature = "unicode-normalization")]
let mut string = {
use unicode_normalization::UnicodeNormalization;
string.nfc().collect::<String>()
};
#[cfg(not(feature = "unicode-normalization"))]
let mut string = string.to_owned();
string.retain(|c| !c.is_whitespace());
let glyph_buffer = &mut self.glyph_buffer;
let cache = &mut self.cache;
cache.font.glyphs(&string, glyph_buffer);
glyph_buffer
.drain(..)
.map(move |glyph| cache.render_glyph(glyph))
}
pub fn cache_string(&mut self, string: &str) -> Result<(), CacheError> {
self.render_string(string).map(|r| r.map(|_| ())).collect()
}
pub fn replace_texture(&mut self, mut texture: T) -> T {
self.clear();
core::mem::swap(&mut self.cache.texture, &mut texture);
texture
}
pub fn texture(&self) -> &T {
&self.cache.texture
}
pub fn font(&self) -> &dyn FontProvider {
self.cache.font.as_ref()
}
}
impl<T: Texture> Cache<T> {
fn clear(&mut self) {
self.map.clear();
self.h_cursor = 0;
self.v_cursor = 0;
self.current_line_height = 0;
}
fn render_glyph(&mut self, glyph: Glyph) -> Result<(Metrics, TextureGlyph), CacheError> {
if let Some(tex_glyph) = self.map.get(&glyph) {
return Ok((self.font.metrics(glyph), *tex_glyph));
}
let metrics = self.font.metrics(glyph);
let bounds = metrics.bounds.unwrap();
if bounds.width > self.texture.width() || bounds.height > self.texture.height() {
return Err(CacheError::TextureTooSmall);
}
if bounds.width + self.h_cursor > self.texture.width() {
self.h_cursor = 0;
self.v_cursor += self.current_line_height + 1;
self.current_line_height = 0;
}
if bounds.height + self.v_cursor > self.texture.height() {
return Err(CacheError::OutOfSpace);
}
let pixel_type = self.font.pixel_type();
let data = self.font.rasterize(glyph)?;
let gpu = TextureGlyph {
glyph,
bounds: Bounds {
x: self.h_cursor as i32,
y: self.v_cursor as i32,
width: bounds.width,
height: bounds.height,
},
};
self.texture.put_rect(pixel_type, &data[..], &gpu);
self.h_cursor += gpu.bounds.width + 1;
self.current_line_height = self.current_line_height.max(gpu.bounds.height);
self.map.insert(glyph, gpu);
Ok((self.font.metrics(glyph), gpu))
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Glyph(pub u32);
#[derive(Copy, Clone, Debug)]
pub struct TextureGlyph {
pub glyph: Glyph,
pub bounds: Bounds,
}
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct Metrics {
pub bounds: Option<Bounds>,
pub bearing_x: f32,
pub advance_x: f32,
pub bearing_y: f32,
pub advance_y: f32,
}
#[derive(Copy, Clone, Debug)]
pub struct Bounds {
pub x: i32,
pub y: i32,
pub width: u32,
pub height: u32,
}
#[derive(Copy, Clone, Debug)]
pub enum CacheError {
TextureTooSmall,
OutOfSpace,
NonRenderableGlyph(Glyph),
}
#[cfg(feature = "std")]
use std::{error::Error, fmt};
#[cfg(feature = "std")]
impl fmt::Display for CacheError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CacheError::TextureTooSmall => {
write!(f, "The texture is too small to render the given input")
}
CacheError::OutOfSpace => write!(
f,
"The cache is out of space, and must be cleared before more rendering"
),
CacheError::NonRenderableGlyph(glyph) => {
write!(f, "Attempted to render an un-renderable glyph: {:?}", glyph)
}
}
}
}
#[cfg(feature = "std")]
impl Error for CacheError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
None
}
}
pub enum PixelType {
Alpha,
RGBA,
}