TextureHandler.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Diagnostics.CodeAnalysis;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text.RegularExpressions;
  11. namespace OpenVIII
  12. {
  13. /// <summary>
  14. /// This contains functions to Load High res mod versions of textures and get scale vector.
  15. /// </summary>
  16. public class TextureHandler : IDisposable
  17. {
  18. #region Fields
  19. private static readonly ConcurrentDictionary<string, Texture2D> PngCache = new ConcurrentDictionary<string, Texture2D>();
  20. private static readonly ConcurrentDictionary<string, TextureHandler> TextureHandlerCache = new ConcurrentDictionary<string, TextureHandler>();
  21. private Texture_Base _classic;
  22. private bool _disposedValue;
  23. /// <summary>
  24. /// If i'm expecting a 256x256 and get a 128x256 pad the pixels with transparent ones.
  25. /// </summary>
  26. private bool _enforceSquare;
  27. #endregion Fields
  28. #region Properties
  29. public IEnumerable<Texture2D> AllTexture2Ds => Grid.Select(x => Textures[x.col, x.row]);
  30. /// <summary>
  31. /// Original sub 256x265 texture, required for fallback when issues happen.
  32. /// </summary>
  33. public Texture_Base Classic { get => _classic; private set { _classic = value; if (value != null) ClassicSize = new Vector2(value.GetWidth, value.GetHeight); } }
  34. public int ClassicHeight => (int)(ClassicSize == Vector2.Zero ? Size.Y : ClassicSize.Y);
  35. /// <summary>
  36. /// X = width and Y = height. The Size of original texture. Will be used in scaling
  37. /// </summary>
  38. public Vector2 ClassicSize { get; private set; }
  39. public int ClassicWidth => (int)(ClassicSize == Vector2.Zero ? Size.X : ClassicSize.X);
  40. public Color[] Colors { get; private set; }
  41. public uint Count { get; protected set; }
  42. public IEnumerable<(int col, int row)> Grid =>
  43. (from row in Enumerable.Range(0, (int)Rows)
  44. from col in Enumerable.Range(0, (int)Cols)
  45. select (col, row));
  46. public int Height => (int)Size.Y;
  47. public bool Modded { get; private set; }
  48. public string ModdedFilename { get; private set; }
  49. public ushort Palette { get; protected set; }
  50. /// <summary>
  51. /// Scale vector from big to original
  52. /// </summary>
  53. public Vector2 ReverseScaleFactor => Size == Vector2.Zero || ClassicSize == Vector2.Zero ? Vector2.One : ClassicSize / Size;
  54. /// <summary>
  55. /// Scale vector from original to big
  56. /// </summary>
  57. public Vector2 ScaleFactor => Size == Vector2.Zero || ClassicSize == Vector2.Zero ? Vector2.One : Size / ClassicSize;
  58. /// <summary>
  59. /// X = width and Y = height. The Size of big version texture. Will be used in scaling
  60. /// </summary>
  61. public Vector2 Size { get; private set; }
  62. public int Width => (int)Size.X;
  63. protected uint Cols { get; set; }
  64. protected string Filename { get; set; }
  65. protected uint Rows { get; set; }
  66. protected uint StartOffset { get; set; }
  67. protected Texture2D[,] Textures { get; private set; }
  68. #endregion Properties
  69. #region Indexers
  70. public Texture2D this[int c, int r] => Textures[c, r];
  71. #endregion Indexers
  72. #region Methods
  73. public static Vector2 Abs(Vector2 v) => new Vector2(Math.Abs(v.X), Math.Abs(v.Y));
  74. public static TextureHandler Create(string filename, uint cols) => Create(filename, cols, 1);
  75. public static TextureHandler Create(string filename, uint cols, uint rows) => Create(filename, null, cols, rows);
  76. public static TextureHandler Create(string filename, Texture_Base classic, ushort palette = 0, Color[] colors = null) => Create(filename, classic, 1, 1, palette: palette, colors: colors);
  77. public static TextureHandler Create(string filename, Texture_Base classic, uint cols, uint rows, ushort palette = 0, Color[] colors = null)
  78. {
  79. var (pngPath, _) = FindPng(filename, palette);
  80. if (!string.IsNullOrWhiteSpace(pngPath) && TextureHandlerCache.TryGetValue(pngPath, out var ret)) return ret;
  81. ret = new TextureHandler
  82. {
  83. ModdedFilename = pngPath,
  84. Filename = filename,
  85. Classic = classic,
  86. Cols = cols,
  87. Rows = rows,
  88. Palette = palette,
  89. Colors = colors
  90. };
  91. ret.Init();
  92. if (ret.Modded && !string.IsNullOrWhiteSpace(ret.ModdedFilename))
  93. {
  94. TextureHandlerCache.TryAdd(ret.ModdedFilename, ret);
  95. }
  96. return ret;
  97. }
  98. public static TextureHandler CreateFromPng(string filename, int classicWidth, int classicHeight, ushort palette, bool enforceSquare, bool forceReload = false)
  99. {
  100. var (s, _) = FindPng(filename, palette);
  101. if (string.IsNullOrWhiteSpace(s)) return null;
  102. if (!TextureHandlerCache.TryGetValue(s, out var ret))
  103. {
  104. ret = new TextureHandler
  105. {
  106. _enforceSquare = enforceSquare,
  107. ModdedFilename = filename,
  108. //Modded = string.IsNullOrWhiteSpace(s),
  109. Filename = filename,
  110. ClassicSize = new Vector2(classicWidth, classicHeight),
  111. Cols = 1,
  112. Rows = 1,
  113. Palette = palette
  114. };
  115. ret.Init();
  116. if (ret.Modded && !string.IsNullOrWhiteSpace(ret.ModdedFilename))
  117. {
  118. TextureHandlerCache.TryAdd(ret.ModdedFilename, ret);
  119. }
  120. }
  121. else if (forceReload && ret.Modded)
  122. {
  123. ret.Reload();
  124. }
  125. return ret;
  126. }
  127. public static explicit operator Texture2D(TextureHandler t)
  128. {
  129. if (t.Count == 0)
  130. return null;
  131. if (t.Count == 1)
  132. return t[0, 0];
  133. throw new Exception("TextureHandler can only be cast to Texture2D if there is only one texture in the array use [cols,rows] instead");
  134. //return null;
  135. }
  136. [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
  137. public static (string PNGpath, byte[] zzzPNG) FindPng(string path, int palette = -1)
  138. {
  139. if (File.Exists(path))
  140. return (path, null);
  141. var bn = Regex.Escape(Path.GetFileNameWithoutExtension(Regex.Replace(path, @"\{[\d\.\:]+\}", "",
  142. RegexOptions.IgnoreCase | RegexOptions.Compiled)));
  143. var textures = Path.Combine(Memory.FF8Dir, "textures");
  144. if (!Directory.Exists(textures)) return (null, null);
  145. var pngStrings = Directory.GetFiles(textures, $"*{bn}*.png", SearchOption.AllDirectories);
  146. if (pngStrings.Length == 1) return (pngStrings[0], null);
  147. var bn1 = bn;
  148. var limited = pngStrings.Where(x => x.IndexOf(bn1, StringComparison.OrdinalIgnoreCase) >= 0)
  149. .OrderBy(x => x.Length).ThenBy(x => x, StringComparer.InvariantCultureIgnoreCase);
  150. if (limited.Any())
  151. {
  152. var re1 = new Regex(@".+[\\/]+" + bn + @"_(\d{1,2})\.png",
  153. RegexOptions.IgnoreCase | RegexOptions.Compiled);
  154. var re2 = new Regex(@".+[\\/]+" + bn + @"\.png", RegexOptions.IgnoreCase | RegexOptions.Compiled);
  155. var matches = (limited.Select(x => new { x, m1 = re1.Match(x) })
  156. .Select(t => new { t, m2 = re2.Match(t.x) })
  157. .Where(t => (t.t.m1.Success || t.m2.Success))
  158. .OrderByDescending(t => t.t.m1.Success)
  159. .Select(t => t.t.m1.Success ? t.t.m1 : t.m2));
  160. var tex = matches.FirstOrDefault(x =>
  161. (x.Groups.Count == 2 && int.TryParse(x.Groups[1].Value, out var p) && p == palette) ||
  162. x.Groups.Count == 1)
  163. ?.Value;
  164. if (!string.IsNullOrWhiteSpace(tex)) return (tex, null);
  165. }
  166. var zzz = ArchiveZzz.Load(Memory.Archives.ZZZ_MAIN);
  167. if (zzz == null || !zzz.IsOpen) return (null, null);
  168. bn += ".png";
  169. if (zzz.ArchiveMap.FindString(ref bn, out _) != default)
  170. return PngCache.ContainsKey(bn) ? (bn, null) : (bn, zzz.GetBinaryFile(bn));
  171. return (null, null);
  172. }
  173. public static Vector2 GetOffset(Rectangle old, Rectangle @new) => GetOffset(old.Location.ToVector2(), @new.Location.ToVector2());
  174. public static Vector2 GetOffset(Vector2 oldLoc, Vector2 newLoc) => Abs(oldLoc - newLoc);
  175. public static Vector2 GetScale(Vector2 old, Vector2 @new)
  176. {
  177. if (Math.Abs(@new.Y) < float.Epsilon && Math.Abs(@new.X) > float.Epsilon)
  178. return new Vector2(@new.X / old.X);
  179. if (Math.Abs(@new.Y) > float.Epsilon && Math.Abs(@new.X) < float.Epsilon)
  180. return new Vector2(@new.Y / old.Y);
  181. if (Math.Abs(@new.Y) < float.Epsilon && Math.Abs(@new.X) < float.Epsilon)
  182. return Vector2.One;
  183. return @new / old;
  184. }
  185. public static Vector2 GetScale(Texture_Base old, Texture2D @new) => new Vector2((float)@new.Width / old.GetWidth, (float)@new.Height / old.GetHeight);
  186. public static Vector2 GetScale(Point oldSize, Point newSize) => GetScale(oldSize.ToVector2(), newSize.ToVector2());
  187. public static implicit operator Rectangle(TextureHandler v) => new Rectangle(new Point(0), v.Size.ToPoint());
  188. /// <summary>
  189. /// Load Texture from a mod
  190. /// </summary>
  191. /// <param name="path"></param>
  192. /// <returns></returns>
  193. // ReSharper disable once InconsistentNaming
  194. public static Texture2D LoadPNG(string path, int palette = -1, bool forceSquare = false)
  195. {
  196. //Debug.Assert(!path.ToLower().Contains("c0m071"));
  197. var (pngPath, zzzPNG) = File.Exists(path) ? (path, null) : FindPng(path, palette);
  198. Texture2D tex = null;
  199. if (!string.IsNullOrWhiteSpace(pngPath))
  200. {
  201. if (PngCache.TryGetValue(pngPath, out tex))
  202. {
  203. }
  204. else if (zzzPNG != null && zzzPNG.Length > 0)
  205. {
  206. using (var fs = new MemoryStream(zzzPNG, false))
  207. {
  208. tex = Texture2D.FromStream(Memory.Graphics.GraphicsDevice, fs);
  209. PngCache.TryAdd(pngPath, tex);
  210. }
  211. }
  212. else if (File.Exists(pngPath))
  213. {
  214. using (var fs = new FileStream(pngPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  215. {
  216. tex = Texture2D.FromStream(Memory.Graphics.GraphicsDevice, fs);
  217. PngCache.TryAdd(pngPath, tex);
  218. }
  219. }
  220. }
  221. if (tex == null || !forceSquare || tex.Width == tex.Height) return tex;
  222. var s = Math.Max(tex.Width, tex.Height);
  223. var tmp = new RenderTarget2D(Memory.Graphics.GraphicsDevice, s, s);
  224. using (tex)
  225. {
  226. Memory.Graphics.GraphicsDevice.SetRenderTarget(tmp);
  227. Memory.SpriteBatchStartAlpha();
  228. Memory.Graphics.GraphicsDevice.Clear(Color.TransparentBlack);
  229. Memory.SpriteBatch.Draw(tex, new Rectangle(0, 0, tex.Width, tex.Height), Color.White);
  230. Memory.SpriteBatchEnd();
  231. Memory.Graphics.GraphicsDevice.SetRenderTarget(null);
  232. }
  233. tex = tmp;
  234. return tex;
  235. }
  236. public static Rectangle Scale(Rectangle src, Vector2 scale)
  237. {
  238. src.Location = (src.Location.ToVector2() * scale).ToPoint();//.RoundedPoint();
  239. src.Size = (src.Size.ToVector2() * scale).ToPoint();//.RoundedPoint();
  240. return src;
  241. }
  242. public static Rectangle ToRectangle(Texture2D t) => new Rectangle(0, 0, t?.Width ?? 0, t?.Height ?? 0);
  243. public static Rectangle ToRectangle(TextureHandler t) => new Rectangle(0, 0, (int)t.ClassicSize.X, (int)t.ClassicSize.Y);
  244. public static Rectangle ToRectangle(Vector2 loc, Vector2 size) => new Rectangle(loc.ToPoint(), size.ToPoint());
  245. public static Vector2 ToVector2(Texture2D t) => t != null ? new Vector2(t.Width, t.Height) : Vector2.Zero;
  246. public static Texture2D UseBest(Texture_Base old, Texture2D @new, ushort palette = 0, Color[] colors = null) => UseBest(old, @new, out var _, palette, colors);
  247. public static Texture2D UseBest(Texture_Base old, Texture2D @new, out Vector2 scale, ushort palette = 0, Color[] colors = null)
  248. {
  249. if (@new == null && old != null)
  250. {
  251. scale = Vector2.One;
  252. if (old.GetClutCount <= 1)
  253. return old.GetTexture();
  254. var tex = colors != null ? old.GetTexture(colors) : old.GetTexture(palette);
  255. return tex;
  256. }
  257. scale = old != null ? GetScale(old, @new) : Vector2.Zero;
  258. return @new;
  259. }
  260. // This code added to correctly implement the disposable pattern.
  261. public void Dispose() =>
  262. // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  263. Dispose(true);
  264. public void Draw(Rectangle dst, Rectangle? src, Color color)
  265. {
  266. if (src != null)
  267. {
  268. _Draw(dst, src.Value, color);
  269. }
  270. //drawing texture directly
  271. else
  272. {
  273. _Draw(dst, color);
  274. }
  275. }
  276. public void Draw(Rectangle dst, Color color) => Draw(dst, null, color);
  277. public void Draw(Rectangle dst, Color color, float rotation, Vector2 origin, SpriteEffects effects, float depth)
  278. {
  279. if (Rows == 1 && Cols == 1)
  280. Memory.SpriteBatch.Draw(Textures[0, 0], dst, null, color, rotation, origin, effects, depth);
  281. else
  282. {
  283. throw new Exception("had not coded this to draw from multiple textures");
  284. }
  285. }
  286. public Vector2 GetScale(int cols = 0, int rows = 0) => ScaleFactor;
  287. public void Merge()
  288. {
  289. if (Rows * Cols <= 1 || Textures == null || Textures.Length < Rows * Cols) return;
  290. if (Memory.IsMainThread)
  291. {
  292. var width = 0;
  293. var height = 0;
  294. if (!(AllTexture2Ds.Any(x => x == null)))
  295. {
  296. for (var r = 0; r < (int)Rows; r++)
  297. {
  298. var rowWidth = 0;
  299. var rowHeight = 0;
  300. for (var c = 0; c < (int)Cols && Textures[c, r] != null; c++)
  301. {
  302. rowWidth += Textures[c, r].Width;
  303. if (rowHeight < Textures[c, r].Height)
  304. rowHeight = Textures[c, r].Height;
  305. }
  306. if (width < rowWidth)
  307. width = rowWidth;
  308. height += rowHeight;
  309. }
  310. }
  311. if (width == 0 || height == 0)
  312. {
  313. Rows = 0;
  314. Cols = 0;
  315. Count = 0;
  316. Textures = null;
  317. return;
  318. }
  319. var tex = new Texture2D(Memory.Graphics.GraphicsDevice, width, height, false, SurfaceFormat.Color);
  320. var dst = new Rectangle();
  321. for (var r = 0; r < (int)Rows; r++)
  322. {
  323. dst.Y += r > 0 ? Textures[0, r - 1].Height : 0;
  324. for (var c = 0; c < (int)Cols; c++)
  325. {
  326. dst.Height = Textures[c, r].Height;
  327. dst.Width = Textures[c, r].Width;
  328. dst.X += c > 0 ? Textures[c - 1, r].Width : 0;
  329. var buffer = new Color[dst.Height * dst.Width];
  330. Textures[c, r].GetData(buffer);
  331. tex.SetData(0, dst, buffer, 0, buffer.Length);
  332. //Textures[c, r].Dispose();
  333. }
  334. dst.X = 0;
  335. }
  336. foreach (var t in Textures)
  337. t.Dispose();
  338. Textures = new Texture2D[1, 1];
  339. Textures[0, 0] = tex;
  340. Rows = 1;
  341. Cols = 1;
  342. Count = 1;
  343. }
  344. else
  345. {
  346. Memory.MainThreadOnlyActions.Enqueue(this.Merge);
  347. }
  348. }
  349. public void Save() => Save("", true);
  350. public void Save(string outPath, bool replace)
  351. {
  352. var clean = Path.GetFileNameWithoutExtension(Regex.Replace(Filename, @"{[^}]+}", ""));
  353. clean = $"{Path.GetFileName(clean)}_{(Palette).ToString()}.png";
  354. outPath = Path.Combine(string.IsNullOrWhiteSpace(outPath) ? Path.GetTempPath() : outPath, clean);
  355. if ((!File.Exists(outPath) || replace)
  356. && (Textures != null && Textures.Length > 0 && Textures[0, 0] != null))
  357. using (var fs = File.Create(outPath))
  358. Textures[0, 0].SaveAsPng(fs, Textures[0, 0].Width, Textures[0, 0].Height);
  359. else
  360. Debug.WriteLine($"{this} :: Textures is null or empty! :: {Filename}");
  361. }
  362. /// <summary>
  363. /// Remove all transparent rows and cols of pixels
  364. /// </summary>
  365. /// <param name="src"></param>
  366. /// <returns></returns>
  367. public Rectangle Trim(Rectangle src) => _process(Rectangle.Empty, src, Color.TransparentBlack, _Trim_SingleTexture);
  368. protected virtual void Dispose(bool disposing)
  369. {
  370. if (_disposedValue) return;
  371. if (disposing)
  372. {
  373. // TODO: dispose managed state (managed objects).
  374. }
  375. if (!string.IsNullOrWhiteSpace(ModdedFilename) && PngCache.TryRemove(ModdedFilename, out var tex))
  376. {
  377. if (!tex.IsDisposed)
  378. {
  379. tex.Dispose();
  380. }
  381. }
  382. if (!string.IsNullOrWhiteSpace(Filename) && TextureHandlerCache.TryRemove(Filename, out var textureHandler))
  383. {
  384. foreach (var t in textureHandler.Textures)
  385. {
  386. if (!t.IsDisposed)
  387. {
  388. t.Dispose();
  389. }
  390. }
  391. }
  392. // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
  393. // TODO: set large fields to null.
  394. // TODO need an easy way to remove old textures from cache.
  395. _disposedValue = true;
  396. }
  397. protected void Process()
  398. {
  399. if (Memory.Graphics?.GraphicsDevice == null) return;
  400. var size = Vector2.Zero;
  401. var oldSize = Vector2.Zero;
  402. Texture_Base tex = null;
  403. var aw = ArchiveWorker.Load(Memory.Archives.A_MENU); // TODO remove this should be done outside of texture handler.
  404. var listOfFiles = aw.GetListOfFiles(); // TODO remove this.
  405. uint c2 = 0;
  406. uint r2 = 0;
  407. var total = Rows * Cols;
  408. for (uint r = 0; r < Rows; r++)
  409. {
  410. for (uint c = 0; c < Cols; c++)
  411. {
  412. Texture2D pngTex;
  413. var path = "";
  414. if (listOfFiles != null)
  415. {
  416. var value = string.Format(Filename, c + r * Cols + StartOffset);
  417. path = listOfFiles.FirstOrDefault(x => (x.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0));
  418. }
  419. if (!string.IsNullOrWhiteSpace(path))
  420. {
  421. tex = Texture_Base.Open(aw.GetBinaryFile(path));
  422. if (Classic == null && c2 < Cols) oldSize.X += tex?.GetWidth ?? ClassicWidth;
  423. pngTex = LoadPNG(path, Palette, _enforceSquare);
  424. }
  425. else
  426. {
  427. pngTex = !string.IsNullOrWhiteSpace(ModdedFilename) ? LoadPNG(ModdedFilename, Palette, _enforceSquare) : LoadPNG(Filename, Palette, _enforceSquare);
  428. }
  429. if (tex == null && total == 1) tex = Classic;
  430. Textures[c, r] = (UseBest(tex, pngTex, Palette, Colors));
  431. if (pngTex != null) Modded = true;
  432. if (c2 < Cols && Textures[c2, r2] != null) size.X += Textures[c2++, r2].Width;
  433. }
  434. if (Classic == null && r2 < Rows) oldSize.Y += tex?.GetHeight ?? ClassicHeight;
  435. if (r2 < Rows && Textures.LongLength > r2 + c2 - 1 && Textures[c2 - 1, r2] != null) size.Y += Textures[c2 - 1, r2++].Height;
  436. }
  437. Size = size;
  438. if (Classic == null && ClassicSize == Vector2.Zero) ClassicSize = oldSize;
  439. }
  440. private static Rectangle _Draw(Texture2D tex, Rectangle dst, Rectangle src, Color color)
  441. {
  442. Memory.SpriteBatch.Draw(tex, dst, src, color);
  443. return src;
  444. }
  445. private void _Draw(Rectangle dst, Rectangle src, Color color)
  446. => _process(dst, src, color, _Draw);
  447. private void _Draw(Rectangle dst, Color color)
  448. {
  449. if (Rows == 1 && Cols == 1 && dst.Height > 0 && dst.Width > 0)
  450. Memory.SpriteBatch.Draw(Textures[0, 0], dst, color);
  451. else
  452. {
  453. //throw new Exception($"{this}::code broken for multiple pcs. I think");
  454. var dstOffset = Vector2.Zero;
  455. var dstV = Vector2.Zero;
  456. dstOffset.X = dst.X;
  457. dstOffset.Y = dst.Y;
  458. for (uint r = 0; r < Rows; r++)
  459. {
  460. for (uint c = 0; c < Cols; c++)
  461. {
  462. var scale = GetScale(Size, dst.Size.ToVector2());
  463. var texture = Textures[c, r];
  464. if (texture != null)
  465. {
  466. dstV = ToVector2(texture) * scale;
  467. Memory.SpriteBatch.Draw(texture, dstOffset, null, color, 0f, Vector2.Zero, scale, SpriteEffects.None, 0f);
  468. }
  469. dstOffset.X += dstV.X;
  470. }
  471. dstOffset.Y += dstV.Y;
  472. }
  473. }
  474. }
  475. /// <summary>
  476. /// Process the texture with the given variables.
  477. /// <para>Only used by trim and draw.</para>
  478. /// <para>Trim really only needs src variable</para>
  479. /// </summary>
  480. /// <param name="dst"></param>
  481. /// <param name="src"></param>
  482. /// <param name="color"></param>
  483. /// <param name="single"></param>
  484. /// <returns></returns>
  485. private Rectangle _process(
  486. Rectangle dst, Rectangle src, Color color,
  487. Func<Texture2D, Rectangle, Rectangle, Color, Rectangle> single)
  488. {
  489. var ret = Rectangle.Empty;
  490. if (Memory.IsMainThread) // Some code may only work on main thread.
  491. {
  492. //all extra code is only used for multiple pcs
  493. var dstOffset = Vector2.Zero; // only if Intersects
  494. var dst2 = Rectangle.Empty; // only if Intersects
  495. var offset = Vector2.Zero;
  496. var cnt = Rectangle.Empty;
  497. for (uint r = 0; r < Rows; r++)
  498. {
  499. var drawn = false; // only if Intersects
  500. offset.X = 0;
  501. for (uint c = 0; c < Cols; c++)
  502. {
  503. //Start: if were always only one texture pcs
  504. var source2 = Scale(src, ScaleFactor);
  505. cnt = ContainerRectangle(offset, Textures[c, r]);
  506. if (cnt.Contains(source2))
  507. {
  508. source2.Location = (GetOffset(cnt, source2)).ToPoint();
  509. return single(Textures[c, r], dst, source2, color);
  510. }
  511. //End
  512. //This part is for if a given src rectangle overlaps >=2 textures
  513. if (cnt.Intersects(source2))
  514. {
  515. var src2 = Rectangle.Intersect(cnt, source2);
  516. src2.Location = (GetOffset(cnt, src2)).ToPoint();
  517. dst2 = Scale(dst, GetScale(source2.Size, src2.Size));
  518. dst2.Location = (dst.Location);
  519. dst2.Offset(dstOffset);
  520. if (ret == Rectangle.Empty)
  521. ret = single(Textures[c, r], dst2, src2, color);
  522. else
  523. Rectangle.Union(ret, single(Textures[c, r], dst2, src2, color));
  524. drawn = true;
  525. dstOffset.X += dst2.Width;
  526. }
  527. offset.X += cnt.Width;
  528. }
  529. offset.Y += cnt.Height;
  530. if (drawn)
  531. dstOffset.Y += dst2.Height;
  532. }
  533. }
  534. else throw new InvalidOperationException($"{this} Must run in main thread.");
  535. return ret;
  536. }
  537. private Rectangle _Trim_SingleTexture(Texture2D tex, Rectangle dst, Rectangle src, Color color)
  538. {
  539. var ret = Rectangle.Empty;
  540. ret.Offset(-1, -1);
  541. // storage of colors.
  542. var tmp = new Color[src.Width * src.Height];
  543. // colors of all pixels
  544. tex.GetData(0, src, tmp, 0, tmp.Length);
  545. // max x and y values
  546. var x2 = src.Width;
  547. var y2 = src.Height;
  548. // check each pixel's color
  549. for (var y1 = 0; y1 < y2; y1++)
  550. {
  551. for (var x1 = 0; x1 < x2; x1++)
  552. {
  553. var a = tmp[x1 + y1 * src.Width];
  554. if (a.A != 0)
  555. {
  556. // grab high and low bounds of non transparent pixels.
  557. if (ret.Y < 0 || ret.X > x1)
  558. {
  559. ret.X = x1;
  560. }
  561. else if (ret.Width == 0 || ret.Width < x1)
  562. ret.Width = x1;
  563. // do same for Y axis.
  564. if (ret.Y < 0 || ret.Y > y1)
  565. {
  566. ret.Y = y1;
  567. }
  568. else if (ret.Height == 0 || ret.Height < y1)
  569. ret.Height = y1;
  570. }
  571. }
  572. }
  573. //using height and width as a bottom and right x/y
  574. //converting them back to height and width.
  575. ret.Width -= ret.X;
  576. ret.Height -= ret.Y;
  577. ret.Width += 1;
  578. ret.Height += 1;
  579. ret.Offset(src.X, src.Y);
  580. ret = Scale(ret, ReverseScaleFactor);
  581. //src = Scale(src, ReverseScaleFactor);
  582. return ret;
  583. }
  584. private Rectangle ContainerRectangle(Vector2 offset, Texture2D tex)
  585. {
  586. var cnt = ToRectangle(tex);
  587. cnt.Offset(offset);
  588. return cnt;
  589. }
  590. private void Init()
  591. {
  592. Size = Vector2.Zero;
  593. Count = Cols * Rows;
  594. Textures = new Texture2D[Cols, Rows];
  595. StartOffset = 0;
  596. //load textures;
  597. Process();
  598. //unload Classic
  599. Classic = null;
  600. //Merge the texture pieces into one.
  601. Merge();
  602. if (!Modded && Memory.EnableDumpingData)
  603. Memory.MainThreadOnlyActions.Enqueue(this.Save);
  604. //if(ScaleFactor.X > ScaleFactor.Y && ScaleFactor.X/ScaleFactor.Y == 2f)
  605. //{
  606. // var t = new Texture2D(Memory.graphics.GraphicsDevice, (int)(ClassicWidth * ScaleFactor.Y), Height);
  607. // var c = new Color[t.Width * t.Height];
  608. // Textures[0, 0].GetData(0, new Rectangle(0, 0, t.Width, t.Height), c, 0, c.Length);
  609. // t.SetData(c);
  610. // Textures[0, 0] = t;
  611. // Memory.MainThreadOnlyActions.Enqueue(this.Save);
  612. //}
  613. }
  614. private void Reload()
  615. {
  616. if (Rows * Cols == 1)
  617. {
  618. Textures[0, 0].Dispose();
  619. if (PngCache.TryRemove(ModdedFilename, out var value) && !value.IsDisposed)
  620. value.Dispose();
  621. Textures[0, 0] = LoadPNG(ModdedFilename, Palette, _enforceSquare);
  622. }
  623. else
  624. throw new Exception("too many textures reload not setup for >1 texture");
  625. }
  626. #endregion Methods
  627. // To detect redundant calls
  628. // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
  629. // ~TextureHandler() {
  630. // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  631. // Dispose(false);
  632. // }
  633. // TODO: uncomment the following line if the finalizer is overridden above.// GC.SuppressFinalize(this);
  634. }
  635. }