ProjectExporterController.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using AssetBank.Settings;
  7. using UnityEditor;
  8. using UnityEditor.Animations;
  9. using UnityEngine;
  10. using UnityEngine.Audio;
  11. using UnityEngine.Video;
  12. namespace AssetBank.DockableWindow
  13. {
  14. public class ProjectExporterController
  15. {
  16. private static readonly string ProjectRoot = Path.GetDirectoryName(Application.dataPath);
  17. private readonly ProjectExporterSettings _settings;
  18. public ProjectExporterController()
  19. {
  20. _settings = ProjectExporterSettings.GetOrCreateSettings();
  21. }
  22. // Finds assets based on a search filter (e.g., "t:Scene") and builds a hierarchical model.
  23. public static AssetModel GetAssets(string filter)
  24. {
  25. var root = new AssetModel("Assets", "Assets");
  26. var assetGuids = AssetDatabase.FindAssets(filter, new[] { "Assets" });
  27. foreach (var guid in assetGuids)
  28. {
  29. var path = AssetDatabase.GUIDToAssetPath(guid);
  30. if (filter.Contains("t:ScriptableObject") && !path.EndsWith(".asset"))
  31. {
  32. continue;
  33. }
  34. var parts = path.Split('/');
  35. var currentNode = root;
  36. for (int i = 1; i < parts.Length; i++) // Start at 1 to skip "Assets"
  37. {
  38. var part = parts[i];
  39. var child = currentNode.Children.FirstOrDefault(c => c.Name == part);
  40. if (child == null)
  41. {
  42. var currentPath = string.Join("/", parts.Take(i + 1));
  43. child = new AssetModel(currentPath, part);
  44. currentNode.Children.Add(child);
  45. }
  46. currentNode = child;
  47. }
  48. }
  49. return root;
  50. }
  51. // Lists all files in the ProjectSettings directory.
  52. public AssetModel GetProjectSettingsFiles()
  53. {
  54. var settingsRootPath = Path.Combine(ProjectRoot, "ProjectSettings");
  55. var root = new AssetModel(settingsRootPath, "ProjectSettings");
  56. if (Directory.Exists(settingsRootPath))
  57. {
  58. // Filter to only include *.asset files.
  59. var files = Directory.GetFiles(settingsRootPath, "*.asset", SearchOption.AllDirectories);
  60. foreach (var file in files)
  61. {
  62. var relativePath = Path.GetRelativePath(ProjectRoot, file);
  63. root.Children.Add(new AssetModel(relativePath, Path.GetFileName(file)));
  64. }
  65. }
  66. return root;
  67. }
  68. // Scans the entire Assets folder for .meta files and builds a hierarchical model.
  69. public AssetModel GetAllMetaFiles()
  70. {
  71. var assetsRootPath = Application.dataPath; // This is the "Assets" folder
  72. var root = new AssetModel("Assets", "Assets");
  73. var files = Directory.GetFiles(assetsRootPath, "*.meta", SearchOption.AllDirectories);
  74. foreach (var file in files)
  75. {
  76. var relativePath = "Assets/" + Path.GetRelativePath(assetsRootPath, file).Replace('\\', '/');
  77. var parts = relativePath.Split('/');
  78. var currentNode = root;
  79. for (int i = 1; i < parts.Length; i++) // Start at 1 to skip "Assets"
  80. {
  81. var part = parts[i];
  82. var child = currentNode.Children.FirstOrDefault(c => c.Name == part);
  83. if (child == null)
  84. {
  85. var currentPath = string.Join("/", parts.Take(i + 1));
  86. child = new AssetModel(currentPath, part);
  87. currentNode.Children.Add(child);
  88. }
  89. currentNode = child;
  90. }
  91. }
  92. return root;
  93. }
  94. private string FindPythonExecutable()
  95. {
  96. var venvPath = Path.Combine(ProjectRoot, "venv", "bin", "python3");
  97. if (File.Exists(venvPath))
  98. {
  99. return venvPath;
  100. }
  101. venvPath = Path.Combine(ProjectRoot, "venv", "bin", "python");
  102. if (File.Exists(venvPath))
  103. {
  104. return venvPath;
  105. }
  106. return "python3";
  107. }
  108. private string GetConversionScriptPath()
  109. {
  110. var guids = AssetDatabase.FindAssets("convert_scene");
  111. if (guids.Length == 0)
  112. {
  113. UnityEngine.Debug.LogError("Conversion script 'convert_scene.py' not found.");
  114. return null;
  115. }
  116. var path = AssetDatabase.GUIDToAssetPath(guids[0]);
  117. return Path.Combine(ProjectRoot, path);
  118. }
  119. // Executes the Python conversion script for the selected assets.
  120. public void ExportAssets(AssetModel rootNode, string customExportPath = null)
  121. {
  122. var assetsToExport = new List<string>();
  123. CollectSelectedAssets(rootNode, assetsToExport);
  124. var filteredAssets = FilterAssets(assetsToExport);
  125. var pythonExecutable = FindPythonExecutable();
  126. var conversionScript = GetConversionScriptPath();
  127. if (string.IsNullOrEmpty(conversionScript)) return;
  128. var outputDirectory = customExportPath ?? Path.Combine(ProjectRoot, "Library", "ProjectDataExport");
  129. Directory.CreateDirectory(outputDirectory);
  130. var whitelistSettings = ComponentWhitelistSettings.GetOrCreateSettings();
  131. var whitelist = string.Join(",", whitelistSettings.WhitelistedComponents);
  132. EditorUtility.DisplayProgressBar("Exporting...", "Starting export process...", 0f);
  133. try
  134. {
  135. for (int i = 0; i < filteredAssets.Count; i++)
  136. {
  137. var relativeAssetPath = filteredAssets[i];
  138. var progress = (float)i / filteredAssets.Count;
  139. EditorUtility.DisplayProgressBar("Exporting...", $"Processing {Path.GetFileName(relativeAssetPath)}", progress);
  140. var absoluteAssetPath = Path.Combine(ProjectRoot, relativeAssetPath);
  141. var outputJsonPath = Path.Combine(outputDirectory, relativeAssetPath.Replace('/', Path.DirectorySeparatorChar) + ".json");
  142. var fileOutputDir = Path.GetDirectoryName(outputJsonPath);
  143. if (!Directory.Exists(fileOutputDir))
  144. {
  145. Directory.CreateDirectory(fileOutputDir);
  146. }
  147. var arguments =
  148. $"\"{conversionScript}\" \"{absoluteAssetPath}\" \"{outputJsonPath}\" --whitelist \"{whitelist}\"";
  149. var process = new Process
  150. {
  151. StartInfo = new ProcessStartInfo
  152. {
  153. FileName = pythonExecutable,
  154. Arguments = arguments,
  155. RedirectStandardOutput = true,
  156. RedirectStandardError = true,
  157. UseShellExecute = false,
  158. CreateNoWindow = true
  159. }
  160. };
  161. process.Start();
  162. string output = process.StandardOutput.ReadToEnd();
  163. string error = process.StandardError.ReadToEnd();
  164. process.WaitForExit();
  165. if (process.ExitCode != 0)
  166. {
  167. UnityEngine.Debug.LogError($"Error exporting {relativeAssetPath}: {error}");
  168. }
  169. else
  170. {
  171. UnityEngine.Debug.Log($"Successfully exported {relativeAssetPath}: {output}");
  172. }
  173. }
  174. }
  175. finally
  176. {
  177. EditorUtility.ClearProgressBar();
  178. }
  179. }
  180. private List<string> FilterAssets(List<string> assetPaths)
  181. {
  182. if (_settings == null)
  183. {
  184. UnityEngine.Debug.LogWarning("ProjectExporterSettings not found. Skipping filtering.");
  185. return assetPaths;
  186. }
  187. var ignoredFolders = _settings.FoldersToIgnore;
  188. var ignoredExtensions = _settings.FileExtensionsToIgnore.Select(ext => ext.StartsWith(".") ? ext : "." + ext).ToList();
  189. var ignoredUnityTypes = _settings.UnityTypesToIgnore;
  190. var filteredList = new List<string>();
  191. foreach (var path in assetPaths)
  192. {
  193. if (ignoredFolders.Any(folder => path.StartsWith(folder, StringComparison.OrdinalIgnoreCase)))
  194. {
  195. continue;
  196. }
  197. var extension = Path.GetExtension(path);
  198. if (ignoredExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
  199. {
  200. continue;
  201. }
  202. var assetPathForTypeCheck = path.EndsWith(".meta") ? path[..^5] : path;
  203. var assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPathForTypeCheck);
  204. if (assetType != null && IsTypeIgnored(assetType, ignoredUnityTypes))
  205. {
  206. continue;
  207. }
  208. filteredList.Add(path);
  209. }
  210. return filteredList;
  211. }
  212. private bool IsTypeIgnored(Type assetType, List<IgnoredUnityType> ignoredTypes)
  213. {
  214. foreach (var ignoredType in ignoredTypes)
  215. {
  216. if (ignoredType.assetType == UnityAssetType.Custom)
  217. {
  218. if (!string.IsNullOrEmpty(ignoredType.customType) && assetType.Name.Equals(ignoredType.customType, StringComparison.OrdinalIgnoreCase))
  219. {
  220. return true;
  221. }
  222. }
  223. else if (GetSystemTypeForEnum(ignoredType.assetType) == assetType)
  224. {
  225. return true;
  226. }
  227. }
  228. return false;
  229. }
  230. private Type GetSystemTypeForEnum(UnityAssetType unityAssetType)
  231. {
  232. switch (unityAssetType)
  233. {
  234. case UnityAssetType.Animation: return typeof(AnimationClip);
  235. case UnityAssetType.AnimatorController: return typeof(AnimatorController);
  236. case UnityAssetType.AnimatorOverrideController: return typeof(AnimatorOverrideController);
  237. case UnityAssetType.AudioClip: return typeof(AudioClip);
  238. case UnityAssetType.AudioMixer: return typeof(AudioMixer);
  239. case UnityAssetType.ComputeShader: return typeof(ComputeShader);
  240. case UnityAssetType.Font: return typeof(Font);
  241. case UnityAssetType.GUISkin: return typeof(GUISkin);
  242. case UnityAssetType.Material: return typeof(Material);
  243. case UnityAssetType.Mesh: return typeof(Mesh);
  244. case UnityAssetType.Model: return typeof(GameObject);
  245. case UnityAssetType.PhysicMaterial: return typeof(PhysicMaterial);
  246. case UnityAssetType.Prefab: return typeof(GameObject);
  247. case UnityAssetType.Scene: return typeof(SceneAsset);
  248. case UnityAssetType.Script: return typeof(MonoScript);
  249. case UnityAssetType.Shader: return typeof(Shader);
  250. case UnityAssetType.Sprite: return typeof(Sprite);
  251. case UnityAssetType.Texture: return typeof(Texture2D);
  252. case UnityAssetType.VideoClip: return typeof(VideoClip);
  253. case UnityAssetType.RenderTexture: return typeof(RenderTexture);
  254. case UnityAssetType.LightmapParameters: return typeof(LightmapParameters);
  255. default: return null;
  256. }
  257. }
  258. // Recursively collects the paths of all selected assets.
  259. private void CollectSelectedAssets(AssetModel node, List<string> selectedPaths)
  260. {
  261. // If the node itself is a file and is selected, add it.
  262. if (node.Children.Count == 0 && node.IsSelected)
  263. {
  264. selectedPaths.Add(node.Path);
  265. }
  266. // Recurse into children
  267. foreach (var child in node.Children)
  268. {
  269. CollectSelectedAssets(child, selectedPaths);
  270. }
  271. }
  272. }
  273. }