Texture2DManager.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using FontStashSharp.Interfaces;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Drawing;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace Veldrid.Common
  9. {
  10. internal class Texture2DManager : ITexture2DManager,IDisposable
  11. {
  12. private readonly GraphicsDevice _gd;
  13. private readonly List<WeakReference<Texture>> _textures;
  14. private bool _disposed;
  15. public Texture2DManager(GraphicsDevice gd)
  16. {
  17. _gd = gd;
  18. _textures = new List<WeakReference<Texture>>();
  19. }
  20. ~Texture2DManager()
  21. {
  22. Dispose(false);
  23. }
  24. public Veldrid.Texture CreateTexture(int width, int height)
  25. {
  26. var texture = _gd.ResourceFactory.CreateTexture(
  27. new TextureDescription(
  28. (uint)width, (uint)height, 1,
  29. 1, 1,
  30. PixelFormat.B8_G8_R8_A8_UNorm,
  31. TextureUsage.Sampled,
  32. TextureType.Texture2D,
  33. TextureSampleCount.Count1));
  34. _textures.Add(new WeakReference<Texture>(texture));
  35. return texture;
  36. }
  37. public void Dispose()
  38. {
  39. Dispose(true);
  40. }
  41. private void Dispose(bool disposing)
  42. {
  43. if (_disposed)
  44. return;
  45. _disposed = true;
  46. if (disposing)
  47. {
  48. foreach (var wt in _textures)
  49. if (wt.TryGetTarget(out var texture))
  50. texture.Dispose();
  51. }
  52. }
  53. public Size GetTextureSize(Veldrid.Texture texture)
  54. {
  55. var t = texture as Texture;
  56. if (t is null)
  57. return Size.Empty;
  58. return new Size((int)t.Width, (int)t.Height);
  59. }
  60. public void SetTextureData(Veldrid.Texture texture, System.Drawing.Rectangle bounds, byte[] data)
  61. {
  62. if (texture is Texture t)
  63. _gd.UpdateTexture(t, data, (uint)bounds.X, (uint)bounds.Y, 0, (uint)bounds.Width, (uint)bounds.Height, 1, 0, 0);
  64. }
  65. }
  66. }