-
-
Save mdsitton/13118a074f89565992aed406e14eda7e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
using UnityEngine; | |
using UnityEngine.TextCore.LowLevel; | |
using TMPro; | |
using System.Globalization; | |
class LyricText : MonoBehaviour | |
{ | |
[SerializeField] | |
TextMeshProUGUI currentPhraseDisplay; | |
[SerializeField] | |
TextMeshProUGUI nextPhraseDisplay; | |
[SerializeField] | |
TextMeshProUGUI fadePhraseDisplay; | |
[SerializeField] | |
Font[] fallbackFonts; | |
TMP_FontAsset dynamicFont; | |
List<Phrase> phrases; | |
private IEnumerable<uint> GetUTF32Chars(string s) | |
{ | |
var tee = StringInfo.GetTextElementEnumerator(s); | |
while (tee.MoveNext()) | |
{ | |
yield return (uint)char.ConvertToUtf32(s, tee.ElementIndex); | |
} | |
} | |
private string UTF32ToString(uint[] input) | |
{ | |
string[] output = new string[input.Length]; | |
for (int i = 0; i < input.Length; ++i) | |
{ | |
output[i] = char.ConvertFromUtf32((int)input[i]); | |
} | |
return string.Concat(output); | |
} | |
private TMP_FontAsset LoadFontAsset(Font sourceFont, uint[] characters, out uint[] missingGlphs) | |
{ | |
TMP_FontAsset dynamicFont = TMP_FontAsset.CreateFontAsset(sourceFont, 90, 9, GlyphRenderMode.SDFAA, 1024, 1024, AtlasPopulationMode.Dynamic); | |
dynamicFont.TryAddCharacters(characters, out missingGlphs); | |
if (missingGlphs != null && missingGlphs.Length != 0) | |
{ | |
Debug.Log($"Characters not supported by font: {UTF32ToString(missingGlphs)}"); | |
} | |
return dynamicFont; | |
} | |
private IEnumerable<uint> GetLyricUTF32Chars() | |
{ | |
foreach (Phrase phrase in phrases) | |
{ | |
foreach (uint codePoint in GetUTF32Chars(phrase.text)) | |
{ | |
yield return codePoint; | |
} | |
} | |
} | |
public void SetupFont() | |
{ | |
uint[] startingGlyphs = GetLyricUTF32Chars().Distinct().ToArray(); | |
uint[] remainingGlyphs = startingGlyphs; | |
List<TMP_FontAsset> fontAssets = new List<TMP_FontAsset>(); | |
foreach (Font font in fallbackFonts) | |
{ | |
fontAssets.Add(LoadFontAsset(font, remainingGlyphs, out remainingGlyphs)); | |
if (remainingGlyphs == null) | |
break; | |
} | |
Debug.Log($"starting glyphs: {UTF32ToString(startingGlyphs)}"); | |
dynamicFont = fontAssets[0]; | |
for (int i = 1; i < fontAssets.Count; ++i) | |
{ | |
dynamicFont.fallbackFontAssetTable.Add(fontAssets[i]); | |
} | |
currentPhraseDisplay.font = dynamicFont; | |
nextPhraseDisplay.font = dynamicFont; | |
fadePhraseDisplay.font = dynamicFont; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment