AtlasUtilityWindow.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  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 string AssetBundleName;
  358. public string AssetBundleVariant;
  359. public List<TextureInfo> TextureInfoList;
  360. public void Create(int index, Parameter parameter)
  361. {
  362. SpriteMetaData[] spriteMetaDatas = new SpriteMetaData[TextureInfoList.Count];
  363. Color[] atlasColors = new Color[Width * Height];
  364. for (int i = 0; i < Height; i++)
  365. {
  366. for (int j = 0; j < Width; j++)
  367. {
  368. atlasColors[i * Width + j] = new Color(0, 0, 0, 0);
  369. }
  370. }
  371. for (int i = 0; i < TextureInfoList.Count; i++)
  372. {
  373. TextureInfo textureInfo = TextureInfoList[i];
  374. Vector2 lowerLeft = textureInfo.LowerLeft + new Vector2(parameter.Padding, parameter.Padding);
  375. int width;
  376. int height;
  377. spriteMetaDatas[i].rect = textureInfo.Rect;
  378. spriteMetaDatas[i].pivot = textureInfo.Pivot;
  379. spriteMetaDatas[i].name = textureInfo.Name;
  380. spriteMetaDatas[i].border = textureInfo.Border;
  381. spriteMetaDatas[i].alignment = (int)SpriteAlignment.Custom;
  382. width = textureInfo.Width - parameter.Padding * 2;
  383. height = textureInfo.Height - parameter.Padding * 2;
  384. for (int j = 0; j < height; j++)
  385. {
  386. for (int k = 0; k < width; k++)
  387. {
  388. int row = (int)lowerLeft.y + j;
  389. int column = (int)lowerLeft.x + k;
  390. atlasColors[row * Width + column] = textureInfo.Colors[j * width + k];
  391. }
  392. }
  393. }
  394. string path;
  395. if (index == 0)
  396. {
  397. path = parameter.Path + ".png";
  398. }
  399. else
  400. {
  401. path = $"{parameter.Path} ({index}).png";
  402. }
  403. if (File.Exists(path))
  404. {
  405. TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(path);
  406. AssetBundleName = importer.assetBundleName;
  407. AssetBundleVariant = importer.assetBundleVariant;
  408. AssetDatabase.DeleteAsset(path);
  409. AssetDatabase.Refresh();
  410. }
  411. Texture2D texture2D = new Texture2D(Width, Height, TextureFormat.RGBA32, false);
  412. texture2D.SetPixels(0, 0, Width, Height, atlasColors);
  413. texture2D.Apply();
  414. File.WriteAllBytes(path, texture2D.EncodeToPNG());
  415. AssetDatabase.ImportAsset(path);
  416. TextureImporter textureImporter = (TextureImporter)AssetImporter.GetAtPath(path);
  417. if (!string.IsNullOrEmpty(AssetBundleName))
  418. {
  419. textureImporter.assetBundleName = AssetBundleName;
  420. }
  421. if (!string.IsNullOrEmpty(AssetBundleVariant))
  422. {
  423. textureImporter.assetBundleVariant = AssetBundleVariant;
  424. }
  425. textureImporter.spritesheet = spriteMetaDatas;
  426. textureImporter.maxTextureSize = Mathf.Max(Width, Height);
  427. textureImporter.isReadable = true;
  428. textureImporter.alphaIsTransparency = true;
  429. textureImporter.textureType = TextureImporterType.Sprite;
  430. textureImporter.spriteImportMode = SpriteImportMode.Multiple;
  431. textureImporter.SaveAndReimport();
  432. string atlasGUID = AssetDatabase.AssetPathToGUID(path);
  433. List<string> newAtlasReferenceList = new List<string>();
  434. List<string> newSourceReferenceList = new List<string>();
  435. for (int i = 0; i < spriteMetaDatas.Length; i++)
  436. {
  437. newAtlasReferenceList.Add($"fileID: {21300000 + i * 2}, guid: {atlasGUID}");
  438. newSourceReferenceList.Add($"fileID: {21300000}, guid: {TextureInfoList[i].GUID}");
  439. }
  440. List<string> fromReferenceList = new List<string>();
  441. List<string> toReferenceList = new List<string>();
  442. List<string> itemList = ReferenceTable.ReadAllLine();
  443. for (int i = 0; i < itemList.Count; i++)
  444. {
  445. itemList[i] = itemList[i].TrimEnd((char)13);
  446. string atlasReference = itemList[i].Split('|')[0];
  447. string sourceReference = itemList[i].Split('|')[1];
  448. for (int j = 0; j < newSourceReferenceList.Count; j++)
  449. {
  450. if (newSourceReferenceList[j] == sourceReference)
  451. {
  452. fromReferenceList.Add(atlasReference);
  453. toReferenceList.Add(newAtlasReferenceList[j]);
  454. }
  455. }
  456. }
  457. for (int i = 0; i < newSourceReferenceList.Count; i++)
  458. {
  459. fromReferenceList.Add(newSourceReferenceList[i]);
  460. toReferenceList.Add(newAtlasReferenceList[i]);
  461. }
  462. List<string> newItemList = new List<string>();
  463. for (int i = 0; i < itemList.Count; i++)
  464. {
  465. newItemList.Add(itemList[i]);
  466. }
  467. for (int i = 0; i < newAtlasReferenceList.Count; i++)
  468. {
  469. newItemList.Add($"{newAtlasReferenceList[i]}|{newSourceReferenceList[i]}");
  470. }
  471. ReferenceTable.WriteAllLine(newItemList);
  472. }
  473. }
  474. #region Variable
  475. protected Vector2 ScrollPosition;
  476. protected GUIStyle TitleGuiStyle;
  477. protected int AntiCrush;
  478. protected AtlasUtility Script;
  479. protected SerializedObject SerializedObject;
  480. protected SerializedProperty PackSize;
  481. protected SerializedProperty PackPath;
  482. protected SerializedProperty PackName;
  483. protected SerializedProperty PackPadding;
  484. protected SerializedProperty SlicePath;
  485. protected SerializedProperty SlicePadding;
  486. protected SerializedProperty atlas;
  487. protected SerializedProperty Target;
  488. protected SerializedProperty TextureList;
  489. protected SerializedProperty SpriteSheet;
  490. protected SerializedProperty VirtualTextureList;
  491. protected SerializedProperty PackPlan;
  492. #endregion
  493. public void OnEnable()
  494. {
  495. Script = GetAtlasUtility();
  496. SerializedObject = new SerializedObject(Script);
  497. PackSize = SerializedObject.FindProperty("PackSize");
  498. PackPath = SerializedObject.FindProperty("PackPath");
  499. PackName = SerializedObject.FindProperty("PackName");
  500. SlicePath = SerializedObject.FindProperty("SlicePath");
  501. SlicePadding = SerializedObject.FindProperty("SlicePadding");
  502. atlas = SerializedObject.FindProperty("Atlas");
  503. Target = SerializedObject.FindProperty("Target");
  504. TextureList = SerializedObject.FindProperty("TextureList");
  505. SpriteSheet = SerializedObject.FindProperty("SpriteSheet");
  506. PackPadding = SerializedObject.FindProperty("PackPadding");
  507. VirtualTextureList = SerializedObject.FindProperty("VirtualTextureList");
  508. PackPlan = SerializedObject.FindProperty("PackPlan");
  509. TitleGuiStyle = new GUIStyle();
  510. TitleGuiStyle.fontSize = 20;
  511. TitleGuiStyle.alignment = TextAnchor.MiddleCenter;
  512. TitleGuiStyle.normal.textColor = new Color(0.75f, 0.75f, 0.75f, 1);
  513. }
  514. [MenuItem("DashGame/AtlasUtility")]
  515. public static void ShowWindow()
  516. {
  517. Type inspectorType = Type.GetType("UnityEditor.InspectorWindow,UnityEditor.dll");
  518. AtlasUtilityWindow window = GetWindow<AtlasUtilityWindow>(inspectorType);
  519. window.titleContent = new GUIContent("AtlasUtility");
  520. window.Show();
  521. }
  522. public static AtlasUtility GetAtlasUtility()
  523. {
  524. foreach (var path in Directory.GetFiles(Application.dataPath, "*SerializeObject.prefab", SearchOption.AllDirectories))
  525. {
  526. AtlasUtility atlasUtility = AssetDatabase.LoadAssetAtPath<GameObject>(path.GetRelativePath()).GetComponent<AtlasUtility>();
  527. if (atlasUtility != null)
  528. {
  529. return atlasUtility;
  530. }
  531. }
  532. throw new Exception();
  533. }
  534. protected void Pack()
  535. {
  536. Parameter parameter = CreatePackParameter();
  537. List<TextureInfo> textureInfoList = GetTextureInfoList(parameter);
  538. if (textureInfoList.Count == 0)
  539. {
  540. throw new Exception("TextureList is empty");
  541. }
  542. EditorUtility.DisplayProgressBar("Packing", "Calculate layout", 0.5f);
  543. List<Atlas> atlasList = new List<Atlas>();
  544. while (true)
  545. {
  546. Box box = CreateBox(parameter, textureInfoList);
  547. textureInfoList = FillBox(box, parameter, textureInfoList, atlasList);
  548. if (textureInfoList.Count == 0)
  549. {
  550. break;
  551. }
  552. }
  553. if (EditorUtility.DisplayDialog("AtlasUtility", $"{atlasList.Count} atlas will be created", "Go ahead", "Cancel"))
  554. {
  555. for (int i = 0; i < atlasList.Count; i++)
  556. {
  557. EditorUtility.DisplayProgressBar("Packing", "Create atlas", (i + 1)/(float) atlasList.Count);
  558. atlasList[i].Create(i, parameter);
  559. }
  560. }
  561. EndPack();
  562. }
  563. protected void EndPack()
  564. {
  565. EditorUtility.ClearProgressBar();
  566. }
  567. protected Parameter CreatePackParameter()
  568. {
  569. string directory = Script.PackPath.TrimEnd('/', '\\') + "/";
  570. if (directory.Length < 6 || directory.Substring(0, 6).ToLower() != "assets")
  571. {
  572. throw new Exception("PackPath must be inside the Assets folder");
  573. }
  574. if (!Directory.Exists(directory))
  575. {
  576. throw new Exception("directory doesn't exist");
  577. }
  578. if (string.IsNullOrEmpty(Script.PackName) || Script.PackName.Any(Path.GetInvalidFileNameChars().Contains))
  579. {
  580. throw new Exception("PackName is invalid");
  581. }
  582. if (Script.PackPadding < 0)
  583. {
  584. Script.PackPadding = 0;
  585. }
  586. if (Script.PackPlan == global::AtlasUtility.PackPlan.Fixed)
  587. {
  588. if (Script.PackSize <= 2)
  589. {
  590. throw new Exception("Size of atlas must be equal or greater than 2");
  591. }
  592. if (!Mathf.IsPowerOfTwo(Script.PackSize))
  593. {
  594. throw new Exception("Size of atlas must be power of 2");
  595. }
  596. }
  597. else if (Script.PackPlan == global::AtlasUtility.PackPlan.Smallest)
  598. {
  599. if (Script.PackSize <= 0)
  600. {
  601. Script.PackSize = 8192;
  602. }
  603. else
  604. {
  605. Script.PackSize = ExMath.PrevPOT(Script.PackSize);
  606. }
  607. }
  608. for (int i = 0; i < Script.TextureList.Count; i++)
  609. {
  610. for (int j = i+1; j < Script.TextureList.Count; j++)
  611. {
  612. if (Script.TextureList[i].name == Script.TextureList[j].name)
  613. {
  614. Debug.LogWarning($"发现名字相同的图片 {Script.TextureList[i].name}");
  615. }
  616. }
  617. }
  618. Parameter parameter = new Parameter
  619. {
  620. Path = directory + Script.PackName,
  621. PackPlan = Script.PackPlan,
  622. Padding = Script.PackPadding,
  623. TextureSize = Script.PackSize,
  624. TextureList = Script.TextureList,
  625. VirtualTextureList = Script.VirtualTextureList
  626. };
  627. return parameter;
  628. }
  629. protected List<TextureInfo> GetTextureInfoList(Parameter parameter)
  630. {
  631. List<TextureInfo> textureInfoList = new List<TextureInfo>();
  632. for (int i = 0; i < parameter.TextureList.Count; i++)
  633. {
  634. if (parameter.TextureList[i] != null)
  635. {
  636. EditorUtility.DisplayProgressBar("Packing", "Read textures", (i + 1)/(float) parameter.TextureList.Count);
  637. textureInfoList.Add(new TextureInfo(parameter.Padding, parameter.TextureList[i]));
  638. }
  639. }
  640. for (int i = 0; i < parameter.VirtualTextureList.Count; i++)
  641. {
  642. Texture2D texture = new Texture2D(parameter.VirtualTextureList[i].Width, parameter.VirtualTextureList[i].Height);
  643. texture.name = parameter.VirtualTextureList[i].Name;
  644. Color randomColor = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), 1);
  645. for (int j = 0; j < parameter.VirtualTextureList[i].Width; j++)
  646. {
  647. for (int k = 0; k < parameter.VirtualTextureList[i].Height; k++)
  648. {
  649. texture.SetPixel(j, k, randomColor);
  650. }
  651. }
  652. texture.Apply();
  653. textureInfoList.Add(new TextureInfo(parameter.Padding, texture, parameter.VirtualTextureList[i].Width, parameter.VirtualTextureList[i].Height));
  654. }
  655. EditorUtility.ClearProgressBar();
  656. return textureInfoList;
  657. }
  658. protected Box CreateBox(Parameter parameter, List<TextureInfo> textureInfoList)
  659. {
  660. int maxTextureLength = (int) textureInfoList.MyMax(TextureInfo.max);
  661. if (maxTextureLength > parameter.TextureSize)
  662. {
  663. EndPack();
  664. throw new Exception("A texture's width or height is bigger than Size/MaxSize");
  665. }
  666. if (parameter.PackPlan == global::AtlasUtility.PackPlan.Fixed)
  667. {
  668. return new Box(parameter.TextureSize, parameter.TextureSize, new Vector2(0, 0));
  669. }
  670. else if (parameter.PackPlan == global::AtlasUtility.PackPlan.Smallest)
  671. {
  672. int totalArea = textureInfoList.Sum(debris => debris.Area);
  673. int length = ExMath.NextPOT(Mathf.Sqrt(totalArea));
  674. length = Mathf.Min(length, parameter.TextureSize);
  675. length = Mathf.Max(length, maxTextureLength);
  676. if (length* length/2f >= totalArea)
  677. {
  678. return new Box(length, length/2, new Vector2(0, 0));
  679. }
  680. else
  681. {
  682. return new Box(length, length, new Vector2(0, 0));
  683. }
  684. }
  685. else
  686. {
  687. throw new Exception();
  688. }
  689. }
  690. protected List<JagBox> CreateJagBox(List<Box> emptyBoxList)
  691. {
  692. List<JagBox> jagBoxList = new List<JagBox>();
  693. if (emptyBoxList.Count == 0)
  694. {
  695. return jagBoxList;
  696. }
  697. List<Box> boxList = new List<Box>() { emptyBoxList[0] };
  698. for (int i = 0; i < emptyBoxList.Count - 1; i++)
  699. {
  700. int x1 = (int)emptyBoxList[i].LowerRight.x;
  701. int x2 = (int)emptyBoxList[i + 1].LowerLeft.x;
  702. if (x1 == x2)
  703. {
  704. boxList.Add(emptyBoxList[i + 1]);
  705. }
  706. else
  707. {
  708. jagBoxList.Add(new JagBox(boxList));
  709. boxList = new List<Box>();
  710. boxList.Add(emptyBoxList[i + 1]);
  711. }
  712. }
  713. jagBoxList.Add(new JagBox(boxList));
  714. return jagBoxList;
  715. }
  716. protected List<TextureInfo> FillBox(Box box, Parameter parameter, List<TextureInfo> textureInfoList, List<Atlas> atlasList)
  717. {
  718. textureInfoList.MySort(TextureInfo.SortByWidth);
  719. while (true)
  720. {
  721. List<Box> emptyBoxList = new List<Box>();
  722. List<TextureInfo> atlasTextureInfoList = new List<TextureInfo>();
  723. List<TextureInfo> remainTexureInfoList = new List<TextureInfo>(textureInfoList);
  724. FillChildBox(box, remainTexureInfoList, atlasTextureInfoList, emptyBoxList);
  725. List<JagBox> jagBoxList = CreateJagBox(emptyBoxList);
  726. remainTexureInfoList.MySort(TextureInfo.SortByMax);
  727. FillJagBox(remainTexureInfoList, atlasTextureInfoList, jagBoxList);
  728. if (remainTexureInfoList.Count == 0)
  729. {
  730. atlasList.Add(CreateAtlas(box, atlasTextureInfoList));
  731. return remainTexureInfoList;
  732. }
  733. else
  734. {
  735. if (box.Width > box.Height)
  736. {
  737. box = new Box(box.Height, box.Width, Vector2.zero);
  738. }
  739. else if (box.Height > box.Width)
  740. {
  741. box = new Box(box.Height, box.Height, Vector2.zero);
  742. }
  743. else if (box.Width == box.Height)
  744. {
  745. int newLength = ExMath.NextPOT(box.Width + 1);
  746. if (newLength > parameter.TextureSize)
  747. {
  748. atlasList.Add(CreateAtlas(box, atlasTextureInfoList));
  749. return remainTexureInfoList;
  750. }
  751. else
  752. {
  753. box = new Box(newLength, newLength/2, Vector2.zero);
  754. }
  755. }
  756. }
  757. }
  758. }
  759. protected void FillChildBox(Box box, List<TextureInfo> remainTextureInfoList, List<TextureInfo> atlasTextureInfoList, List<Box> emptyBoxList)
  760. {
  761. if (box.Valid)
  762. {
  763. for (int i = 0; i < remainTextureInfoList.Count; i++)
  764. {
  765. if (box.CanFill(remainTextureInfoList[i]))
  766. {
  767. TextureInfo textureInfo = remainTextureInfoList[i];
  768. remainTextureInfoList.Remove(textureInfo);
  769. textureInfo.LowerLeft = box.LowerLeft;
  770. atlasTextureInfoList.Add(textureInfo);
  771. Vector2 lowerLeftUp = box.LowerLeft + new Vector2(0, textureInfo.Height);
  772. Vector2 lowerLeftRight = box.LowerLeft + new Vector2(textureInfo.Width, 0);
  773. Box upChildBox = new Box(textureInfo.Width, box.Height - textureInfo.Height, lowerLeftUp);
  774. Box rightChildBox = new Box(box.Width - textureInfo.Width, box.Height, lowerLeftRight);
  775. FillChildBox(upChildBox, remainTextureInfoList, atlasTextureInfoList, emptyBoxList);
  776. FillChildBox(rightChildBox, remainTextureInfoList, atlasTextureInfoList, emptyBoxList);
  777. return;
  778. }
  779. }
  780. emptyBoxList.Add(box);
  781. }
  782. }
  783. protected void FillJagBox(List<TextureInfo> remainTextureInfoList, List<TextureInfo> atlasTextureInfoList, List<JagBox> jagBoxList)
  784. {
  785. for (int i = 0; i < jagBoxList.Count; i++)
  786. {
  787. for (int j = 0; j < remainTextureInfoList.Count; j++)
  788. {
  789. if (jagBoxList[i].CanFill(remainTextureInfoList[j]))
  790. {
  791. jagBoxList.AddRange(jagBoxList[i].Fill(remainTextureInfoList[j]));
  792. atlasTextureInfoList.Add(remainTextureInfoList[j]);
  793. remainTextureInfoList.Remove(remainTextureInfoList[j]);
  794. break;
  795. }
  796. }
  797. }
  798. }
  799. protected Atlas CreateAtlas(Box box, List<TextureInfo> textureInfoList)
  800. {
  801. Atlas atlas = new Atlas
  802. {
  803. Width = box.Width,
  804. Height = box.Height,
  805. TextureInfoList = textureInfoList,
  806. };
  807. return atlas;
  808. }
  809. protected void CollectDebugInfo()
  810. {
  811. Parameter parameter = CreateDebugParameter();
  812. List<TextureInfo> debrisList = GetTextureInfoList(parameter);
  813. StringBuilder stringBuilder = new StringBuilder();
  814. for (int i = 0; i < debrisList.Count; i++)
  815. {
  816. stringBuilder.AppendLine($"Width:{debrisList[i].Width} Height:{debrisList[i].Height} Pivot:{debrisList[i].Pivot} Border:{debrisList[i].Border}");
  817. }
  818. if (string.IsNullOrEmpty(stringBuilder.ToString()))
  819. {
  820. throw new Exception("TextureList is empty");
  821. }
  822. else
  823. {
  824. StreamWriter streamWriter = new StreamWriter(parameter.Path);
  825. streamWriter.WriteLine(Application.unityVersion);
  826. streamWriter.Write(stringBuilder.ToString());
  827. streamWriter.Close();
  828. AssetDatabase.ImportAsset(parameter.Path);
  829. }
  830. }
  831. protected Parameter CreateDebugParameter()
  832. {
  833. string directory = Script.PackPath.TrimEnd('/', '\\') + "/";
  834. if (directory.Length < 6 || directory.Substring(0, 6).ToLower() != "assets")
  835. {
  836. throw new Exception("PackPath must be inside the Assets folder");
  837. }
  838. if (!Directory.Exists(directory))
  839. {
  840. throw new Exception("directory doesn't exist");
  841. }
  842. Parameter parameter = new Parameter
  843. {
  844. Path = directory + "DebugInfo_" + Script.PackName + ".txt",
  845. TextureList = Script.TextureList,
  846. VirtualTextureList = Script.VirtualTextureList
  847. };
  848. return parameter;
  849. }
  850. protected void Slice()
  851. {
  852. Parameter parameter = CreateSliceParameter();
  853. string spriteSheetPath = AssetDatabase.GetAssetPath(parameter.SpriteSheet);
  854. TextureImporter textureImporter = (TextureImporter)AssetImporter.GetAtPath(spriteSheetPath);
  855. if (textureImporter.spritesheet.Length == 0)
  856. {
  857. throw new Exception("There is no child sprite");
  858. }
  859. if (!textureImporter.isReadable)
  860. {
  861. textureImporter.isReadable = true;
  862. textureImporter.SaveAndReimport();
  863. }
  864. for (int k = 0; k < textureImporter.spritesheet.Length; k++)
  865. {
  866. SpriteMetaData metaData = textureImporter.spritesheet[k];
  867. EditorUtility.DisplayProgressBar("Slicing", $"Create {metaData.name}", (k + 1)/(float) textureImporter.spritesheet.Length);
  868. int width = (int)metaData.rect.width + 2 * parameter.Padding;
  869. int height = (int)metaData.rect.height + 2 * parameter.Padding;
  870. Texture2D texture2D = new Texture2D(width, height, TextureFormat.RGBA32, false);
  871. Color[] atlasColors = parameter.SpriteSheet.GetPixels((int)metaData.rect.x, (int)metaData.rect.y, (int)metaData.rect.width, (int)metaData.rect.height);
  872. Color[] textureColors = new Color[width * height];
  873. for (int i = 0; i < height; i++)
  874. {
  875. for (int j = 0; j < width; j++)
  876. {
  877. if (i < parameter.Padding || j < parameter.Padding || i >= height - parameter.Padding || j >= width - parameter.Padding)
  878. {
  879. textureColors[i * width + j] = new Color(0, 0, 0, 0);
  880. }
  881. else
  882. {
  883. int x = i - parameter.Padding;
  884. int y = j - parameter.Padding;
  885. textureColors[i * width + j] = atlasColors[x * (int)metaData.rect.width + y];
  886. }
  887. }
  888. }
  889. texture2D.SetPixels(textureColors);
  890. texture2D.Apply();
  891. string spritePath = (parameter.Path + metaData.name + ".png").GetUnRepeatFileName();
  892. File.WriteAllBytes(spritePath, texture2D.EncodeToPNG());
  893. AssetDatabase.ImportAsset(spritePath);
  894. TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(spritePath);
  895. TextureImporterSettings importerSetting = new TextureImporterSettings();
  896. importer.ReadTextureSettings(importerSetting);
  897. importerSetting.textureType = TextureImporterType.Sprite;
  898. importerSetting.spritePivot = metaData.pivot;
  899. importerSetting.spriteBorder = metaData.border;
  900. importerSetting.spriteAlignment = metaData.alignment;
  901. importerSetting.alphaIsTransparency = true;
  902. importer.SetTextureSettings(importerSetting);
  903. importer.isReadable = true;
  904. importer.name = metaData.name;
  905. importer.spriteImportMode = SpriteImportMode.Single;
  906. importer.maxTextureSize = ExMath.NextPOT(Mathf.Max(width, height));
  907. importer.SaveAndReimport();
  908. }
  909. EditorUtility.ClearProgressBar();
  910. }
  911. protected Parameter CreateSliceParameter()
  912. {
  913. string directory = Script.SlicePath.TrimEnd('/', '\\') + "/";
  914. if (!Directory.Exists(directory))
  915. {
  916. throw new Exception("directory doesn't exist");
  917. }
  918. if (Script.SlicePadding < 0)
  919. {
  920. Script.SlicePadding = 0;
  921. }
  922. if (Script.SpriteSheet == null)
  923. {
  924. throw new Exception("SpriteSheet is null");
  925. }
  926. Parameter parameter = new Parameter
  927. {
  928. Path = directory,
  929. Padding = Script.SlicePadding,
  930. SpriteSheet = Script.SpriteSheet
  931. };
  932. return parameter;
  933. }
  934. protected void GetSelectedPath(ref string value)
  935. {
  936. if (Selection.assetGUIDs.Length > 0)
  937. {
  938. string path = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);
  939. path = Path.GetDirectoryName(path);
  940. if (string.IsNullOrEmpty(path))
  941. {
  942. value = "Assets";
  943. }
  944. else
  945. {
  946. value = path;
  947. }
  948. }
  949. }
  950. public void OnGUI()
  951. {
  952. SerializedObject.Update();
  953. ScrollPosition = EditorGUILayout.BeginScrollView(ScrollPosition);
  954. DrawPackArea();
  955. DrawSliceArea();
  956. DrawSearchReferenceArea();
  957. DrawSetReferenceArea();
  958. DrawDebugArea();
  959. SerializedObject.ApplyModifiedProperties();
  960. }
  961. public void DrawPackArea()
  962. {
  963. EditorGUILayout.LabelField("AtlasUtility", TitleGuiStyle, GUILayout.Height(30));
  964. EditorGUILayout.BeginHorizontal();
  965. EditorGUILayout.PropertyField(PackPath);
  966. if (GUILayout.Button("UseSelectedPath"))
  967. {
  968. GetSelectedPath(ref Script.PackPath);
  969. }
  970. EditorGUILayout.EndHorizontal();
  971. EditorGUILayout.PropertyField(PackName);
  972. EditorGUILayout.PropertyField(PackPlan, new GUIContent("Pack Plan"));
  973. if (Script.PackPlan == global::AtlasUtility.PackPlan.Fixed)
  974. {
  975. EditorGUILayout.PropertyField(PackSize, new GUIContent("Size"));
  976. }
  977. else if (Script.PackPlan == global::AtlasUtility.PackPlan.Smallest)
  978. {
  979. EditorGUILayout.PropertyField(PackSize, new GUIContent("Max Size"));
  980. }
  981. EditorGUILayout.Separator();
  982. EditorGUILayout.PropertyField(atlas);
  983. if (Script.Atlas != null)
  984. {
  985. List<string> childPathList = ReferenceManager.GetChildPathList(AssetDatabase.GetAssetPath(Script.Atlas));
  986. for (int i = 0; i < childPathList.Count; i++)
  987. {
  988. Script.TextureList.Add(AssetDatabase.LoadAssetAtPath<Texture2D>(childPathList[i]));
  989. }
  990. Script.Atlas = null;
  991. }
  992. EditorGUILayout.PropertyField(PackPadding, new GUIContent("Padding"));
  993. EditorGUILayout.PropertyField(TextureList, true);
  994. if (GUILayout.Button("Pack", GUILayout.Height(30)))
  995. {
  996. Pack();
  997. }
  998. EditorGUILayout.Separator();
  999. }
  1000. public void DrawSliceArea()
  1001. {
  1002. EditorGUILayout.Separator();
  1003. EditorGUILayout.PropertyField(SlicePadding, new GUIContent("Padding"));
  1004. EditorGUILayout.BeginHorizontal();
  1005. EditorGUILayout.PropertyField(SlicePath);
  1006. if (GUILayout.Button("UseSelectedPath"))
  1007. {
  1008. GetSelectedPath(ref Script.SlicePath);
  1009. }
  1010. EditorGUILayout.EndHorizontal();
  1011. EditorGUILayout.PropertyField(SpriteSheet);
  1012. if (GUILayout.Button("Slice", GUILayout.Height(30)))
  1013. {
  1014. Slice();
  1015. }
  1016. EditorGUILayout.Separator();
  1017. }
  1018. public void DrawSearchReferenceArea()
  1019. {
  1020. EditorGUILayout.Separator();
  1021. EditorGUILayout.PropertyField(Target);
  1022. if (GUILayout.Button("SearchReference", GUILayout.Height(30)))
  1023. {
  1024. ReferenceManager.FindReference(AssetDatabase.GetAssetPath(Script.Target));
  1025. }
  1026. EditorGUILayout.Separator();
  1027. }
  1028. public void DrawSetReferenceArea()
  1029. {
  1030. EditorGUILayout.Separator();
  1031. if (GUILayout.Button("ChangeReference", GUILayout.Height(30)))
  1032. {
  1033. ReferenceManager.ChangeAllReference();
  1034. }
  1035. EditorGUILayout.Separator();
  1036. EditorGUILayout.Separator();
  1037. if (GUILayout.Button("ResetAllReference", GUILayout.Height(30)))
  1038. {
  1039. ReferenceManager.ResetAllReference();
  1040. }
  1041. EditorGUILayout.Separator();
  1042. }
  1043. public void DrawDebugArea()
  1044. {
  1045. EditorGUILayout.Separator();
  1046. if (GUILayout.Button("CollectDebugInfo", GUILayout.Height(30)))
  1047. {
  1048. CollectDebugInfo();
  1049. }
  1050. EditorGUILayout.EndScrollView();
  1051. }
  1052. }
  1053. }