TextureZIM.cs 1.6 KB

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