TexturePoolCache.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Ryujinx.Graphics.Gpu.Image
  4. {
  5. /// <summary>
  6. /// Texture pool cache.
  7. /// This can keep multiple texture pools, and return the current one as needed.
  8. /// It is useful for applications that uses multiple texture pools.
  9. /// </summary>
  10. class TexturePoolCache : IDisposable
  11. {
  12. private const int MaxCapacity = 4;
  13. private GpuContext _context;
  14. private LinkedList<TexturePool> _pools;
  15. /// <summary>
  16. /// Constructs a new instance of the texture pool.
  17. /// </summary>
  18. /// <param name="context">GPU context that the texture pool belongs to</param>
  19. public TexturePoolCache(GpuContext context)
  20. {
  21. _context = context;
  22. _pools = new LinkedList<TexturePool>();
  23. }
  24. /// <summary>
  25. /// Finds a cache texture pool, or creates a new one if not found.
  26. /// </summary>
  27. /// <param name="address">Start address of the texture pool</param>
  28. /// <param name="maximumId">Maximum ID of the texture pool</param>
  29. /// <returns>The found or newly created texture pool</returns>
  30. public TexturePool FindOrCreate(ulong address, int maximumId)
  31. {
  32. TexturePool pool;
  33. // First we try to find the pool.
  34. for (LinkedListNode<TexturePool> node = _pools.First; node != null; node = node.Next)
  35. {
  36. pool = node.Value;
  37. if (pool.Address == address)
  38. {
  39. if (pool.CacheNode != _pools.Last)
  40. {
  41. _pools.Remove(pool.CacheNode);
  42. pool.CacheNode = _pools.AddLast(pool);
  43. }
  44. return pool;
  45. }
  46. }
  47. // If not found, create a new one.
  48. pool = new TexturePool(_context, address, maximumId);
  49. pool.CacheNode = _pools.AddLast(pool);
  50. if (_pools.Count > MaxCapacity)
  51. {
  52. TexturePool oldestPool = _pools.First.Value;
  53. _pools.RemoveFirst();
  54. oldestPool.Dispose();
  55. oldestPool.CacheNode = null;
  56. }
  57. return pool;
  58. }
  59. /// <summary>
  60. /// Disposes the texture pool cache.
  61. /// It's an error to use the texture pool cache after disposal.
  62. /// </summary>
  63. public void Dispose()
  64. {
  65. foreach (TexturePool pool in _pools)
  66. {
  67. pool.Dispose();
  68. }
  69. _pools.Clear();
  70. }
  71. }
  72. }