Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/runtime fonts #963

Open
wants to merge 7 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Blish HUD/Blish HUD.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@
<PackageReference Include="Newtonsoft.Json" Version="[13.0.1]" />
<PackageReference Include="NLog" Version="4.6.7" PrivateAssets="all" />
<PackageReference Include="SemanticVersioning" Version="1.2.2" PrivateAssets="all" />
<PackageReference Include="SpriteFontPlus.MonoGame" Version="0.7.0.22" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.14.1" PrivateAssets="all" />
<PackageReference Include="System.Resources.Extensions" Version="6.0.0" />
<PackageReference Include="protobuf-net" Version="3.0.101" PrivateAssets="all" />
Expand Down
42 changes: 42 additions & 0 deletions Blish HUD/GameServices/Content/BitmapFontEx.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Microsoft.Xna.Framework.Graphics;
using MonoGame.Extended.BitmapFonts;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Blish_HUD.Content {
/// <summary>
/// Extends <see cref="BitmapFont"/> to allow disposing of its glyph lookup texture.
/// </summary>
public class BitmapFontEx : BitmapFont, IDisposable {
private readonly Texture2D _texture;

/// <summary>
/// Creates a <see cref="BitmapFontEx"/> with the provided identifier name, glyph regions, line height, and texture to draw letters from.
/// </summary>
/// <param name="name">Name to identify the font with.</param>
/// <param name="regions">Regions of the glyphs on the <c>texture</c>.</param>
/// <param name="lineHeight">Line height of the font.</param>
/// <param name="texture">Lookup texture to draw letters from.</param>
public BitmapFontEx(string name, IEnumerable<BitmapFontRegion> regions, int lineHeight, Texture2D texture) : base(name, regions, lineHeight) {
_texture = texture ?? throw new ArgumentNullException(nameof(texture));
}

/// <summary>
/// Creates a <see cref="BitmapFontEx"/> with the provided identifier name, glyph regions and line height.
/// </summary>
/// <param name="name">Name to identify the font with.</param>
/// <param name="regions">Regions of the glyphs on the <c>texture</c>.</param>
/// <param name="lineHeight">Line height of the font.</param>
public BitmapFontEx(string name, IReadOnlyList<BitmapFontRegion> regions, int lineHeight) : base(name, regions, lineHeight) {
_texture = regions?.FirstOrDefault()?.TextureRegion?.Texture ?? throw new ArgumentException($"Parameter '{nameof(regions)}' was null or empty.");
}

/// <summary>
/// Disposes the lookup texture of this <see cref="BitmapFontEx"/> to free memory. Renders this <see cref="BitmapFontEx"/> unusable.
/// </summary>
public void Dispose() {
_texture?.Dispose();
}
}
}
21 changes: 21 additions & 0 deletions Blish HUD/GameServices/ContentService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using MonoGame.Extended.BitmapFonts;
using SpriteFontPlus;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text.RegularExpressions;
Expand Down Expand Up @@ -103,8 +105,27 @@ public enum FontStyle {

public DatAssetCache DatAssetCache { get; private set; }

internal IReadOnlyList<CharacterRange> Gw2CharacterRanges { get; private set; }

internal ContentService() {
SetServiceModules(this.DatAssetCache = new DatAssetCache(this));

Gw2CharacterRanges = new List<CharacterRange> {
CharacterRange.BasicLatin,
CharacterRange.Latin1Supplement,
CharacterRange.LatinExtendedA,
new CharacterRange('₣', '₾'), // Currency Symbols
new CharacterRange('←', '⇿'), // Arrows
new CharacterRange('∀', '⋿'), // Mathematical Operators
new CharacterRange('①', '⓿'), // Enclosed Alphanumerics
new CharacterRange('─', '╿'), // Box Drawing
new CharacterRange('■', '◿'), // Geometric Shapes
// Cause crash with only windows shipped .NET Runtime.
//new CharacterRange('\u2000', '\u206F'), // General Punctuation
//new CharacterRange('℀', '⅏'), // Letterlike Symbols
//new CharacterRange('⌀', '⏺'), // Miscellaneous Technical
//new CharacterRange('☀', '♪'), // Miscellaneous Symbols
};
}

protected override void Initialize() {
Expand Down
44 changes: 41 additions & 3 deletions Blish HUD/GameServices/Modules/Managers/ContentsManager.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using Blish_HUD.Content;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using MonoGame.Extended.BitmapFonts;
using SpriteFontPlus;
using System;
using System.IO;

Expand Down Expand Up @@ -92,8 +92,46 @@ public SoundEffect GetSound(string soundPath) {
return null;
}

public BitmapFont GetBitmapFont(string fontPath) {
throw new NotImplementedException();
/// <summary>
/// Loads a <see cref="SpriteFont"/> from a TrueTypeFont (*.ttf) file.
/// </summary>
/// <param name="fontPath">The path to the TTF font file.</param>
/// <param name="fontSize">Size of the font.</param>
/// <param name="textureSize">Size of the <see cref="SpriteFont.Texture"/>.<br/>A greater <c>fontSize</c> results in bigger glyphs which may require more texture space.</param>
public SpriteFont GetSpriteFont(string fontPath, int fontSize, int textureSize = 1392) {
if (fontSize <= 0) {
throw new ArgumentException("Font size must be greater than 0.", nameof(fontSize));
}

if (textureSize <= 0) {
throw new ArgumentException("Texture size must be greater than 0.", nameof(textureSize));
}

long fontDataLength = _reader.GetFileBytes(fontPath, out byte[] fontData);

if (fontDataLength > 0) {
using var ctx = GameService.Graphics.LendGraphicsDeviceContext();
try {
var result = TtfFontBaker.Bake(fontData, fontSize, textureSize, textureSize,
GameService.Content.Gw2CharacterRanges).CreateSpriteFont(ctx.GraphicsDevice);
Logger.Debug("Successfully loaded font {dataReaderFilePath}.", _reader.GetPathRepresentation(fontPath));
return result;
} catch (Exception e) {
Logger.Warn(e, "Unable to load font {dataReaderFilePath}.", _reader.GetPathRepresentation(fontPath));
}
}
return null;
}

/// <summary>
/// Loads a <see cref="BitmapFontEx"/> from a TrueTypeFont (*.ttf) file.
/// </summary>
/// <param name="fontPath">The path to the TTF font file.</param>
/// <param name="fontSize">Size of the font.</param>
/// <param name="lineHeight">Sets the line height. By default, <see cref="SpriteFont.LineSpacing"/> will be used.</param>
/// <param name="textureSize">Size of the <see cref="SpriteFont.Texture"/>.<br/>A greater <c>fontSize</c> results in bigger glyphs which may require more texture space.</param>
public BitmapFontEx GetBitmapFont(string fontPath, int fontSize, int lineHeight = 0, int textureSize = 1392) {
return GetSpriteFont(fontPath, fontSize, textureSize)?.ToBitmapFont(lineHeight);
}

/// <summary>
Expand Down
43 changes: 43 additions & 0 deletions Blish HUD/_Extensions/SpriteFontExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using Blish_HUD.Content;
using Microsoft.Xna.Framework.Graphics;
using MonoGame.Extended.BitmapFonts;
using MonoGame.Extended.TextureAtlases;
using System;
using System.Collections.Generic;

namespace Blish_HUD {
public static class SpriteFontExtensions {
/// <summary>
/// Converts a <see cref="SpriteFont"/> to a <see cref="BitmapFontEx"/>.
/// </summary>
/// <param name="font">The <see cref="SpriteFont"/> to convert.</param>
/// <param name="lineHeight">Line height for the <see cref="BitmapFontEx"/>. By default, <see cref="SpriteFont.LineSpacing"/> will be used.</param>
/// <returns>A <see cref="BitmapFontEx"/> as result of the conversion.</returns>
public static BitmapFontEx ToBitmapFont(this SpriteFont font, int lineHeight = 0) {
if (lineHeight < 0) {
throw new ArgumentException("Line height cannot be negative.", nameof(lineHeight));
}

var regions = new List<BitmapFontRegion>();

var glyphs = font.GetGlyphs();

foreach (var glyph in glyphs.Values) {
var glyphTextureRegion = new TextureRegion2D(font.Texture,
glyph.BoundsInTexture.Left,
glyph.BoundsInTexture.Top,
glyph.BoundsInTexture.Width,
glyph.BoundsInTexture.Height);

var region = new BitmapFontRegion(glyphTextureRegion,
glyph.Character,
glyph.Cropping.Left,
glyph.Cropping.Top,
(int)glyph.WidthIncludingBearings);

regions.Add(region);
}
return new BitmapFontEx($"{typeof(BitmapFontEx)}_{Guid.NewGuid():n}", regions, lineHeight > 0 ? lineHeight : font.LineSpacing, font.Texture);
}
}
}