dancer-godot/addons/BehaviorDebug/BehaviorDebugControl.cs

122 lines
2.9 KiB
C#

#if TOOLS
using System.Diagnostics;
using System.Linq;
using Godot.Collections;
namespace Dancer;
[Tool]
public sealed partial class BehaviorDebugControl : Control
{
private Tree _tree = null!;
private ItemList _itemList = null!;
private int _selectedIndex;
public override void _Ready()
{
_tree = GetNode<Tree>("%Tree");
_itemList = GetNode<ItemList>("%List");
_tree.Columns = 2;
_tree.SetColumnTitle(0, "Node");
_tree.SetColumnTitle(1, "State");
_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)
{
_tree.GetRoot()?.Free();
Visit(data);
return;
void Visit(Dictionary node, TreeItem? parent = null)
{
var item = _tree.CreateItem(parent);
UpdateTreeItem(node, item);
foreach (var nodeChild in node["children"].As<Array<Dictionary>>()) Visit(nodeChild, item);
}
}
private void UpdateTree(Dictionary data)
{
if (_tree.GetRoot() is not { } root)
{
SetTree(data);
return;
}
Visit(data, root);
return;
void Visit(Dictionary node, TreeItem item)
{
UpdateTreeItem(node, item);
var dataChildren = node["children"].AsGodotArray<Dictionary>();
for (var i = 0; i < dataChildren.Count; i++)
{
Visit(dataChildren[i], item.GetChild(i));
}
}
}
private static void UpdateTreeItem(Dictionary node, TreeItem item)
{
var rawName = node["name"].As<string>();
var rawType = node["type"].As<string>();
var displayName = (
!string.IsNullOrWhiteSpace(rawName)
? rawName
: rawType
)
switch
{
"Sequence" => "→",
"MemoSequence" => "→*",
"Selector" => "?",
var other => other,
};
item.SetText(0, displayName);
var state = node["state"].As<string>();
var bgColor = state switch
{
"Idle" => Color.FromOkHsl(.653f, .3f, .2f),
"Running" => Color.FromOkHsl(.222f, .7f, .3f),
"Success" => Color.FromOkHsl(.375f, .3f, .2f),
"Failure" => Color.FromOkHsl(.055f, .3f, .2f),
_ => throw new UnreachableException(),
};
item.SetCustomBgColor(1, bgColor);
item.SetCustomColor(1, Colors.AntiqueWhite);
item.SetText(1, state);
}
}
#endif