#if TOOLS using System.Diagnostics; using Godot.Collections; [Tool] public sealed partial class BehaviorDebugControl : Control { private static readonly PackedScene BehaviorDebugGraphNodeScene = GD.Load("res://addons/BehaviorDebug/behavior_debug_graph_node.tscn"); private GraphEdit _graph = null!; private ItemList _itemList = null!; private int _selectedIndex; public override void _Ready() { _graph = GetNode("%Graph"); _itemList = GetNode("%List"); _itemList.ItemSelected += ItemListOnItemSelected; } private void ItemListOnItemSelected(long index) { _selectedIndex = (int)index; SetTree(_trees[(int)index].tree); } private readonly System.Collections.Generic.List<(ulong instanceId, Dictionary tree)> _trees = []; public void AddTreeData(Array raw) { (ulong instanceId, Dictionary tree) data = (raw[0].AsUInt64(), raw[1].AsGodotDictionary()); var idx = _trees.FindIndex(tuple => tuple.instanceId == data.instanceId); if (idx == -1) { _trees.Add(data); _itemList.AddItem($"{data.instanceId}"); return; } _trees[idx] = data; if (idx == _selectedIndex) { UpdateTree(data.tree); } } private void SetTree(Dictionary data) { for (var i = 0; i < _graph.GetChildCount(); i++) { if (_graph.GetChildOrNull(i) is { } node) node.QueueFree(); } Visit(data); _graph.ArrangeNodes(); return; BehaviorDebugGraphNode Visit(Dictionary btNode, BehaviorDebugGraphNode? parentGraphNode = null) { var graphNode = BehaviorDebugGraphNodeScene.Instantiate(); var btNodeChildren = btNode["children"].As>(); graphNode.SetDescendantCount(btNodeChildren.Count); _graph.AddChild(graphNode); UpdateGraphNode(btNode, graphNode); for (var index = 0; index < btNodeChildren.Count; index++) { var nodeChild = btNodeChildren[index]; var childGraphNode = Visit(nodeChild, graphNode); _graph.ConnectNode(graphNode.Name, index, childGraphNode.Name, 0); } return graphNode; } } private void UpdateTree(Dictionary data) { if (_graph.GetChildCount() == 1) { SetTree(data); return; } var graphEditIndex = 0; Visit(data); return; void Visit(Dictionary btNode) { BehaviorDebugGraphNode graphNode; while (true) { if (graphEditIndex >= _graph.GetChildCount()) throw new UnreachableException(); var inspectedNode = _graph.GetChildOrNull(graphEditIndex); graphEditIndex += 1; if (inspectedNode is not null) { graphNode = inspectedNode; break; } } UpdateGraphNode(btNode, graphNode); var btNodeChildren = btNode["children"].AsGodotArray(); foreach (var btNodeChild in btNodeChildren) Visit(btNodeChild); } } private static void UpdateGraphNode(Dictionary btNode, BehaviorDebugGraphNode graphNode) { var rawName = btNode["name"].As(); var rawType = btNode["type"].As(); var displayName = ( !string.IsNullOrWhiteSpace(rawName) ? rawName : rawType ) switch { "Sequence" => "→", "MemoSequence" => "→*", "Selector" => "?", var other => other, }; graphNode.Title = displayName; graphNode.State = btNode["state"].As(); } } #endif