GraphBuilder.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.Collections.Generic;
  2. using IntelligentProjectAnalyzer.Editor.DependencyViewer;
  3. namespace IntelligentProjectAnalyzer.Editor.Graphing
  4. {
  5. public class GraphBuilder
  6. {
  7. private readonly DependencyGraph _dependencyGraph;
  8. private readonly AssetNodeResolver _nodeResolver = new();
  9. public GraphBuilder(DependencyGraph dependencyGraph)
  10. {
  11. _dependencyGraph = dependencyGraph;
  12. }
  13. public SerializableGraph BuildFromRoot(string rootAssetGuid)
  14. {
  15. var graph = new SerializableGraph();
  16. var guidToIndexMap = new Dictionary<string, int>();
  17. var guidsToProcess = new Queue<string>();
  18. var processedGuids = new HashSet<string>();
  19. guidsToProcess.Enqueue(rootAssetGuid);
  20. processedGuids.Add(rootAssetGuid);
  21. while (guidsToProcess.Count > 0)
  22. {
  23. var currentGuid = guidsToProcess.Dequeue();
  24. if (!guidToIndexMap.ContainsKey(currentGuid))
  25. {
  26. var node = AssetNodeResolver.CreateNodeFromGuid(currentGuid);
  27. graph.Nodes.Add(node);
  28. guidToIndexMap[currentGuid] = graph.Nodes.Count - 1;
  29. }
  30. ProcessConnections(currentGuid, guidsToProcess, processedGuids);
  31. }
  32. foreach (var node in graph.Nodes)
  33. {
  34. var sourceIndex = guidToIndexMap[node.Guid];
  35. var dependencies = _dependencyGraph.GetDependencies(node.Guid);
  36. foreach (var dependencyGuid in dependencies)
  37. {
  38. if (guidToIndexMap.TryGetValue(dependencyGuid, out var targetIndex))
  39. {
  40. graph.Links.Add(new GraphLink { Source = sourceIndex, Target = targetIndex });
  41. }
  42. }
  43. }
  44. return graph;
  45. }
  46. private void ProcessConnections(string guid, Queue<string> toProcess, HashSet<string> processed)
  47. {
  48. EnqueueUnprocessed(_dependencyGraph.GetDependencies(guid), toProcess, processed);
  49. EnqueueUnprocessed(_dependencyGraph.GetReferences(guid), toProcess, processed);
  50. }
  51. private void EnqueueUnprocessed(List<string> targetGuids, Queue<string> toProcess, HashSet<string> processed)
  52. {
  53. foreach (var targetGuid in targetGuids)
  54. {
  55. if (processed.Contains(targetGuid)) continue;
  56. toProcess.Enqueue(targetGuid);
  57. processed.Add(targetGuid);
  58. }
  59. }
  60. }
  61. }