| | 1 | | using System.Collections.Generic; |
| | 2 | | using SixLabors.Fonts; |
| | 3 | | using System.Linq; |
| | 4 | | using System; |
| | 5 | |
|
| | 6 | | /// <summary> |
| | 7 | | /// Sprite font generation and drawing module. |
| | 8 | | /// </summary> |
| | 9 | | namespace Imagini.Fonts |
| | 10 | | { |
| | 11 | | /// <summary> |
| | 12 | | /// Represents a sprite font. |
| | 13 | | /// </summary> |
| | 14 | | public class SpriteFont : IDisposable |
| | 15 | | { |
| | 16 | | /// <summary> |
| | 17 | | /// Returns the pages of this sprite font. |
| | 18 | | /// </summary> |
| 71 | 19 | | public IReadOnlyList<SpriteFontPage> Pages { get; private set; } |
| | 20 | |
|
| | 21 | | /// <summary> |
| | 22 | | /// Gets the font for which this sprite font was generated. |
| | 23 | | /// </summary> |
| 22 | 24 | | public Font Font { get; private set; } |
| | 25 | |
|
| 9 | 26 | | private List<(char start, char end)> _rangeLookup = new List<(char start, char end)>(); |
| | 27 | |
|
| 0 | 28 | | public SpriteFont(Font font, IEnumerable<char> symbols, |
| 9 | 29 | | int textureSize = 512, int padding = 1) |
| | 30 | | { |
| 9 | 31 | | ISet<char> chars = Symbols.GetPrintable(symbols); |
| 9 | 32 | | var pages = new List<SpriteFontPage>(); |
| | 33 | | do |
| | 34 | | { |
| 16 | 35 | | var before = chars.Count; |
| 16 | 36 | | var page = new SpriteFontPage(font, ref chars, textureSize, padding); |
| 16 | 37 | | var after = chars.Count; |
| 16 | 38 | | if (after == before) |
| 1 | 39 | | throw new ImaginiException("Texture size is too small"); |
| 15 | 40 | | pages.Add(page); |
| 15 | 41 | | _rangeLookup.Add((page.Start, page.End)); |
| 15 | 42 | | } while (chars.Any()); |
| 8 | 43 | | Pages = pages; |
| 8 | 44 | | Font = font; |
| 8 | 45 | | } |
| | 46 | |
|
| | 47 | | /// <summary> |
| | 48 | | /// Returns index of the page that can contain the specified glyph. |
| | 49 | | /// Returns -1 if the glyph code point is out of range. |
| | 50 | | /// </summary> |
| | 51 | | public int GetPageIndex(char glyph) |
| | 52 | | { |
| 0 | 53 | | return _rangeLookup.FindIndex(pair => |
| 0 | 54 | | glyph >= pair.start && |
| 84 | 55 | | glyph <= pair.end); |
| | 56 | | } |
| | 57 | |
|
| | 58 | | /// <summary> |
| | 59 | | /// Indicates if this object is disposed. |
| | 60 | | /// </summary> |
| 4 | 61 | | public bool IsDisposed { get; private set; } |
| | 62 | | /// <summary> |
| | 63 | | /// Disposes the object. |
| | 64 | | /// </summary> |
| | 65 | | public void Dispose() |
| | 66 | | { |
| 2 | 67 | | if (IsDisposed) return; |
| 10 | 68 | | foreach(var page in Pages) |
| 3 | 69 | | page.Texture.Dispose(); |
| 2 | 70 | | Pages = null; |
| 2 | 71 | | IsDisposed = true; |
| 2 | 72 | | } |
| | 73 | | } |
| | 74 | | } |