TextureZIM.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using SixLabors.ImageSharp.PixelFormats;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using UnityEngine;
  8. namespace ZIM.Unity
  9. {
  10. public class Texture2DZIM
  11. {
  12. public Texture2D Texture;
  13. public int Width, Height;
  14. public Vector2 Size => new Vector2(Width, Height);
  15. public Texture2DZIM(int width, int height, TextureFormat textureFormat = TextureFormat.RGB24, bool mipChain = false)
  16. {
  17. Texture = new Texture2D(width, height, textureFormat, mipChain);
  18. Width = width;
  19. Height = height;
  20. }
  21. public Texture2DZIM(Texture2D texture)
  22. {
  23. Texture = texture;
  24. Width = texture.width;
  25. Height = texture.height;
  26. }
  27. public void ReadPixels(RenderTexture rTex)
  28. {
  29. var old_rt = RenderTexture.active;
  30. RenderTexture.active = rTex;
  31. Texture.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
  32. Texture.Apply();
  33. RenderTexture.active = old_rt;
  34. }
  35. ~Texture2DZIM()
  36. {
  37. GameObject.Destroy(Texture);
  38. }
  39. public Color[] GetPixels() => Texture.GetPixels();
  40. public Vector2Int IndexToCoord(int i)
  41. {
  42. var y = i / Width;
  43. var x = i % Width;
  44. return new Vector2Int(x, y);
  45. }
  46. public int CoordToIndex(int x, int y)
  47. {
  48. return y * Width + x;
  49. }
  50. public static implicit operator Texture2D(Texture2DZIM i) => i?.Texture;
  51. public static implicit operator bool(Texture2DZIM i) => i?.Texture != null;
  52. }
  53. }