added behavior trees!

This commit is contained in:
Lilith Schier 2026-06-27 17:15:15 +02:00
parent 4d0ad13bf3
commit d362d93b12
9 changed files with 510 additions and 197 deletions

367
src/behavior/Behavior.cs Normal file
View file

@ -0,0 +1,367 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Chickensoft.Collections;
namespace Dancer.Behavior;
public sealed class Tree(Node root)
{
public Node Root { get; } = root;
public EntityTable Blackboard { get; } = new();
public Random Random { get; init; } = new();
public Result Tick() => Process(0f);
public Result Process(double delta)
{
return Root.Tick(new()
{
Delta = delta,
Blackboard = Blackboard,
Random = Random,
});
}
public void Halt() => Root.Halt();
}
public enum Result
{
Running,
Success,
Failure,
}
public enum NodeState
{
Idle,
Running,
Success,
Failure,
}
public abstract class Node
{
public NodeState State { get; private set; } = NodeState.Idle;
public Result Tick(in Context context)
{
if (State is not NodeState.Running) OnStart(context);
var result = OnTick(in context);
State = result.ToState();
return result;
}
public void Halt()
{
if (State is NodeState.Running) OnHalt();
State = NodeState.Idle;
}
/// <summary>
/// Called before this node is ticked while in any state but
/// <see cref="NodeState.Running"/>.
///
/// This will be called when a node is ticked for the first time,
/// or if its last tick resulted in anything but <see cref="Result.Running"/>.
/// </summary>
/// <param name="context"></param>
protected virtual void OnStart(in Context context)
{
}
/// <summary>
/// Called when this Node is ticked.
/// </summary>
/// <param name="context"></param>
protected abstract Result OnTick(in Context context);
/// <summary>
/// Called whenever this node is halted forcibly,
/// but only if its state is <see cref="NodeState.Running"/>.
/// Therefore, this will never be called twice in a row.
/// Before being ticked again, <see cref="OnStart"/> is guaranteed
/// to be called first.
/// </summary>
protected virtual void OnHalt()
{
}
}
public readonly record struct Context
{
public double Delta { get; init; }
public required EntityTable Blackboard { get; init; }
public Random Random { get; init; }
}
public static class BehaviorTreeExtensions
{
extension(Result result)
{
public NodeState ToState() => result switch
{
Result.Running => NodeState.Running,
Result.Success => NodeState.Success,
Result.Failure => NodeState.Failure,
_ => throw new UnreachableException(),
};
}
extension(NodeState result)
{
public Result? ToResult() => result switch
{
NodeState.Idle => null,
NodeState.Running => Result.Running,
NodeState.Success => Result.Success,
NodeState.Failure => Result.Failure,
_ => throw new UnreachableException(),
};
}
}
public abstract class ListNode(Node[] children) : Node, IEnumerable<Node>
{
public Node[] Children { get; } = children;
public IEnumerator<Node> GetEnumerator() => ((IEnumerable<Node>)Children).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => Children.GetEnumerator();
}
public sealed class Sequence(Node[] children) : ListNode(children)
{
private int _runningChildIdx;
protected override Result OnTick(in Context context)
{
var result = Result.Success;
int childIdx;
for (childIdx = 0; childIdx < Children.Length; childIdx++)
{
var child = Children[childIdx];
switch (child.Tick(context))
{
case Result.Running:
result = Result.Running;
goto LoopDone;
case Result.Success:
break;
case Result.Failure:
result = Result.Failure;
goto LoopDone;
default:
throw new UnreachableException();
}
}
LoopDone:
if (State is NodeState.Running && childIdx < _runningChildIdx)
{
Children[_runningChildIdx].Halt();
}
if (result is Result.Running) _runningChildIdx = childIdx;
return result;
}
protected override void OnHalt() => Children[_runningChildIdx].Halt();
}
public sealed class MemoSequence(Node[] children) : ListNode(children)
{
private int _runningChildIdx;
protected override void OnStart(in Context context) => _runningChildIdx = 0;
protected override Result OnTick(in Context context)
{
var result = Result.Success;
int childIdx;
for (childIdx = _runningChildIdx; childIdx < Children.Length; childIdx++)
{
var child = Children[childIdx];
switch (child.Tick(context))
{
case Result.Running:
result = Result.Running;
goto LoopDone;
case Result.Success:
break;
case Result.Failure:
result = Result.Failure;
goto LoopDone;
default:
throw new UnreachableException();
}
}
LoopDone:
if (result is Result.Running) _runningChildIdx = childIdx;
return result;
}
protected override void OnHalt() => Children[_runningChildIdx].Halt();
}
public sealed class Selector(Node[] children) : ListNode(children)
{
private int _runningChildIdx;
protected override Result OnTick(in Context context)
{
var result = Result.Failure;
int childIdx;
for (childIdx = 0; childIdx < Children.Length; childIdx++)
{
var child = Children[childIdx];
switch (child.Tick(context))
{
case Result.Running:
result = Result.Running;
goto LoopDone;
case Result.Success:
result = Result.Success;
goto LoopDone;
case Result.Failure:
break;
default:
throw new UnreachableException();
}
}
LoopDone:
if (State is NodeState.Running && childIdx < _runningChildIdx)
{
Children[_runningChildIdx].Halt();
}
if (result is Result.Running) _runningChildIdx = childIdx;
return result;
}
protected override void OnHalt() => Children[_runningChildIdx].Halt();
}
public sealed class DoNothing : Node
{
protected override Result OnTick(in Context context) => Result.Running;
}
public abstract class DecoratorNode(Node child) : Node
{
public Node Child { get; } = child;
protected override void OnHalt() => Child.Halt();
}
public sealed class Invert(Node child) : DecoratorNode(child)
{
protected override Result OnTick(in Context context) =>
Child.Tick(context) switch
{
Result.Running => Result.Running,
Result.Success => Result.Failure,
Result.Failure => Result.Success,
_ => throw new UnreachableException(),
};
}
public sealed class AlwaysSucceed(Node child) : DecoratorNode(child)
{
protected override Result OnTick(in Context context) =>
Child.Tick(context) switch
{
Result.Running => Result.Running,
Result.Success or Result.Failure => Result.Success,
_ => throw new UnreachableException(),
};
}
public sealed class AlwaysFail(Node child) : DecoratorNode(child)
{
protected override Result OnTick(in Context context) =>
Child.Tick(context) switch
{
Result.Running => Result.Running,
Result.Success or Result.Failure => Result.Failure,
_ => throw new UnreachableException(),
};
}
public delegate bool OnTickCheck(in Context context);
public sealed class Check(OnTickCheck predicate) : Node
{
public Check(Func<bool> predicate) : this((in _) => predicate())
{
}
protected override Result OnTick(in Context context) =>
predicate(in context) ? Result.Success : Result.Failure;
}
public sealed class WaitUntil(OnTickCheck predicate) : Node
{
public WaitUntil(Func<bool> predicate) : this((in _) => predicate())
{
}
protected override Result OnTick(in Context context) =>
predicate(in context) ? Result.Success : Result.Running;
}
public delegate Result OnTickAction(in Context context);
public delegate void OnTickActionWithoutResult(in Context context);
public sealed class Action(OnTickAction action) : Node
{
public Action(System.Action action) : this((in _) =>
{
action();
return Result.Success;
})
{
}
public Action(Func<Result> action) : this((in _) => action())
{
}
public Action(OnTickActionWithoutResult action) : this((in context) =>
{
action(in context);
return Result.Success;
})
{
}
protected override Result OnTick(in Context context) => action(context);
}
public sealed class Delay(double time) : Node
{
public double RandomVariation { get; set; }
private double TimeLeft { get; set; }
protected override void OnStart(in Context context)
{
TimeLeft = time;
if (RandomVariation != 0.0)
{
TimeLeft += context.Random.NextDouble() * 2.0 * RandomVariation - RandomVariation;
}
}
protected override Result OnTick(in Context context)
{
if (TimeLeft <= 0f) return Result.Success;
TimeLeft -= context.Delta;
return Result.Running;
}
}

View file

@ -0,0 +1 @@
uid://b13p3uohc7a3i