Batcher.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Veldrid.Common
  7. {
  8. public class Batcher<TTexture> where TTexture : notnull
  9. {
  10. private Stack<BatchGroup> _batchGroups;
  11. private Dictionary<TTexture, BatchGroup> _batchItems;
  12. public Batcher()
  13. {
  14. _batchItems = new Dictionary<TTexture, BatchGroup>();
  15. _batchGroups = new Stack<BatchGroup>();
  16. }
  17. public ref BatchItem Add(TTexture texture)
  18. {
  19. if (!_batchItems.TryGetValue(texture, out var group))
  20. {
  21. group = GetBatchGroup();
  22. group.Clear();
  23. _batchItems[texture] = group;
  24. }
  25. return ref group.Add();
  26. }
  27. public void Clear()
  28. {
  29. foreach (var group in this)
  30. ReturnBatchGroup(group.Value);
  31. _batchItems.Clear();
  32. }
  33. public Dictionary<TTexture, BatchGroup>.Enumerator GetEnumerator() =>
  34. _batchItems.GetEnumerator();
  35. private BatchGroup GetBatchGroup()
  36. {
  37. if (!_batchGroups.TryPop(out var group))
  38. group = new BatchGroup();
  39. return group;
  40. }
  41. private void ReturnBatchGroup(BatchGroup group) => _batchGroups.Push(group);
  42. }
  43. }