JsonDataTrimmer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using AssetBank.Editor.SchemaConverter.Data.Input;
  4. using AssetBank.Settings;
  5. using Newtonsoft.Json;
  6. using Newtonsoft.Json.Linq;
  7. using UnityEngine;
  8. namespace AssetBank.Editor.Tools
  9. {
  10. public static class JsonDataTrimmer
  11. {
  12. public static string Process(string rawJsonText, ProjectExporterSettings settings)
  13. {
  14. var processedJson = ShortenBrokenPrefabGameObjects(rawJsonText);
  15. var allComponents = JArray.Parse(processedJson);
  16. // Pass 1: Build the definitive ruleset
  17. var rules = settings.SafeComponents.ToDictionary(r => r.Component, r => r.ExposedFields.ToHashSet());
  18. if (!settings.OverrideHardcodedDefaults)
  19. {
  20. foreach (var hardcodedRule in settings.HardcodedComponents)
  21. {
  22. if (rules.TryGetValue(hardcodedRule.Component, out var userRules))
  23. {
  24. userRules.UnionWith(hardcodedRule.ExposedFields);
  25. }
  26. else
  27. {
  28. rules[hardcodedRule.Component] = hardcodedRule.ExposedFields.ToHashSet();
  29. }
  30. }
  31. }
  32. // Pass 2: Create a fully trimmed copy of every component
  33. var trimmedComponentMap = new Dictionary<string, JObject>();
  34. foreach (var component in allComponents.Children<JObject>())
  35. {
  36. var anchorId = component["anchor_id"]?.ToString();
  37. if (string.IsNullOrEmpty(anchorId)) continue;
  38. var trimmedComponent = component.DeepClone() as JObject;
  39. var dataBlock = trimmedComponent["data"] as JObject;
  40. if (dataBlock == null || !dataBlock.HasValues)
  41. {
  42. trimmedComponentMap[anchorId] = trimmedComponent;
  43. continue;
  44. }
  45. var componentProperty = dataBlock.Properties().FirstOrDefault();
  46. if (componentProperty == null)
  47. {
  48. trimmedComponentMap[anchorId] = trimmedComponent;
  49. continue;
  50. }
  51. var componentName = componentProperty.Name;
  52. var componentJObject = componentProperty.Value as JObject;
  53. if (componentJObject == null)
  54. {
  55. trimmedComponentMap[anchorId] = trimmedComponent;
  56. continue;
  57. }
  58. if (rules.TryGetValue(componentName, out var exposedFields))
  59. {
  60. if (exposedFields.Contains("*"))
  61. {
  62. trimmedComponentMap[anchorId] = trimmedComponent;
  63. continue;
  64. }
  65. var propertiesToKeep = new HashSet<string>(exposedFields);
  66. var currentKeys = componentJObject.Properties().Select(p => p.Name).ToList();
  67. foreach (var key in currentKeys)
  68. {
  69. if (!propertiesToKeep.Contains(key))
  70. {
  71. componentJObject.Remove(key);
  72. }
  73. }
  74. }
  75. else
  76. {
  77. componentJObject.RemoveAll();
  78. }
  79. trimmedComponentMap[anchorId] = trimmedComponent;
  80. }
  81. // Pass 3: Final Assembly
  82. var finalOutput = new JArray();
  83. var embeddedIds = new HashSet<string>();
  84. // First, identify all components that will be embedded into GameObjects
  85. foreach (var originalComponent in allComponents.Children<JObject>())
  86. {
  87. if (originalComponent["data"]?["GameObject"]?["m_Component"] is JArray componentList)
  88. {
  89. foreach (var compRef in componentList.Children<JObject>())
  90. {
  91. if (compRef["component"]?["fileID"]?.ToString() is var fileID && !string.IsNullOrEmpty(fileID))
  92. {
  93. embeddedIds.Add(fileID);
  94. }
  95. }
  96. }
  97. }
  98. // Now, build the final output, preserving order
  99. foreach (var originalComponent in allComponents.Children<JObject>())
  100. {
  101. var anchorId = originalComponent["anchor_id"]?.ToString();
  102. if (string.IsNullOrEmpty(anchorId) || embeddedIds.Contains(anchorId))
  103. {
  104. // If a component has no ID, or it's a child of a GameObject, skip it.
  105. // Children will be added via their parent GameObject.
  106. continue;
  107. }
  108. // Get the trimmed version of the current component
  109. if (!trimmedComponentMap.TryGetValue(anchorId, out var trimmedComponent))
  110. {
  111. // Should not happen, but as a safeguard, add the original.
  112. finalOutput.Add(originalComponent.DeepClone());
  113. continue;
  114. }
  115. // If it's a GameObject, embed its already-trimmed children
  116. if (originalComponent["data"]?["GameObject"] is JObject originalGameObjectData)
  117. {
  118. var trimmedGameObjectData = trimmedComponent["data"]["GameObject"] as JObject;
  119. var componentList = originalGameObjectData["m_Component"] as JArray;
  120. if (trimmedGameObjectData != null && componentList != null)
  121. {
  122. var newComponentList = new JArray();
  123. var gameObjectName = originalGameObjectData["m_Name"]?.ToString() ?? "Unnamed";
  124. foreach (var compRef in componentList.Children<JObject>())
  125. {
  126. var fileID = compRef["component"]?["fileID"]?.ToString();
  127. if (string.IsNullOrEmpty(fileID)) continue;
  128. if (trimmedComponentMap.TryGetValue(fileID, out var linkedComponent))
  129. {
  130. var clonedData = linkedComponent["data"].DeepClone() as JObject;
  131. (clonedData?.Properties().FirstOrDefault()?.Value as JObject)?.Remove("m_GameObject");
  132. // Re-inject the anchor_id to preserve the link information after trimming.
  133. if (clonedData != null)
  134. {
  135. clonedData.AddFirst(new JProperty("anchor_id", fileID));
  136. }
  137. newComponentList.Add(clonedData);
  138. }
  139. else
  140. {
  141. Debug.LogWarning($"JsonDataTrimmer: Could not find component with anchor_id '{fileID}' referenced by GameObject '{gameObjectName}'.");
  142. }
  143. }
  144. trimmedGameObjectData["m_Component"] = newComponentList;
  145. }
  146. }
  147. finalOutput.Add(trimmedComponent);
  148. }
  149. return finalOutput.ToString(Newtonsoft.Json.Formatting.None);
  150. }
  151. private static string ShortenBrokenPrefabGameObjects(string data)
  152. {
  153. var nodes = JsonConvert.DeserializeObject<List<OriginalNode>>(data);
  154. if (nodes == null)
  155. {
  156. return data;
  157. }
  158. const string gameObjectTypeId = "1";
  159. const string prefabTypeId = "1001";
  160. const string transformTypeId = "4";
  161. var allGameObjects = nodes.Where(n => n.type_id == gameObjectTypeId).ToList();
  162. var allTransforms = nodes.Where(n => n.type_id == transformTypeId).ToList();
  163. var allPrefabs = nodes.Where(n => n.type_id == prefabTypeId).ToList();
  164. var restOfComponents = nodes.Where(n => n.type_id != gameObjectTypeId && n.type_id != prefabTypeId && n.type_id != transformTypeId).ToList();
  165. foreach (var gameObject in allGameObjects)
  166. {
  167. var nodeIndex = nodes.IndexOf(gameObject);
  168. var prefabInstanceId = gameObject.data?["GameObject"]?["m_PrefabInstance"]?["fileID"]?.ToString();
  169. if (string.IsNullOrEmpty(prefabInstanceId) || prefabInstanceId == "0") continue;
  170. var prefab = allPrefabs.FirstOrDefault(p => p.anchor_id == prefabInstanceId);
  171. if (prefab == null)
  172. {
  173. Debug.LogWarning($"JsonDataTrimmer: Could not find prefab with anchor_id '{prefabInstanceId}' referenced by GameObject '{gameObject.data?["GameObject"]?["m_Name"]}'.");
  174. continue;
  175. }
  176. var prefabGuid = prefab.data?["PrefabInstance"]?["m_SourcePrefab"]?["guid"]?.ToString();
  177. if (string.IsNullOrEmpty(prefabGuid))
  178. {
  179. Debug.LogWarning($"JsonDataTrimmer: Could not find GUID for prefab with anchor_id '{prefabInstanceId}' referenced by GameObject '{gameObject.data?["GameObject"]?["m_Name"]}'.");
  180. continue;
  181. }
  182. var relatedTransform = allTransforms.FirstOrDefault(t => t.data?["Transform"]?["m_PrefabInstance"]?["fileID"]?.ToString() == prefabInstanceId);
  183. if (relatedTransform == null)
  184. {
  185. Debug.LogWarning($"JsonDataTrimmer: Could not find Transform with anchor_id '{prefabInstanceId}' referenced by GameObject '{gameObject.data?["GameObject"]?["m_Name"]}'.");
  186. continue;
  187. }
  188. var relatedComponents = restOfComponents.Where(c => c.data?.SelectToken("*.m_GameObject.fileID")?.ToString() == gameObject.anchor_id).ToList();
  189. var newNode = new OriginalNode
  190. {
  191. type_id = gameObject.type_id,
  192. anchor_id = gameObject.anchor_id,
  193. data = gameObject.data
  194. };
  195. var jArray = new JArray();
  196. foreach (var component in relatedComponents)
  197. {
  198. jArray.Add(JObject.FromObject(new
  199. {
  200. component = new
  201. {
  202. fileID = component.anchor_id
  203. }
  204. }));
  205. }
  206. jArray.Add(JObject.FromObject(new
  207. {
  208. component = new
  209. {
  210. fileID = relatedTransform.anchor_id
  211. }
  212. }));
  213. newNode.data["GameObject"]!["m_Component"] = jArray;
  214. nodes[nodeIndex] = newNode;
  215. }
  216. return JsonConvert.SerializeObject(nodes, Formatting.None);
  217. }
  218. }
  219. }