AtlasUtilityWindow.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. namespace AtlasUtility
  2. {
  3. using UnityEditor;
  4. using UnityEngine;
  5. using UnityEditor.SceneManagement;
  6. using System;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Reflection;
  11. using System.Collections.Generic;
  12. using Random = UnityEngine.Random;
  13. public class AtlasUtilityWindow : EditorWindow
  14. {
  15. protected class Box
  16. {
  17. public bool Valid
  18. {
  19. get
  20. {
  21. if (Width > 0 && Height > 0)
  22. {
  23. return true;
  24. }
  25. else
  26. {
  27. return false;
  28. }
  29. }
  30. }
  31. public Vector2 LowerLeft;
  32. public Vector2 UpperLeft
  33. {
  34. get { return LowerLeft + new Vector2(0, Height); }
  35. }
  36. public Vector2 LowerRight
  37. {
  38. get { return LowerLeft + new Vector2(Width, 0); }
  39. }
  40. public Vector2 UpperRight
  41. {
  42. get { return LowerLeft + new Vector2(Width, Height); }
  43. }
  44. public int Width;
  45. public int Height;
  46. public Box(int width, int height, Vector2 lowerLeft)
  47. {
  48. Width = width;
  49. Height = height;
  50. LowerLeft = lowerLeft;
  51. }
  52. public bool CanFill(TextureInfo textureInfo)
  53. {
  54. if (textureInfo.Width <= Width && textureInfo.Height <= Height)
  55. {
  56. return true;
  57. }
  58. else
  59. {
  60. return false;
  61. }
  62. }
  63. }
  64. protected class JagBox
  65. {
  66. public class Pair
  67. {
  68. public int Low;
  69. public int High;
  70. public Pair(int low, int high)
  71. {
  72. Low = low;
  73. High = high;
  74. }
  75. }
  76. public bool Valid
  77. {
  78. get
  79. {
  80. if (BoxList.Count == 0)
  81. {
  82. return false;
  83. }
  84. else
  85. {
  86. return true;
  87. }
  88. }
  89. }
  90. public int Width
  91. {
  92. get { return (int) BoxList.MySum(box => box.Width); }
  93. }
  94. public Vector2 UpperRight;
  95. public List<Box> BoxList;
  96. public Dictionary<Pair, Pair> XCoordDic;
  97. public Dictionary<Pair, Pair> YCoordDic;
  98. public JagBox(List<Box> boxList)
  99. {
  100. BoxList = boxList;
  101. if (boxList.Count == 0)
  102. {
  103. return;
  104. }
  105. UpperRight = boxList.Back(0).UpperRight;
  106. XCoordDic = new Dictionary<Pair, Pair>();
  107. YCoordDic = new Dictionary<Pair, Pair>();
  108. for (int i = 0; i < boxList.Count; i++)
  109. {
  110. Pair xPair = new Pair((int) boxList[i].LowerLeft.x, (int) boxList[i].LowerRight.x);
  111. Pair yPair = new Pair((int) boxList[i].LowerLeft.y, (int) boxList[i].UpperRight.y);
  112. XCoordDic.Add(yPair, xPair);
  113. YCoordDic.Add(xPair, yPair);
  114. }
  115. }
  116. public int GetBoxIndex(int x)
  117. {
  118. x = (int) UpperRight.x - x;
  119. List<Pair> xPairList = YCoordDic.Keys.ToList();
  120. for (int i = xPairList.Count - 1; i >= 0; i--)
  121. {
  122. if (xPairList[i].Low <= x && x <= xPairList[i].High)
  123. {
  124. return i;
  125. }
  126. }
  127. throw new Exception("An error occured");
  128. }
  129. public bool CanFill(TextureInfo textureInfo)
  130. {
  131. if (textureInfo.Width > Width)
  132. {
  133. return false;
  134. }
  135. int boxIndex = GetBoxIndex(textureInfo.Width);
  136. int boxOffset = 0;
  137. reLoop:
  138. Box sliceBox = BoxList[boxIndex + boxOffset];
  139. for (int i = boxIndex + boxOffset; i < BoxList.Count + boxOffset; i++)
  140. {
  141. if (BoxList[i].Height < textureInfo.Height)
  142. {
  143. if (boxIndex + boxOffset > 0)
  144. {
  145. boxOffset--;
  146. goto reLoop;
  147. }
  148. else
  149. {
  150. return false;
  151. }
  152. }
  153. }
  154. textureInfo.SliceBox = sliceBox;
  155. textureInfo.BoxOffset = boxOffset;
  156. return true;
  157. }
  158. public List<Box> VerticalSlice(TextureInfo textureInfo, int fillWidth, int fillHeight)
  159. {
  160. fillWidth = (int) (fillWidth - (BoxList.Back(-textureInfo.BoxOffset).UpperRight.x - textureInfo.SliceBox.UpperRight.x));
  161. int leftBoxWidth = textureInfo.SliceBox.Width - fillWidth;
  162. int leftBoxHeight = textureInfo.SliceBox.Height;
  163. Vector2 leftBoxLowerLeft = textureInfo.SliceBox.LowerLeft;
  164. Box leftBox = new Box(leftBoxWidth, leftBoxHeight, leftBoxLowerLeft);
  165. int downBoxWidth = fillWidth;
  166. int downBoxHeight = textureInfo.SliceBox.Height - fillHeight;
  167. Vector2 downBoxLowerLeft = textureInfo.SliceBox.LowerLeft + new Vector2(textureInfo.SliceBox.Width - fillWidth, 0);
  168. Box downBox = new Box(downBoxWidth, downBoxHeight, downBoxLowerLeft);
  169. return new List<Box>() {leftBox, downBox};
  170. }
  171. public List<Box> HorizontalSlice(TextureInfo textureInfo, int fillWidth, int fillHeight)
  172. {
  173. fillWidth = (int)(fillWidth - (BoxList.Back(-textureInfo.BoxOffset).UpperRight.x - textureInfo.SliceBox.UpperRight.x));
  174. int leftBoxWidth = textureInfo.SliceBox.Width - fillWidth;
  175. int leftBoxHeight = fillHeight;
  176. Vector2 leftBoxLowerLeft = textureInfo.SliceBox.LowerLeft + new Vector2(0, textureInfo.SliceBox.Height - fillHeight);
  177. Box leftBox = new Box(leftBoxWidth, leftBoxHeight, leftBoxLowerLeft);
  178. int downBoxWidth = textureInfo.SliceBox.Width;
  179. int downBoxHeight = textureInfo.SliceBox.Height - fillHeight;
  180. Vector2 downBoxLowerLeft = textureInfo.SliceBox.LowerLeft;
  181. Box downBox = new Box(downBoxWidth, downBoxHeight, downBoxLowerLeft);
  182. return new List<Box>() { leftBox, downBox };
  183. }
  184. public List<JagBox> Fill(TextureInfo textureInfo)
  185. {
  186. textureInfo.LowerLeft = BoxList.Back(-textureInfo.BoxOffset).UpperRight + new Vector2(-textureInfo.Width, -textureInfo.Height);
  187. int fillWidth = textureInfo.Width;
  188. int fillHeight = textureInfo.Height;
  189. bool verticalSlice = fillWidth > fillHeight;
  190. List<Box> childBoxList = verticalSlice ? VerticalSlice(textureInfo, fillWidth, fillHeight) : HorizontalSlice(textureInfo, fillWidth, fillHeight);
  191. List<Box> leftBoxList = new List<Box>();
  192. List<Box> downBoxList = new List<Box>();
  193. for (int i = 0; i < BoxList.IndexOf(textureInfo.SliceBox); i++)
  194. {
  195. leftBoxList.Add(BoxList[i]);
  196. }
  197. if (childBoxList[0].Valid)
  198. {
  199. leftBoxList.Add(childBoxList[0]);
  200. }
  201. if (childBoxList[1].Valid)
  202. {
  203. downBoxList.Add(childBoxList[1]);
  204. }
  205. for (int i = BoxList.IndexOf(textureInfo.SliceBox) + 1; i < BoxList.Count + textureInfo.BoxOffset; i++)
  206. {
  207. downBoxList.Add(new Box(BoxList[i].Width, BoxList[i].Height - fillHeight, BoxList[i].LowerLeft));
  208. }
  209. JagBox leftJagBox = new JagBox(leftBoxList);
  210. JagBox downJagBox = new JagBox(downBoxList);
  211. List<JagBox> jagBoxList = new List<JagBox>();
  212. if (downJagBox.Valid)
  213. {
  214. jagBoxList.Add(downJagBox);
  215. }
  216. if (leftJagBox.Valid)
  217. {
  218. jagBoxList.Add(leftJagBox);
  219. }
  220. return jagBoxList;
  221. }
  222. }
  223. protected class TextureInfo
  224. {
  225. public int Max
  226. {
  227. get
  228. {
  229. if (Width > Height)
  230. {
  231. return Width;
  232. }
  233. else
  234. {
  235. return Height;
  236. }
  237. }
  238. }
  239. public int Area
  240. {
  241. get { return Width*Height; }
  242. }
  243. public string Name
  244. {
  245. get { return Texture.name; }
  246. }
  247. public Rect Rect
  248. {
  249. get { return new Rect(LowerLeft.x + Padding, LowerLeft.y + Padding, Width - 2*Padding, Height - 2*Padding); }
  250. }
  251. public Vector2 LowerLeft;
  252. public Vector2 UpperLeft
  253. {
  254. get { return LowerLeft + new Vector2(0, Height); }
  255. }
  256. public Vector2 LowerRight
  257. {
  258. get { return LowerLeft + new Vector2(Width, 0); }
  259. }
  260. public Vector2 UpperRight
  261. {
  262. get { return LowerLeft + new Vector2(Width, Height); }
  263. }
  264. public Color[] Colors;
  265. public Vector4 Pivot;
  266. public Vector4 Border;
  267. public int BoxOffset;
  268. public Box SliceBox;
  269. public int Width;
  270. public int Height;
  271. public int RawWidth;
  272. public int RawHeight;
  273. public int Padding;
  274. public string GUID;
  275. public Texture2D Texture;
  276. public TextureInfo(int padding, Texture2D texture2D, int width, int height)
  277. {
  278. Width = width + padding*2;
  279. Height = height + padding*2;
  280. Padding = padding;
  281. Texture = texture2D;
  282. }
  283. public TextureInfo(int padding, Texture2D texture2D)
  284. {
  285. Initialize(padding, texture2D);
  286. }
  287. public void Initialize(int padding, Texture2D texture2D)
  288. {
  289. Texture = texture2D;
  290. string assetPath = AssetDatabase.GetAssetPath(texture2D);
  291. TextureImporter textureImporter = (TextureImporter)AssetImporter.GetAtPath(assetPath);
  292. Pivot = textureImporter.spritePivot;
  293. Border = textureImporter.spriteBorder;
  294. GUID = AssetDatabase.AssetPathToGUID(assetPath);
  295. RawWidth = Texture.width;
  296. RawHeight = Texture.height;
  297. object[] args = new object[2];
  298. MethodInfo methodInfo = typeof(TextureImporter).GetMethod("GetWidthAndHeight", BindingFlags.NonPublic | BindingFlags.Instance);
  299. methodInfo.Invoke(textureImporter, args);
  300. int originWidth = (int)args[0];
  301. int originHeight = (int)args[1];
  302. if (RawWidth < originWidth || RawHeight < originHeight)
  303. {
  304. Debug.LogWarning($"Note {texture2D.name} was scaled down");
  305. }
  306. if (!textureImporter.isReadable)
  307. {
  308. textureImporter.isReadable = true;
  309. textureImporter.SaveAndReimport();
  310. }
  311. Colors = texture2D.GetPixels(0, 0, RawWidth, RawHeight);
  312. Width = RawWidth + padding * 2;
  313. Height = RawHeight + padding * 2;
  314. Padding = padding;
  315. }
  316. public static float max(TextureInfo textureInfo)
  317. {
  318. return textureInfo.Max;
  319. }
  320. public static bool SortByMax(TextureInfo a, TextureInfo b)
  321. {
  322. if (a.Max < b.Max)
  323. {
  324. return true;
  325. }
  326. else
  327. {
  328. return false;
  329. }
  330. }
  331. public static bool SortByWidth(TextureInfo a, TextureInfo b)
  332. {
  333. if (a.Width < b.Width)
  334. {
  335. return true;
  336. }
  337. else
  338. {
  339. return false;
  340. }
  341. }
  342. }
  343. protected class Parameter
  344. {
  345. public int Padding;
  346. public int TextureSize;
  347. public string Path;
  348. public PackPlan PackPlan;
  349. public Texture2D SpriteSheet;
  350. public List<Texture2D> TextureList;
  351. public List<AtlasUtility.VirtualTexture> VirtualTextureList;
  352. }
  353. protected class Atlas
  354. {
  355. public int Width;
  356. public int Height;
  357. public List<TextureInfo> TextureInfoList;
  358. public void Create(int index, Parameter parameter)
  359. {
  360. SpriteMetaData[] spriteMetaDatas = new SpriteMetaData[TextureInfoList.Count];
  361. Color[] atlasColors = new Color[Width * Height];
  362. for (int i = 0; i < Height; i++)
  363. {
  364. for (int j = 0; j < Width; j++)
  365. {
  366. atlasColors[i * Width + j] = new Color(0, 0, 0, 0);
  367. }
  368. }
  369. for (int i = 0; i < TextureInfoList.Count; i++)
  370. {
  371. TextureInfo textureInfo = TextureInfoList[i];
  372. Vector2 lowerLeft = textureInfo.LowerLeft + new Vector2(parameter.Padding, parameter.Padding);
  373. int width;
  374. int height;
  375. spriteMetaDatas[i].rect = textureInfo.Rect;
  376. spriteMetaDatas[i].pivot = textureInfo.Pivot;
  377. spriteMetaDatas[i].name = textureInfo.Name;
  378. spriteMetaDatas[i].border = textureInfo.Border;
  379. spriteMetaDatas[i].alignment = (int)SpriteAlignment.Custom;
  380. width = textureInfo.Width - parameter.Padding * 2;
  381. height = textureInfo.Height - parameter.Padding * 2;
  382. for (int j = 0; j < height; j++)
  383. {
  384. for (int k = 0; k < width; k++)
  385. {
  386. int row = (int)lowerLeft.y + j;
  387. int column = (int)lowerLeft.x + k;
  388. atlasColors[row * Width + column] = textureInfo.Colors[j * width + k];
  389. }
  390. }
  391. }
  392. string path;
  393. if (index == 0)
  394. {
  395. path = parameter.Path + ".png";
  396. }
  397. else
  398. {
  399. path = $"{parameter.Path} ({index}).png";
  400. }
  401. if (File.Exists(path))
  402. {
  403. AssetDatabase.DeleteAsset(path);
  404. AssetDatabase.Refresh();
  405. }
  406. Texture2D texture2D = new Texture2D(Width, Height, TextureFormat.RGBA32, false);
  407. texture2D.SetPixels(0, 0, Width, Height, atlasColors);
  408. texture2D.Apply();
  409. File.WriteAllBytes(path, texture2D.EncodeToPNG());
  410. AssetDatabase.ImportAsset(path);
  411. TextureImporter textureImporter = (TextureImporter)AssetImporter.GetAtPath(path);
  412. textureImporter.spritesheet = spriteMetaDatas;
  413. textureImporter.maxTextureSize = Mathf.Max(Width, Height);
  414. textureImporter.isReadable = true;
  415. textureImporter.alphaIsTransparency = true;
  416. textureImporter.textureType = TextureImporterType.Sprite;
  417. textureImporter.spriteImportMode = SpriteImportMode.Multiple;
  418. textureImporter.SaveAndReimport();
  419. string atlasGUID = AssetDatabase.AssetPathToGUID(path);
  420. List<string> newAtlasReferenceList = new List<string>();
  421. List<string> newSourceReferenceList = new List<string>();
  422. for (int i = 0; i < spriteMetaDatas.Length; i++)
  423. {
  424. newAtlasReferenceList.Add($"fileID: {21300000 + i * 2}, guid: {atlasGUID}");
  425. newSourceReferenceList.Add($"fileID: {21300000}, guid: {TextureInfoList[i].GUID}");
  426. }
  427. List<string> fromReferenceList = new List<string>();
  428. List<string> toReferenceList = new List<string>();
  429. List<string> itemList = ReferenceTable.ReadAllLine();
  430. for (int i = 0; i < itemList.Count; i++)
  431. {
  432. itemList[i] = itemList[i].TrimEnd((char)13);
  433. string atlasReference = itemList[i].Split('|')[0];
  434. string sourceReference = itemList[i].Split('|')[1];
  435. for (int j = 0; j < newSourceReferenceList.Count; j++)
  436. {
  437. if (newSourceReferenceList[j] == sourceReference)
  438. {
  439. fromReferenceList.Add(atlasReference);
  440. toReferenceList.Add(newAtlasReferenceList[j]);
  441. }
  442. }
  443. }
  444. for (int i = 0; i < newSourceReferenceList.Count; i++)
  445. {
  446. fromReferenceList.Add(newSourceReferenceList[i]);
  447. toReferenceList.Add(newAtlasReferenceList[i]);
  448. }
  449. List<string> newItemList = new List<string>();
  450. for (int i = 0; i < itemList.Count; i++)
  451. {
  452. newItemList.Add(itemList[i]);
  453. }
  454. for (int i = 0; i < newAtlasReferenceList.Count; i++)
  455. {
  456. newItemList.Add($"{newAtlasReferenceList[i]}|{newSourceReferenceList[i]}");
  457. }
  458. ReferenceTable.WriteAllLine(newItemList);
  459. }
  460. }
  461. #region Variable
  462. protected Vector2 ScrollPosition;
  463. protected GUIStyle TitleGuiStyle;
  464. protected int AntiCrush;
  465. protected AtlasUtility Script;
  466. protected SerializedObject SerializedObject;
  467. protected SerializedProperty PackSize;
  468. protected SerializedProperty PackPath;
  469. protected SerializedProperty PackName;
  470. protected SerializedProperty PackPadding;
  471. protected SerializedProperty SlicePath;
  472. protected SerializedProperty SlicePadding;
  473. protected SerializedProperty atlas;
  474. protected SerializedProperty TextureList;
  475. protected SerializedProperty SpriteSheet;
  476. protected SerializedProperty VirtualTextureList;
  477. protected SerializedProperty PackPlan;
  478. #endregion
  479. public void OnEnable()
  480. {
  481. Script = SerializeObject.GetAtlasUtility();
  482. SerializedObject = new SerializedObject(Script);
  483. PackSize = SerializedObject.FindProperty("PackSize");
  484. PackPath = SerializedObject.FindProperty("PackPath");
  485. PackName = SerializedObject.FindProperty("PackName");
  486. SlicePath = SerializedObject.FindProperty("SlicePath");
  487. SlicePadding = SerializedObject.FindProperty("SlicePadding");
  488. atlas = SerializedObject.FindProperty("Atlas");
  489. TextureList = SerializedObject.FindProperty("TextureList");
  490. SpriteSheet = SerializedObject.FindProperty("SpriteSheet");
  491. PackPadding = SerializedObject.FindProperty("PackPadding");
  492. VirtualTextureList = SerializedObject.FindProperty("VirtualTextureList");
  493. PackPlan = SerializedObject.FindProperty("PackPlan");
  494. TitleGuiStyle = new GUIStyle();
  495. TitleGuiStyle.fontSize = 20;
  496. TitleGuiStyle.alignment = TextAnchor.MiddleCenter;
  497. TitleGuiStyle.normal.textColor = new Color(0.75f, 0.75f, 0.75f, 1);
  498. }
  499. [MenuItem("DashGame/AtlasUtility")]
  500. public static void ShowWindow()
  501. {
  502. Type inspectorType = Type.GetType("UnityEditor.InspectorWindow,UnityEditor.dll");
  503. AtlasUtilityWindow window = GetWindow<AtlasUtilityWindow>(inspectorType);
  504. window.titleContent = new GUIContent("AtlasUtility");
  505. window.Show();
  506. }
  507. protected void Pack()
  508. {
  509. Parameter parameter = CreatePackParameter();
  510. List<TextureInfo> textureInfoList = GetTextureInfoList(parameter);
  511. if (textureInfoList.Count == 0)
  512. {
  513. throw new Exception("TextureList is empty");
  514. }
  515. EditorUtility.DisplayProgressBar("Packing", "Calculate layout", 0.5f);
  516. List<Atlas> atlasList = new List<Atlas>();
  517. while (true)
  518. {
  519. Box box = CreateBox(parameter, textureInfoList);
  520. textureInfoList = FillBox(box, parameter, textureInfoList, atlasList);
  521. if (textureInfoList.Count == 0)
  522. {
  523. break;
  524. }
  525. }
  526. if (EditorUtility.DisplayDialog("AtlasUtility", $"{atlasList.Count} atlas will be created", "Go ahead", "Cancel"))
  527. {
  528. for (int i = 0; i < atlasList.Count; i++)
  529. {
  530. EditorUtility.DisplayProgressBar("Packing", "Create atlas", (i + 1)/(float) atlasList.Count);
  531. atlasList[i].Create(i, parameter);
  532. }
  533. }
  534. EndPack();
  535. }
  536. protected void EndPack()
  537. {
  538. EditorUtility.ClearProgressBar();
  539. }
  540. protected Parameter CreatePackParameter()
  541. {
  542. string directory = Script.PackPath.TrimEnd('/', '\\') + "/";
  543. if (directory.Length < 6 || directory.Substring(0, 6).ToLower() != "assets")
  544. {
  545. throw new Exception("PackPath must be inside the Assets folder");
  546. }
  547. if (!Directory.Exists(directory))
  548. {
  549. throw new Exception("directory doesn't exist");
  550. }
  551. if (string.IsNullOrEmpty(Script.PackName) || Script.PackName.Any(Path.GetInvalidFileNameChars().Contains))
  552. {
  553. throw new Exception("PackName is invalid");
  554. }
  555. if (Script.PackPadding < 0)
  556. {
  557. Script.PackPadding = 0;
  558. }
  559. if (Script.PackPlan == global::AtlasUtility.PackPlan.Fixed)
  560. {
  561. if (Script.PackSize <= 2)
  562. {
  563. throw new Exception("Size of atlas must be equal or greater than 2");
  564. }
  565. if (!Mathf.IsPowerOfTwo(Script.PackSize))
  566. {
  567. throw new Exception("Size of atlas must be power of 2");
  568. }
  569. }
  570. else if (Script.PackPlan == global::AtlasUtility.PackPlan.Smallest)
  571. {
  572. if (Script.PackSize <= 0)
  573. {
  574. Script.PackSize = 8192;
  575. }
  576. else
  577. {
  578. Script.PackSize = ExMath.PrevPOT(Script.PackSize);
  579. }
  580. }
  581. Parameter parameter = new Parameter
  582. {
  583. Path = directory + Script.PackName,
  584. PackPlan = Script.PackPlan,
  585. Padding = Script.PackPadding,
  586. TextureSize = Script.PackSize,
  587. TextureList = Script.TextureList,
  588. VirtualTextureList = Script.VirtualTextureList
  589. };
  590. return parameter;
  591. }
  592. protected List<TextureInfo> GetTextureInfoList(Parameter parameter)
  593. {
  594. List<TextureInfo> textureInfoList = new List<TextureInfo>();
  595. for (int i = 0; i < parameter.TextureList.Count; i++)
  596. {
  597. if (parameter.TextureList[i] != null)
  598. {
  599. EditorUtility.DisplayProgressBar("Packing", "Read textures", (i + 1)/(float) parameter.TextureList.Count);
  600. textureInfoList.Add(new TextureInfo(parameter.Padding, parameter.TextureList[i]));
  601. }
  602. }
  603. for (int i = 0; i < parameter.VirtualTextureList.Count; i++)
  604. {
  605. Texture2D texture = new Texture2D(parameter.VirtualTextureList[i].Width, parameter.VirtualTextureList[i].Height);
  606. texture.name = parameter.VirtualTextureList[i].Name;
  607. Color randomColor = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), 1);
  608. for (int j = 0; j < parameter.VirtualTextureList[i].Width; j++)
  609. {
  610. for (int k = 0; k < parameter.VirtualTextureList[i].Height; k++)
  611. {
  612. texture.SetPixel(j, k, randomColor);
  613. }
  614. }
  615. texture.Apply();
  616. textureInfoList.Add(new TextureInfo(parameter.Padding, texture, parameter.VirtualTextureList[i].Width, parameter.VirtualTextureList[i].Height));
  617. }
  618. EditorUtility.ClearProgressBar();
  619. return textureInfoList;
  620. }
  621. protected Box CreateBox(Parameter parameter, List<TextureInfo> textureInfoList)
  622. {
  623. int maxTextureLength = (int) textureInfoList.MyMax(TextureInfo.max);
  624. if (maxTextureLength > parameter.TextureSize)
  625. {
  626. EndPack();
  627. throw new Exception("A texture's width or height is bigger than Size/MaxSize");
  628. }
  629. if (parameter.PackPlan == global::AtlasUtility.PackPlan.Fixed)
  630. {
  631. return new Box(parameter.TextureSize, parameter.TextureSize, new Vector2(0, 0));
  632. }
  633. else if (parameter.PackPlan == global::AtlasUtility.PackPlan.Smallest)
  634. {
  635. int totalArea = textureInfoList.Sum(debris => debris.Area);
  636. int length = ExMath.NextPOT(Mathf.Sqrt(totalArea));
  637. length = Mathf.Min(length, parameter.TextureSize);
  638. length = Mathf.Max(length, maxTextureLength);
  639. if (length* length/2f >= totalArea)
  640. {
  641. return new Box(length, length/2, new Vector2(0, 0));
  642. }
  643. else
  644. {
  645. return new Box(length, length, new Vector2(0, 0));
  646. }
  647. }
  648. else
  649. {
  650. throw new Exception();
  651. }
  652. }
  653. protected List<JagBox> CreateJagBox(List<Box> emptyBoxList)
  654. {
  655. List<JagBox> jagBoxList = new List<JagBox>();
  656. if (emptyBoxList.Count == 0)
  657. {
  658. return jagBoxList;
  659. }
  660. List<Box> boxList = new List<Box>() { emptyBoxList[0] };
  661. for (int i = 0; i < emptyBoxList.Count - 1; i++)
  662. {
  663. int x1 = (int)emptyBoxList[i].LowerRight.x;
  664. int x2 = (int)emptyBoxList[i + 1].LowerLeft.x;
  665. if (x1 == x2)
  666. {
  667. boxList.Add(emptyBoxList[i + 1]);
  668. }
  669. else
  670. {
  671. jagBoxList.Add(new JagBox(boxList));
  672. boxList = new List<Box>();
  673. boxList.Add(emptyBoxList[i + 1]);
  674. }
  675. }
  676. jagBoxList.Add(new JagBox(boxList));
  677. return jagBoxList;
  678. }
  679. protected List<TextureInfo> FillBox(Box box, Parameter parameter, List<TextureInfo> textureInfoList, List<Atlas> atlasList)
  680. {
  681. textureInfoList.MySort(TextureInfo.SortByWidth);
  682. while (true)
  683. {
  684. List<Box> emptyBoxList = new List<Box>();
  685. List<TextureInfo> atlasTextureInfoList = new List<TextureInfo>();
  686. List<TextureInfo> remainTexureInfoList = new List<TextureInfo>(textureInfoList);
  687. FillChildBox(box, remainTexureInfoList, atlasTextureInfoList, emptyBoxList);
  688. List<JagBox> jagBoxList = CreateJagBox(emptyBoxList);
  689. remainTexureInfoList.MySort(TextureInfo.SortByMax);
  690. FillJagBox(remainTexureInfoList, atlasTextureInfoList, jagBoxList);
  691. if (remainTexureInfoList.Count == 0)
  692. {
  693. atlasList.Add(CreateAtlas(box, atlasTextureInfoList));
  694. return remainTexureInfoList;
  695. }
  696. else
  697. {
  698. if (box.Width > box.Height)
  699. {
  700. box = new Box(box.Height, box.Width, Vector2.zero);
  701. }
  702. else if (box.Height > box.Width)
  703. {
  704. box = new Box(box.Height, box.Height, Vector2.zero);
  705. }
  706. else if (box.Width == box.Height)
  707. {
  708. int newLength = ExMath.NextPOT(box.Width + 1);
  709. if (newLength > parameter.TextureSize)
  710. {
  711. atlasList.Add(CreateAtlas(box, atlasTextureInfoList));
  712. return remainTexureInfoList;
  713. }
  714. else
  715. {
  716. box = new Box(newLength, newLength/2, Vector2.zero);
  717. }
  718. }
  719. }
  720. }
  721. }
  722. protected void FillChildBox(Box box, List<TextureInfo> remainTextureInfoList, List<TextureInfo> atlasTextureInfoList, List<Box> emptyBoxList)
  723. {
  724. if (box.Valid)
  725. {
  726. for (int i = 0; i < remainTextureInfoList.Count; i++)
  727. {
  728. if (box.CanFill(remainTextureInfoList[i]))
  729. {
  730. TextureInfo textureInfo = remainTextureInfoList[i];
  731. remainTextureInfoList.Remove(textureInfo);
  732. textureInfo.LowerLeft = box.LowerLeft;
  733. atlasTextureInfoList.Add(textureInfo);
  734. Vector2 lowerLeftUp = box.LowerLeft + new Vector2(0, textureInfo.Height);
  735. Vector2 lowerLeftRight = box.LowerLeft + new Vector2(textureInfo.Width, 0);
  736. Box upChildBox = new Box(textureInfo.Width, box.Height - textureInfo.Height, lowerLeftUp);
  737. Box rightChildBox = new Box(box.Width - textureInfo.Width, box.Height, lowerLeftRight);
  738. FillChildBox(upChildBox, remainTextureInfoList, atlasTextureInfoList, emptyBoxList);
  739. FillChildBox(rightChildBox, remainTextureInfoList, atlasTextureInfoList, emptyBoxList);
  740. return;
  741. }
  742. }
  743. emptyBoxList.Add(box);
  744. }
  745. }
  746. protected void FillJagBox(List<TextureInfo> remainTextureInfoList, List<TextureInfo> atlasTextureInfoList, List<JagBox> jagBoxList)
  747. {
  748. for (int i = 0; i < jagBoxList.Count; i++)
  749. {
  750. for (int j = 0; j < remainTextureInfoList.Count; j++)
  751. {
  752. if (jagBoxList[i].CanFill(remainTextureInfoList[j]))
  753. {
  754. jagBoxList.AddRange(jagBoxList[i].Fill(remainTextureInfoList[j]));
  755. atlasTextureInfoList.Add(remainTextureInfoList[j]);
  756. remainTextureInfoList.Remove(remainTextureInfoList[j]);
  757. break;
  758. }
  759. }
  760. }
  761. }
  762. protected Atlas CreateAtlas(Box box, List<TextureInfo> textureInfoList)
  763. {
  764. Atlas atlas = new Atlas
  765. {
  766. Width = box.Width,
  767. Height = box.Height,
  768. TextureInfoList = textureInfoList,
  769. };
  770. return atlas;
  771. }
  772. protected void CollectDebugInfo()
  773. {
  774. Parameter parameter = CreateDebugParameter();
  775. List<TextureInfo> debrisList = GetTextureInfoList(parameter);
  776. StringBuilder stringBuilder = new StringBuilder();
  777. for (int i = 0; i < debrisList.Count; i++)
  778. {
  779. stringBuilder.AppendLine($"Width:{debrisList[i].Width} Height:{debrisList[i].Height} Pivot:{debrisList[i].Pivot} Border:{debrisList[i].Border}");
  780. }
  781. if (string.IsNullOrEmpty(stringBuilder.ToString()))
  782. {
  783. throw new Exception("TextureList is empty");
  784. }
  785. else
  786. {
  787. StreamWriter streamWriter = new StreamWriter(parameter.Path);
  788. streamWriter.WriteLine(Application.unityVersion);
  789. streamWriter.Write(stringBuilder.ToString());
  790. streamWriter.Close();
  791. AssetDatabase.ImportAsset(parameter.Path);
  792. }
  793. }
  794. protected Parameter CreateDebugParameter()
  795. {
  796. string directory = Script.PackPath.TrimEnd('/', '\\') + "/";
  797. if (directory.Length < 6 || directory.Substring(0, 6).ToLower() != "assets")
  798. {
  799. throw new Exception("PackPath must be inside the Assets folder");
  800. }
  801. if (!Directory.Exists(directory))
  802. {
  803. throw new Exception("directory doesn't exist");
  804. }
  805. Parameter parameter = new Parameter
  806. {
  807. Path = directory + "DebugInfo_" + Script.PackName + ".txt",
  808. TextureList = Script.TextureList,
  809. VirtualTextureList = Script.VirtualTextureList
  810. };
  811. return parameter;
  812. }
  813. protected void Slice()
  814. {
  815. Parameter parameter = CreateSliceParameter();
  816. string spriteSheetPath = AssetDatabase.GetAssetPath(parameter.SpriteSheet);
  817. TextureImporter textureImporter = (TextureImporter)AssetImporter.GetAtPath(spriteSheetPath);
  818. if (textureImporter.spritesheet.Length == 0)
  819. {
  820. throw new Exception("There is no child sprite");
  821. }
  822. if (!textureImporter.isReadable)
  823. {
  824. textureImporter.isReadable = true;
  825. textureImporter.SaveAndReimport();
  826. }
  827. for (int k = 0; k < textureImporter.spritesheet.Length; k++)
  828. {
  829. SpriteMetaData metaData = textureImporter.spritesheet[k];
  830. EditorUtility.DisplayProgressBar("Slicing", $"Create {metaData.name}", (k + 1)/(float) textureImporter.spritesheet.Length);
  831. int width = (int)metaData.rect.width + 2 * parameter.Padding;
  832. int height = (int)metaData.rect.height + 2 * parameter.Padding;
  833. Texture2D texture2D = new Texture2D(width, height, TextureFormat.RGBA32, false);
  834. Color[] atlasColors = parameter.SpriteSheet.GetPixels((int)metaData.rect.x, (int)metaData.rect.y, (int)metaData.rect.width, (int)metaData.rect.height);
  835. Color[] textureColors = new Color[width * height];
  836. for (int i = 0; i < height; i++)
  837. {
  838. for (int j = 0; j < width; j++)
  839. {
  840. if (i < parameter.Padding || j < parameter.Padding || i >= height - parameter.Padding || j >= width - parameter.Padding)
  841. {
  842. textureColors[i * width + j] = new Color(0, 0, 0, 0);
  843. }
  844. else
  845. {
  846. int x = i - parameter.Padding;
  847. int y = j - parameter.Padding;
  848. textureColors[i * width + j] = atlasColors[x * (int)metaData.rect.width + y];
  849. }
  850. }
  851. }
  852. texture2D.SetPixels(textureColors);
  853. texture2D.Apply();
  854. string spritePath = (parameter.Path + metaData.name + ".png").GetUnRepeatFileName();
  855. File.WriteAllBytes(spritePath, texture2D.EncodeToPNG());
  856. AssetDatabase.ImportAsset(spritePath);
  857. TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(spritePath);
  858. TextureImporterSettings importerSetting = new TextureImporterSettings();
  859. importer.ReadTextureSettings(importerSetting);
  860. importerSetting.textureType = TextureImporterType.Sprite;
  861. importerSetting.spritePivot = metaData.pivot;
  862. importerSetting.spriteBorder = metaData.border;
  863. importerSetting.spriteAlignment = metaData.alignment;
  864. importerSetting.alphaIsTransparency = true;
  865. importer.SetTextureSettings(importerSetting);
  866. importer.isReadable = true;
  867. importer.name = metaData.name;
  868. importer.spriteImportMode = SpriteImportMode.Single;
  869. importer.maxTextureSize = ExMath.NextPOT(Mathf.Max(width, height));
  870. importer.SaveAndReimport();
  871. }
  872. EditorUtility.ClearProgressBar();
  873. }
  874. protected Parameter CreateSliceParameter()
  875. {
  876. string directory = Script.SlicePath.TrimEnd('/', '\\') + "/";
  877. if (!Directory.Exists(directory))
  878. {
  879. throw new Exception("directory doesn't exist");
  880. }
  881. if (Script.SlicePadding < 0)
  882. {
  883. Script.SlicePadding = 0;
  884. }
  885. if (Script.SpriteSheet == null)
  886. {
  887. throw new Exception("SpriteSheet is null");
  888. }
  889. Parameter parameter = new Parameter
  890. {
  891. Path = directory,
  892. Padding = Script.SlicePadding,
  893. SpriteSheet = Script.SpriteSheet
  894. };
  895. return parameter;
  896. }
  897. protected void GetSelectedPath()
  898. {
  899. if (Selection.assetGUIDs.Length > 0)
  900. {
  901. string path = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);
  902. path = Path.GetDirectoryName(path);
  903. if (string.IsNullOrEmpty(path))
  904. {
  905. Script.PackPath = "Assets";
  906. }
  907. else
  908. {
  909. Script.PackPath = path;
  910. }
  911. }
  912. }
  913. public void OnGUI()
  914. {
  915. SerializedObject.Update();
  916. ScrollPosition = EditorGUILayout.BeginScrollView(ScrollPosition);
  917. EditorGUILayout.LabelField("AtlasUtility", TitleGuiStyle, GUILayout.Height(30));
  918. EditorGUILayout.BeginHorizontal();
  919. EditorGUILayout.PropertyField(PackPath);
  920. if (GUILayout.Button("GetSelectedPath"))
  921. {
  922. GetSelectedPath();
  923. }
  924. EditorGUILayout.EndHorizontal();
  925. EditorGUILayout.PropertyField(PackName);
  926. EditorGUILayout.PropertyField(PackPlan, new GUIContent("Pack Plan"));
  927. if (Script.PackPlan == global::AtlasUtility.PackPlan.Fixed)
  928. {
  929. EditorGUILayout.PropertyField(PackSize, new GUIContent("Size"));
  930. }
  931. else if (Script.PackPlan == global::AtlasUtility.PackPlan.Smallest)
  932. {
  933. EditorGUILayout.PropertyField(PackSize, new GUIContent("Max Size"));
  934. }
  935. EditorGUILayout.Separator();
  936. EditorGUILayout.PropertyField(atlas);
  937. if (Script.Atlas != null)
  938. {
  939. List<string> childPathList = ReferenceManager.GetChildPathList(AssetDatabase.GetAssetPath(Script.Atlas));
  940. for (int i = 0; i < childPathList.Count; i++)
  941. {
  942. Script.TextureList.Add(AssetDatabase.LoadAssetAtPath<Texture2D>(childPathList[i]));
  943. }
  944. Script.Atlas = null;
  945. }
  946. EditorGUILayout.PropertyField(PackPadding, new GUIContent("Padding"));
  947. EditorGUILayout.PropertyField(TextureList, true);
  948. if (GUILayout.Button("Pack", GUILayout.Height(30)))
  949. {
  950. Pack();
  951. }
  952. EditorGUILayout.Separator();
  953. EditorGUILayout.Separator();
  954. EditorGUILayout.PropertyField(SlicePadding, new GUIContent("Padding"));
  955. EditorGUILayout.PropertyField(SlicePath);
  956. EditorGUILayout.PropertyField(SpriteSheet);
  957. if (GUILayout.Button("Slice", GUILayout.Height(30)))
  958. {
  959. Slice();
  960. }
  961. EditorGUILayout.Separator();
  962. EditorGUILayout.Separator();
  963. if (GUILayout.Button("ChangeReference", GUILayout.Height(30)))
  964. {
  965. ReferenceManager.ChangeAllReference();
  966. }
  967. EditorGUILayout.Separator();
  968. EditorGUILayout.Separator();
  969. if (GUILayout.Button("ResetAllReference", GUILayout.Height(30)))
  970. {
  971. ReferenceManager.ResetAllReference();
  972. }
  973. EditorGUILayout.Separator();
  974. if (GUILayout.Button("CollectDebugInfo", GUILayout.Height(30)))
  975. {
  976. CollectDebugInfo();
  977. }
  978. EditorGUILayout.EndScrollView();
  979. SerializedObject.ApplyModifiedProperties();
  980. }
  981. }
  982. }