1use nadir_assets::{
19 Asset, AssetError, AssetPath, AssetServer, DecodeCtx, FinalizeCtx, Handle, Scope,
20};
21use nadir_codec::font;
22use nadir_core::IVec2;
23
24use crate::{Atlas, AtlasSprite, Texture};
25
26const METRIC: i32 = i16::MAX as i32;
30
31#[derive(Clone, Debug, PartialEq)]
41pub struct Font {
42 face: String,
43 size: i32,
44 line_height: u32,
45 base: u32,
46 atlas: String,
47 sprite: String,
48 glyphs: Vec<(char, Glyph)>,
50 kerning: Vec<(char, char, i32)>,
52 fallback: Glyph,
53 last_frame: u32,
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub(crate) enum Misfit {
61 NoSprite,
63 TooFewFrames(usize),
65}
66
67#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
70pub struct Glyph {
71 frame: Option<u32>,
72 offset: IVec2,
73 advance: i32,
74}
75
76impl Font {
77 pub fn load_now_in(
92 server: &mut AssetServer,
93 path: &str,
94 scope: Scope,
95 ctx: &mut FinalizeCtx<'_>,
96 ) -> Result<Handle<Font>, AssetError> {
97 let handle = server.load_now_in::<Font>(path, scope, ctx)?;
98 let font = server.get(handle).ok_or_else(|| {
99 AssetError::Invalid(format!("the font `{path}` is not in the asset server"))
100 })?;
101 let atlas_path = font.atlas.clone();
102 let atlas = server.load_now_in::<Atlas>(&atlas_path, scope, ctx)?;
103 let (Some(font), Some(atlas)) = (server.get(handle), server.get(atlas)) else {
104 return Err(AssetError::Invalid(format!(
105 "the font `{path}` or its atlas `{atlas_path}` is not in the asset server"
106 )));
107 };
108 font.sprite_in(atlas).map_err(|misfit| {
109 AssetError::Invalid(format!("the font `{path}`: {}", font.misfit(misfit)))
110 })?;
111 let pages: Vec<String> = atlas
112 .pages()
113 .iter()
114 .map(|page| page.path().to_string())
115 .collect();
116 for page in pages {
117 server.load_in::<Texture>(&page, scope);
118 }
119 Ok(handle)
120 }
121
122 pub fn face(&self) -> &str {
124 &self.face
125 }
126
127 pub fn size(&self) -> i32 {
130 self.size
131 }
132
133 pub fn line_height(&self) -> u32 {
135 self.line_height
136 }
137
138 pub fn base(&self) -> u32 {
140 self.base
141 }
142
143 pub fn atlas(&self) -> &str {
146 &self.atlas
147 }
148
149 pub fn sprite(&self) -> &str {
152 &self.sprite
153 }
154
155 pub fn glyph(&self, character: char) -> Option<Glyph> {
157 let index = self
158 .glyphs
159 .binary_search_by_key(&character, |&(id, _)| id)
160 .ok()?;
161 self.glyphs.get(index).map(|&(_, glyph)| glyph)
162 }
163
164 pub fn fallback(&self) -> Glyph {
167 self.fallback
168 }
169
170 pub fn kerning(&self, first: char, second: char) -> i32 {
173 self.kerning
174 .binary_search_by_key(&(first, second), |&(a, b, _)| (a, b))
175 .map_or(0, |index| self.kerning[index].2)
176 }
177
178 pub(crate) fn sprite_in<'a>(&self, atlas: &'a Atlas) -> Result<&'a AtlasSprite, Misfit> {
181 let sprite = atlas.sprite(&self.sprite).ok_or(Misfit::NoSprite)?;
182 let frames = sprite.frames().len();
183 if self.last_frame as usize >= frames {
184 return Err(Misfit::TooFewFrames(frames));
185 }
186 Ok(sprite)
187 }
188
189 pub(crate) fn misfit(&self, misfit: Misfit) -> String {
191 match misfit {
192 Misfit::NoSprite => format!("its atlas has no sprite `{}`", self.sprite),
193 Misfit::TooFewFrames(frames) => format!(
194 "its glyphs name frame {} of the sprite `{}`, which has {frames}",
195 self.last_frame, self.sprite
196 ),
197 }
198 }
199}
200
201impl Glyph {
202 pub fn frame(&self) -> Option<usize> {
206 self.frame.map(|frame| frame as usize)
207 }
208
209 pub fn offset(&self) -> IVec2 {
214 self.offset
215 }
216
217 pub fn advance(&self) -> i32 {
219 self.advance
220 }
221}
222
223impl Asset for Font {
224 type Decoded = Font;
225 const EXTENSIONS: &'static [&'static str] = &["kbj"];
226
227 fn decode(bytes: &[u8], ctx: &DecodeCtx<'_>) -> Result<Font, AssetError> {
228 let file = font::parse(bytes, ctx.limits()).map_err(AssetError::Decode)?;
229 AssetPath::new(&file.atlas)
230 .ok()
231 .filter(|path| path.as_str() == file.atlas && path.extension() == Some("kbj"))
232 .ok_or_else(|| {
233 AssetError::Invalid(format!(
234 "its atlas, `{}`, is not the path of an atlas file",
235 file.atlas
236 ))
237 })?;
238 let within = |value: i32| (-METRIC..=METRIC).contains(&value);
239 let line_height = i32::try_from(file.line_height)
240 .ok()
241 .filter(|&height| within(height))
242 .ok_or_else(|| {
243 AssetError::Invalid(format!(
244 "its line height, {}, is past {METRIC} pixels",
245 file.line_height
246 ))
247 })?;
248 let metrics = |what: String, x: i32, y: i32, advance: i32| {
249 if within(x) && within(y) && within(advance) {
250 Ok(())
251 } else {
252 Err(AssetError::Invalid(format!(
253 "{what}'s offset ({x}, {y}) or advance {advance} is past {METRIC} pixels"
254 )))
255 }
256 };
257 let mut last_frame = file.fallback.frame;
258 let mut glyphs = Vec::with_capacity(file.glyphs.len());
259 for glyph in &file.glyphs {
260 metrics(
261 format!("the glyph {:?} (U+{:04X})", glyph.id, glyph.id as u32),
262 glyph.x,
263 glyph.y,
264 glyph.advance,
265 )?;
266 last_frame = last_frame.max(glyph.frame.unwrap_or(0));
267 glyphs.push((
268 glyph.id,
269 Glyph {
270 frame: glyph.frame,
271 offset: IVec2::new(glyph.x, glyph.y),
272 advance: glyph.advance,
273 },
274 ));
275 }
276 let fallback = &file.fallback;
277 metrics(
278 "the fallback".to_string(),
279 fallback.x,
280 fallback.y,
281 fallback.advance,
282 )?;
283 let mut kerning = Vec::with_capacity(file.kerning.len());
284 for pair in &file.kerning {
285 if !within(pair.amount) {
286 return Err(AssetError::Invalid(format!(
287 "the kerning of {:?} and {:?}, {}, is past {METRIC} pixels",
288 pair.first, pair.second, pair.amount
289 )));
290 }
291 kerning.push((pair.first, pair.second, pair.amount));
292 }
293 Ok(Font {
294 face: file.face,
295 size: file.size,
296 line_height: line_height as u32,
297 base: file.base,
298 atlas: file.atlas,
299 sprite: file.sprite,
300 glyphs,
301 kerning,
302 fallback: Glyph {
303 frame: Some(fallback.frame),
304 offset: IVec2::new(fallback.x, fallback.y),
305 advance: fallback.advance,
306 },
307 last_frame,
308 })
309 }
310
311 fn finalize(decoded: Font, _: &mut FinalizeCtx<'_>) -> Result<Self, AssetError> {
312 Ok(decoded)
313 }
314}
315
316#[cfg(test)]
317pub(crate) mod tests {
318 use super::*;
319 use nadir_codec::{Limits, json, kbj};
320
321 pub(crate) fn kbj(text: &str) -> Vec<u8> {
323 let value = json::parse(text, Limits::default()).expect("the test's JSON");
324 kbj::encode(&value, Limits::default()).expect("encodable")
325 }
326
327 pub(crate) fn decoded(text: &str) -> Result<Font, AssetError> {
329 Font::decode(
330 &kbj(text),
331 &DecodeCtx::new("atlas/fonts/tiny.font.kbj", Limits::default()),
332 )
333 }
334
335 pub(crate) const FONT: &str = r#"{ "version": 1,
338 "face": "Tiny", "size": -6, "line_height": 6, "base": 5,
339 "atlas": "atlas/fonts.kbj", "sprite": "fonts/tiny",
340 "glyphs": [
341 { "id": 32, "x": 0, "y": 0, "advance": 2 },
342 { "id": 65, "frame": 0, "x": 0, "y": 1, "advance": 4 },
343 { "id": 86, "frame": 1, "x": 0, "y": 1, "advance": 4 },
344 { "id": 105, "frame": 2, "x": 1, "y": 1, "advance": 3 } ],
345 "kerning": [ [65, 66, -1], [65, 86, -1], [66, 86, -1], [86, 65, -1] ],
346 "fallback": { "frame": 3, "x": 0, "y": 0, "advance": 4 } }"#;
347
348 #[test]
349 fn its_glyphs_and_kerning_are_found_by_character() {
350 let font = decoded(FONT).expect("a font");
351 assert_eq!(
352 (font.face(), font.size(), font.line_height(), font.base()),
353 ("Tiny", -6, 6, 5)
354 );
355 assert_eq!(
356 (font.atlas(), font.sprite()),
357 ("atlas/fonts.kbj", "fonts/tiny")
358 );
359 let a = font.glyph('A').expect("A");
360 assert_eq!(
361 (a.frame(), a.offset(), a.advance()),
362 (Some(0), IVec2::new(0, 1), 4)
363 );
364 let space = font.glyph(' ').expect("a space");
365 assert_eq!((space.frame(), space.advance()), (None, 2));
366 assert_eq!(font.glyph('i').expect("i").offset(), IVec2::new(1, 1));
367 assert!(font.glyph('B').is_none());
368 assert!(font.glyph('\0').is_none());
369 assert_eq!(font.fallback().frame(), Some(3));
370 assert_eq!(font.kerning('A', 'V'), -1);
371 assert_eq!(font.kerning('A', 'B'), -1, "a character it lacks");
372 assert_eq!(font.kerning('V', 'A'), -1);
373 assert_eq!(font.kerning('A', 'A'), 0);
374 assert_eq!(font.kerning('V', 'i'), 0);
375 assert_eq!(font.last_frame, 3);
376 }
377
378 #[test]
379 fn an_atlas_that_is_not_an_atlas_file_s_path_is_refused() {
380 for path in [
381 "atlas/../fonts.kbj",
382 "atlas/fonts.qoi",
383 "Atlas/fonts.kbj",
384 "/atlas/fonts.kbj",
385 ] {
386 let text = FONT.replacen("atlas/fonts.kbj", path, 1);
387 assert_eq!(
388 decoded(&text),
389 Err(AssetError::Invalid(format!(
390 "its atlas, `{path}`, is not the path of an atlas file"
391 ))),
392 "{path}"
393 );
394 }
395 let text = FONT.replacen(r#""version": 1"#, r#""version": 2"#, 1);
397 assert!(matches!(
398 decoded(&text),
399 Err(AssetError::Decode(nadir_codec::CodecError::Font { ref at, .. })) if at == "version"
400 ));
401 }
402
403 #[test]
404 fn metrics_past_32767_either_way_are_refused_and_up_to_it_taken() {
405 let cases = [
406 (r#""advance": 4 },"#, r#""advance": 32768 },"#),
407 (r#""x": 1, "y": 1"#, r#""x": -32768, "y": 1"#),
408 (
409 r#""x": 0, "y": 0, "advance": 4 }"#,
410 r#""x": 0, "y": 40000, "advance": 4 }"#,
411 ),
412 ("[65, 86, -1]", "[65, 86, -32768]"),
413 (r#""line_height": 6"#, r#""line_height": 32768"#),
414 ];
415 for (from, to) in cases {
416 let text = FONT.replacen(from, to, 1);
417 assert_ne!(text, FONT, "{from}");
418 assert!(
419 matches!(decoded(&text), Err(AssetError::Invalid(_))),
420 "{to}: {:?}",
421 decoded(&text)
422 );
423 let edge = text.replace("32768", "32767").replace("40000", "-32767");
424 assert!(decoded(&edge).is_ok(), "{edge}");
425 }
426 }
427
428 pub(crate) fn atlas(frames: usize) -> Atlas {
430 let frame =
431 r#"{ "page": 0, "x": 0, "y": 0, "w": 3, "h": 4, "ox": 0, "oy": 0, "sw": 3, "sh": 4 }"#;
432 let frames = vec![frame; frames].join(", ");
433 let text = format!(
434 r#"{{ "version": 2,
435 "pages": [ {{ "path": "atlas/fonts_0.qoi", "w": 16, "h": 8 }} ],
436 "sprites": [ {{ "name": "fonts/tiny", "frames": [ {frames} ], "pivot": [0.0, 0.0] }} ] }}"#
437 );
438 Atlas::decode(
439 &kbj(&text),
440 &DecodeCtx::new("atlas/fonts.kbj", Limits::default()),
441 )
442 .expect("an atlas")
443 }
444
445 #[test]
446 fn the_atlas_must_have_its_sprite_with_every_frame_its_glyphs_name() {
447 let font = decoded(FONT).expect("a font");
448 assert!(font.sprite_in(&atlas(4)).is_ok());
449 assert_eq!(font.sprite_in(&atlas(3)), Err(Misfit::TooFewFrames(3)));
450 assert_eq!(
451 font.misfit(Misfit::TooFewFrames(3)),
452 "its glyphs name frame 3 of the sprite `fonts/tiny`, which has 3"
453 );
454 let other = decoded(&FONT.replacen("fonts/tiny", "fonts/big", 1)).expect("a font");
455 assert_eq!(other.sprite_in(&atlas(4)), Err(Misfit::NoSprite));
456 assert_eq!(
457 other.misfit(Misfit::NoSprite),
458 "its atlas has no sprite `fonts/big`"
459 );
460 }
461
462 #[test]
463 fn it_is_made_with_nothing_in_its_context() {
464 let font = decoded(FONT).expect("a font");
465 assert_eq!(
466 Font::finalize(font.clone(), &mut FinalizeCtx::new()),
467 Ok(font)
468 );
469 }
470}