├── .gitattributes ├── .gitignore ├── FontExtension ├── FieldFont.cs ├── FieldFontImporter.cs ├── FieldFontProcessor.cs ├── FieldGlyph.cs ├── FloatHelper.cs ├── FontDescription.cs ├── FontExtension.csproj ├── KerningPair.cs ├── Metrics.cs ├── Properties │ └── AssemblyInfo.cs ├── app.config └── packages.config ├── LICENSE ├── MonoMSDF.sln ├── MonoMSDF ├── Content │ ├── Content.mgcb │ ├── FieldFontEffect.fx │ ├── arial.ini │ ├── freetype6.dll │ ├── msdfgen.exe │ └── zlib1.dll ├── Game1.cs ├── Icon.ico ├── MonoMSDF.csproj ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Text │ ├── GlyphRenderInfo.cs │ ├── Quad.cs │ └── TextRenderer.cs ├── app.config ├── app.manifest └── packages.config ├── README.md └── gallery.PNG /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /FontExtension/FieldFont.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.Xna.Framework.Content; 5 | 6 | namespace FontExtension 7 | { 8 | public class FieldFont 9 | { 10 | [ContentSerializer] private readonly Dictionary Glyphs; 11 | [ContentSerializer] private readonly string NameBackend; 12 | [ContentSerializer] private readonly float PxRangeBackend; 13 | [ContentSerializer] private readonly List KerningPairsBackend; 14 | 15 | public FieldFont() 16 | { 17 | } 18 | 19 | public FieldFont(string name, IReadOnlyCollection glyphs, IReadOnlyCollection kerningPairs, float pxRange) 20 | { 21 | this.NameBackend = name; 22 | this.PxRangeBackend = pxRange; 23 | this.KerningPairsBackend = kerningPairs.ToList(); 24 | 25 | this.Glyphs = new Dictionary(glyphs.Count); 26 | foreach (var glyph in glyphs) 27 | { 28 | this.Glyphs.Add(glyph.Character, glyph); 29 | } 30 | } 31 | 32 | /// 33 | /// Name of the font 34 | /// 35 | public string Name => this.NameBackend; 36 | 37 | /// 38 | /// Distance field effect range in pixels 39 | /// 40 | public float PxRange => this.PxRangeBackend; 41 | 42 | /// 43 | /// Kerning pairs available in this font 44 | /// 45 | public IReadOnlyList KerningPairs => this.KerningPairsBackend; 46 | 47 | /// 48 | /// Characters supported by this font 49 | /// 50 | [ContentSerializerIgnore] 51 | public IEnumerable SupportedCharacters => this.Glyphs.Keys; 52 | 53 | /// 54 | /// Returns the glyph for the given character, or throws an exception when the glyph is not supported by this font 55 | /// 56 | public FieldGlyph GetGlyph(char c) 57 | { 58 | if (this.Glyphs.TryGetValue(c, out FieldGlyph glyph)) 59 | { 60 | return glyph; 61 | } 62 | 63 | throw new InvalidOperationException($"Character '{c}' not found in font {this.Name}. Did you forget to include it in the character ranges?"); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /FontExtension/FieldFontImporter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using IniParser; 5 | using Microsoft.Xna.Framework.Content.Pipeline; 6 | 7 | namespace FontExtension 8 | { 9 | [ContentImporter(".ini", DisplayName = "Field Font Importer", DefaultProcessor = "FieldFontProcessor")] 10 | public class FieldFontImporter : ContentImporter 11 | { 12 | public override FontDescription Import(string filename, ContentImporterContext context) 13 | { 14 | return Parse(filename); 15 | } 16 | 17 | private static FontDescription Parse(string filename) 18 | { 19 | var parser = new FileIniDataParser(); 20 | var data = parser.ReadFile(filename); 21 | 22 | var fontSection = data.Sections["font"]; 23 | var path = fontSection["path"]; 24 | 25 | var characterSection = data.Sections["characters"]; 26 | 27 | 28 | var characters = ParseRanges(characterSection["ranges"]); 29 | 30 | return new FontDescription(path, characters); 31 | } 32 | 33 | 34 | private static char[] ParseRanges(string ranges) 35 | { 36 | var tuples = ParseTuples(ranges); 37 | 38 | var characters = new HashSet(); 39 | foreach (var tuple in tuples) 40 | { 41 | // Every tuple should consist of two characters seperated by a comma 42 | var parts = tuple.Split(','); 43 | if (parts.Length != 2) 44 | { 45 | throw new Exception($"Unexpected number of tuple elements in tuple: {tuple}"); 46 | } 47 | 48 | if (parts[0].Length != 1 || parts[1].Length != 1) 49 | { 50 | throw new Exception($"A tuple can only contain two characters seperated by a comma: {tuple}"); 51 | } 52 | 53 | // Compute the entire character range from the two extremes (inclusive) 54 | var start = parts[0][0]; 55 | var end = parts[1][0]; 56 | 57 | for (int i = start; i <= end; i++) 58 | { 59 | characters.Add((char) i); 60 | } 61 | 62 | } 63 | 64 | return characters.ToArray(); 65 | } 66 | 67 | /// 68 | /// Parses tuples, and returns an enumerable with the contents of each tuple (so without the braces) 69 | /// 70 | private static IEnumerable ParseTuples(string ranges) 71 | { 72 | var tuples = new List(); 73 | 74 | // -1 signals the we have not seen the opening brace of the tuple yet 75 | var start = -1; 76 | for (var i = 0; i < ranges.Length; i++) 77 | { 78 | var c = ranges[i]; 79 | if (start > -1) 80 | { 81 | if (c == ')') 82 | { 83 | var length = i - start - 1; 84 | if (length < 1) 85 | { 86 | throw new Exception($"Empty tuple at position {start}"); 87 | } 88 | tuples.Add(ranges.Substring(start + 1, length)); 89 | start = -1; 90 | } 91 | else if (c == '(') 92 | { 93 | throw new Exception( 94 | $"Unexpected character '(', tuple was already openened at position {start}"); 95 | } 96 | } 97 | else if (c == '(') 98 | { 99 | start = i; 100 | } 101 | } 102 | 103 | return tuples; 104 | } 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /FontExtension/FieldFontProcessor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Diagnostics; 5 | using System.IO; 6 | using System.Threading.Tasks; 7 | using Microsoft.Xna.Framework; 8 | using Microsoft.Xna.Framework.Content.Pipeline; 9 | using RoyT.TrueType.Helpers; 10 | 11 | namespace FontExtension 12 | { 13 | 14 | [ContentProcessor(DisplayName = "Field Font Processor")] 15 | public class FieldFontProcessor : ContentProcessor 16 | { 17 | [DisplayName("msdfgen path")] 18 | [Description("Path to the msdfgen binary used to generate the multi-spectrum signed distance field")] 19 | [DefaultValue("msdfgen.exe")] 20 | public virtual string ExternalPath { get; set; } = "msdfgen.exe"; 21 | 22 | 23 | [DisplayName("resolution")] 24 | [Description("Resolution of the the texture to store a single glyph in")] 25 | [DefaultValue(32)] 26 | public virtual uint Resolution { get; set; } = 32; 27 | 28 | [DisplayName("range")] 29 | [Description("Distance field range, in pixels in the output texture")] 30 | [DefaultValue(4)] 31 | public virtual uint Range { get; set; } = 4; 32 | 33 | 34 | public override FieldFont Process(FontDescription input, ContentProcessorContext context) 35 | { 36 | var msdfgen = Path.Combine(Directory.GetCurrentDirectory(), this.ExternalPath); 37 | var objPath = Path.Combine(Directory.GetCurrentDirectory(), "obj"); 38 | 39 | if (File.Exists(msdfgen)) 40 | { 41 | var glyphs = new FieldGlyph[input.Characters.Count]; 42 | 43 | // Generate a distance field for each character using msdfgen 44 | Parallel.For( 45 | 0, 46 | input.Characters.Count, 47 | i => 48 | { 49 | var c = input.Characters[i]; 50 | glyphs[i] = CreateFieldGlyphForCharacter(c, input, msdfgen, objPath); 51 | }); 52 | 53 | var kerning = ReadKerningInformation(input.Path, input.Characters); 54 | return new FieldFont(input.Path, glyphs, kerning, this.Range); 55 | } 56 | 57 | throw new FileNotFoundException( 58 | "Could not find msdfgen. Check your content processor parameters", 59 | msdfgen); 60 | } 61 | 62 | private FieldGlyph CreateFieldGlyphForCharacter(char c, FontDescription input, string msdfgen, string objPath) 63 | { 64 | var metrics = CreateDistanceFieldForCharacter(input, msdfgen, objPath, c); 65 | var path = GetOuputPath(objPath, input, c); 66 | var bytes = File.ReadAllBytes(path); 67 | var glyph = new FieldGlyph(c, bytes, metrics); 68 | 69 | return glyph; 70 | } 71 | 72 | private Metrics CreateDistanceFieldForCharacter(FontDescription font, string msdfgen, string objPath, char c) 73 | { 74 | var outputPath = GetOuputPath(objPath, font, c); 75 | var startInfo = new ProcessStartInfo(msdfgen) 76 | { 77 | UseShellExecute = false, 78 | RedirectStandardOutput = true, 79 | Arguments = $"-font \"{font.Path}\" {(int)c} -o \"{outputPath}\" -size {this.Resolution} {this.Resolution} -pxrange {this.Range} -autoframe -printmetrics" 80 | }; 81 | 82 | var process = System.Diagnostics.Process.Start(startInfo); 83 | if (process == null) 84 | { 85 | throw new InvalidOperationException("Could not start msdfgen.exe"); 86 | } 87 | 88 | var output = process.StandardOutput.ReadToEnd(); 89 | return ParseOutput(output); 90 | } 91 | 92 | private static Metrics ParseOutput(string output) 93 | { 94 | var advance = 0.0f; 95 | var scale = 0.0f; 96 | var translation = Vector2.Zero; 97 | 98 | foreach (var line in output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)) 99 | { 100 | ParseLine(line, "advance = ", FloatHelper.ParseInvariant, ref advance); 101 | ParseLine(line, "scale = ", FloatHelper.ParseInvariant, ref scale); 102 | ParseLine(line, "translate = ", ParseVector2, ref translation); 103 | } 104 | 105 | return new Metrics(advance, scale, translation); 106 | } 107 | 108 | private static string GetOuputPath(string objPath, FontDescription font, char c) 109 | { 110 | var name = Path.GetFileNameWithoutExtension(font.Path); 111 | return Path.Combine(objPath, $"{name}-{(int)c}.bmp"); 112 | } 113 | 114 | private static Vector2 ParseVector2(string text) 115 | { 116 | var args = text.Split(','); 117 | return new Vector2(FloatHelper.ParseInvariant(args[0]), FloatHelper.ParseInvariant(args[1])); 118 | } 119 | 120 | private static void ParseLine(string line, string match, Func resultParser, ref T result) 121 | { 122 | if (line.StartsWith(match, StringComparison.InvariantCultureIgnoreCase)) 123 | { 124 | var value = line.Substring(match.Length).Trim(); 125 | result = resultParser(value); 126 | } 127 | } 128 | 129 | private static List ReadKerningInformation(string path, IReadOnlyList characters) 130 | { 131 | var pairs = new List(); 132 | 133 | var font = RoyT.TrueType.TrueTypeFont.FromFile(path); 134 | 135 | foreach (var left in characters) 136 | { 137 | foreach (var right in characters) 138 | { 139 | var kerning = KerningHelper.GetHorizontalKerning(left, right, font); 140 | if (kerning > 0 || kerning < 0) 141 | { 142 | // Scale the kerning by the same factor MSDFGEN scales it 143 | pairs.Add(new KerningPair(left, right, kerning / 64.0f)); 144 | } 145 | } 146 | } 147 | 148 | return pairs; 149 | } 150 | } 151 | } -------------------------------------------------------------------------------- /FontExtension/FieldGlyph.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework.Content; 2 | 3 | namespace FontExtension 4 | { 5 | public class FieldGlyph 6 | { 7 | [ContentSerializer] private readonly char CharacterBackend; 8 | [ContentSerializer] private readonly byte[] BitmapBackend; 9 | [ContentSerializer] private readonly Metrics MetricsBackend; 10 | 11 | public FieldGlyph() 12 | { 13 | 14 | } 15 | 16 | public FieldGlyph(char character, byte[] bitmap, Metrics metrics) 17 | { 18 | this.CharacterBackend = character; 19 | this.BitmapBackend = bitmap; 20 | this.MetricsBackend = metrics; 21 | } 22 | 23 | /// 24 | /// The character this glyph represents 25 | /// 26 | public char Character => this.CharacterBackend; 27 | /// 28 | /// Distance field for this character 29 | /// 30 | public byte[] Bitmap => this.BitmapBackend; 31 | /// 32 | /// Metrics for this character 33 | /// 34 | public Metrics Metrics => this.MetricsBackend; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /FontExtension/FloatHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | 3 | namespace FontExtension 4 | { 5 | public static class FloatHelper 6 | { 7 | public static float ParseInvariant(string value) => float.Parse(value, CultureInfo.InvariantCulture); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /FontExtension/FontDescription.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace FontExtension 5 | { 6 | public class FontDescription 7 | { 8 | public FontDescription(string path, params char[] characters) 9 | { 10 | this.Path = path; 11 | this.Characters = characters.ToList().AsReadOnly(); 12 | } 13 | 14 | public string Path { get; } 15 | public IReadOnlyList Characters { get; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /FontExtension/FontExtension.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | 8.0.30703 7 | 2.0 8 | {EBF08DC7-916D-4133-BADE-38C31E29F18A} 9 | Library 10 | Properties 11 | FontExtension 12 | FontExtension 13 | v4.7 14 | 512 15 | 16 | 17 | 18 | 19 | 20 | true 21 | full 22 | false 23 | bin\Debug\ 24 | DEBUG;TRACE 25 | prompt 26 | 4 27 | 28 | 29 | pdbonly 30 | true 31 | bin\Release\ 32 | TRACE 33 | prompt 34 | 4 35 | 36 | 37 | 38 | ..\packages\ini-parser.2.5.2\lib\net20\INIFileParser.dll 39 | 40 | 41 | ..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll 42 | 43 | 44 | ..\packages\MonoGame.Framework.Portable.3.7.0.1708\lib\portable-net45+win8+wpa81\MonoGame.Framework.dll 45 | 46 | 47 | ..\packages\MonoGame.Framework.Content.Pipeline.Portable.3.7.0.1708\lib\portable-net45+win8+wpa81\MonoGame.Framework.Content.Pipeline.dll 48 | 49 | 50 | ..\packages\RoyT.TrueType.0.1.1\lib\netstandard1.6\RoyT.TrueType.dll 51 | 52 | 53 | 54 | ..\packages\System.AppContext.4.3.0\lib\net463\System.AppContext.dll 55 | 56 | 57 | 58 | ..\packages\System.Console.4.3.0\lib\net46\System.Console.dll 59 | 60 | 61 | ..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll 62 | 63 | 64 | ..\packages\System.Diagnostics.Tracing.4.3.0\lib\net462\System.Diagnostics.Tracing.dll 65 | 66 | 67 | ..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll 68 | 69 | 70 | ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll 71 | 72 | 73 | ..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll 74 | True 75 | 76 | 77 | 78 | ..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll 79 | 80 | 81 | ..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll 82 | 83 | 84 | ..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll 85 | 86 | 87 | ..\packages\System.Linq.4.3.0\lib\net463\System.Linq.dll 88 | 89 | 90 | ..\packages\System.Linq.Expressions.4.3.0\lib\net463\System.Linq.Expressions.dll 91 | 92 | 93 | ..\packages\System.Net.Http.4.3.0\lib\net46\System.Net.Http.dll 94 | 95 | 96 | ..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll 97 | 98 | 99 | 100 | ..\packages\System.Reflection.4.3.0\lib\net462\System.Reflection.dll 101 | 102 | 103 | ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll 104 | 105 | 106 | ..\packages\System.Runtime.Extensions.4.3.0\lib\net462\System.Runtime.Extensions.dll 107 | 108 | 109 | ..\packages\System.Runtime.InteropServices.4.3.0\lib\net463\System.Runtime.InteropServices.dll 110 | 111 | 112 | ..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll 113 | True 114 | 115 | 116 | ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll 117 | 118 | 119 | ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll 120 | 121 | 122 | ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll 123 | 124 | 125 | ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll 126 | 127 | 128 | ..\packages\System.Text.RegularExpressions.4.3.0\lib\net463\System.Text.RegularExpressions.dll 129 | 130 | 131 | 132 | 133 | ..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 159 | -------------------------------------------------------------------------------- /FontExtension/KerningPair.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework.Content; 2 | 3 | namespace FontExtension 4 | { 5 | public class KerningPair 6 | { 7 | [ContentSerializer] private readonly char LeftBackend; 8 | [ContentSerializer] private readonly char RightBackend; 9 | [ContentSerializer] private readonly float AdvanceBackend; 10 | 11 | public KerningPair() 12 | { 13 | 14 | } 15 | 16 | public KerningPair(char left, char right, float advance) 17 | { 18 | this.LeftBackend = left; 19 | this.RightBackend = right; 20 | this.AdvanceBackend = advance; 21 | } 22 | 23 | public char Left => this.LeftBackend; 24 | public char Right => this.RightBackend; 25 | public float Advance => this.AdvanceBackend; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /FontExtension/Metrics.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Content; 3 | 4 | namespace FontExtension 5 | { 6 | public class Metrics 7 | { 8 | [ContentSerializer] private readonly float AdvanceBackend; 9 | [ContentSerializer] private readonly float ScaleBackend; 10 | [ContentSerializer] private readonly Vector2 TranslationBackend; 11 | 12 | public Metrics() 13 | { 14 | 15 | } 16 | 17 | public Metrics(float advance, float scale, Vector2 translation) 18 | { 19 | this.AdvanceBackend = advance; 20 | this.ScaleBackend = scale; 21 | this.TranslationBackend = translation; 22 | } 23 | 24 | public float Advance => this.AdvanceBackend; 25 | public float Scale => this.ScaleBackend; 26 | public Vector2 Translation => this.TranslationBackend; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /FontExtension/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("FontExtension")] 9 | [assembly: AssemblyProduct("FontExtension")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyDescription("")] 12 | [assembly: AssemblyCompany("")] 13 | [assembly: AssemblyCopyright("Copyright © 2018")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("597b4008-2083-4375-a6eb-5f6e0d801e5d")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /FontExtension/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /FontExtension/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 R. A. Triesscheijn 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. -------------------------------------------------------------------------------- /MonoMSDF.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27428.2037 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonoMSDF", "MonoMSDF\MonoMSDF.csproj", "{9860181B-EFE7-48F1-AC6C-4CD9C855F1E4}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FontExtension", "FontExtension\FontExtension.csproj", "{EBF08DC7-916D-4133-BADE-38C31E29F18A}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Debug|x86 = Debug|x86 14 | Release|Any CPU = Release|Any CPU 15 | Release|x86 = Release|x86 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {9860181B-EFE7-48F1-AC6C-4CD9C855F1E4}.Debug|Any CPU.ActiveCfg = Debug|x86 19 | {9860181B-EFE7-48F1-AC6C-4CD9C855F1E4}.Debug|x86.ActiveCfg = Debug|x86 20 | {9860181B-EFE7-48F1-AC6C-4CD9C855F1E4}.Debug|x86.Build.0 = Debug|x86 21 | {9860181B-EFE7-48F1-AC6C-4CD9C855F1E4}.Release|Any CPU.ActiveCfg = Release|x86 22 | {9860181B-EFE7-48F1-AC6C-4CD9C855F1E4}.Release|x86.ActiveCfg = Release|x86 23 | {9860181B-EFE7-48F1-AC6C-4CD9C855F1E4}.Release|x86.Build.0 = Release|x86 24 | {EBF08DC7-916D-4133-BADE-38C31E29F18A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {EBF08DC7-916D-4133-BADE-38C31E29F18A}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {EBF08DC7-916D-4133-BADE-38C31E29F18A}.Debug|x86.ActiveCfg = Debug|Any CPU 27 | {EBF08DC7-916D-4133-BADE-38C31E29F18A}.Debug|x86.Build.0 = Debug|Any CPU 28 | {EBF08DC7-916D-4133-BADE-38C31E29F18A}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {EBF08DC7-916D-4133-BADE-38C31E29F18A}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {EBF08DC7-916D-4133-BADE-38C31E29F18A}.Release|x86.ActiveCfg = Release|Any CPU 31 | {EBF08DC7-916D-4133-BADE-38C31E29F18A}.Release|x86.Build.0 = Release|Any CPU 32 | EndGlobalSection 33 | GlobalSection(SolutionProperties) = preSolution 34 | HideSolutionNode = FALSE 35 | EndGlobalSection 36 | GlobalSection(ExtensibilityGlobals) = postSolution 37 | SolutionGuid = {F28C2187-0713-4D2B-97F3-246A413D203C} 38 | EndGlobalSection 39 | EndGlobal 40 | -------------------------------------------------------------------------------- /MonoMSDF/Content/Content.mgcb: -------------------------------------------------------------------------------- 1 | 2 | #----------------------------- Global Properties ----------------------------# 3 | 4 | /outputDir:bin/$(Platform) 5 | /intermediateDir:obj/$(Platform) 6 | /platform:Windows 7 | /config: 8 | /profile:HiDef 9 | /compress:False 10 | 11 | #-------------------------------- References --------------------------------# 12 | 13 | /reference:..\..\FontExtension\bin\Debug\FontExtension.dll 14 | 15 | #---------------------------------- Content ---------------------------------# 16 | 17 | #begin arial.ini 18 | /importer:FieldFontImporter 19 | /processor:FieldFontProcessor 20 | /processorParam:ExternalPath=msdfgen.exe 21 | /processorParam:Resolution=64 22 | /processorParam:Range=4 23 | /build:arial.ini 24 | 25 | #begin FieldFontEffect.fx 26 | /importer:EffectImporter 27 | /processor:EffectProcessor 28 | /processorParam:DebugMode=Auto 29 | /build:FieldFontEffect.fx 30 | 31 | -------------------------------------------------------------------------------- /MonoMSDF/Content/FieldFontEffect.fx: -------------------------------------------------------------------------------- 1 | #define VS_SHADERMODEL vs_5_0 2 | #define PS_SHADERMODEL ps_5_0 3 | 4 | // Mix of the enhanced shader from https://discourse.libcinder.org/t/cinder-sdftext-initial-release-wip/171/13 and the original msdf shader 5 | 6 | 7 | matrix WorldViewProjection; 8 | float2 TextureSize; 9 | float4 ForegroundColor; 10 | float PxRange; 11 | 12 | texture GlyphTexture; 13 | sampler glyphSampler = sampler_state 14 | { 15 | Texture = (GlyphTexture); 16 | AddressU = CLAMP; 17 | AddressV = CLAMP; 18 | MagFilter = LINEAR; 19 | MinFilter = LINEAR; 20 | Mipfilter = LINEAR; 21 | }; 22 | 23 | struct VertexShaderInput 24 | { 25 | float4 Position : POSITION0; 26 | float2 TexCoord : TEXCOORD0; 27 | }; 28 | 29 | struct VertexShaderOutput 30 | { 31 | float4 Position : POSITION0; 32 | float2 TexCoord : TEXCOORD0; 33 | }; 34 | 35 | VertexShaderOutput MainVS(in VertexShaderInput input) 36 | { 37 | VertexShaderOutput output = (VertexShaderOutput)0; 38 | output.Position = mul(input.Position, WorldViewProjection); 39 | output.TexCoord = input.TexCoord; 40 | 41 | return output; 42 | } 43 | 44 | float2 SafeNormalize(in float2 v) 45 | { 46 | float len = length(v); 47 | len = (len > 0.0) ? 1.0 / len : 0.0; 48 | return v * len; 49 | } 50 | 51 | float Median(float a, float b, float c) 52 | { 53 | return max(min(a, b), min(max(a, b), c)); 54 | } 55 | 56 | float4 MainPS(VertexShaderOutput input) : COLOR 57 | { 58 | // Convert normalized texture coordinates to absolute texture coordinates 59 | float2 uv = input.TexCoord * TextureSize; 60 | 61 | // Calculate derivatives 62 | float2 Jdx = ddx(uv); 63 | float2 Jdy = ddy(uv); 64 | 65 | // Sample texture 66 | float3 samp = tex2D(glyphSampler, input.TexCoord).rgb; 67 | 68 | // Calculate the signed distance (in texels) 69 | float sigDist = Median(samp.r, samp.g, samp.b) - 0.5f; 70 | 71 | // For proper anti-aliasing we need to calculate the signed distance in pixels. 72 | // We do this using the derivatives. 73 | float2 gradDist = SafeNormalize(float2(ddx(sigDist), ddy(sigDist))); 74 | float2 grad = float2(gradDist.x * Jdx.x + gradDist.y * Jdy.x, gradDist.x * Jdx.y + gradDist.y * Jdy.y); 75 | 76 | // Apply anti-aliasing 77 | const float thickness = 0.125f; 78 | const float normalization = thickness * 0.5f * sqrt(2.0f); 79 | 80 | float afWidth = min(normalization * length(grad), 0.5f); 81 | float opacity = smoothstep(0.0f - afWidth, 0.0f + afWidth, sigDist); 82 | 83 | // Apply pre-multiplied alpha with gamma correction 84 | 85 | float4 color; 86 | color.a = pow(abs(ForegroundColor.a * opacity), 1.0f / 2.2f); 87 | color.rgb = ForegroundColor.rgb * color.a; 88 | 89 | return color; 90 | } 91 | 92 | float4 AltPS(VertexShaderOutput input) : COLOR 93 | { 94 | float2 msdfUnit = PxRange / TextureSize; 95 | float3 samp = tex2D(glyphSampler, input.TexCoord).rgb; 96 | 97 | float sigDist = Median(samp.r, samp.g, samp.b) - 0.5f; 98 | sigDist = sigDist * dot(msdfUnit, 0.5f / fwidth(input.TexCoord)); 99 | 100 | float opacity = clamp(sigDist + 0.5f, 0.0f, 1.0f); 101 | return ForegroundColor * opacity; 102 | } 103 | 104 | technique SmallText 105 | { 106 | pass P0 107 | { 108 | VertexShader = compile VS_SHADERMODEL MainVS(); 109 | PixelShader = compile PS_SHADERMODEL MainPS(); 110 | } 111 | }; 112 | 113 | technique LargeText 114 | { 115 | pass P0 116 | { 117 | VertexShader = compile VS_SHADERMODEL MainVS(); 118 | PixelShader = compile PS_SHADERMODEL AltPS(); 119 | } 120 | }; 121 | -------------------------------------------------------------------------------- /MonoMSDF/Content/arial.ini: -------------------------------------------------------------------------------- 1 | [font] 2 | path=C:\Windows\Fonts\arial.ttf 3 | 4 | [characters] 5 | ;See https://unicode-table.com/en for a nice overview of characters available in unicode 6 | ;Include space, and all standard printable ASCII characters and unicode arrows 7 | ranges=( ,~),(←,↙) -------------------------------------------------------------------------------- /MonoMSDF/Content/freetype6.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roy-t/MSDF/1a5191113af77060059c0de961586aa2ceec62cb/MonoMSDF/Content/freetype6.dll -------------------------------------------------------------------------------- /MonoMSDF/Content/msdfgen.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roy-t/MSDF/1a5191113af77060059c0de961586aa2ceec62cb/MonoMSDF/Content/msdfgen.exe -------------------------------------------------------------------------------- /MonoMSDF/Content/zlib1.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roy-t/MSDF/1a5191113af77060059c0de961586aa2ceec62cb/MonoMSDF/Content/zlib1.dll -------------------------------------------------------------------------------- /MonoMSDF/Game1.cs: -------------------------------------------------------------------------------- 1 | using FontExtension; 2 | using Microsoft.Xna.Framework; 3 | using Microsoft.Xna.Framework.Graphics; 4 | using Microsoft.Xna.Framework.Input; 5 | using MonoMSDF.Text; 6 | 7 | namespace MonoMSDF 8 | { 9 | /// 10 | /// This is the main type for your game. 11 | /// 12 | public class Game1 : Game 13 | { 14 | private GraphicsDeviceManager graphics; 15 | private TextRenderer textRenderer; 16 | 17 | public Game1() 18 | { 19 | this.graphics = new GraphicsDeviceManager(this) 20 | { 21 | PreferredBackBufferWidth = 1080, 22 | PreferredBackBufferHeight = 768, 23 | SynchronizeWithVerticalRetrace = false, 24 | GraphicsProfile = GraphicsProfile.HiDef 25 | }; 26 | 27 | this.Content.RootDirectory = "Content"; 28 | } 29 | 30 | protected override void LoadContent() 31 | { 32 | var effect = this.Content.Load("FieldFontEffect"); 33 | var font = this.Content.Load("arial"); 34 | 35 | this.textRenderer = new TextRenderer(effect, font, this.GraphicsDevice); 36 | } 37 | 38 | protected override void Update(GameTime gameTime) 39 | { 40 | if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed 41 | || Keyboard.GetState().IsKeyDown(Keys.Escape)) 42 | Exit(); 43 | 44 | base.Update(gameTime); 45 | } 46 | 47 | protected override void Draw(GameTime gameTime) 48 | { 49 | this.GraphicsDevice.Clear(Color.Black); 50 | 51 | this.GraphicsDevice.BlendState = BlendState.AlphaBlend; 52 | this.GraphicsDevice.DepthStencilState = DepthStencilState.None; 53 | this.GraphicsDevice.RasterizerState = RasterizerState.CullNone; 54 | 55 | var viewport = this.GraphicsDevice.Viewport; 56 | 57 | //var world = Matrix.CreateScale(0.01f) * Matrix.CreateRotationY((float)gameTime.TotalGameTime.TotalSeconds); 58 | var world = Matrix.CreateScale(0.01f) * Matrix.Identity; 59 | var view = Matrix.CreateLookAt(Vector3.Backward , Vector3.Forward, Vector3.Up); 60 | var projection = Matrix.CreatePerspectiveFieldOfView( 61 | MathHelper.PiOver2, 62 | viewport.Width / (float) viewport.Height, 63 | 0.01f, 64 | 1000.0f); 65 | 66 | var wvp = world * view * projection; 67 | 68 | this.textRenderer.Render("→~!435&^%$", wvp); 69 | 70 | 71 | world = Matrix.CreateScale(0.01f) * Matrix.CreateRotationY((float)gameTime.TotalGameTime.TotalSeconds) * Matrix.CreateRotationZ(MathHelper.PiOver4); 72 | view = Matrix.CreateLookAt(Vector3.Backward, Vector3.Forward, Vector3.Up); 73 | projection = Matrix.CreatePerspectiveFieldOfView( 74 | MathHelper.PiOver2, 75 | viewport.Width / (float)viewport.Height, 76 | 0.01f, 77 | 1000.0f); 78 | 79 | wvp = world * view * projection; 80 | 81 | this.textRenderer.Render(" To Infinity And Beyond!", wvp); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /MonoMSDF/Icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roy-t/MSDF/1a5191113af77060059c0de961586aa2ceec62cb/MonoMSDF/Icon.ico -------------------------------------------------------------------------------- /MonoMSDF/MonoMSDF.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | x86 7 | 8.0.30703 8 | 2.0 9 | {9860181B-EFE7-48F1-AC6C-4CD9C855F1E4} 10 | WinExe 11 | Properties 12 | MonoMSDF 13 | MonoMSDF 14 | 512 15 | Windows 16 | v4.7 17 | 18 | true 19 | 20 | 21 | 22 | 23 | x86 24 | true 25 | full 26 | false 27 | bin\$(MonoGamePlatform)\$(Platform)\$(Configuration)\ 28 | DEBUG;TRACE;WINDOWS 29 | prompt 30 | 4 31 | 32 | 33 | x86 34 | pdbonly 35 | true 36 | bin\$(MonoGamePlatform)\$(Platform)\$(Configuration)\ 37 | TRACE;WINDOWS 38 | prompt 39 | 4 40 | 41 | 42 | Icon.ico 43 | 44 | 45 | app.manifest 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | ..\packages\MonoGame.Framework.WindowsDX.3.7.0.1708\lib\net45\MonoGame.Framework.dll 58 | 59 | 60 | ..\packages\SharpDX.4.0.1\lib\net45\SharpDX.dll 61 | 62 | 63 | ..\packages\SharpDX.Direct2D1.4.0.1\lib\net45\SharpDX.Direct2D1.dll 64 | 65 | 66 | ..\packages\SharpDX.Direct3D11.4.0.1\lib\net45\SharpDX.Direct3D11.dll 67 | 68 | 69 | ..\packages\SharpDX.Direct3D9.4.0.1\lib\net45\SharpDX.Direct3D9.dll 70 | 71 | 72 | ..\packages\SharpDX.DXGI.4.0.1\lib\net45\SharpDX.DXGI.dll 73 | 74 | 75 | ..\packages\SharpDX.Mathematics.4.0.1\lib\net45\SharpDX.Mathematics.dll 76 | 77 | 78 | ..\packages\SharpDX.MediaFoundation.4.0.1\lib\net45\SharpDX.MediaFoundation.dll 79 | 80 | 81 | ..\packages\SharpDX.XAudio2.4.0.1\lib\net45\SharpDX.XAudio2.dll 82 | 83 | 84 | ..\packages\SharpDX.XInput.4.0.1\lib\net45\SharpDX.XInput.dll 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | {ebf08dc7-916d-4133-bade-38c31e29f18a} 101 | FontExtension 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 110 | 111 | 112 | 113 | 120 | -------------------------------------------------------------------------------- /MonoMSDF/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace MonoMSDF 4 | { 5 | #if WINDOWS || LINUX 6 | /// 7 | /// The main class. 8 | /// 9 | public static class Program 10 | { 11 | /// 12 | /// The main entry point for the application. 13 | /// 14 | [STAThread] 15 | static void Main() 16 | { 17 | using (var game = new Game1()) 18 | game.Run(); 19 | } 20 | } 21 | #endif 22 | } 23 | -------------------------------------------------------------------------------- /MonoMSDF/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("MonoMSDF")] 9 | [assembly: AssemblyProduct("MonoMSDF")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyDescription("")] 12 | [assembly: AssemblyCompany("")] 13 | [assembly: AssemblyCopyright("Copyright © 2018")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("233e57e9-d1e4-4942-bbf1-8ca37ea8dd08")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /MonoMSDF/Text/GlyphRenderInfo.cs: -------------------------------------------------------------------------------- 1 | using FontExtension; 2 | using Microsoft.Xna.Framework.Graphics; 3 | 4 | namespace MonoMSDF.Text 5 | { 6 | public sealed class GlyphRenderInfo 7 | { 8 | public char Character { get; } 9 | public Texture2D Texture { get; } 10 | public Metrics Metrics { get; } 11 | 12 | public GlyphRenderInfo(char character, Texture2D texture, Metrics metrics) 13 | { 14 | this.Character = character; 15 | this.Texture = texture; 16 | this.Metrics = metrics; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /MonoMSDF/Text/Quad.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xna.Framework; 2 | using Microsoft.Xna.Framework.Graphics; 3 | 4 | namespace MonoMSDF.Text 5 | { 6 | public sealed class Quad 7 | { 8 | private readonly VertexPositionTexture[] Vertices; 9 | private readonly short[] Indices; 10 | 11 | public Quad() 12 | { 13 | this.Vertices = new[] 14 | { 15 | new VertexPositionTexture( 16 | new Vector3(0, 0, 0), 17 | new Vector2(1, 1)), 18 | new VertexPositionTexture( 19 | new Vector3(0, 0, 0), 20 | new Vector2(0, 1)), 21 | new VertexPositionTexture( 22 | new Vector3(0, 0, 0), 23 | new Vector2(0, 0)), 24 | new VertexPositionTexture( 25 | new Vector3(0, 0, 0), 26 | new Vector2(1, 0)) 27 | }; 28 | 29 | this.Indices = new short[] { 0, 1, 2, 2, 3, 0 }; 30 | } 31 | 32 | /// 33 | /// Renders a fullscreen quad (when using device coordinates) 34 | /// 35 | public void Render(GraphicsDevice device) 36 | => Render(device, Vector2.One * -1, Vector2.One); 37 | 38 | public void Render(GraphicsDevice device, Vector2 v1, Vector2 v2) 39 | { 40 | this.Vertices[0].Position.X = v2.X; 41 | this.Vertices[0].Position.Y = v1.Y; 42 | 43 | this.Vertices[1].Position.X = v1.X; 44 | this.Vertices[1].Position.Y = v1.Y; 45 | 46 | this.Vertices[2].Position.X = v1.X; 47 | this.Vertices[2].Position.Y = v2.Y; 48 | 49 | this.Vertices[3].Position.X = v2.X; 50 | this.Vertices[3].Position.Y = v2.Y; 51 | 52 | device.DrawUserIndexedPrimitives( 53 | PrimitiveType.TriangleList, 54 | this.Vertices, 55 | 0, 56 | 4, 57 | this.Indices, 58 | 0, 59 | 2); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /MonoMSDF/Text/TextRenderer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Linq; 4 | using FontExtension; 5 | using Microsoft.Xna.Framework; 6 | using Microsoft.Xna.Framework.Graphics; 7 | 8 | namespace MonoMSDF.Text 9 | { 10 | public sealed class TextRenderer 11 | { 12 | private const string LargeTextTechnique = "LargeText"; 13 | private const string SmallTextTechnique = "SmallText"; 14 | 15 | private readonly Effect Effect; 16 | private readonly FieldFont Font; 17 | private readonly GraphicsDevice Device; 18 | private readonly Quad Quad; 19 | private readonly Dictionary Cache; 20 | 21 | public TextRenderer(Effect effect, FieldFont font, GraphicsDevice device) 22 | { 23 | this.Effect = effect; 24 | this.Font = font; 25 | this.Device = device; 26 | 27 | this.Quad = new Quad(); 28 | this.Cache = new Dictionary(); 29 | 30 | this.ForegroundColor = Color.White; 31 | this.EnableKerning = true; 32 | this.OptimizeForTinyText = false; 33 | } 34 | 35 | public Color ForegroundColor { get; set; } 36 | public bool EnableKerning { get; set; } 37 | 38 | /// 39 | /// Disables text anti-aliasing which might cause blurry text when the text is rendered tiny 40 | /// 41 | public bool OptimizeForTinyText { get; set; } 42 | 43 | public void Render(string text, Matrix worldViewProjection) 44 | { 45 | if (string.IsNullOrEmpty(text)) 46 | return; 47 | 48 | var sequence = text.Select(GetRenderInfo).ToArray(); 49 | var textureWidth = sequence[0].Texture.Width; 50 | var textureHeight = sequence[0].Texture.Height; 51 | 52 | this.Effect.Parameters["WorldViewProjection"].SetValue(worldViewProjection); 53 | this.Effect.Parameters["PxRange"].SetValue(this.Font.PxRange); 54 | this.Effect.Parameters["TextureSize"].SetValue(new Vector2(textureWidth, textureHeight)); 55 | this.Effect.Parameters["ForegroundColor"].SetValue(Color.White.ToVector4()); 56 | 57 | if (this.OptimizeForTinyText) 58 | { 59 | this.Effect.CurrentTechnique = this.Effect.Techniques[SmallTextTechnique]; 60 | } 61 | else 62 | { 63 | this.Effect.CurrentTechnique = this.Effect.Techniques[LargeTextTechnique]; 64 | } 65 | 66 | 67 | var pen = Vector2.Zero; 68 | for (var i = 0; i < sequence.Length; i++) 69 | { 70 | var current = sequence[i]; 71 | 72 | this.Effect.Parameters["GlyphTexture"].SetValue(current.Texture); 73 | this.Effect.CurrentTechnique.Passes[0].Apply(); 74 | 75 | var glyphHeight = textureHeight * (1.0f / current.Metrics.Scale); 76 | var glyphWidth = textureWidth * (1.0f / current.Metrics.Scale); 77 | 78 | var left = pen.X - current.Metrics.Translation.X; 79 | var bottom = pen.Y - current.Metrics.Translation.Y; 80 | 81 | var right = left + glyphWidth; 82 | var top = bottom + glyphHeight; 83 | 84 | if (!char.IsWhiteSpace(current.Character)) 85 | { 86 | this.Quad.Render(this.Device, new Vector2(left, bottom), new Vector2(right, top)); 87 | } 88 | 89 | pen.X += current.Metrics.Advance; 90 | 91 | if (this.EnableKerning && i < sequence.Length - 1) 92 | { 93 | var next = sequence[i + 1]; 94 | 95 | var pair = this.Font.KerningPairs.FirstOrDefault( 96 | x => x.Left == current.Character && x.Right == next.Character); 97 | 98 | if (pair != null) 99 | { 100 | 101 | pen.X += pair.Advance; 102 | } 103 | 104 | } 105 | } 106 | } 107 | 108 | private GlyphRenderInfo GetRenderInfo(char c) 109 | { 110 | if(this.Cache.TryGetValue(c, out var value)) 111 | { 112 | return value; 113 | } 114 | 115 | var unit = LoadRenderInfo(c); 116 | this.Cache.Add(c, unit); 117 | return unit; 118 | } 119 | 120 | private GlyphRenderInfo LoadRenderInfo(char c) 121 | { 122 | var glyph = this.Font.GetGlyph(c); 123 | using (var stream = new MemoryStream(glyph.Bitmap)) 124 | { 125 | var texture = Texture2D.FromStream(this.Device, stream); 126 | var unit = new GlyphRenderInfo(c, texture, glyph.Metrics); 127 | 128 | 129 | return unit; 130 | } 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /MonoMSDF/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /MonoMSDF/app.manifest: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | true/pm 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /MonoMSDF/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MSDF 2 | A signed distance field font sample for monogame. 3 | 4 | ![Sample](https://raw.githubusercontent.com/roy-t/MSDF/master/gallery.PNG "Sample") 5 | 6 | This sample shows how you can integrate [msdfgen](https://github.com/Chlumsky/msdfgen) into your content pipeline to generated signed distance field fonts, and how to correctly render these fonts. Including correct kerning courtesy of my [TrueType library](https://github.com/roy-t/TrueType). 7 | 8 | For more info visit my [blog](https://roy-t.nl). 9 | 10 | ## The content pipeline project 11 | This sample includes a content pipeline project compatible with Monogame 3.0+. The content processor requires you set the path to the msdfgen binary. I recommend you generate it from [this fork](https://github.com/ckohnert/msdfgen) as it fixes many issues with complicated fonts. 12 | 13 | ## The game project 14 | The game project contains a simple utility class and shader to draw 3D moving text. 15 | 16 | 17 | # Why (multi-channel) signed distance fields? 18 | 19 | Signed distance fields are a technique first described by Valve in [this paper](https://steamcdn-a.akamaihd.net/apps/valve/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf). In short a signed distance field is a sort-of height map. Where sea-level are the actually boundaries of the glyph. Everything above sea level is outside the glyph, and everything below sea level is inside the glyph. When a height map is upscaled the GPU fills in the gaps using linear interpolation. The linear interpolation of the height map introduces less noise/faults than interpolating a sharp boundary would do, but we still get the same information. 20 | 21 | Traditional signed distance fields only use one channel, but they sometimes have trouble representing sharp corners. Multi-channel signed distance fields solve this problem by using three color channels to store slope information. 22 | 23 | # Advantages 24 | 25 | - High quality text rendering 26 | - Low memory usage 27 | - Fast rendering (the shader is very simple) 28 | 29 | # Drawbacks 30 | 31 | - No automatic mechanism to determine the right signed distance field size to capture all details 32 | - No multi-color glyphs (like emoji) 33 | - Straight lines might look slightly wavery sometimes 34 | 35 | # Alternatives 36 | 37 | - SpriteFonts, the standard in XNA and MonoGame, look good when rendered at the same size as the sprites were saved, but upscaling and downscaling quickly leads to a serious degradation in quality. 38 | - A library like [slug](http://sluglibrary.com/) which renders text directly from the outline data in the font. So no details are missed and no manual configuration is required. -------------------------------------------------------------------------------- /gallery.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roy-t/MSDF/1a5191113af77060059c0de961586aa2ceec62cb/gallery.PNG --------------------------------------------------------------------------------