BitmapFont.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. // Copyright (c) Craftwork Games. All rights reserved.
  2. // Licensed under the MIT license.
  3. // See LICENSE file in the project root for full license information.
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Text;
  9. using Microsoft.Xna.Framework;
  10. using Microsoft.Xna.Framework.Graphics;
  11. using MonoGame.Extended.Content.BitmapFonts;
  12. using MonoGame.Extended.Graphics;
  13. namespace MonoGame.Extended.BitmapFonts;
  14. public sealed class BitmapFont
  15. {
  16. private readonly Dictionary<int, BitmapFontCharacter> _characters;
  17. public string Face { get; }
  18. public int Size { get; }
  19. public int LineHeight { get; }
  20. public int LetterSpacing { get; set; }
  21. public int LineSpacing {get; set;}
  22. public bool UseKernings { get; set; } = true;
  23. public BitmapFont(string face, int size, int lineHeight, IEnumerable<BitmapFontCharacter> characters)
  24. :this(face, size, lineHeight, 0, 0, characters) { }
  25. public BitmapFont(string face, int size, int lineHeight, int letterSpacing, int lineSpacing, IEnumerable<BitmapFontCharacter> characters)
  26. {
  27. Face = face;
  28. Size = size;
  29. LineHeight = lineHeight;
  30. LetterSpacing = letterSpacing;
  31. LineSpacing = lineSpacing;
  32. _characters = new Dictionary<int, BitmapFontCharacter>();
  33. foreach(BitmapFontCharacter character in characters)
  34. {
  35. _characters.Add(character.Character, character);
  36. }
  37. }
  38. public BitmapFontCharacter GetCharacter(int character) => _characters.TryGetValue(character, out BitmapFontCharacter fontCharacter) ? fontCharacter : null;/* _characters[character];*/
  39. public bool TryGetCharacter(int character, out BitmapFontCharacter value) => _characters.TryGetValue(character, out value);
  40. public SizeF MeasureString(string text)
  41. {
  42. if (string.IsNullOrEmpty(text))
  43. return SizeF.Empty;
  44. var stringRectangle = GetStringRectangle(text);
  45. return new SizeF(stringRectangle.Width, stringRectangle.Height);
  46. }
  47. public SizeF MeasureString(StringBuilder text)
  48. {
  49. if (text == null || text.Length == 0)
  50. return SizeF.Empty;
  51. var stringRectangle = GetStringRectangle(text);
  52. return new SizeF(stringRectangle.Width, stringRectangle.Height);
  53. }
  54. public RectangleF GetStringRectangle(string text)
  55. {
  56. return GetStringRectangle(text, Vector2.Zero);
  57. }
  58. public RectangleF GetStringRectangle(string text, Vector2 position)
  59. {
  60. var glyphs = GetGlyphs(text, position);
  61. var rectangle = new RectangleF(position.X, position.Y, 0, LineHeight);
  62. foreach (var glyph in glyphs)
  63. {
  64. if (glyph.Character != null)
  65. {
  66. var right = glyph.Position.X + glyph.Character.TextureRegion.Width;
  67. if (right > rectangle.Right)
  68. rectangle.Width = (int)(right - rectangle.Left);
  69. }
  70. if (glyph.CharacterID == '\n')
  71. rectangle.Height += LineHeight;
  72. }
  73. return rectangle;
  74. }
  75. public RectangleF GetStringRectangle(StringBuilder text, Vector2? position = null)
  76. {
  77. var position1 = position ?? new Vector2();
  78. var glyphs = GetGlyphs(text, position1);
  79. var rectangle = new RectangleF(position1.X, position1.Y, 0, LineHeight);
  80. foreach (var glyph in glyphs)
  81. {
  82. if (glyph.Character != null)
  83. {
  84. var right = glyph.Position.X + glyph.Character.TextureRegion.Width;
  85. if (right > rectangle.Right)
  86. rectangle.Width = (int)(right - rectangle.Left);
  87. }
  88. if (glyph.CharacterID == '\n')
  89. rectangle.Height += LineHeight + LineSpacing;
  90. }
  91. return rectangle;
  92. }
  93. public struct BitmapFontGlyph
  94. {
  95. public int CharacterID;
  96. public Vector2 Position;
  97. public BitmapFontCharacter Character;
  98. }
  99. public StringGlyphEnumerable GetGlyphs(string text, Vector2? position = null)
  100. {
  101. return new StringGlyphEnumerable(this, text, position);
  102. }
  103. public StringBuilderGlyphEnumerable GetGlyphs(StringBuilder text, Vector2? position)
  104. {
  105. return new StringBuilderGlyphEnumerable(this, text, position);
  106. }
  107. public struct StringGlyphEnumerable : IEnumerable<BitmapFontGlyph>
  108. {
  109. private readonly StringGlyphEnumerator _enumerator;
  110. public StringGlyphEnumerable(BitmapFont font, string text, Vector2? position)
  111. {
  112. _enumerator = new StringGlyphEnumerator(font, text, position);
  113. }
  114. public StringGlyphEnumerator GetEnumerator()
  115. {
  116. return _enumerator;
  117. }
  118. IEnumerator<BitmapFontGlyph> IEnumerable<BitmapFontGlyph>.GetEnumerator()
  119. {
  120. return _enumerator;
  121. }
  122. IEnumerator IEnumerable.GetEnumerator()
  123. {
  124. return _enumerator;
  125. }
  126. }
  127. public struct StringGlyphEnumerator : IEnumerator<BitmapFontGlyph>
  128. {
  129. private readonly BitmapFont _font;
  130. private readonly string _text;
  131. private int _index;
  132. private readonly Vector2 _position;
  133. private Vector2 _positionDelta;
  134. private BitmapFontGlyph _currentGlyph;
  135. private BitmapFontGlyph? _previousGlyph;
  136. object IEnumerator.Current
  137. {
  138. get
  139. {
  140. // casting a struct to object will box it, behaviour we want to avoid...
  141. throw new InvalidOperationException();
  142. }
  143. }
  144. public BitmapFontGlyph Current => _currentGlyph;
  145. public StringGlyphEnumerator(BitmapFont font, string text, Vector2? position)
  146. {
  147. _font = font;
  148. _text = text;
  149. _index = -1;
  150. _position = position ?? new Vector2();
  151. _positionDelta = new Vector2();
  152. _currentGlyph = new BitmapFontGlyph();
  153. _previousGlyph = null;
  154. }
  155. public bool MoveNext()
  156. {
  157. if (++_index >= _text.Length)
  158. return false;
  159. var character = GetUnicodeCodePoint(_text, ref _index);
  160. _currentGlyph.CharacterID = character;
  161. _font.TryGetCharacter(character, out _currentGlyph.Character);
  162. _currentGlyph.Position = _position + _positionDelta;
  163. if (_currentGlyph.Character != null)
  164. {
  165. _currentGlyph.Position.X += _currentGlyph.Character.XOffset;
  166. _currentGlyph.Position.Y += _currentGlyph.Character.YOffset;
  167. _positionDelta.X += _currentGlyph.Character.XAdvance + _font.LetterSpacing;
  168. }
  169. if (_font.UseKernings && _previousGlyph?.Character != null)
  170. {
  171. if (_previousGlyph.Value.Character.Kernings.TryGetValue(character, out var amount))
  172. {
  173. _positionDelta.X += amount;
  174. _currentGlyph.Position.X += amount;
  175. }
  176. }
  177. _previousGlyph = _currentGlyph;
  178. if (character != '\n')
  179. return true;
  180. _positionDelta.Y += _font.LineHeight + _font.LineSpacing;
  181. _positionDelta.X = 0;
  182. _previousGlyph = null;
  183. return true;
  184. }
  185. private static int GetUnicodeCodePoint(string text, ref int index)
  186. {
  187. return char.IsHighSurrogate(text[index]) && ++index < text.Length
  188. ? char.ConvertToUtf32(text[index - 1], text[index])
  189. : text[index];
  190. }
  191. public void Dispose()
  192. {
  193. }
  194. public void Reset()
  195. {
  196. _positionDelta = new Vector2();
  197. _index = -1;
  198. _previousGlyph = null;
  199. }
  200. }
  201. public struct StringBuilderGlyphEnumerable : IEnumerable<BitmapFontGlyph>
  202. {
  203. private readonly StringBuilderGlyphEnumerator _enumerator;
  204. public StringBuilderGlyphEnumerable(BitmapFont font, StringBuilder text, Vector2? position)
  205. {
  206. _enumerator = new StringBuilderGlyphEnumerator(font, text, position);
  207. }
  208. public StringBuilderGlyphEnumerator GetEnumerator()
  209. {
  210. return _enumerator;
  211. }
  212. IEnumerator<BitmapFontGlyph> IEnumerable<BitmapFontGlyph>.GetEnumerator()
  213. {
  214. return _enumerator;
  215. }
  216. IEnumerator IEnumerable.GetEnumerator()
  217. {
  218. return _enumerator;
  219. }
  220. }
  221. public struct StringBuilderGlyphEnumerator : IEnumerator<BitmapFontGlyph>
  222. {
  223. private readonly BitmapFont _font;
  224. private readonly StringBuilder _text;
  225. private int _index;
  226. private readonly Vector2 _position;
  227. private Vector2 _positionDelta;
  228. private BitmapFontGlyph _currentGlyph;
  229. private BitmapFontGlyph? _previousGlyph;
  230. object IEnumerator.Current
  231. {
  232. get
  233. {
  234. // casting a struct to object will box it, behaviour we want to avoid...
  235. throw new InvalidOperationException();
  236. }
  237. }
  238. public BitmapFontGlyph Current => _currentGlyph;
  239. public StringBuilderGlyphEnumerator(BitmapFont font, StringBuilder text, Vector2? position)
  240. {
  241. _font = font;
  242. _text = text;
  243. _index = -1;
  244. _position = position ?? new Vector2();
  245. _positionDelta = new Vector2();
  246. _currentGlyph = new BitmapFontGlyph();
  247. _previousGlyph = null;
  248. }
  249. public bool MoveNext()
  250. {
  251. if (++_index >= _text.Length)
  252. return false;
  253. var character = GetUnicodeCodePoint(_text, ref _index);
  254. _currentGlyph = new BitmapFontGlyph
  255. {
  256. CharacterID = character,
  257. Character = _font.GetCharacter(character),
  258. Position = _position + _positionDelta
  259. };
  260. if (_currentGlyph.Character != null)
  261. {
  262. _currentGlyph.Position.X += _currentGlyph.Character.XOffset;
  263. _currentGlyph.Position.Y += _currentGlyph.Character.YOffset;
  264. _positionDelta.X += _currentGlyph.Character.XAdvance + _font.LetterSpacing;
  265. }
  266. if (_font.UseKernings && _previousGlyph.HasValue && _previousGlyph.Value.Character != null)
  267. {
  268. int amount;
  269. if (_previousGlyph.Value.Character.Kernings.TryGetValue(character, out amount))
  270. {
  271. _positionDelta.X += amount;
  272. _currentGlyph.Position.X += amount;
  273. }
  274. }
  275. _previousGlyph = _currentGlyph;
  276. if (character != '\n')
  277. return true;
  278. _positionDelta.Y += _font.LineHeight + _font.LineSpacing;
  279. _positionDelta.X = _position.X;
  280. _previousGlyph = null;
  281. return true;
  282. }
  283. private static int GetUnicodeCodePoint(StringBuilder text, ref int index)
  284. {
  285. return char.IsHighSurrogate(text[index]) && ++index < text.Length
  286. ? char.ConvertToUtf32(text[index - 1], text[index])
  287. : text[index];
  288. }
  289. public void Dispose()
  290. {
  291. }
  292. public void Reset()
  293. {
  294. _positionDelta = new Vector2();
  295. _index = -1;
  296. _previousGlyph = null;
  297. }
  298. }
  299. /// <inheritdoc/>
  300. public override string ToString() => $"{Face}";
  301. public static BitmapFont FromFile(GraphicsDevice graphicsDevice, string path)
  302. {
  303. using Stream stream = TitleContainer.OpenStream(path);
  304. return FromStream(graphicsDevice, stream, path);
  305. }
  306. [Obsolete("Use the FromStream() overload that takes an explicit name.")]
  307. public static BitmapFont FromStream(GraphicsDevice graphicsDevice, FileStream stream)
  308. {
  309. return FromStream(graphicsDevice, stream, stream.Name);
  310. }
  311. public static BitmapFont FromStream(GraphicsDevice graphicsDevice, Stream stream, string name)
  312. {
  313. var bmfFile = BitmapFontFileReader.Read(stream, name);
  314. // Load page textures
  315. Dictionary<string, Texture2D> pages = new Dictionary<string, Texture2D>();
  316. for (int i = 0; i < bmfFile.Pages.Count; i++)
  317. {
  318. if (!pages.ContainsKey(bmfFile.Pages[i]))
  319. {
  320. string texturePath = Path.Combine(Path.GetDirectoryName(bmfFile.Path), bmfFile.Pages[i]);
  321. using (Stream textureStream = TitleContainer.OpenStream(texturePath))
  322. {
  323. Texture2D texture = Texture2D.FromStream(graphicsDevice, textureStream);
  324. pages.Add(bmfFile.Pages[i], texture);
  325. }
  326. }
  327. }
  328. // Load Characters
  329. Dictionary<int, BitmapFontCharacter> characters = new Dictionary<int, BitmapFontCharacter>();
  330. for (int i = 0; i < bmfFile.Characters.Count; i++)
  331. {
  332. var charBlock = bmfFile.Characters[i];
  333. Texture2D texture = pages[bmfFile.Pages[charBlock.Page]];
  334. Texture2DRegion region = new Texture2DRegion(texture, charBlock.X, charBlock.Y, charBlock.Width, charBlock.Height);
  335. BitmapFontCharacter character = new BitmapFontCharacter((int)charBlock.ID, region, charBlock.XOffset, charBlock.YOffset, charBlock.XAdvance);
  336. characters.Add(character.Character, character);
  337. }
  338. // Load kernings
  339. for (int i = 0; i < bmfFile.Kernings.Count; i++)
  340. {
  341. var kerningBlock = bmfFile.Kernings[i];
  342. if (characters.TryGetValue((int)kerningBlock.First, out BitmapFontCharacter character))
  343. {
  344. character.Kernings.Add((int)kerningBlock.Second, kerningBlock.Amount);
  345. }
  346. }
  347. return new BitmapFont(
  348. bmfFile.FontName,
  349. bmfFile.Info.FontSize,
  350. bmfFile.Common.LineHeight,
  351. bmfFile.Info.SpacingHoriz,
  352. bmfFile.Info.SpacingVert,
  353. characters.Values
  354. );
  355. }
  356. }