ProjectExporterController.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. using System.Collections.Generic;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using UnityEditor;
  6. using UnityEngine;
  7. using AssetBank.Editor.ProjectExporter;
  8. using System;
  9. using UnityEditor.Animations;
  10. using UnityEngine.Audio;
  11. using UnityEngine.Video;
  12. namespace ProjectExporter
  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 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 exportType)
  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 = Path.Combine(ProjectRoot, "Library", "ProjectDataExport");
  129. Directory.CreateDirectory(outputDirectory);
  130. EditorUtility.DisplayProgressBar("Exporting...", "Starting export process...", 0f);
  131. try
  132. {
  133. for (int i = 0; i < filteredAssets.Count; i++)
  134. {
  135. var relativeAssetPath = filteredAssets[i];
  136. var progress = (float)i / filteredAssets.Count;
  137. EditorUtility.DisplayProgressBar("Exporting...", $"Processing {Path.GetFileName(relativeAssetPath)}", progress);
  138. var absoluteAssetPath = Path.Combine(ProjectRoot, relativeAssetPath);
  139. var outputJsonPath = Path.Combine(outputDirectory, relativeAssetPath.Replace('/', Path.DirectorySeparatorChar) + ".json");
  140. var fileOutputDir = Path.GetDirectoryName(outputJsonPath);
  141. if (!Directory.Exists(fileOutputDir))
  142. {
  143. Directory.CreateDirectory(fileOutputDir);
  144. }
  145. var process = new Process
  146. {
  147. StartInfo = new ProcessStartInfo
  148. {
  149. FileName = pythonExecutable,
  150. Arguments = $"\"{conversionScript}\" \"{absoluteAssetPath}\" \"{outputJsonPath}\"",
  151. RedirectStandardOutput = true,
  152. RedirectStandardError = true,
  153. UseShellExecute = false,
  154. CreateNoWindow = true
  155. }
  156. };
  157. process.Start();
  158. string output = process.StandardOutput.ReadToEnd();
  159. string error = process.StandardError.ReadToEnd();
  160. process.WaitForExit();
  161. if (process.ExitCode != 0)
  162. {
  163. UnityEngine.Debug.LogError($"Error exporting {relativeAssetPath}: {error}");
  164. }
  165. else
  166. {
  167. UnityEngine.Debug.Log($"Successfully exported {relativeAssetPath}: {output}");
  168. }
  169. }
  170. }
  171. finally
  172. {
  173. EditorUtility.ClearProgressBar();
  174. }
  175. }
  176. private List<string> FilterAssets(List<string> assetPaths)
  177. {
  178. if (_settings == null)
  179. {
  180. UnityEngine.Debug.LogWarning("ProjectExporterSettings not found. Skipping filtering.");
  181. return assetPaths;
  182. }
  183. var ignoredFolders = _settings.FoldersToIgnore;
  184. var ignoredExtensions = _settings.FileExtensionsToIgnore.Select(ext => ext.StartsWith(".") ? ext : "." + ext).ToList();
  185. var ignoredUnityTypes = _settings.UnityTypesToIgnore;
  186. var filteredList = new List<string>();
  187. foreach (var path in assetPaths)
  188. {
  189. if (ignoredFolders.Any(folder => path.StartsWith(folder, StringComparison.OrdinalIgnoreCase)))
  190. {
  191. continue;
  192. }
  193. var extension = Path.GetExtension(path);
  194. if (ignoredExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
  195. {
  196. continue;
  197. }
  198. var assetPathForTypeCheck = path.EndsWith(".meta") ? path[..^5] : path;
  199. var assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPathForTypeCheck);
  200. if (assetType != null && IsTypeIgnored(assetType, ignoredUnityTypes))
  201. {
  202. continue;
  203. }
  204. filteredList.Add(path);
  205. }
  206. return filteredList;
  207. }
  208. private bool IsTypeIgnored(Type assetType, List<IgnoredUnityType> ignoredTypes)
  209. {
  210. foreach (var ignoredType in ignoredTypes)
  211. {
  212. if (ignoredType.assetType == UnityAssetType.Custom)
  213. {
  214. if (!string.IsNullOrEmpty(ignoredType.customType) && assetType.Name.Equals(ignoredType.customType, StringComparison.OrdinalIgnoreCase))
  215. {
  216. return true;
  217. }
  218. }
  219. else if (GetSystemTypeForEnum(ignoredType.assetType) == assetType)
  220. {
  221. return true;
  222. }
  223. }
  224. return false;
  225. }
  226. private Type GetSystemTypeForEnum(UnityAssetType unityAssetType)
  227. {
  228. switch (unityAssetType)
  229. {
  230. case UnityAssetType.Animation: return typeof(AnimationClip);
  231. case UnityAssetType.AnimatorController: return typeof(AnimatorController);
  232. case UnityAssetType.AnimatorOverrideController: return typeof(AnimatorOverrideController);
  233. case UnityAssetType.AudioClip: return typeof(AudioClip);
  234. case UnityAssetType.AudioMixer: return typeof(AudioMixer);
  235. case UnityAssetType.ComputeShader: return typeof(ComputeShader);
  236. case UnityAssetType.Font: return typeof(Font);
  237. case UnityAssetType.GUISkin: return typeof(GUISkin);
  238. case UnityAssetType.Material: return typeof(Material);
  239. case UnityAssetType.Mesh: return typeof(Mesh);
  240. case UnityAssetType.Model: return typeof(GameObject);
  241. case UnityAssetType.PhysicMaterial: return typeof(PhysicMaterial);
  242. case UnityAssetType.Prefab: return typeof(GameObject);
  243. case UnityAssetType.Scene: return typeof(SceneAsset);
  244. case UnityAssetType.Script: return typeof(MonoScript);
  245. case UnityAssetType.Shader: return typeof(Shader);
  246. case UnityAssetType.Sprite: return typeof(Sprite);
  247. case UnityAssetType.Texture: return typeof(Texture2D);
  248. case UnityAssetType.VideoClip: return typeof(VideoClip);
  249. case UnityAssetType.RenderTexture: return typeof(RenderTexture);
  250. case UnityAssetType.LightmapParameters: return typeof(LightmapParameters);
  251. default: return null;
  252. }
  253. }
  254. // Recursively collects the paths of all selected assets.
  255. private void CollectSelectedAssets(AssetModel node, List<string> selectedPaths)
  256. {
  257. // If the node itself is a file and is selected, add it.
  258. if (node.Children.Count == 0 && node.IsSelected)
  259. {
  260. selectedPaths.Add(node.Path);
  261. }
  262. // Recurse into children
  263. foreach (var child in node.Children)
  264. {
  265. CollectSelectedAssets(child, selectedPaths);
  266. }
  267. }
  268. }
  269. }