# misc/dynamicfont (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/misc/dynamicfont/

Dynamic font. (DynamicFont, GlyphInfo of the original misc/dynamicfont.js)
- Bakes the chosen characters in one font and one size into a glyph atlas (one image), and draws text by cutting glyphs out of the atlas.
  Every character uses the same image, so Graphic draws it in one batch. (unlike Text, which bakes a texture per string, batching is not broken)
  Used where characters change often and the same characters are drawn many times, like scores, damage numbers and clocks.
- The atlas lays glyphs out in rows within 1024 pixels wide, with a 2 pixel gap between glyphs. (same as the original)
- Characters are counted in grapheme clusters (Hangul final consonants, combining marks, emoji sequences). Characters not in the atlas leave a gap of half the font size and are skipped. (same as the original)
- Characters are baked in white, and color glyphs (emoji) in their own colors. (the original calls fillText in white and the browser draws emoji in their own colors)
- Differences from the original:
  The original setFontAsset(FontAsset) is set_font_family(registered font name). (pass FontAsset.get_family)
  The original getAtlasCanvas is get_atlas_image (`Rc<Image>`). Desktop bakes glyphs with the font faces of the text cache (shaping, synthetic bold and italic included),
  and a character not covered by any face cannot be baked. (the other characters are baked) The web bakes with the browser Canvas2D like the original.
  build_atlas and draw_text take Graphic. (fonts are in Graphic's text cache)

## GlyphInfo (struct) (Clone, Debug, PartialEq)

Glyph info. (original GlyphInfo)
- DynamicFont makes one per character when baking the atlas. Read with get_glyph.

Example: Compute where to draw one glyph

```rust
use vanilla::{GlyphInfo, Rect, Vector2};

let glyph_info = GlyphInfo {
	character: String::from("7"),
	uv_rect: Rect::create(2.0, 2.0, 18.0, 24.0),
	advance: 20.0,
	bearing_x: -1.0,
	bearing_y: 23.0,
};
let pen_position = Vector2::create(100.0, 50.0);
let draw_left = pen_position.x - glyph_info.bearing_x;
let draw_top = pen_position.y - glyph_info.bearing_y;
assert_eq!((draw_left, draw_top), (101.0, 27.0));
assert_eq!(pen_position.x + glyph_info.advance, 120.0);
```

- `pub character: String` (field, since 0.4.0): Character. (one grapheme cluster)
  - returns String
- `pub uv_rect: Rect` (field, since 0.4.0): Position and size in the atlas. (pixels)
  - returns Rect
- `pub advance: f64` (field, since 0.4.0): Horizontal advance. (advance width + letter spacing, pixels)
  - returns f64
- `pub bearing_x: f64` (field, since 0.4.0): Distance from the pen position to the glyph's left pixel. (left is positive)
  - returns f64
- `pub bearing_y: f64` (field, since 0.4.0): Distance from the baseline to the glyph's top pixel. (up is positive)
  - returns f64

## DynamicFont (struct) (Default)

Dynamic font.
- Bake the characters to use once with build_atlas, and draw every frame with draw_text. Both need a Graphic.

Example: Bake score digits and draw them centered

```rust
use vanilla::{DynamicFont, Graphic, Vector2};

fn draw_score(dynamic_font: &mut DynamicFont, graphic: &mut Graphic, score: u32) {
	dynamic_font.build_atlas(graphic, "0123456789");
	let score_text = score.to_string();
	let text_width = dynamic_font.measure_text(&score_text);
	dynamic_font.draw_text(&score_text, Vector2::create(640.0 - text_width * 0.5, 80.0), graphic);
}

let mut dynamic_font = DynamicFont::new();
dynamic_font.set_font_size(48.0);
dynamic_font.set_letter_spacing(2.0);
```

- `pub fn new() -> DynamicFont` (constructor, since 0.4.0): Constructor. (font size 32, letter spacing 0, the default font. Same as the original)
  - returns DynamicFont: A new dynamic font with no atlas. (font name "default")
- `pub fn set_font_family(&mut self, font_family: &str)` (method, since 0.4.0): Sets the font name. (original setFontAsset, pass get_family for a FontAsset)
  - Does not change an already baked atlas. Call rebuild_atlas after changing it.
  - `font_family` &str: Name of a font loaded into Graphic's glyph cache. ("default" is the default font)
- `pub fn get_font_family(&self) -> &str` (method, since 0.4.0): Returns the font name.
  - returns &str: Current font name.
- `pub fn set_font_size(&mut self, font_size: f64)` (method, since 0.4.0): Sets the font size. (pixels, from the next build_atlas)
  - `font_size` f64: Font size. (pixels, characters not in the atlas leave a gap of half of this)
- `pub fn get_font_size(&self) -> f64` (method, since 0.4.0): Returns the font size.
  - returns f64: Current font size. (pixels)
- `pub fn set_letter_spacing(&mut self, letter_spacing: f64)` (method, since 0.4.0): Sets the letter spacing. (pixels, from the next build_atlas)
  - `letter_spacing` f64: Amount added to each character's advance width. (pixels)
- `pub fn get_letter_spacing(&self) -> f64` (method, since 0.4.0): Returns the letter spacing.
  - returns f64: Current letter spacing. (pixels)
- `pub fn get_atlas_image(&self) -> Option<&Rc<Image>>` (method, since 0.4.0): Returns the atlas image. (None if not baked yet, original getAtlasCanvas)
  - returns Option<&Rc<Image>>: The atlas image, 1024 pixels wide. None if not baked yet or after clear_atlas.
- `pub fn get_glyph(&self, character: &str) -> Option<&GlyphInfo>` (method, since 0.4.0): Returns glyph info. (None if not in the atlas)
  - `character` &str: One grapheme cluster.
  - returns Option<&GlyphInfo>: Glyph info of that character. None if not in the atlas.
- `pub fn build_atlas(&mut self, graphic: &mut Graphic, charset: &str)` (method, since 0.4.0): Bakes the atlas. (adds characters of charset not yet present, and rebakes the atlas with all characters)
  - Lays out all held characters again. (the original does the same, the misalignment of earlier baked characters caused by placing only new characters on a new canvas was also fixed in the original)
  - On desktop a character not covered by any face is skipped, and if nothing can be baked the atlas is left as is. (the web bakes with the browser Canvas2D)
  - `graphic` &mut Graphic: Graphic whose glyph cache to use.
  - `charset` &str: Characters to bake. (split into grapheme clusters, characters already present are skipped)
- `pub fn rebuild_atlas(&mut self, graphic: &mut Graphic)` (method, since 0.4.0): Rebakes all held characters. (call after changing the font, size or letter spacing)
  - Characters that cannot be baked are skipped and the rest are baked. (skipped characters are drawn like characters not in the atlas)
  - If nothing can be baked, the atlas is left as is.
  - `graphic` &mut Graphic: Graphic whose glyph cache to use.
- `pub fn draw_text(&self, text: &str, position: Vector2, graphic: &mut Graphic)` (method, since 0.4.0): Draws text. (position is the pen position of the first character, y is the baseline. The color follows Graphic's image tint, original drawText)
  - Draws nothing if there is no atlas.
  - `text` &str: Text to draw. (characters not in the atlas leave a gap of half the font size)
  - `position` Vector2: Pen position of the first character. (x is the pen position, y is the baseline, pixels in the current coordinate system)
  - `graphic` &mut Graphic: Graphic to draw with.

  Example: Draw a yellow damage number

  ```rust
  use vanilla::{Color, DynamicFont, Graphic, Vector2};
  
  fn draw_damage(dynamic_font: &DynamicFont, graphic: &mut Graphic, damage: i32) {
  	graphic.set_image_tint_color(Some(Color::create(1.0, 0.85, 0.2, 1.0)));
  	dynamic_font.draw_text(&damage.to_string(), Vector2::create(300.0, 200.0), graphic);
  	graphic.set_image_tint_color(None);
  }
  ```

- `pub fn measure_text(&self, text: &str) -> f64` (method, since 0.4.0): Measures the text width. (sum of the advance widths in the atlas, half the font size for missing characters)
  - `text` &str: Text to measure.
  - returns f64: Text width. (pixels, including letter spacing)

  Example: Before baking, half the size per character

  ```rust
  use vanilla::DynamicFont;
  
  let mut dynamic_font = DynamicFont::new();
  dynamic_font.set_font_size(40.0);
  assert_eq!(dynamic_font.measure_text("123"), 60.0);
  assert!(dynamic_font.get_atlas_image().is_none());
  ```

- `pub fn clear_atlas(&mut self)` (method, since 0.4.0): Clears the atlas. (original clearAtlas)
