No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UnitBase.cs 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using Unity.VisualScripting.Dependencies.Sqlite;
  8. using UnityEditor;
  9. using UnityEngine;
  10. namespace Unity.VisualScripting
  11. {
  12. [InitializeAfterPlugins]
  13. public static class UnitBase
  14. {
  15. static UnitBase()
  16. {
  17. staticUnitsExtensions = new NonNullableList<Func<IEnumerable<IUnitOption>>>();
  18. dynamicUnitsExtensions = new NonNullableList<Func<IEnumerable<IUnitOption>>>();
  19. contextualUnitsExtensions = new NonNullableList<Func<GraphReference, IEnumerable<IUnitOption>>>();
  20. BackgroundWorker.Schedule(AutoLoad);
  21. }
  22. private static readonly object @lock = new object();
  23. private static HashSet<IUnitOption> options;
  24. private static void AutoLoad()
  25. {
  26. lock (@lock)
  27. {
  28. // If the fuzzy finder was opened really fast,
  29. // a load operation might already have started.
  30. if (options == null)
  31. {
  32. Load();
  33. }
  34. }
  35. }
  36. private static void Load()
  37. {
  38. if (IsUnitOptionsBuilt())
  39. {
  40. // Update before loading if required, ensuring no "in-between" state
  41. // where the loaded options are not yet loaded.
  42. // The update code will not touch the options array if it is null.
  43. if (BoltFlow.Configuration.updateNodesAutomatically)
  44. {
  45. try
  46. {
  47. ProgressUtility.DisplayProgressBar("Checking for codebase changes...", null, 0);
  48. if (requiresUpdate)
  49. {
  50. Update();
  51. }
  52. }
  53. catch (Exception ex)
  54. {
  55. Debug.LogError($"Failed to update node options.\nRetry with '{UnitOptionUtility.GenerateUnitDatabasePath}'.\n{ex}");
  56. }
  57. finally
  58. {
  59. ProgressUtility.ClearProgressBar();
  60. }
  61. }
  62. lock (@lock)
  63. {
  64. using (ProfilingUtility.SampleBlock("Load Node Database"))
  65. {
  66. using (NativeUtility.Module("sqlite3.dll"))
  67. {
  68. ProgressUtility.DisplayProgressBar("Loading node database...", null, 0);
  69. SQLiteConnection database = null;
  70. try
  71. {
  72. database = new SQLiteConnection(BoltFlow.Paths.unitOptions, SQLiteOpenFlags.ReadOnly);
  73. int total;
  74. total = database.Table<UnitOptionRow>().Count();
  75. var progress = 0f;
  76. options = new HashSet<IUnitOption>();
  77. var failedOptions = new Dictionary<UnitOptionRow, Exception>();
  78. foreach (var row in database.Table<UnitOptionRow>())
  79. {
  80. try
  81. {
  82. var option = row.ToOption();
  83. options.Add(option);
  84. }
  85. catch (Exception rowEx)
  86. {
  87. failedOptions.Add(row, rowEx);
  88. }
  89. ProgressUtility.DisplayProgressBar("Loading node database...", BoltCore.Configuration.humanNaming ? row.labelHuman : row.labelProgrammer, progress++ / total);
  90. }
  91. if (failedOptions.Count > 0)
  92. {
  93. var sb = new StringBuilder();
  94. sb.AppendLine($"{failedOptions.Count} node options failed to load and were skipped.");
  95. sb.AppendLine($"Try rebuilding the node options with '{UnitOptionUtility.GenerateUnitDatabasePath}' to purge outdated nodes.");
  96. sb.AppendLine();
  97. foreach (var failedOption in failedOptions)
  98. {
  99. sb.AppendLine(failedOption.Key.favoriteKey);
  100. }
  101. sb.AppendLine();
  102. foreach (var failedOption in failedOptions)
  103. {
  104. sb.AppendLine(failedOption.Key.favoriteKey + ": ");
  105. sb.AppendLine(failedOption.Value.ToString());
  106. sb.AppendLine();
  107. }
  108. Debug.LogWarning(sb.ToString());
  109. }
  110. }
  111. catch (Exception ex)
  112. {
  113. options = new HashSet<IUnitOption>();
  114. Debug.LogError($"Failed to load node options.\nTry to rebuild them with '{UnitOptionUtility.GenerateUnitDatabasePath}'.\n\n{ex}");
  115. }
  116. finally
  117. {
  118. database?.Close();
  119. //ConsoleProfiler.Dump();
  120. ProgressUtility.ClearProgressBar();
  121. }
  122. }
  123. }
  124. }
  125. }
  126. }
  127. private static bool IsUnitOptionsBuilt()
  128. {
  129. return File.Exists(BoltFlow.Paths.unitOptions);
  130. }
  131. public static void Rebuild()
  132. {
  133. if (IsUnitOptionsBuilt())
  134. {
  135. VersionControlUtility.Unlock(BoltFlow.Paths.unitOptions);
  136. File.Delete(BoltFlow.Paths.unitOptions);
  137. }
  138. Build();
  139. }
  140. public static void Build(bool initialBuild = false)
  141. {
  142. if (IsUnitOptionsBuilt()) return;
  143. if (initialBuild)
  144. {
  145. ProgressUtility.SetTitleOverride("Visual Scripting: Initial Node Generation...");
  146. }
  147. const string progressTitle = "Visual Scripting: Building node database...";
  148. lock (@lock)
  149. {
  150. using (ProfilingUtility.SampleBlock("Update Node Database"))
  151. {
  152. using (NativeUtility.Module("sqlite3.dll"))
  153. {
  154. SQLiteConnection database = null;
  155. try
  156. {
  157. ProgressUtility.DisplayProgressBar(progressTitle, "Creating database...", 0);
  158. PathUtility.CreateParentDirectoryIfNeeded(BoltFlow.Paths.unitOptions);
  159. database = new SQLiteConnection(BoltFlow.Paths.unitOptions);
  160. database.CreateTable<UnitOptionRow>();
  161. ProgressUtility.DisplayProgressBar(progressTitle, "Updating codebase...", 0);
  162. UpdateCodebase();
  163. ProgressUtility.DisplayProgressBar(progressTitle, "Updating type mappings...", 0);
  164. UpdateTypeMappings();
  165. ProgressUtility.DisplayProgressBar(progressTitle,
  166. "Converting codebase to node options...", 0);
  167. options = new HashSet<IUnitOption>(GetStaticOptions());
  168. var rows = new HashSet<UnitOptionRow>();
  169. var progress = 0;
  170. var lastShownProgress = 0f;
  171. foreach (var option in options)
  172. {
  173. try
  174. {
  175. var shownProgress = (float)progress / options.Count;
  176. if (shownProgress > lastShownProgress + 0.01f)
  177. {
  178. ProgressUtility.DisplayProgressBar(progressTitle,
  179. "Converting codebase to node options...", shownProgress);
  180. lastShownProgress = shownProgress;
  181. }
  182. rows.Add(option.Serialize());
  183. }
  184. catch (Exception ex)
  185. {
  186. Debug.LogError($"Failed to save option '{option.GetType()}'.\n{ex}");
  187. }
  188. progress++;
  189. }
  190. ProgressUtility.DisplayProgressBar(progressTitle, "Writing to database...", 1);
  191. try
  192. {
  193. database.CreateTable<UnitOptionRow>();
  194. database.InsertAll(rows);
  195. }
  196. catch (Exception ex)
  197. {
  198. Debug.LogError($"Failed to write options to database.\n{ex}");
  199. }
  200. }
  201. finally
  202. {
  203. database?.Close();
  204. ProgressUtility.ClearProgressBar();
  205. ProgressUtility.ClearTitleOverride();
  206. AssetDatabase.Refresh();
  207. //ConsoleProfiler.Dump();
  208. }
  209. }
  210. }
  211. }
  212. }
  213. public static void Update()
  214. {
  215. if (!IsUnitOptionsBuilt())
  216. {
  217. Build();
  218. return;
  219. }
  220. lock (@lock)
  221. {
  222. using (ProfilingUtility.SampleBlock("Update Node Database"))
  223. {
  224. using (NativeUtility.Module("sqlite3.dll"))
  225. {
  226. var progressTitle = "Updating node database...";
  227. SQLiteConnection database = null;
  228. try
  229. {
  230. VersionControlUtility.Unlock(BoltFlow.Paths.unitOptions);
  231. var steps = 7f;
  232. var step = 0f;
  233. ProgressUtility.DisplayProgressBar(progressTitle, "Connecting to database...", step++ / steps);
  234. database = new SQLiteConnection(BoltFlow.Paths.unitOptions);
  235. ProgressUtility.DisplayProgressBar(progressTitle, "Updating type mappings...", step++ / steps);
  236. UpdateTypeMappings();
  237. ProgressUtility.DisplayProgressBar(progressTitle, "Fetching modified scripts...", step++ / steps);
  238. var modifiedScriptGuids = GetModifiedScriptGuids().Distinct().ToHashSet();
  239. ProgressUtility.DisplayProgressBar(progressTitle, "Fetching deleted scripts...", step++ / steps);
  240. var deletedScriptGuids = GetDeletedScriptGuids().Distinct().ToHashSet();
  241. ProgressUtility.DisplayProgressBar(progressTitle, "Updating codebase...", step++ / steps);
  242. var modifiedScriptTypes = modifiedScriptGuids.SelectMany(GetScriptTypes).ToArray();
  243. UpdateCodebase(modifiedScriptTypes);
  244. var outdatedScriptGuids = new HashSet<string>();
  245. outdatedScriptGuids.UnionWith(modifiedScriptGuids);
  246. outdatedScriptGuids.UnionWith(deletedScriptGuids);
  247. ProgressUtility.DisplayProgressBar(progressTitle, "Removing outdated node options...", step++ / steps);
  248. options?.RemoveWhere(option => outdatedScriptGuids.Overlaps(option.sourceScriptGuids));
  249. // We want to use the database level WHERE here for speed,
  250. // so we'll run multiple queries, one for each outdated script GUID.
  251. foreach (var outdatedScriptGuid in outdatedScriptGuids)
  252. {
  253. foreach (var outdatedRowId in database.Table<UnitOptionRow>()
  254. .Where(row => row.sourceScriptGuids.Contains(outdatedScriptGuid))
  255. .Select(row => row.id))
  256. {
  257. database.Delete<UnitOptionRow>(outdatedRowId);
  258. }
  259. }
  260. ProgressUtility.DisplayProgressBar(progressTitle, "Converting codebase to node options...", step++ / steps);
  261. var newOptions = new HashSet<IUnitOption>(modifiedScriptGuids.SelectMany(GetScriptTypes)
  262. .Distinct()
  263. .SelectMany(GetIncrementalOptions));
  264. var rows = new HashSet<UnitOptionRow>();
  265. float progress = 0;
  266. foreach (var newOption in newOptions)
  267. {
  268. options?.Add(newOption);
  269. try
  270. {
  271. ProgressUtility.DisplayProgressBar(progressTitle, newOption.label, (step / steps) + ((1 / step) * (progress / newOptions.Count)));
  272. rows.Add(newOption.Serialize());
  273. }
  274. catch (Exception ex)
  275. {
  276. Debug.LogError($"Failed to serialize option '{newOption.GetType()}'.\n{ex}");
  277. }
  278. progress++;
  279. }
  280. ProgressUtility.DisplayProgressBar(progressTitle, "Writing to database...", 1);
  281. try
  282. {
  283. database.InsertAll(rows);
  284. }
  285. catch (Exception ex)
  286. {
  287. Debug.LogError($"Failed to write options to database.\n{ex}");
  288. }
  289. // Make sure the database is touched to the current date,
  290. // even if we didn't do any change. This will avoid unnecessary
  291. // analysis in future update checks.
  292. File.SetLastWriteTimeUtc(BoltFlow.Paths.unitOptions, DateTime.UtcNow);
  293. }
  294. finally
  295. {
  296. database?.Close();
  297. ProgressUtility.ClearProgressBar();
  298. UnityAPI.Async(AssetDatabase.Refresh);
  299. //ConsoleProfiler.Dump();
  300. }
  301. }
  302. }
  303. }
  304. }
  305. public static IEnumerable<IUnitOption> Subset(UnitOptionFilter filter, GraphReference reference)
  306. {
  307. lock (@lock)
  308. {
  309. if (options == null)
  310. {
  311. Load();
  312. }
  313. var dynamicOptions = UnityAPI.Await(() => GetDynamicOptions().ToHashSet());
  314. var contextualOptions = UnityAPI.Await(() => GetContextualOptions(reference).ToHashSet());
  315. return LinqUtility.Concat<IUnitOption>(options, dynamicOptions, contextualOptions)
  316. .Where((filter ?? UnitOptionFilter.Any).ValidateOption)
  317. .ToArray();
  318. }
  319. }
  320. #region Units
  321. private static CodebaseSubset codebase;
  322. private static void UpdateCodebase(IEnumerable<Type> typeSet = null)
  323. {
  324. using var profilerScope = ProfilingUtility.SampleBlock("UpdateCodebase");
  325. if (typeSet == null)
  326. {
  327. typeSet = Codebase.settingsTypes;
  328. }
  329. else
  330. {
  331. typeSet = typeSet.Where(t => Codebase.settingsTypes.Contains(t));
  332. }
  333. Codebase.UpdateSettings();
  334. codebase = Codebase.Subset(typeSet, TypeFilter.Any.Configured(), MemberFilter.Any.Configured(), TypeFilter.Any.Configured(false));
  335. codebase.Cache();
  336. }
  337. private static IEnumerable<IUnitOption> GetStaticOptions()
  338. {
  339. // Standalones
  340. foreach (var unit in Codebase.ludiqRuntimeTypes.Where(t => typeof(IUnit).IsAssignableFrom(t) &&
  341. t.IsConcrete() &&
  342. t.GetDefaultConstructor() != null &&
  343. !t.HasAttribute<SpecialUnitAttribute>() &&
  344. (EditorPlatformUtility.allowJit || !t.HasAttribute<AotIncompatibleAttribute>()) &&
  345. t.GetDefaultConstructor() != null)
  346. .Select(t => (IUnit)t.Instantiate()))
  347. {
  348. yield return unit.Option();
  349. }
  350. // Self
  351. yield return new This().Option();
  352. // Types
  353. foreach (var type in codebase.types)
  354. {
  355. foreach (var typeOption in GetTypeOptions(type))
  356. {
  357. yield return typeOption;
  358. }
  359. }
  360. // Members
  361. foreach (var member in codebase.members)
  362. {
  363. foreach (var memberOption in GetMemberOptions(member))
  364. {
  365. yield return memberOption;
  366. }
  367. }
  368. // Events
  369. foreach (var eventType in Codebase.ludiqRuntimeTypes.Where(t => typeof(IEventUnit).IsAssignableFrom(t) && t.IsConcrete()))
  370. {
  371. yield return ((IEventUnit)eventType.Instantiate()).Option();
  372. }
  373. // Blank Variables
  374. yield return new GetVariableOption(VariableKind.Flow);
  375. yield return new GetVariableOption(VariableKind.Graph);
  376. yield return new GetVariableOption(VariableKind.Object);
  377. yield return new GetVariableOption(VariableKind.Scene);
  378. yield return new GetVariableOption(VariableKind.Application);
  379. yield return new GetVariableOption(VariableKind.Saved);
  380. yield return new SetVariableOption(VariableKind.Flow);
  381. yield return new SetVariableOption(VariableKind.Graph);
  382. yield return new SetVariableOption(VariableKind.Object);
  383. yield return new SetVariableOption(VariableKind.Scene);
  384. yield return new SetVariableOption(VariableKind.Application);
  385. yield return new SetVariableOption(VariableKind.Saved);
  386. yield return new IsVariableDefinedOption(VariableKind.Flow);
  387. yield return new IsVariableDefinedOption(VariableKind.Graph);
  388. yield return new IsVariableDefinedOption(VariableKind.Object);
  389. yield return new IsVariableDefinedOption(VariableKind.Scene);
  390. yield return new IsVariableDefinedOption(VariableKind.Application);
  391. yield return new IsVariableDefinedOption(VariableKind.Saved);
  392. // Blank Super Unit
  393. yield return SubgraphUnit.WithInputOutput().Option();
  394. // Extensions
  395. foreach (var staticUnitsExtension in staticUnitsExtensions)
  396. {
  397. foreach (var extensionStaticUnit in staticUnitsExtension())
  398. {
  399. yield return extensionStaticUnit;
  400. }
  401. }
  402. }
  403. private static IEnumerable<IUnitOption> GetIncrementalOptions(Type type)
  404. {
  405. if (!codebase.ValidateType(type))
  406. {
  407. yield break;
  408. }
  409. foreach (var typeOption in GetTypeOptions(type))
  410. {
  411. yield return typeOption;
  412. }
  413. foreach (var member in codebase.FilterMembers(type))
  414. {
  415. foreach (var memberOption in GetMemberOptions(member))
  416. {
  417. yield return memberOption;
  418. }
  419. }
  420. }
  421. private static IEnumerable<IUnitOption> GetTypeOptions(Type type)
  422. {
  423. if (type == typeof(object))
  424. {
  425. yield break;
  426. }
  427. // Struct Initializer
  428. if (type.IsStruct())
  429. {
  430. yield return new CreateStruct(type).Option();
  431. }
  432. // Literals
  433. if (type.HasInspector())
  434. {
  435. yield return new Literal(type).Option();
  436. if (EditorPlatformUtility.allowJit)
  437. {
  438. var listType = typeof(List<>).MakeGenericType(type);
  439. yield return new Literal(listType).Option();
  440. }
  441. }
  442. // Exposes
  443. if (!type.IsEnum)
  444. {
  445. yield return new Expose(type).Option();
  446. }
  447. }
  448. private static IEnumerable<IUnitOption> GetMemberOptions(Member member)
  449. {
  450. // Operators are handled with special math units
  451. // that are more elegant than the raw methods
  452. if (member.isOperator)
  453. {
  454. yield break;
  455. }
  456. // Conversions are handled automatically by connections
  457. if (member.isConversion)
  458. {
  459. yield break;
  460. }
  461. if (member.isAccessor)
  462. {
  463. if (member.isPubliclyGettable)
  464. {
  465. yield return new GetMember(member).Option();
  466. }
  467. if (member.isPubliclySettable)
  468. {
  469. yield return new SetMember(member).Option();
  470. }
  471. }
  472. else if (member.isPubliclyInvocable)
  473. {
  474. yield return new InvokeMember(member).Option();
  475. }
  476. }
  477. private static IEnumerable<IUnitOption> GetDynamicOptions()
  478. {
  479. // Super Units
  480. var flowMacros = AssetUtility.GetAllAssetsOfType<ScriptGraphAsset>().ToArray();
  481. foreach (var superUnit in flowMacros.Select(flowMacro => new SubgraphUnit(flowMacro)))
  482. {
  483. yield return superUnit.Option();
  484. }
  485. // Extensions
  486. foreach (var dynamicUnitsExtension in dynamicUnitsExtensions)
  487. {
  488. foreach (var extensionDynamicUnit in dynamicUnitsExtension())
  489. {
  490. yield return extensionDynamicUnit;
  491. }
  492. }
  493. }
  494. private static IEnumerable<IUnitOption> GetContextualOptions(GraphReference reference)
  495. {
  496. foreach (var variableKind in Enum.GetValues(typeof(VariableKind)).Cast<VariableKind>())
  497. {
  498. foreach (var graphVariableName in EditorVariablesUtility.GetVariableNameSuggestions(variableKind, reference))
  499. {
  500. yield return new GetVariableOption(variableKind, graphVariableName);
  501. yield return new SetVariableOption(variableKind, graphVariableName);
  502. yield return new IsVariableDefinedOption(variableKind, graphVariableName);
  503. }
  504. }
  505. // Extensions
  506. foreach (var contextualUnitsExtension in contextualUnitsExtensions)
  507. {
  508. foreach (var extensionContextualUnitOption in contextualUnitsExtension(reference))
  509. {
  510. yield return extensionContextualUnitOption;
  511. }
  512. }
  513. }
  514. #endregion
  515. #region Scripts
  516. private static Dictionary<Type, HashSet<string>> typesToGuids;
  517. private static Dictionary<string, HashSet<Type>> guidsToTypes;
  518. private static void UpdateTypeMappings()
  519. {
  520. using var profilerScope = ProfilingUtility.SampleBlock("UpdateTypeMappings");
  521. typesToGuids = new Dictionary<Type, HashSet<string>>();
  522. guidsToTypes = new Dictionary<string, HashSet<Type>>();
  523. UnityAPI.AwaitForever(() =>
  524. {
  525. foreach (var script in UnityEngine.Resources.FindObjectsOfTypeAll<MonoScript>())
  526. {
  527. var type = script.GetClass();
  528. // Skip scripts without types
  529. if (type == null)
  530. {
  531. continue;
  532. }
  533. var path = AssetDatabase.GetAssetPath(script);
  534. // Skip built-in Unity plugins, which are referenced by full path
  535. if (!path.StartsWith("Assets"))
  536. {
  537. continue;
  538. }
  539. var guid = AssetDatabase.AssetPathToGUID(path);
  540. // Add the GUID to the list, even if it doesn't have any type
  541. if (!guidsToTypes.ContainsKey(guid))
  542. {
  543. guidsToTypes.Add(guid, new HashSet<Type>());
  544. }
  545. if (!typesToGuids.ContainsKey(type))
  546. {
  547. typesToGuids.Add(type, new HashSet<string>());
  548. }
  549. typesToGuids[type].Add(guid);
  550. guidsToTypes[guid].Add(type);
  551. }
  552. });
  553. }
  554. public static IEnumerable<string> GetScriptGuids(Type type)
  555. {
  556. if (typesToGuids == null)
  557. {
  558. UpdateTypeMappings();
  559. }
  560. using (var recursion = Recursion.New(1))
  561. {
  562. return GetScriptGuids(recursion, type).ToArray(); // No delayed execution for recursion disposal
  563. }
  564. }
  565. private static IEnumerable<string> GetScriptGuids(Recursion recursion, Type type)
  566. {
  567. if (!recursion?.TryEnter(type) ?? false)
  568. {
  569. yield break;
  570. }
  571. if (typesToGuids.ContainsKey(type))
  572. {
  573. foreach (var guid in typesToGuids[type])
  574. {
  575. yield return guid;
  576. }
  577. }
  578. // Loop through generic arguments.
  579. // For example, a List<Enemy> type should return the script GUID for Enemy.
  580. if (type.IsGenericType)
  581. {
  582. foreach (var genericArgument in type.GetGenericArguments())
  583. {
  584. foreach (var genericGuid in GetScriptGuids(recursion, genericArgument))
  585. {
  586. yield return genericGuid;
  587. }
  588. }
  589. }
  590. }
  591. public static IEnumerable<Type> GetScriptTypes(string guid)
  592. {
  593. if (guidsToTypes == null)
  594. {
  595. UpdateTypeMappings();
  596. }
  597. if (guidsToTypes.ContainsKey(guid))
  598. {
  599. return guidsToTypes[guid];
  600. }
  601. else
  602. {
  603. return Enumerable.Empty<Type>();
  604. }
  605. }
  606. private static bool requiresUpdate => GetModifiedScriptGuids().Any() || GetDeletedScriptGuids().Any();
  607. private static IEnumerable<string> GetModifiedScriptGuids()
  608. {
  609. var guids = new HashSet<string>();
  610. UnityAPI.AwaitForever(() =>
  611. {
  612. var databaseTimestamp = File.GetLastWriteTimeUtc(BoltFlow.Paths.unitOptions);
  613. foreach (var script in UnityEngine.Resources.FindObjectsOfTypeAll<MonoScript>())
  614. {
  615. var path = AssetDatabase.GetAssetPath(script);
  616. var guid = AssetDatabase.AssetPathToGUID(path);
  617. // Skip built-in Unity plugins, which are referenced by full path
  618. if (!path.StartsWith("Assets"))
  619. {
  620. continue;
  621. }
  622. var scriptTimestamp = File.GetLastWriteTimeUtc(Path.Combine(Paths.project, path));
  623. if (scriptTimestamp > databaseTimestamp)
  624. {
  625. guids.Add(guid);
  626. }
  627. }
  628. });
  629. return guids;
  630. }
  631. private static IEnumerable<string> GetDeletedScriptGuids()
  632. {
  633. if (!IsUnitOptionsBuilt())
  634. {
  635. return Enumerable.Empty<string>();
  636. }
  637. using (NativeUtility.Module("sqlite3.dll"))
  638. {
  639. SQLiteConnection database = null;
  640. try
  641. {
  642. HashSet<string> databaseGuids;
  643. lock (@lock)
  644. {
  645. database = new SQLiteConnection(BoltFlow.Paths.unitOptions);
  646. databaseGuids = database.Query<UnitOptionRow>($"SELECT DISTINCT {nameof(UnitOptionRow.sourceScriptGuids)} FROM {nameof(UnitOptionRow)}")
  647. .Select(row => row.sourceScriptGuids)
  648. .NotNull()
  649. .SelectMany(guids => guids.Split(','))
  650. .ToHashSet();
  651. }
  652. var assetGuids = UnityAPI.AwaitForever(() => UnityEngine.Resources
  653. .FindObjectsOfTypeAll<MonoScript>()
  654. .Where(script => script.GetClass() != null)
  655. .Select(script => AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(script)))
  656. .ToHashSet());
  657. databaseGuids.ExceptWith(assetGuids);
  658. return databaseGuids;
  659. }
  660. finally
  661. {
  662. database?.Close();
  663. }
  664. }
  665. }
  666. #endregion
  667. #region Extensions
  668. public static NonNullableList<Func<IEnumerable<IUnitOption>>> staticUnitsExtensions { get; }
  669. public static NonNullableList<Func<IEnumerable<IUnitOption>>> dynamicUnitsExtensions { get; }
  670. public static NonNullableList<Func<GraphReference, IEnumerable<IUnitOption>>> contextualUnitsExtensions { get; }
  671. #endregion
  672. #region Duplicates
  673. public static IEnumerable<T> WithoutInheritedDuplicates<T>(this IEnumerable<T> items, Func<T, IUnitOption> optionSelector, CancellationToken cancellation)
  674. {
  675. // Doing everything we can to avoid reflection here, as it then becomes the main search bottleneck
  676. var _items = items.ToArray();
  677. var pseudoDeclarers = new HashSet<Member>();
  678. foreach (var item in _items.Cancellable(cancellation))
  679. {
  680. var option = optionSelector(item);
  681. if (option is IMemberUnitOption memberOption)
  682. {
  683. if (memberOption.targetType == memberOption.pseudoDeclarer.targetType)
  684. {
  685. pseudoDeclarers.Add(memberOption.pseudoDeclarer);
  686. }
  687. }
  688. }
  689. foreach (var item in _items.Cancellable(cancellation))
  690. {
  691. var option = optionSelector(item);
  692. if (option is IMemberUnitOption memberOption)
  693. {
  694. if (pseudoDeclarers.Contains(memberOption.member) || !pseudoDeclarers.Contains(memberOption.pseudoDeclarer))
  695. {
  696. yield return item;
  697. }
  698. }
  699. else
  700. {
  701. yield return item;
  702. }
  703. }
  704. }
  705. #endregion
  706. }
  707. }