tree based bt debugger
This commit is contained in:
parent
c9967f09d9
commit
b5d5a8f9f3
12 changed files with 271 additions and 19 deletions
|
|
@ -31,4 +31,7 @@
|
|||
<TrimmerRootAssembly Include="GodotSharp" />
|
||||
<TrimmerRootAssembly Include="$(TargetName)" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="addons\BehaviorDebug\behavior_debug_dock.tscn" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
|
|
|||
38
addons/BehaviorDebug/BehaviorDebug.cs
Normal file
38
addons/BehaviorDebug/BehaviorDebug.cs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
#if TOOLS
|
||||
|
||||
using Dancer;
|
||||
using Godot.Collections;
|
||||
|
||||
[Tool]
|
||||
public partial class BehaviorDebug : EditorPlugin
|
||||
{
|
||||
private BtEditorDebugger _btEditorDebugger = new BtEditorDebugger();
|
||||
|
||||
public override void _EnterTree() => AddDebuggerPlugin(_btEditorDebugger);
|
||||
public override void _ExitTree() => RemoveDebuggerPlugin(_btEditorDebugger);
|
||||
|
||||
private partial class BtEditorDebugger : EditorDebuggerPlugin
|
||||
{
|
||||
private BehaviorDebugControl? _behaviorTreeView1;
|
||||
private static readonly PackedScene DebuggerScene = GD.Load<PackedScene>("res://addons/BehaviorDebug/behavior_debug_dock.tscn");
|
||||
public override bool _HasCapture(string capture) => capture == "behavior_debug";
|
||||
public override bool _Capture(string message, Array data, int sessionId)
|
||||
{
|
||||
if (message == "behavior_debug:add_tree")
|
||||
{
|
||||
_behaviorTreeView1?.AddTreeData(data);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public override void _SetupSession(int sessionId)
|
||||
{
|
||||
_behaviorTreeView1 = DebuggerScene.Instantiate<BehaviorDebugControl>();
|
||||
_behaviorTreeView1.Name = "Behavior Trees";
|
||||
var session = GetSession(sessionId);
|
||||
session.AddSessionTab(_behaviorTreeView1);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
1
addons/BehaviorDebug/BehaviorDebug.cs.uid
Normal file
1
addons/BehaviorDebug/BehaviorDebug.cs.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://c020bo6cuy6cd
|
||||
122
addons/BehaviorDebug/BehaviorDebugControl.cs
Normal file
122
addons/BehaviorDebug/BehaviorDebugControl.cs
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
#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
|
||||
1
addons/BehaviorDebug/BehaviorDebugControl.cs.uid
Normal file
1
addons/BehaviorDebug/BehaviorDebugControl.cs.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://btd3yxqnv5nhw
|
||||
23
addons/BehaviorDebug/behavior_debug_dock.tscn
Normal file
23
addons/BehaviorDebug/behavior_debug_dock.tscn
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
[gd_scene format=3 uid="uid://b8j1734h5i2ve"]
|
||||
|
||||
[ext_resource type="Script" uid="uid://btd3yxqnv5nhw" path="res://addons/BehaviorDebug/BehaviorDebugControl.cs" id="1_6f7wn"]
|
||||
|
||||
[node name="HSplitContainer" type="HSplitContainer" unique_id=381231242]
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
split_offsets = PackedInt32Array(200)
|
||||
split_offset = 200
|
||||
script = ExtResource("1_6f7wn")
|
||||
|
||||
[node name="List" type="ItemList" parent="." unique_id=664607271]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
|
||||
[node name="Tree" type="Tree" parent="." unique_id=1995434049]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
columns = 2
|
||||
column_titles_visible = true
|
||||
7
addons/BehaviorDebug/plugin.cfg
Normal file
7
addons/BehaviorDebug/plugin.cfg
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
[plugin]
|
||||
|
||||
name="BehaviorDebug"
|
||||
description=""
|
||||
author="blossomfiend"
|
||||
version="1.0"
|
||||
script="BehaviorDebug.cs"
|
||||
|
|
@ -34,7 +34,7 @@ project/assembly_name="Dancer"
|
|||
|
||||
[editor_plugins]
|
||||
|
||||
enabled=PackedStringArray("res://addons/AsepriteWizard/plugin.cfg", "res://addons/TileMapDual/plugin.cfg")
|
||||
enabled=PackedStringArray("res://addons/AsepriteWizard/plugin.cfg", "res://addons/BehaviorDebug/plugin.cfg", "res://addons/TileMapDual/plugin.cfg")
|
||||
|
||||
[input]
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ using System;
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using Chickensoft.Collections;
|
||||
|
||||
namespace Dancer.Behavior;
|
||||
|
|
@ -27,6 +28,8 @@ public sealed class Tree(Node root)
|
|||
}
|
||||
|
||||
public void Halt() => Root.Halt();
|
||||
|
||||
public Godot.Collections.Dictionary DebugData => Root.DebugData;
|
||||
}
|
||||
|
||||
public enum Result
|
||||
|
|
@ -44,9 +47,12 @@ public enum NodeState
|
|||
Failure,
|
||||
}
|
||||
|
||||
[Tool]
|
||||
public abstract class Node
|
||||
{
|
||||
public NodeState State { get; private set; } = NodeState.Idle;
|
||||
public virtual Node[] Children => [];
|
||||
public virtual string? Name { get; init; }
|
||||
|
||||
public Result Tick(in Context context)
|
||||
{
|
||||
|
|
@ -90,6 +96,16 @@ public abstract class Node
|
|||
protected virtual void OnHalt()
|
||||
{
|
||||
}
|
||||
|
||||
public Godot.Collections.Dictionary DebugData =>
|
||||
new()
|
||||
{
|
||||
["type"] = GetType().Name,
|
||||
["name"] = Name ?? "",
|
||||
["state"] = State.ToString(),
|
||||
["children"] =
|
||||
new Godot.Collections.Array(Children.Select(c => Variant.CreateFrom(c.DebugData))),
|
||||
};
|
||||
}
|
||||
|
||||
public readonly record struct Context
|
||||
|
|
@ -128,10 +144,14 @@ public static class BehaviorTreeExtensions
|
|||
|
||||
public abstract class ListNode(Node[] children) : Node, IEnumerable<Node>
|
||||
{
|
||||
public Node[] Children { get; } = children;
|
||||
public override Node[] Children { get; } = children;
|
||||
|
||||
public IEnumerator<Node> GetEnumerator() => ((IEnumerable<Node>)Children).GetEnumerator();
|
||||
IEnumerator IEnumerable.GetEnumerator() => Children.GetEnumerator();
|
||||
protected override void OnHalt()
|
||||
{
|
||||
foreach (var child in Children) child.Halt();
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class Sequence(Node[] children) : ListNode(children)
|
||||
|
|
@ -161,9 +181,13 @@ public sealed class Sequence(Node[] children) : ListNode(children)
|
|||
}
|
||||
|
||||
LoopDone:
|
||||
if (State is NodeState.Running && childIdx < _runningChildIdx)
|
||||
// if (State is NodeState.Running && childIdx < _runningChildIdx)
|
||||
// {
|
||||
// Children[_runningChildIdx].Halt();
|
||||
// }
|
||||
if (State is NodeState.Running or NodeState.Failure)
|
||||
{
|
||||
Children[_runningChildIdx].Halt();
|
||||
for (var i = childIdx + 1; i < Children.Length; i++) Children[i].Halt();
|
||||
}
|
||||
|
||||
if (result is Result.Running) _runningChildIdx = childIdx;
|
||||
|
|
@ -171,7 +195,7 @@ public sealed class Sequence(Node[] children) : ListNode(children)
|
|||
return result;
|
||||
}
|
||||
|
||||
protected override void OnHalt() => Children[_runningChildIdx].Halt();
|
||||
// protected override void OnHalt() => Children[_runningChildIdx].Halt();
|
||||
}
|
||||
|
||||
public sealed class MemoSequence(Node[] children) : ListNode(children)
|
||||
|
|
@ -204,11 +228,15 @@ public sealed class MemoSequence(Node[] children) : ListNode(children)
|
|||
|
||||
LoopDone:
|
||||
if (result is Result.Running) _runningChildIdx = childIdx;
|
||||
if (State is NodeState.Running or NodeState.Failure)
|
||||
{
|
||||
for (var i = childIdx + 1; i < Children.Length; i++) Children[i].Halt();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
protected override void OnHalt() => Children[_runningChildIdx].Halt();
|
||||
// protected override void OnHalt() => Children[_runningChildIdx].Halt();
|
||||
}
|
||||
|
||||
public sealed class Selector(Node[] children) : ListNode(children)
|
||||
|
|
@ -238,9 +266,13 @@ public sealed class Selector(Node[] children) : ListNode(children)
|
|||
}
|
||||
|
||||
LoopDone:
|
||||
if (State is NodeState.Running && childIdx < _runningChildIdx)
|
||||
// if (State is NodeState.Running && childIdx < _runningChildIdx)
|
||||
// {
|
||||
// Children[_runningChildIdx].Halt();
|
||||
// }
|
||||
if (State is NodeState.Running or NodeState.Success)
|
||||
{
|
||||
Children[_runningChildIdx].Halt();
|
||||
for (var i = childIdx + 1; i < Children.Length; i++) Children[i].Halt();
|
||||
}
|
||||
|
||||
if (result is Result.Running) _runningChildIdx = childIdx;
|
||||
|
|
@ -248,7 +280,7 @@ public sealed class Selector(Node[] children) : ListNode(children)
|
|||
return result;
|
||||
}
|
||||
|
||||
protected override void OnHalt() => Children[_runningChildIdx].Halt();
|
||||
// protected override void OnHalt() => Children[_runningChildIdx].Halt();
|
||||
}
|
||||
|
||||
public sealed class DoNothing : Node
|
||||
|
|
@ -259,6 +291,7 @@ public sealed class DoNothing : Node
|
|||
public abstract class DecoratorNode(Node child) : Node
|
||||
{
|
||||
public Node Child { get; } = child;
|
||||
public override Node[] Children => [Child];
|
||||
protected override void OnHalt() => Child.Halt();
|
||||
}
|
||||
|
||||
|
|
@ -349,9 +382,11 @@ public sealed class Action(OnTickAction action) : Node
|
|||
|
||||
public sealed class Delay(double time) : Node
|
||||
{
|
||||
public double RandomVariation { get; set; }
|
||||
public double RandomVariation { get; init; }
|
||||
private double TimeLeft { get; set; }
|
||||
|
||||
public override string Name => $"Delay by {time:0.000}±{RandomVariation:0.000}s";
|
||||
|
||||
protected override void OnStart(in Context context)
|
||||
{
|
||||
TimeLeft = time;
|
||||
|
|
@ -371,9 +406,15 @@ public sealed class Delay(double time) : Node
|
|||
|
||||
public sealed class PlayAnimation(StringName animation) : Node
|
||||
{
|
||||
/// <summary>
|
||||
/// Set to true to have this node wait until the started animation has finished.
|
||||
/// </summary>
|
||||
public bool WaitForFinish { get; set; } = false;
|
||||
|
||||
private bool _hasAnimationFinished;
|
||||
|
||||
public override string Name => $"Play animation {animation}";
|
||||
|
||||
protected override void OnStart(in Context context)
|
||||
{
|
||||
if (context.AnimationPlayer is not { } animationPlayer) throw new InvalidOperationException();
|
||||
|
|
@ -404,3 +445,8 @@ public sealed class PlayAnimation(StringName animation) : Node
|
|||
_hasAnimationFinished = true;
|
||||
}
|
||||
}
|
||||
|
||||
public interface IHasBehaviorTree
|
||||
{
|
||||
public Tree Tree { get; }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
using System;
|
||||
using System.Diagnostics;
|
||||
using Bt = Dancer.Behavior;
|
||||
|
||||
|
|
@ -6,7 +5,7 @@ namespace Dancer;
|
|||
|
||||
[Meta(typeof(IAutoNode))]
|
||||
public sealed partial class Birb : CharacterBody2D, IAttackable,
|
||||
IProvide<IHitboxOwner>, IHitboxOwner
|
||||
IProvide<IHitboxOwner>, IHitboxOwner, Bt.IHasBehaviorTree
|
||||
{
|
||||
public override void _Notification(int what) => this.Notify(what);
|
||||
|
||||
|
|
@ -26,7 +25,7 @@ public sealed partial class Birb : CharacterBody2D, IAttackable,
|
|||
|
||||
private float _hp;
|
||||
|
||||
private Bt.Tree Tree { get; set; } = null!;
|
||||
public Bt.Tree Tree { get; private set; } = null!;
|
||||
private float TargetVelocity { get; set; }
|
||||
|
||||
private MotionGoal _motionGoal = new MotionGoal.Stop();
|
||||
|
|
@ -46,26 +45,34 @@ public sealed partial class Birb : CharacterBody2D, IAttackable,
|
|||
HealthBar.MinValue = 0f;
|
||||
HealthBar.MaxValue = MaxHp;
|
||||
Tree = CreateTree();
|
||||
SendTreeDebugData();
|
||||
}
|
||||
|
||||
private void SendTreeDebugData()
|
||||
{
|
||||
if (EngineDebugger.IsActive())
|
||||
EngineDebugger.SendMessage("behavior_debug:add_tree",
|
||||
new() { GetInstanceId(), Tree.DebugData });
|
||||
}
|
||||
|
||||
private Bt.Tree CreateTree() => new(
|
||||
new Bt.Selector([
|
||||
new Bt.Sequence([
|
||||
new Bt.Check(() => Target is not null),
|
||||
new Bt.Check(() => Target is not null) { Name = "Has target?" },
|
||||
new Bt.Action(() => FaceToward(Target!.GlobalPosition)),
|
||||
new Bt.Selector([
|
||||
new Bt.MemoSequence([
|
||||
new Bt.Sequence([
|
||||
new Bt.Check(() => StabHitbox.GetOverlappingBodies().Contains(Target)),
|
||||
new Bt.MemoSequence([
|
||||
new Bt.Action(Stop),
|
||||
new Bt.Action(Stop) { Name = "Stop" },
|
||||
new Bt.PlayAnimation("prepare_attack"),
|
||||
new Bt.Delay(0.4) { RandomVariation = 0.2 },
|
||||
]),
|
||||
]),
|
||||
new Bt.PlayAnimation("stab"),
|
||||
new Bt.Action(() => _state = State.Attacking),
|
||||
new Bt.WaitUntil(() => _state is not State.Attacking),
|
||||
new Bt.WaitUntil(() => _state is not State.Attacking) { Name = "Done attacking?" },
|
||||
]),
|
||||
new Bt.MemoSequence([
|
||||
new Bt.Delay(0.1) { RandomVariation = 0.05 },
|
||||
|
|
@ -82,7 +89,7 @@ public sealed partial class Birb : CharacterBody2D, IAttackable,
|
|||
return WalkTo(targetPosition)
|
||||
? Bt.Result.Success
|
||||
: Bt.Result.Running;
|
||||
}),
|
||||
}) { Name = "Walk to target" },
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
|
|
@ -107,6 +114,7 @@ public sealed partial class Birb : CharacterBody2D, IAttackable,
|
|||
public void OnPhysicsProcess(double delta)
|
||||
{
|
||||
Tree.Process(delta);
|
||||
SendTreeDebugData();
|
||||
|
||||
var velocity = Velocity;
|
||||
switch (_motionGoal)
|
||||
|
|
|
|||
|
|
@ -229,6 +229,7 @@ debug_color = Color(0, 0.6, 0.69803923, 0)
|
|||
|
||||
[node name="HealthBar" type="ProgressBar" parent="." unique_id=369348156]
|
||||
unique_name_in_owner = true
|
||||
visible = false
|
||||
anchors_preset = 5
|
||||
anchor_left = 0.5
|
||||
anchor_right = 0.5
|
||||
|
|
@ -239,7 +240,8 @@ offset_bottom = -33.0
|
|||
grow_horizontal = 2
|
||||
theme_override_styles/background = SubResource("StyleBoxFlat_lyo8d")
|
||||
theme_override_styles/fill = SubResource("StyleBoxFlat_ba6cv")
|
||||
value = 50.0
|
||||
max_value = 4.0
|
||||
value = 4.0
|
||||
show_percentage = false
|
||||
|
||||
[node name="AnimationPlayer" type="AnimationPlayer" parent="." unique_id=695394949]
|
||||
|
|
|
|||
|
|
@ -264,6 +264,7 @@ advance_expression = "not IsHoldingWall()"
|
|||
|
||||
[sub_resource type="AnimationNodeStateMachine" id="AnimationNodeStateMachine_yllr7"]
|
||||
allow_transition_to_self = true
|
||||
states/End/position = Vector2(772, 100)
|
||||
states/front_kick/node = SubResource("AnimationNodeAnimation_qjkh3")
|
||||
states/front_kick/position = Vector2(604.5, 41.5)
|
||||
states/idle/node = SubResource("AnimationNodeAnimation_yw30f")
|
||||
|
|
@ -273,7 +274,7 @@ states/run/position = Vector2(628.5, 203.5)
|
|||
states/wall_hold/node = SubResource("AnimationNodeAnimation_boad6")
|
||||
states/wall_hold/position = Vector2(362.82965, 231.5)
|
||||
transitions = ["front_kick", "idle", SubResource("AnimationNodeStateMachineTransition_boad6"), "idle", "front_kick", SubResource("AnimationNodeStateMachineTransition_rgyib"), "Start", "idle", SubResource("AnimationNodeStateMachineTransition_hg6s5"), "idle", "run", SubResource("AnimationNodeStateMachineTransition_8t03j"), "run", "idle", SubResource("AnimationNodeStateMachineTransition_2ieo8"), "run", "front_kick", SubResource("AnimationNodeStateMachineTransition_ebec5"), "idle", "wall_hold", SubResource("AnimationNodeStateMachineTransition_yllr7"), "wall_hold", "idle", SubResource("AnimationNodeStateMachineTransition_kb6p2")]
|
||||
graph_offset = Vector2(-59.670364, -27)
|
||||
graph_offset = Vector2(-103.670364, -38)
|
||||
|
||||
[node name="Player" type="CharacterBody2D" unique_id=500011307]
|
||||
physics_interpolation_mode = 1
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue