73 lines
No EOL
1.8 KiB
C#
73 lines
No EOL
1.8 KiB
C#
using SDL2;
|
|
|
|
namespace KumiScript.Renderer
|
|
{
|
|
public class ManagedFont : IDisposable
|
|
{
|
|
SDLFont _font;
|
|
int _cachesize;
|
|
SDL.SDL_Color _color;
|
|
SDLRenderer _renderer;
|
|
Dictionary<char, Glyph> _glyphs;
|
|
LinkedList<char> _incidence;
|
|
|
|
public ManagedFont(string path, int points, SDL.SDL_Color color, SDLRenderer renderer, int num_cache)
|
|
{
|
|
_font = new SDLFont(path, points);
|
|
_renderer = renderer;
|
|
_color = color;
|
|
_glyphs = new Dictionary<char, Glyph>();
|
|
_incidence = new LinkedList<char>();
|
|
_cachesize = num_cache;
|
|
}
|
|
|
|
public Glyph GetGlyph(char c)
|
|
{
|
|
UpdateFreq(c);
|
|
Glyph? g;
|
|
if (!_glyphs.TryGetValue(c, out g))
|
|
return CacheGlyph(c);
|
|
|
|
return g;
|
|
}
|
|
|
|
private Glyph CacheGlyph(char c)
|
|
{
|
|
if (_glyphs.Count >= _cachesize)
|
|
PurgeCache();
|
|
|
|
Glyph g = new Glyph(c, _font, _color, _renderer);
|
|
_glyphs.Add(c, g);
|
|
return g;
|
|
}
|
|
|
|
private void UpdateFreq(char c)
|
|
{
|
|
_incidence.Remove(c);
|
|
_incidence.AddFirst(c);
|
|
return;
|
|
}
|
|
|
|
private void PurgeCache()
|
|
{
|
|
for (int i = _cachesize - 1; i > _cachesize * .75; i--)
|
|
{
|
|
char c = _incidence.Last();
|
|
Glyph g = _glyphs[c];
|
|
_glyphs.Remove(c);
|
|
g.Dispose();
|
|
_incidence.RemoveLast();
|
|
}
|
|
return;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
List<Glyph> glyphs = _glyphs.Values.ToList();
|
|
foreach (Glyph g in glyphs)
|
|
g.Dispose();
|
|
|
|
_font.Dispose();
|
|
}
|
|
}
|
|
} |