InTerra_MaskCreator.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using UnityEditor;
  4. using System.IO;
  5. using System.Linq;
  6. namespace InTerra
  7. {
  8. public class InTerra_MaskCreator : EditorWindow
  9. {
  10. static bool normalInMask;
  11. bool info;
  12. int format;
  13. string path = "";
  14. string file = "";
  15. Vector2Int resolution;
  16. struct TextureField
  17. {
  18. public Texture2D texture;
  19. public int channel;
  20. public TextureImporter importer;
  21. public TextureImporterCompression compression;
  22. public TextureImporterType type;
  23. public bool isReadable;
  24. public bool isChanged;
  25. }
  26. TextureField metallic;
  27. TextureField height;
  28. TextureField ao;
  29. TextureField smooth;
  30. TextureField normal;
  31. bool isResOk;
  32. bool invertRough;
  33. float progress;
  34. public static void OpenWindow(bool normalMask)
  35. {
  36. InTerra_MaskCreator window = (InTerra_MaskCreator)EditorWindow.GetWindow<InTerra_MaskCreator>(true, "Mask Map Creator", true);
  37. Vector2 size = normalMask ? new Vector2(320, 280) : new Vector2(425, 280);
  38. normalInMask = normalMask;
  39. window.minSize = size;
  40. window.maxSize = size;
  41. #if UNITY_2020_1_OR_NEWER
  42. Rect main = EditorGUIUtility.GetMainWindowPosition();
  43. Rect pos = window.position;
  44. float centerWidth = (main.width - pos.width) * 0.5f;
  45. float centerHeight = (main.height - pos.height) * 0.5f;
  46. pos.x = main.x + centerWidth;
  47. pos.y = main.y + centerHeight;
  48. window.position = pos;
  49. #else
  50. InTerra_Data.CenterOnMainWin(window);
  51. #endif
  52. }
  53. void OnGUI()
  54. {
  55. if (normalInMask)
  56. {
  57. NormalInMask();
  58. }
  59. else
  60. {
  61. Mask();
  62. }
  63. }
  64. //============================================================================================
  65. //------------------------------------ NORMAL-MASK CREATOR ------------------------------
  66. //============================================================================================
  67. void NormalInMask()
  68. {
  69. Vector2 size = new Vector2(330, 285);
  70. using (new GUILayout.VerticalScope(EditorStyles.helpBox))
  71. {
  72. using (new GUILayout.HorizontalScope())
  73. {
  74. using (var check = new EditorGUI.ChangeCheckScope())
  75. {
  76. normal = SelectTextureField("Normal Map", normal, false);
  77. ao = SelectTextureField("A. Occlusion", ao, true);
  78. height = SelectTextureField("Heightmap", height, true);
  79. if (check.changed)
  80. {
  81. isResOk = CheckTexturesResolution();
  82. }
  83. }
  84. }
  85. }
  86. GUI.enabled = false;
  87. if (normal.texture != null)
  88. {
  89. GUI.enabled = true;
  90. if (!isResOk)
  91. {
  92. EditorGUILayout.HelpBox("Textures must have the same resolution!", MessageType.Warning);
  93. size = new Vector2(320, 320);
  94. GUI.enabled = false;
  95. }
  96. }
  97. FileAndPathFields(250);
  98. info = EditorGUILayout.Foldout(info, "Normal-Mask map Texture info", true);
  99. if (info)
  100. {
  101. EditorGUILayout.HelpBox("In the Import Settings the Texture Type has to be set as \"Default\" and \"sRGB(Color Texture)\" has to be unchecked! \n\nChannels info:\nRed - A.Occlusion \nGreen - Bitangent(Green) from Normal map \nBlue - Height map\nAlpha - Tangent(Red) from Normal map", MessageType.None);
  102. size = new Vector2(320, 380);
  103. }
  104. minSize = size;
  105. maxSize = size;
  106. EditorGUILayout.Space();
  107. GUIStyle buttonStyleBold = new GUIStyle(GUI.skin.button) { fontStyle = FontStyle.Bold };
  108. if (GUILayout.Button("Save", buttonStyleBold))
  109. {
  110. if (!FinalCheck())
  111. {
  112. Focus();
  113. }
  114. else
  115. {
  116. EditorUtility.DisplayProgressBar("Saving", "Getting Pixels...", progress);
  117. Color[] ga = ImprterSetReadWriteAndGetPixels(ref normal);
  118. Color[] r = ImprterSetReadWriteAndGetPixels(ref ao);
  119. Color[] b = ImprterSetReadWriteAndGetPixels(ref height);
  120. EditorUtility.DisplayProgressBar("Saving", "Setting Pixels...", progress);
  121. Color[] outputCol = new Color[ga.Length];
  122. if (ao.texture == null) ao.channel = 4;
  123. if (height.texture == null) height.channel = 5;
  124. for (int i = 0; i < outputCol.Length; i++)
  125. {
  126. outputCol[i] = new Color(ChooseChanel(r[i], ao.channel), ga[i].g, ChooseChanel(b[i], height.channel), ga[i].r);
  127. }
  128. Texture2D n_h_ao_texture = new Texture2D(normal.texture.width, normal.texture.height, TextureFormat.RGBAHalf, true);
  129. n_h_ao_texture.SetPixels(outputCol);
  130. progress += 0.3f;
  131. EditorUtility.DisplayProgressBar("Saving", "Encoding and Saving...", progress);
  132. SaveMaskTexture(format, n_h_ao_texture, path);
  133. DestroyImmediate(n_h_ao_texture);
  134. progress += 0.1f;
  135. EditorUtility.DisplayProgressBar("Saving", "Importer settings...", progress);
  136. ImporterSetOriginalValues(normal);
  137. ImporterSetOriginalValues(height);
  138. ImporterSetOriginalValues(ao);
  139. EditorUtility.ClearProgressBar();
  140. EditorApplication.delayCall += () =>
  141. {
  142. Close();
  143. };
  144. }
  145. }
  146. }
  147. //=======================================================================================
  148. //------------------------------- MASK MAP CREATOR ---------------------------------
  149. //=======================================================================================
  150. void Mask()
  151. {
  152. Vector2 size = new Vector2(442, 287);
  153. using (new GUILayout.VerticalScope(EditorStyles.helpBox))
  154. {
  155. using (new GUILayout.HorizontalScope())
  156. {
  157. using (var check = new EditorGUI.ChangeCheckScope())
  158. {
  159. metallic = SelectTextureField("Metallic", metallic, true);
  160. ao = SelectTextureField("A. Occlusion", ao, true);
  161. height = SelectTextureField("Heightmap", height, true);
  162. using (new GUILayout.VerticalScope())
  163. {
  164. smooth = SelectTextureField("Smoothness", smooth, true);
  165. EditorStyles.label.fontSize = 10;
  166. invertRough = EditorGUILayout.ToggleLeft(new GUIContent() { text = "Invert Roughness", tooltip = "This option will convert the Roughness texture into Smoothness texture." }, invertRough);
  167. EditorStyles.label.fontSize = 12;
  168. }
  169. EditorGUILayout.GetControlRect(GUILayout.Width(1));
  170. if (check.changed)
  171. {
  172. isResOk = CheckTexturesResolution();
  173. }
  174. }
  175. }
  176. }
  177. GUI.enabled = false;
  178. if (metallic.texture != null || ao.texture != null || height.texture != null || smooth.texture != null)
  179. {
  180. GUI.enabled = true;
  181. if (!isResOk)
  182. {
  183. EditorGUILayout.HelpBox("Textures must have the same resolution!", MessageType.Warning);
  184. size = new Vector2(425, 320);
  185. GUI.enabled = false;
  186. }
  187. }
  188. minSize = size;
  189. maxSize = size;
  190. FileAndPathFields(350);
  191. EditorGUILayout.Space();
  192. GUIStyle buttonStyleBold = new GUIStyle(GUI.skin.button) { fontStyle = FontStyle.Bold };
  193. if (GUILayout.Button("Save", buttonStyleBold))
  194. {
  195. if (!FinalCheck())
  196. {
  197. Focus();
  198. }
  199. else
  200. {
  201. EditorUtility.DisplayProgressBar("Saving", "Getting Pixels...", progress);
  202. Color[] r = ImprterSetReadWriteAndGetPixels(ref metallic);
  203. Color[] g = ImprterSetReadWriteAndGetPixels(ref ao);
  204. Color[] b = ImprterSetReadWriteAndGetPixels(ref height);
  205. Color[] a = ImprterSetReadWriteAndGetPixels(ref smooth);
  206. Color[] outputCol = new Color[resolution.x * resolution.y];
  207. EditorUtility.DisplayProgressBar("Saving", "Setting Pixels...", progress);
  208. if (ao.texture == null) ao.channel = 4;
  209. if (height.texture == null) height.channel = 5;
  210. for (int i = 0; i < outputCol.Length; i++)
  211. {
  212. if (invertRough) a[i] = Color.white - a[i];
  213. outputCol[i] = new Color(ChooseChanel(r[i], metallic.channel), ChooseChanel(g[i], ao.channel), ChooseChanel(b[i], height.channel), ChooseChanel(a[i], smooth.channel));
  214. }
  215. progress += 0.1f;
  216. EditorUtility.DisplayProgressBar("Saving", "Encoding and Saving...", progress);
  217. Texture2D maskTexture = new Texture2D(resolution.x, resolution.y, TextureFormat.RGBAHalf, true);
  218. maskTexture.SetPixels(outputCol);
  219. SaveMaskTexture(format, maskTexture, path);
  220. DestroyImmediate(maskTexture);
  221. progress += 0.1f;
  222. EditorUtility.DisplayProgressBar("Saving", "Importer settings...", progress);
  223. ImporterSetOriginalValues(metallic);
  224. ImporterSetOriginalValues(ao);
  225. ImporterSetOriginalValues(height);
  226. ImporterSetOriginalValues(smooth);
  227. EditorUtility.ClearProgressBar();
  228. EditorApplication.delayCall += () =>
  229. {
  230. Close();
  231. };
  232. }
  233. }
  234. }
  235. //=====================================================================================
  236. GUIContent Tooltip(string tooltip)
  237. {
  238. return new GUIContent() { tooltip = tooltip };
  239. }
  240. bool CheckTexturesResolution()
  241. {
  242. List<int> widthRes = new List<int>();
  243. List<int> heightRes = new List<int>();
  244. AddTextureRes(metallic.texture);
  245. AddTextureRes(ao.texture);
  246. AddTextureRes(height.texture);
  247. AddTextureRes(smooth.texture);
  248. AddTextureRes(normal.texture);
  249. void AddTextureRes(Texture2D t)
  250. {
  251. if (t != null)
  252. {
  253. widthRes.Add(t.width);
  254. heightRes.Add(t.width);
  255. }
  256. }
  257. return (widthRes.Distinct().ToList().Count <= 1) && (heightRes.Distinct().ToList().Count <= 1);
  258. }
  259. TextureField SelectTextureField(string name, TextureField tf, bool channel)
  260. {
  261. GUILayout.BeginVertical();
  262. using (new GUILayout.HorizontalScope(EditorStyles.helpBox, GUILayout.MinWidth(105)))
  263. {
  264. var style = new GUIStyle(EditorStyles.boldLabel) { alignment = TextAnchor.MiddleCenter };
  265. var styleMini = new GUIStyle(EditorStyles.miniLabel) { alignment = TextAnchor.MiddleCenter };
  266. style.alignment = TextAnchor.UpperCenter;
  267. style.fixedWidth = 80;
  268. GUILayout.Label(name, style);
  269. string tooltip = " ";
  270. switch (name)
  271. {
  272. case "Metallic":
  273. tooltip = "Metallic Texture usually is not a part of ground materials texture set and can be left empty.";
  274. break;
  275. case "A. Occlusion":
  276. tooltip = "Texture can be aslo refered as \"AO\" or \"Ambient Occlusion\".";
  277. break;
  278. case "Heightmap":
  279. tooltip = "Texture can be aslo refered as Bump map. Displacement map can be also used.";
  280. break;
  281. case "Smoothness":
  282. tooltip = "Roughness texture can be used instead of Smoothness but the “Invert Roughness” has to be checked.";
  283. break;
  284. case "Normal Map":
  285. tooltip = "Normal map texture in GL (OpenGL) format";
  286. break;
  287. }
  288. GUILayout.Label(new GUIContent() { text = "?", tooltip = tooltip }, styleMini, GUILayout.MaxWidth(10));
  289. }
  290. using (var check = new EditorGUI.ChangeCheckScope())
  291. {
  292. tf.texture = (Texture2D)EditorGUILayout.ObjectField(tf.texture, typeof(Texture2D), false, GUILayout.Width(105), GUILayout.Height(105));
  293. if (check.changed)
  294. {
  295. PathAndFile(tf.texture);
  296. }
  297. }
  298. tf.importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(tf.texture)) as TextureImporter;
  299. if (channel)
  300. {
  301. var ch = new List<string> { "Red" };
  302. if (tf.texture != null && tf.importer != null)
  303. {
  304. if (tf.importer.textureType != TextureImporterType.SingleChannel)
  305. {
  306. ch.Add("Green");
  307. ch.Add("Blue");
  308. }
  309. if (tf.importer.DoesSourceTextureHaveAlpha())
  310. {
  311. ch.Add("Alpha");
  312. }
  313. tf.channel = EditorGUILayout.Popup(Tooltip("Map Channel"), tf.channel, ch.ToArray(), GUILayout.Width(105));
  314. }
  315. else
  316. {
  317. GUI.enabled = false;
  318. EditorGUILayout.Popup(Tooltip("Map Channel"), tf.channel, ch.ToArray(), GUILayout.Width(105));
  319. GUI.enabled = true;
  320. }
  321. }
  322. else
  323. {
  324. tf.channel = 0;
  325. EditorGUILayout.GetControlRect(GUILayout.Width(100));
  326. }
  327. GUILayout.EndVertical();
  328. return tf;
  329. }
  330. void PathAndFile(Texture2D texture)
  331. {
  332. if (texture != null && string.IsNullOrEmpty(path))
  333. {
  334. path = AssetDatabase.GetAssetPath(texture);
  335. path = Path.GetDirectoryName(path);
  336. path = path.Replace("\\", "/");
  337. file = texture.name + "_Mask";
  338. resolution = new Vector2Int(texture.width, texture.height);
  339. }
  340. }
  341. string FileAndPathFields(int width)
  342. {
  343. using (new GUILayout.HorizontalScope())
  344. {
  345. EditorGUILayout.LabelField("File Name:", EditorStyles.miniLabel);
  346. EditorGUILayout.LabelField("Format:", EditorStyles.miniLabel, GUILayout.MaxWidth(50));
  347. }
  348. using (new GUILayout.HorizontalScope())
  349. {
  350. string[] sFormat = { "png", "tga" };
  351. file = EditorGUILayout.TextField(file);
  352. Repaint();
  353. format = EditorGUILayout.Popup(format, sFormat, GUILayout.MaxWidth(50));
  354. }
  355. EditorGUILayout.LabelField("Path:", EditorStyles.miniLabel);
  356. using (new GUILayout.HorizontalScope())
  357. {
  358. GUILayout.TextField(path, new GUIStyle(EditorStyles.helpBox) { wordWrap = false }, GUILayout.Width(width));
  359. if (GUILayout.Button("change", EditorStyles.miniButton))
  360. {
  361. string absPath = EditorUtility.SaveFolderPanel("Save textures to folder", path, "");
  362. if (absPath.Contains(Application.dataPath))
  363. {
  364. path = absPath.Substring(absPath.IndexOf("Assets"));
  365. }
  366. else if (!string.IsNullOrEmpty(absPath))
  367. {
  368. path = absPath;
  369. }
  370. }
  371. }
  372. return path;
  373. }
  374. bool FinalCheck()
  375. {
  376. if (!CheckTexturesResolution())
  377. {
  378. EditorUtility.DisplayDialog("Texture resolution ", "Textures must have the same resolution!", "OK");
  379. }
  380. return CheckTexturesResolution() && CheckCrunchedCompression() && ValidPathAndName();
  381. }
  382. Color[] ImprterSetReadWriteAndGetPixels(ref TextureField tf)
  383. {
  384. if (tf.importer != null)
  385. {
  386. tf.isReadable = tf.importer.isReadable;
  387. tf.compression = tf.importer.textureCompression;
  388. tf.type = tf.importer.textureType;
  389. if (!tf.isReadable || tf.compression != TextureImporterCompression.Uncompressed || tf.type != TextureImporterType.Default)
  390. {
  391. tf.importer.isReadable = true;
  392. tf.importer.textureCompression = TextureImporterCompression.Uncompressed;
  393. tf.importer.crunchedCompression = false;
  394. tf.importer.textureType = TextureImporterType.Default;
  395. tf.isChanged = true;
  396. tf.importer.SaveAndReimport();
  397. AssetDatabase.Refresh();
  398. }
  399. progress += 0.1f; EditorUtility.DisplayProgressBar("Saving", "Getting Pixels...", progress);
  400. return tf.texture.GetPixels(0, 0, tf.texture.width, tf.texture.height);
  401. }
  402. else
  403. {
  404. progress += 0.1f; EditorUtility.DisplayProgressBar("Saving", "Getting Pixels...", progress);
  405. return new Color[resolution.x * resolution.y]; ;
  406. }
  407. }
  408. bool CheckCrunchedCompression()
  409. {
  410. bool isOK = false;
  411. List<bool> crunched = new List<bool>();
  412. CheckCrunched(metallic);
  413. CheckCrunched(ao);
  414. CheckCrunched(height);
  415. CheckCrunched(smooth);
  416. CheckCrunched(normal);
  417. void CheckCrunched(TextureField tf)
  418. {
  419. if (tf.importer != null)
  420. {
  421. crunched.Add(tf.importer.crunchedCompression);
  422. }
  423. }
  424. if (!crunched.Contains(true))
  425. {
  426. isOK = true;
  427. }
  428. else
  429. {
  430. if (EditorUtility.DisplayDialog("Crunched Compression", "Some texture(s) are using Crunched Compression, if you will continue the Crunched Compression will be set off. Do you want to continue?", "Yes", "Cancel"))
  431. {
  432. isOK = true;
  433. }
  434. }
  435. return isOK;
  436. }
  437. bool ValidPathAndName()
  438. {
  439. bool isOK = false;
  440. bool nameOk = !string.IsNullOrEmpty(file);
  441. bool folderOk = path.Length > 3;
  442. string pf = path;
  443. if (!folderOk)
  444. {
  445. EditorUtility.DisplayDialog("Invalid Folder", "You cannot save the File in the root of the drive, please choose a folder!", "OK");
  446. }
  447. if (!nameOk)
  448. {
  449. EditorUtility.DisplayDialog("Empty name ", "You need to enter a file name!", "OK");
  450. }
  451. if (nameOk && folderOk)
  452. {
  453. pf += "/" + file;
  454. pf += format == 0 ? ".png" : ".tga";
  455. if (!File.Exists(pf) || (EditorUtility.DisplayDialog("File already exists", "File " + Path.GetFileName(pf) + " already exists. Do you want to replace it?", "Yes", "Cancel")))
  456. {
  457. isOK = true;
  458. path = pf;
  459. }
  460. }
  461. return isOK;
  462. }
  463. float ChooseChanel(Color col, int channel)
  464. {
  465. float output;
  466. switch (channel)
  467. {
  468. case 0:
  469. output = col.r;
  470. break;
  471. case 1:
  472. output = col.g;
  473. break;
  474. case 2:
  475. output = col.b;
  476. break;
  477. case 3:
  478. output = col.a;
  479. break;
  480. case 4:
  481. output = 1.0f;
  482. break;
  483. case 5:
  484. output = 0.5f;
  485. break;
  486. default:
  487. return 0.0f;
  488. }
  489. return output;
  490. }
  491. void SaveMaskTexture(int format, Texture2D texture, string path)
  492. {
  493. try
  494. {
  495. switch (format)
  496. {
  497. case 0:
  498. File.WriteAllBytes(path, texture.EncodeToPNG());
  499. break;
  500. case 1:
  501. File.WriteAllBytes(path, texture.EncodeToTGA());
  502. break;
  503. }
  504. SetTextureLinear(path);
  505. AssetDatabase.Refresh();
  506. }
  507. catch
  508. {
  509. Debug.LogWarning("Saving File " + path + " failed.");
  510. }
  511. }
  512. void SetTextureLinear(string path)
  513. {
  514. EditorApplication.delayCall += () =>
  515. {
  516. TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter;
  517. if (importer != null)
  518. {
  519. importer.sRGBTexture = false;
  520. AssetDatabase.ImportAsset(path);
  521. AssetDatabase.Refresh();
  522. }
  523. };
  524. }
  525. void ImporterSetOriginalValues(TextureField tf)
  526. {
  527. if (tf.isChanged)
  528. {
  529. tf.importer.isReadable = tf.isReadable;
  530. tf.importer.textureCompression = tf.compression;
  531. tf.importer.textureType = tf.type;
  532. tf.importer.SaveAndReimport();
  533. AssetDatabase.Refresh();
  534. progress += 0.1f; EditorUtility.DisplayProgressBar("Saving", "Importer settings...", progress);
  535. }
  536. }
  537. }
  538. }