MB3_MeshBakerGrouperEditor.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. //----------------------------------------------
  2. // MeshBaker
  3. // Copyright © 2011-2012 Ian Deane
  4. //----------------------------------------------
  5. using UnityEngine;
  6. using System.Collections;
  7. using System.IO;
  8. using System;
  9. using System.Collections.Specialized;
  10. using System.Collections.Generic;
  11. using System.Text.RegularExpressions;
  12. using DigitalOpus.MB.Core;
  13. using UnityEditor;
  14. namespace DigitalOpus.MB.MBEditor
  15. {
  16. [CustomEditor(typeof(MB3_MeshBakerGrouper))]
  17. [CanEditMultipleObjects]
  18. public class MB3_MeshBakerGrouperEditor : Editor
  19. {
  20. long lastBoundsCheckRefreshTime = 0;
  21. static GUIContent gc_ClusterType = new GUIContent("Cluster Type", "The scene will be divided cells. Meshes in each cell will be grouped into a single mesh baker");
  22. static GUIContent gc_GridOrigin = new GUIContent("Origin", "The scene will be divided into of cells. Meshes in each cell will be grouped into a single baker. This sets the origin for the clustering.");
  23. static GUIContent gc_CellSize = new GUIContent("Cell Size", "The scene will be divided into a grid of cells. Meshes in each cell will be grouped into a single baker. This sets the size of the cells.");
  24. static GUIContent gc_ClusterOnLMIndex = new GUIContent("Group By Lightmap Index", "Meshes sharing a lightmap index will be grouped together.");
  25. static GUIContent gc_NumSegements = new GUIContent("Num Pie Segments", "Number of segments/slices in the pie.");
  26. static GUIContent gc_PieAxis = new GUIContent("Pie Axis", "Scene will be divided into segments about this axis.");
  27. static GUIContent gc_ClusterByLODLevel = new GUIContent("Cluster By LOD Level", "A baker will be created for each LOD level.");
  28. static GUIContent gc_ClusterDistance = new GUIContent("Max Distance", "Source meshes closer than this value will be grouped into clusters.");
  29. static GUIContent gc_IncludeCellsWithOnlyOneRenderer = new GUIContent("Include Cells With Only One Renderer", "There is no benefit in combining meshes with only one mesh except to adjust UVs to share an atlas.");
  30. static GUIContent gc_Settings = new GUIContent("Use Shared Settings Asset", "Different bakers can share the same settings. If this field is None, then the settings below will be used.");
  31. static GUIContent gc_PieRingSpacing = new GUIContent("Ring Spacing", "Pie segments will be divided into rings.");
  32. static GUIContent gc_PieCombineAllInCenterRing = new GUIContent("Combine Center Ring Segments Together", "All segments in the centermost ring will be merged into a single segment.");
  33. private SerializedObject grouper;
  34. private SerializedProperty clusterType, gridOrigin, cellSize, clusterOnLMIndex, numSegments, pieAxis, clusterByLODLevel,
  35. clusterDistance, includeCellsWithOnlyOneRenderer, mbSettings, mbSettingsAsset, pieRingSpacing, pieCombineAllInCenterRing;
  36. private MB_MeshBakerSettingsEditor meshBakerSettingsMe;
  37. private MB_MeshBakerSettingsEditor meshBakerSettingsExternal;
  38. public void OnEnable()
  39. {
  40. lastBoundsCheckRefreshTime = 0;
  41. grouper = new SerializedObject(target);
  42. SerializedProperty d = grouper.FindProperty("data");
  43. clusterType = grouper.FindProperty("clusterType");
  44. includeCellsWithOnlyOneRenderer = d.FindPropertyRelative("includeCellsWithOnlyOneRenderer");
  45. gridOrigin = d.FindPropertyRelative("origin");
  46. cellSize = d.FindPropertyRelative("cellSize");
  47. clusterOnLMIndex = d.FindPropertyRelative("clusterOnLMIndex");
  48. clusterByLODLevel = d.FindPropertyRelative("clusterByLODLevel");
  49. numSegments = d.FindPropertyRelative("pieNumSegments");
  50. pieAxis = d.FindPropertyRelative("pieAxis");
  51. clusterDistance = d.FindPropertyRelative("maxDistBetweenClusters");
  52. mbSettings = grouper.FindProperty("meshBakerSettings");
  53. mbSettingsAsset = grouper.FindProperty("meshBakerSettingsAsset");
  54. pieRingSpacing = d.FindPropertyRelative("ringSpacing");
  55. pieCombineAllInCenterRing = d.FindPropertyRelative("combineSegmentsInInnermostRing");
  56. meshBakerSettingsMe = new MB_MeshBakerSettingsEditor();
  57. meshBakerSettingsMe.OnEnable(mbSettings);
  58. if (mbSettingsAsset.objectReferenceValue != null)
  59. {
  60. meshBakerSettingsExternal = new MB_MeshBakerSettingsEditor();
  61. UnityEngine.Object targetObj;
  62. string propertyName;
  63. ((MB3_MeshCombinerSettings)mbSettingsAsset.objectReferenceValue).GetMeshBakerSettingsAsSerializedProperty(out propertyName, out targetObj);
  64. SerializedProperty meshBakerSettings = new SerializedObject(targetObj).FindProperty(propertyName);
  65. meshBakerSettingsExternal.OnEnable(meshBakerSettings);
  66. }
  67. }
  68. public void OnDisable()
  69. {
  70. if (meshBakerSettingsMe != null) meshBakerSettingsMe.OnDisable();
  71. if (meshBakerSettingsExternal != null) meshBakerSettingsExternal.OnDisable();
  72. }
  73. public override void OnInspectorGUI()
  74. {
  75. grouper.Update();
  76. DrawGrouperInspector();
  77. if (GUILayout.Button("Generate Mesh Bakers"))
  78. {
  79. for(int tIdx = 0; tIdx < targets.Length; tIdx++)
  80. {
  81. _generateMeshBakers(targets[tIdx]);
  82. }
  83. }
  84. if (GUILayout.Button("Bake All Child MeshBakers"))
  85. {
  86. for (int tIdx = 0; tIdx < targets.Length; tIdx++)
  87. {
  88. _bakeAllChildMeshBakers(targets[tIdx], ref grouper);
  89. }
  90. }
  91. string buttonTextEnableRenderers = "Disable Renderers On All Child MeshBaker Source Objs";
  92. bool enableRenderers = false;
  93. {
  94. MB3_MeshBakerGrouper tbg = (MB3_MeshBakerGrouper)target;
  95. MB3_MeshBakerCommon bc = tbg.GetComponentInChildren<MB3_MeshBakerCommon>();
  96. if (bc != null && bc.GetObjectsToCombine().Count > 0)
  97. {
  98. GameObject go = bc.GetObjectsToCombine()[0];
  99. if (go != null && go.GetComponent<Renderer>() != null && go.GetComponent<Renderer>().enabled == false)
  100. {
  101. buttonTextEnableRenderers = "Enable Renderers On All Child MeshBaker Source Objs";
  102. enableRenderers = true;
  103. }
  104. }
  105. }
  106. if (GUILayout.Button(buttonTextEnableRenderers))
  107. {
  108. for (int tIdx = 0; tIdx < targets.Length; tIdx++)
  109. {
  110. _enableDisableRenderers(targets[tIdx], enableRenderers);
  111. }
  112. }
  113. if (GUILayout.Button("Delete All Child Mesh Bakers & Combined Meshes"))
  114. {
  115. if (EditorUtility.DisplayDialog("Delete Mesh Bakers", "Delete all child mesh bakers", "OK", "Cancel"))
  116. {
  117. for (int i = 0; i < targets.Length; i++)
  118. {
  119. MB3_MeshBakerGrouper tbg = (MB3_MeshBakerGrouper)targets[i];
  120. tbg.DeleteAllChildMeshBakers();
  121. }
  122. }
  123. }
  124. if (DateTime.UtcNow.Ticks - lastBoundsCheckRefreshTime > 10000000)
  125. {
  126. MB3_TextureBaker tb = ((MB3_MeshBakerGrouper)target).GetComponent<MB3_TextureBaker>();
  127. if (tb != null)
  128. {
  129. MB3_MeshBakerGrouper tbg = (MB3_MeshBakerGrouper)target;
  130. List<GameObject> gos = tb.GetObjectsToCombine();
  131. Bounds b = new Bounds(Vector3.zero, Vector3.one);
  132. if (gos.Count > 0 && gos[0] != null && gos[0].GetComponent<Renderer>() != null)
  133. {
  134. b = gos[0].GetComponent<Renderer>().bounds;
  135. }
  136. for (int i = 0; i < gos.Count; i++)
  137. {
  138. if (gos[i] != null && gos[i].GetComponent<Renderer>() != null)
  139. {
  140. b.Encapsulate(gos[i].GetComponent<Renderer>().bounds);
  141. }
  142. }
  143. tbg.sourceObjectBounds = b;
  144. lastBoundsCheckRefreshTime = DateTime.UtcNow.Ticks;
  145. }
  146. }
  147. grouper.ApplyModifiedProperties();
  148. }
  149. public void DrawGrouperInspector()
  150. {
  151. EditorGUILayout.HelpBox("This component helps you group meshes that are close together so they can be combined together." +
  152. " It generates multiple MB3_MeshBaker objects from the List Of Objects to be combined in the MB3_TextureBaker component." +
  153. " Objects that are close together will be grouped together and added to a new child MB3_MeshBaker object.\n\n" +
  154. " TIP: Try the new agglomerative cluster type. It's awsome!", MessageType.Info);
  155. MB3_MeshBakerGrouper tbg = (MB3_MeshBakerGrouper)target;
  156. MB3_TextureBaker tb = tbg.GetComponent<MB3_TextureBaker>();
  157. EditorGUILayout.PropertyField(clusterType, gc_ClusterType);
  158. MB3_MeshBakerGrouper.ClusterType gg = (MB3_MeshBakerGrouper.ClusterType)clusterType.enumValueIndex;
  159. if ((gg == MB3_MeshBakerGrouper.ClusterType.none && !(tbg.grouper is MB3_MeshBakerGrouperNone)) ||
  160. (gg == MB3_MeshBakerGrouper.ClusterType.grid && !(tbg.grouper is MB3_MeshBakerGrouperGrid)) ||
  161. (gg == MB3_MeshBakerGrouper.ClusterType.pie && !(tbg.grouper is MB3_MeshBakerGrouperPie)) ||
  162. (gg == MB3_MeshBakerGrouper.ClusterType.agglomerative && !(tbg.grouper is MB3_MeshBakerGrouperCluster))
  163. )
  164. {
  165. tbg.CreateGrouper(gg, tbg.data);
  166. tbg.clusterType = gg;
  167. }
  168. if (clusterType.enumValueIndex == (int)MB3_MeshBakerGrouper.ClusterType.grid)
  169. {
  170. EditorGUILayout.PropertyField(gridOrigin, gc_GridOrigin);
  171. EditorGUILayout.PropertyField(cellSize, gc_CellSize);
  172. }
  173. else if (clusterType.enumValueIndex == (int)MB3_MeshBakerGrouper.ClusterType.pie)
  174. {
  175. EditorGUILayout.PropertyField(gridOrigin, gc_GridOrigin);
  176. EditorGUILayout.PropertyField(numSegments, gc_NumSegements);
  177. EditorGUILayout.PropertyField(pieAxis, gc_PieAxis);
  178. EditorGUILayout.PropertyField(pieRingSpacing, gc_PieRingSpacing);
  179. EditorGUILayout.PropertyField(pieCombineAllInCenterRing, gc_PieCombineAllInCenterRing);
  180. }
  181. else if (clusterType.enumValueIndex == (int)MB3_MeshBakerGrouper.ClusterType.agglomerative)
  182. {
  183. float dist = clusterDistance.floatValue;
  184. float maxDist = 100f;
  185. float minDist = .000001f;
  186. MB3_MeshBakerGrouperCluster cl = null;
  187. if (tbg.grouper is MB3_MeshBakerGrouperCluster)
  188. {
  189. cl = (MB3_MeshBakerGrouperCluster)tbg.grouper;
  190. maxDist = cl._ObjsExtents;
  191. minDist = cl._minDistBetweenClusters;
  192. if (dist < minDist)
  193. {
  194. dist = Mathf.Lerp(minDist, maxDist, .11f);
  195. }
  196. }
  197. dist = EditorGUILayout.Slider(gc_ClusterDistance, dist, minDist, maxDist);
  198. clusterDistance.floatValue = dist;
  199. string btnName = "Refresh Clusters";
  200. if (cl.cluster == null || cl.cluster.clusters == null || cl.cluster.clusters.Length == 0)
  201. {
  202. btnName = "Click To Build Clusters";
  203. }
  204. if (GUILayout.Button(btnName))
  205. {
  206. if (tbg.grouper is MB3_MeshBakerGrouperCluster)
  207. {
  208. MB3_MeshBakerGrouperCluster cg = (MB3_MeshBakerGrouperCluster)tbg.grouper;
  209. if (tb != null)
  210. {
  211. cg.BuildClusters(tb.GetObjectsToCombine(), updateProgressBar);
  212. EditorUtility.ClearProgressBar();
  213. Repaint();
  214. }
  215. }
  216. }
  217. }
  218. EditorGUILayout.PropertyField(clusterOnLMIndex, gc_ClusterOnLMIndex);
  219. EditorGUILayout.PropertyField(clusterByLODLevel, gc_ClusterByLODLevel);
  220. EditorGUILayout.PropertyField(includeCellsWithOnlyOneRenderer, gc_IncludeCellsWithOnlyOneRenderer);
  221. EditorGUILayout.Space();
  222. EditorGUILayout.LabelField("Mesh Baker Settings", EditorStyles.boldLabel);
  223. EditorGUILayout.HelpBox("These settings will be shared by all created Mesh Bakers.", MessageType.Info);
  224. UnityEngine.Object oldObjVal = mbSettingsAsset.objectReferenceValue;
  225. EditorGUILayout.PropertyField(mbSettingsAsset, gc_Settings);
  226. bool doingTextureArrays = false;
  227. if (tb != null && tb.textureBakeResults != null) doingTextureArrays = tb.textureBakeResults.resultType == MB2_TextureBakeResults.ResultType.textureArray;
  228. if (mbSettingsAsset.objectReferenceValue == null)
  229. {
  230. meshBakerSettingsMe.DrawGUI(tbg.meshBakerSettings, true, doingTextureArrays);
  231. }
  232. else
  233. {
  234. if (meshBakerSettingsExternal == null || oldObjVal != mbSettingsAsset.objectReferenceValue)
  235. {
  236. UnityEngine.Object targetObj;
  237. string propertyName;
  238. ((MB3_MeshCombinerSettings)mbSettingsAsset.objectReferenceValue).GetMeshBakerSettingsAsSerializedProperty(out propertyName, out targetObj);
  239. SerializedProperty meshBakerSettings = new SerializedObject(targetObj).FindProperty(propertyName);
  240. }
  241. meshBakerSettingsExternal.DrawGUI(((MB3_MeshCombinerSettings)mbSettingsAsset.objectReferenceValue).data, false, doingTextureArrays);
  242. }
  243. }
  244. private static void _generateMeshBakers(UnityEngine.Object target)
  245. {
  246. MB3_MeshBakerGrouper tbg = (MB3_MeshBakerGrouper)target;
  247. MB3_TextureBaker tb = tbg.GetComponent<MB3_TextureBaker>();
  248. if (tb == null)
  249. {
  250. Debug.LogError("There must be an MB3_TextureBaker attached to this game object.");
  251. return;
  252. }
  253. if (tb.GetObjectsToCombine().Count == 0)
  254. {
  255. Debug.LogError("The MB3_MeshBakerGrouper creates clusters based on the objects to combine in the MB3_TextureBaker component. There were no objects in this list.");
  256. return;
  257. }
  258. //check if any of the objes that will be added to bakers already exist in child bakers
  259. List<GameObject> objsWeAreGrouping = tb.GetObjectsToCombine();
  260. MB3_MeshBakerCommon[] alreadyExistBakers = tbg.GetComponentsInChildren<MB3_MeshBakerCommon>();
  261. bool foundChildBakersWithObjsToCombine = false;
  262. for (int i = 0; i < alreadyExistBakers.Length; i++)
  263. {
  264. List<GameObject> childOjs2Combine = alreadyExistBakers[i].GetObjectsToCombine();
  265. for (int j = 0; j < childOjs2Combine.Count; j++)
  266. {
  267. if (childOjs2Combine[j] != null && objsWeAreGrouping.Contains(childOjs2Combine[j]))
  268. {
  269. foundChildBakersWithObjsToCombine = true;
  270. break;
  271. }
  272. }
  273. }
  274. bool proceed = true;
  275. if (foundChildBakersWithObjsToCombine)
  276. {
  277. proceed = EditorUtility.DisplayDialog("Replace Previous Generated Bakers", "Delete child bakers?\n\n" +
  278. "This grouper has child Mesh Baker objects from a previous clustering. Do you want to delete these and create new ones?", "OK", "Cancel");
  279. }
  280. if (proceed)
  281. {
  282. if (foundChildBakersWithObjsToCombine) tbg.DeleteAllChildMeshBakers();
  283. tbg.grouper.DoClustering(tb, tbg);
  284. }
  285. }
  286. private static void _bakeAllChildMeshBakers(UnityEngine.Object target, ref SerializedObject grouper)
  287. {
  288. MB3_MeshBakerGrouper tbg = (MB3_MeshBakerGrouper)target;
  289. MB3_TextureBaker tb = tbg.GetComponent<MB3_TextureBaker>();
  290. try
  291. {
  292. MB3_MeshBakerCommon[] mBakers = tbg.GetComponentsInChildren<MB3_MeshBakerCommon>();
  293. for (int i = 0; i < mBakers.Length; i++)
  294. {
  295. bool createdDummyMaterialBakeResult;
  296. if (grouper.targetObject == tbg)
  297. {
  298. MB3_MeshBakerEditorFunctions.BakeIntoCombined(mBakers[i], out createdDummyMaterialBakeResult, ref grouper);
  299. }
  300. else
  301. {
  302. MB3_MeshBakerEditorFunctions.BakeIntoCombined(mBakers[i], out createdDummyMaterialBakeResult);
  303. }
  304. }
  305. }
  306. catch (Exception e)
  307. {
  308. Debug.LogError(e);
  309. }
  310. finally
  311. {
  312. EditorUtility.ClearProgressBar();
  313. }
  314. }
  315. private static void _enableDisableRenderers(UnityEngine.Object target, bool enableRenderers)
  316. {
  317. MB3_MeshBakerGrouper tbg = (MB3_MeshBakerGrouper)target;
  318. MB3_TextureBaker tb = tbg.GetComponent<MB3_TextureBaker>();
  319. try
  320. {
  321. MB3_MeshBakerCommon[] mBakers = tbg.GetComponentsInChildren<MB3_MeshBakerCommon>();
  322. for (int i = 0; i < mBakers.Length; i++)
  323. {
  324. mBakers[i].EnableDisableSourceObjectRenderers(enableRenderers);
  325. }
  326. }
  327. catch (Exception e)
  328. {
  329. Debug.LogError(e);
  330. }
  331. finally
  332. {
  333. EditorUtility.ClearProgressBar();
  334. }
  335. }
  336. public bool updateProgressBar(string msg, float progress)
  337. {
  338. //EditorUtility.DisplayProgressBar("Creating Clusters", msg, progress);
  339. return EditorUtility.DisplayCancelableProgressBar("Creating Clusters", msg, progress);
  340. }
  341. }
  342. }