tree based bt debugger

This commit is contained in:
Lilith Schier 2026-06-28 22:46:37 +02:00
parent c9967f09d9
commit b5d5a8f9f3
12 changed files with 271 additions and 19 deletions

View file

@ -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; }
}

View file

@ -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)

View file

@ -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]

View file

@ -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