Skip to content

Commit

Permalink
Reduce allocations of temporary LibraryGraphicPair objects in NativeG…
Browse files Browse the repository at this point in the history
…raphicsManager
  • Loading branch information
ethanmoffat committed May 5, 2023
1 parent 7c5cda4 commit 1300e6f
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 101 deletions.
50 changes: 0 additions & 50 deletions EOLib.Graphics.Test/LibraryGraphicPairTest.cs

This file was deleted.

41 changes: 0 additions & 41 deletions EOLib.Graphics/LibraryGraphicPair.cs

This file was deleted.

26 changes: 16 additions & 10 deletions EOLib.Graphics/NativeGraphicsManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,23 @@
using SixLabors.ImageSharp.Processing;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace EOLib.Graphics
{
[MappedType(BaseType = typeof(INativeGraphicsManager), IsSingleton = true)]
public sealed class NativeGraphicsManager : INativeGraphicsManager
{
private readonly ConcurrentDictionary<LibraryGraphicPair, Texture2D> _cache;
private readonly ConcurrentDictionary<GFXTypes, ConcurrentDictionary<int, Texture2D>> _cache;

private readonly INativeGraphicsLoader _gfxLoader;
private readonly IGraphicsDeviceProvider _graphicsDeviceProvider;

public NativeGraphicsManager(INativeGraphicsLoader gfxLoader, IGraphicsDeviceProvider graphicsDeviceProvider)
{
_cache = new ConcurrentDictionary<LibraryGraphicPair, Texture2D>();
_cache = new ConcurrentDictionary<GFXTypes, ConcurrentDictionary<int, Texture2D>>();
_gfxLoader = gfxLoader;
_graphicsDeviceProvider = graphicsDeviceProvider;
}
Expand All @@ -29,18 +31,16 @@ public Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transp
{
Texture2D ret;

var key = new LibraryGraphicPair((int)file, 100 + resourceVal);

if (_cache.ContainsKey(key))
if (_cache.ContainsKey(file) && _cache[file].ContainsKey(resourceVal))
{
if (reloadFromFile)
{
_cache[key]?.Dispose();
_cache.TryRemove(key, out var _);
_cache[file][resourceVal]?.Dispose();
_cache[file].Remove(resourceVal, out _);
}
else
{
return _cache[key];
return _cache[file][resourceVal];
}
}

Expand All @@ -61,7 +61,12 @@ public Texture2D TextureFromResource(GFXTypes file, int resourceVal, bool transp
}
}

_cache.TryAdd(key, ret);
if (_cache.ContainsKey(file) ||
_cache.TryAdd(file, new ConcurrentDictionary<int, Texture2D>()))
{
_cache[file].TryAdd(resourceVal, ret);
}

return ret;
}

Expand Down Expand Up @@ -96,8 +101,9 @@ private static void CrossPlatformMakeTransparent(Image bmp, Color transparentCol

public void Dispose()
{
foreach (var text in _cache.Values)
foreach (var text in _cache.SelectMany(x => x.Value.Values))
text.Dispose();

_cache.Clear();
}
}
Expand Down

0 comments on commit 1300e6f

Please sign in to comment.