Graph structures and blackboards

A tree that reuses one subtree in several places is really a graph, and the blackboard adds a second graph on top: which node writes each value and which nodes read it. Learn to draw both and check the second before a game runs it.

Every tree on the earlier pages has two kinds of connection, and only one of them is drawn. The drawn one is control: a parent ticks its children in order, and each child reports a status back. The one that is not drawn is data: one node finds the enemy and writes down where it is, and another node, three branches away, reads that and aims. Most bugs in a large tree live in the second kind, because nothing on the screen shows it.

This page is about both. The first half is about control: when the same subtree is used in two places, the tree stops being a tree in the strict sense. The second half is about data: the blackboard turns into a graph of its own, which you can write down, draw and check.

A tree that is really a graph

In a strict tree, every node has exactly one parent. Recursive composition breaks that rule on purpose: a subtree written once in its own file can be used by many trees, and by one tree in several places. Drawn as it is stored, with one box for the subtree and an arrow from every place that uses it, the picture has a node with two parents. That shape is a directed acyclic graph, or DAG: arrows that go one way (from parent to child) and never come back around to where they started. Halo 2’s AI was built this way, and Damian Isla, who wrote it, describes it as a directed acyclic graph rather than a tree.

The DAG is how the tree is stored and edited. It is not how it runs. At run time each use of the subtree is a separate copy with its own state, so the graph is unfolded back into a tree. Two rules follow, and beetree validate already enforces the first:

  • Acyclic. A subtree that includes itself, directly or through another, would never finish unfolding. beetree validate rejects the loop and names the chain of files.
  • One copy per use. If the two uses shared one running copy, an archer running for cover to heal and the same archer running for cover to reload would share one “which step am I on” and corrupt each other. Shared definition, separate state.

The blackboard as data flow

The blackboard is the tree’s shared memory: named variables such as target or arrows that nodes and the game read and write. Event-driven runtimes from Event-driven trees watch it for changes; here it matters for a different reason. When a node writes a variable and another node later reads it, data flows from the first to the second, and those flows form a graph with its own edges: from each writer of a variable to each reader of it.

A tree file can declare that graph. A custom node lists the variables it reads under blackboard_reads and the ones it writes under blackboard_writes, and the blackboard section declares each variable once, with a type and, when there is a safe starting value, a default. With those three in place, a tool can answer questions the drawn tree cannot: who sets target? Who reads it? Is there any order of ticks in which aim reads target before anything has written it?

That last question is the bug data flow causes most often. A reader placed before its writer, or a variable whose name is misspelt in one place, gives a node a value nobody set, and the symptom (an archer aiming at the world origin) appears far from the cause.

A tree you can run

The archer holds a hill. When hurt, it takes cover to heal; when it sees an enemy and has arrows, it aims and shoots; otherwise it takes cover and reloads. Taking cover is one subtree, used in two places. Save both files under the names in their first line.

# file: hill-archer.beetree.yaml
version: "1.0"
metadata:
  name: hill-archer
  description: "Holds a hill: shoots what it sees, and takes cover both to heal and to reload; take-cover is one subtree used in two places"
  tags: [graph-structures, blackboard]
blackboard:
  - {name: target, type: string, description: "Written by find_target; read by aim and shoot. No default: an empty target is never right"}
  - {name: arrows, type: int, default: 12, description: "Written by the game when an arrow is shot or picked up; read by has_arrows"}
custom_nodes:
  - name: FindTarget
    type: condition
    description: "Succeeds when an enemy is in sight, and writes it to target"
    blackboard_writes: [target]
  - name: HasArrows
    type: condition
    description: "Succeeds while arrows is above zero"
    blackboard_reads: [arrows]
  - name: AimAt
    type: action
    description: "Turns toward target; Running until lined up"
    blackboard_reads: [target]
  - name: Shoot
    type: action
    description: "Looses an arrow at target"
    blackboard_reads: [target]
  - name: IsHurt
    type: condition
    description: "Succeeds while health is below a third"
  - name: Reload
    type: action
    description: "Refills the quiver; Running until done"
subtrees:
  - {name: take_cover, file: subtrees/take-cover.beetree.yaml}
tree:
  type: selector
  name: archer_root
  children:
    - type: sequence
      name: retreat_when_hurt
      children:
        - {type: condition, name: hurt, node: IsHurt}
        - {type: subtree, name: cover_to_heal, ref: take_cover}
    - type: sequence
      name: shoot_on_sight
      children:
        - {type: condition, name: enemy_in_sight, node: FindTarget}
        - {type: condition, name: has_arrows, node: HasArrows}
        - {type: action, name: aim, node: AimAt}
        - {type: action, name: shoot, node: Shoot}
    - type: sequence
      name: restock
      children:
        - {type: subtree, name: cover_to_reload, ref: take_cover}
        - {type: action, name: reload, node: Reload}
# file: subtrees/take-cover.beetree.yaml
version: "1.0"
metadata:
  name: take-cover
  description: "Find the nearest cover and run to it"
blackboard:
  - {name: cover_spot, type: string, description: "Written by find_cover; read by run_to_cover"}
custom_nodes:
  - name: FindCover
    type: condition
    description: "Succeeds when there is cover nearby, and writes the nearest spot to cover_spot"
    blackboard_writes: [cover_spot]
  - name: RunTo
    type: action
    description: "Runs to cover_spot; Running until there"
    blackboard_reads: [cover_spot]
tree:
  type: sequence
  name: take_cover
  children:
    - {type: condition, name: find_cover, node: FindCover}
    - {type: action, name: run_to_cover, node: RunTo}

Check both files, then draw the archer:

beetree validate hill-archer.beetree.yaml subtrees/take-cover.beetree.yaml
beetree render hill-archer.beetree.yaml
[SEL] archer_root
├── [SEQ] retreat_when_hurt
│   ├── [CND] hurt
│   └── [SUB] cover_to_heal
│       └── [SEQ] take_cover
│           ├── [CND] find_cover
│           └── [ACT] run_to_cover
├── [SEQ] shoot_on_sight
│   ├── [CND] enemy_in_sight
│   ├── [CND] has_arrows
│   ├── [ACT] aim
│   └── [ACT] shoot
└── [SEQ] restock
    ├── [SUB] cover_to_reload
    │   └── [SEQ] take_cover
    │       ├── [CND] find_cover
    │       └── [ACT] run_to_cover
    └── [ACT] reload

The file holds take_cover once; the drawing shows it twice, because render unfolds the DAG into the tree that runs. Each use gets its own copy, so cover_to_heal and cover_to_reload never share a running run_to_cover. Run the quiet case, with no enemy in sight:

beetree simulate hill-archer.beetree.yaml --override hurt=FAILURE --override enemy_in_sight=FAILURE --override run_to_cover=RUNNING
Simulation: archer_root → RUNNING
──────────────────────────────────────────────────
▶ ? archer_root
  ▶ → retreat_when_hurt
    ● ¿ hurt → FAILURE
  ◀ → retreat_when_hurt → FAILURE
  ▶ → shoot_on_sight
    ● ¿ enemy_in_sight → FAILURE
  ◀ → shoot_on_sight → FAILURE
  ▶ → restock
    ▶ ↗ cover_to_reload
      ▶ → take_cover
        ● ¿ find_cover → SUCCESS
        ● ! run_to_cover → RUNNING
      ◀ → take_cover → RUNNING
    ◀ ↗ cover_to_reload → RUNNING
  ◀ → restock → RUNNING
◀ ? archer_root → RUNNING

The ↗ lines mark where the archer’s own tree enters the subtree, and the second use, cover_to_reload, is the one running.

The data-flow graph

Read the declarations instead of the tree, and the archer’s data flow is three small graphs:

target      enemy_in_sight (writes)  ──▶  aim, shoot (read)
arrows      the game (writes)        ──▶  has_arrows (reads)
cover_spot  find_cover (writes)      ──▶  run_to_cover (reads)

Each writer comes before its readers in the order a tick visits them: enemy_in_sight before aim and shoot in the same sequence, find_cover before run_to_cover. And each read sits behind a gate that only lets the tick through after the write happened: aim runs only when enemy_in_sight succeeded, which is exactly when it wrote target. arrows is written by the game, not by a node, so it has a default, and has_arrows reads 12 before the first arrow is shot.

Put aim before enemy_in_sight, or misspell target as targt in AimAt’s blackboard_reads, and the graph has a reader with no writer. That is the check the engine code below makes.

The subtree’s cover_spot joins the archer’s blackboard: in BeeTreeCraft a subtree’s variables are added to those of the tree that uses it, so both copies of take_cover read and write the same cover_spot. That is safe here, because each copy writes it before reading it. Some engines give each subtree a blackboard of its own and map names in and out (“ports” in BehaviorTree.CPP), which removes the sharing at the cost of writing the mapping.

Engine code

The samples describe the tree the way the data-flow check sees it: each node with the variables it reads, the variables it writes and its children in tick order. DataFlow.Check walks it in that order, keeping the set of variables some earlier node has written (plus those the game provides or that have a default), and reports every read of a variable that is not in the set yet. DataFlow.Edges lists who writes and who reads each variable, which is the table above. Run the check in a unit test or an editor tool, so a reader placed before its writer fails before the game runs.

The check is deliberately simple: it asks whether an earlier node may have written the variable, not whether it must have. A writer in a selector branch that failed did not write, and the check does not notice. That is what guarding each read behind its writer, as the archer does, is for.

Agnostic

FlowNode(name, reads, writes, children)   // one node, as the tree file declares it

check(root, provided):                    // provided: set by the game, or with a default
    written = set(provided)
    problems = []
    visit(node):                          // in the order a tick visits nodes
        for key in node.reads:
            if key not in written:
                problems.add(node.name + " reads " + key + " before anything writes it")
        written.addAll(node.writes)
        for child in node.children: visit(child)
    visit(root)
    return problems

edges(root):                              // key -> (writers, readers)
    for each node: add node.name to writers of each key it writes, readers of each key it reads

Unity C#

// One node of a tree as the data-flow check sees it.
public class FlowNode
{
    public readonly string Name;
    public readonly string[] Reads;
    public readonly string[] Writes;
    public readonly FlowNode[] Children;

    public FlowNode(string name, string[] reads, string[] writes, params FlowNode[] children)
    {
        Name = name;
        Reads = reads ?? new string[0];
        Writes = writes ?? new string[0];
        Children = children;
    }

    public static FlowNode Leaf(string name, string[] reads = null, string[] writes = null) =>
        new FlowNode(name, reads, writes);

    public static FlowNode Branch(string name, params FlowNode[] children) =>
        new FlowNode(name, null, null, children);
}

public static class DataFlow
{
    // Reports every read of a variable that no earlier node in tick order writes.
    // provided: variables the game sets or that have a default.
    public static System.Collections.Generic.List<string> Check(FlowNode root, params string[] provided)
    {
        var written = new System.Collections.Generic.HashSet<string>(provided);
        var problems = new System.Collections.Generic.List<string>();
        Visit(root, written, problems);
        return problems;
    }

    static void Visit(FlowNode node, System.Collections.Generic.HashSet<string> written,
        System.Collections.Generic.List<string> problems)
    {
        foreach (var key in node.Reads)
        {
            if (!written.Contains(key)) problems.Add($"{node.Name} reads {key} before anything writes it");
        }
        foreach (var key in node.Writes) written.Add(key);
        foreach (var child in node.Children) Visit(child, written, problems);
    }

    // Who writes and who reads each variable: the edges of the data-flow graph.
    public static System.Collections.Generic.SortedDictionary<string, string> Edges(FlowNode root)
    {
        var writers = new System.Collections.Generic.SortedDictionary<string, System.Collections.Generic.List<string>>();
        var readers = new System.Collections.Generic.SortedDictionary<string, System.Collections.Generic.List<string>>();
        Collect(root, writers, readers);
        var edges = new System.Collections.Generic.SortedDictionary<string, string>();
        foreach (var key in writers.Keys) edges[key] = "";
        foreach (var key in readers.Keys) edges[key] = "";
        foreach (var key in new System.Collections.Generic.List<string>(edges.Keys))
        {
            var w = writers.TryGetValue(key, out var ws) ? string.Join(", ", ws) : "(nothing)";
            var r = readers.TryGetValue(key, out var rs) ? string.Join(", ", rs) : "(nothing)";
            edges[key] = $"{w} -> {r}";
        }
        return edges;
    }

    static void Collect(FlowNode node,
        System.Collections.Generic.SortedDictionary<string, System.Collections.Generic.List<string>> writers,
        System.Collections.Generic.SortedDictionary<string, System.Collections.Generic.List<string>> readers)
    {
        foreach (var key in node.Writes) Add(writers, key, node.Name);
        foreach (var key in node.Reads) Add(readers, key, node.Name);
        foreach (var child in node.Children) Collect(child, writers, readers);
    }

    static void Add(System.Collections.Generic.SortedDictionary<string, System.Collections.Generic.List<string>> map,
        string key, string name)
    {
        if (!map.TryGetValue(key, out var names)) map[key] = names = new System.Collections.Generic.List<string>();
        names.Add(name);
    }
}

public static class HillArcherFlow
{
    // One copy of take_cover per use, as at run time.
    static FlowNode TakeCover(string use) => FlowNode.Branch(use,
        FlowNode.Leaf("find_cover", writes: new[] { "cover_spot" }),
        FlowNode.Leaf("run_to_cover", reads: new[] { "cover_spot" }));

    public static FlowNode Build() => FlowNode.Branch("archer_root",
        FlowNode.Branch("retreat_when_hurt", FlowNode.Leaf("hurt"), TakeCover("cover_to_heal")),
        FlowNode.Branch("shoot_on_sight",
            FlowNode.Leaf("enemy_in_sight", writes: new[] { "target" }),
            FlowNode.Leaf("has_arrows", reads: new[] { "arrows" }),
            FlowNode.Leaf("aim", reads: new[] { "target" }),
            FlowNode.Leaf("shoot", reads: new[] { "target" })),
        FlowNode.Branch("restock", TakeCover("cover_to_reload"), FlowNode.Leaf("reload")));

    // In a test: no problems, because arrows is set by the game and has a default.
    public static void Check()
    {
        foreach (var problem in DataFlow.Check(Build(), "arrows")) Debug.LogError(problem);
        foreach (var edge in DataFlow.Edges(Build())) Debug.Log($"{edge.Key}: {edge.Value}");
    }
}

GDScript

# One node of a tree as the data-flow check sees it.
class FlowNode:
    var name: String
    var reads: Array[String] = []
    var writes: Array[String] = []
    var children: Array = []

    func _init(n: String, r: Array[String], w: Array[String], c: Array = []):
        name = n
        reads = r
        writes = w
        children = c

# Reports every read of a variable that no earlier node in tick order writes.
# provided: variables the game sets or that have a default.
static func check(root: FlowNode, provided: Array[String]) -> Array[String]:
    var written := {}
    for key in provided:
        written[key] = true
    var problems: Array[String] = []
    _visit(root, written, problems)
    return problems

static func _visit(node: FlowNode, written: Dictionary, problems: Array[String]) -> void:
    for key in node.reads:
        if not written.has(key):
            problems.append("%s reads %s before anything writes it" % [node.name, key])
    for key in node.writes:
        written[key] = true
    for child in node.children:
        _visit(child, written, problems)

# Who writes and who reads each variable: the edges of the data-flow graph.
static func edges(root: FlowNode) -> Dictionary:
    var result := {}   # key -> {"writers": [...], "readers": [...]}
    _collect(root, result)
    return result

static func _collect(node: FlowNode, result: Dictionary) -> void:
    for key in node.writes:
        result.get_or_add(key, {"writers": [], "readers": []})["writers"].append(node.name)
    for key in node.reads:
        result.get_or_add(key, {"writers": [], "readers": []})["readers"].append(node.name)
    for child in node.children:
        _collect(child, result)

# One copy of take_cover per use, as at run time.
static func take_cover(use: String) -> FlowNode:
    return FlowNode.new(use, [], [], [
        FlowNode.new("find_cover", [], ["cover_spot"]),
        FlowNode.new("run_to_cover", ["cover_spot"], []),
    ])

static func hill_archer() -> FlowNode:
    return FlowNode.new("archer_root", [], [], [
        FlowNode.new("retreat_when_hurt", [], [], [FlowNode.new("hurt", [], []), take_cover("cover_to_heal")]),
        FlowNode.new("shoot_on_sight", [], [], [
            FlowNode.new("enemy_in_sight", [], ["target"]),
            FlowNode.new("has_arrows", ["arrows"], []),
            FlowNode.new("aim", ["target"], []),
            FlowNode.new("shoot", ["target"], []),
        ]),
        FlowNode.new("restock", [], [], [take_cover("cover_to_reload"), FlowNode.new("reload", [], [])]),
    ])

Unreal C++

// One node of a tree as the data-flow check sees it.
struct FFlowNode
{
    FString Name;
    TArray<FString> Reads;
    TArray<FString> Writes;
    TArray<TSharedPtr<FFlowNode>> Children;
};

// A read of a variable that no earlier node in tick order writes.
struct FFlowProblem
{
    FString Node;
    FString Key;
};

class FDataFlow
{
public:
    // Provided: variables the game sets or that have a default.
    static TArray<FFlowProblem> Check(const FFlowNode& Root, const TArray<FString>& Provided)
    {
        TMap<FString, bool> Written;
        for (const FString& Key : Provided) Written.Add(Key, true);
        TArray<FFlowProblem> Problems;
        Visit(Root, Written, Problems);
        return Problems;
    }

    // Who writes and who reads each variable: the edges of the data-flow graph.
    static void Edges(const FFlowNode& Node, TMap<FString, TArray<FString>>& Writers,
        TMap<FString, TArray<FString>>& Readers)
    {
        for (const FString& Key : Node.Writes) Writers.FindOrAdd(Key).Add(Node.Name);
        for (const FString& Key : Node.Reads) Readers.FindOrAdd(Key).Add(Node.Name);
        for (const TSharedPtr<FFlowNode>& Child : Node.Children) Edges(*Child, Writers, Readers);
    }

private:
    static void Visit(const FFlowNode& Node, TMap<FString, bool>& Written, TArray<FFlowProblem>& Problems)
    {
        for (const FString& Key : Node.Reads)
        {
            if (!Written.Contains(Key)) Problems.Add(FFlowProblem{Node.Name, Key});
        }
        for (const FString& Key : Node.Writes) Written.Add(Key, true);
        for (const TSharedPtr<FFlowNode>& Child : Node.Children) Visit(*Child, Written, Problems);
    }
};

// A leaf that reads or writes one variable; e.g. Leaf("aim", "target", "") reads target.
inline TSharedPtr<FFlowNode> Leaf(const FString& Name, const FString& Reads, const FString& Writes)
{
    TSharedPtr<FFlowNode> Node = MakeShared<FFlowNode>();
    Node->Name = Name;
    if (!Reads.IsEmpty()) Node->Reads.Add(Reads);
    if (!Writes.IsEmpty()) Node->Writes.Add(Writes);
    return Node;
}

// One copy of take_cover per use, as at run time.
inline TSharedPtr<FFlowNode> TakeCover(const FString& Use)
{
    TSharedPtr<FFlowNode> Node = Leaf(Use, "", "");
    Node->Children.Add(Leaf("find_cover", "", "cover_spot"));
    Node->Children.Add(Leaf("run_to_cover", "cover_spot", ""));
    return Node;
}

The Unity sample describes the whole archer in HillArcherFlow.Build; in Godot, hill_archer() does the same, and in Unreal, assemble it from Leaf and TakeCover the same way. Describing the tree twice, once in the file and once in code, is the price of a hand-written check: a project that loads its trees from files (see Data-driven trees) can build the FlowNodes from the loaded file instead, and then the check cannot drift from the tree.

What BeeTreeCraft shows today

  • subtrees and ref let one tree file be used in several places, and beetree validate rejects a subtree loop and names the chain of files. render, simulate and generate unfold the DAG into a tree, and the generated code builds one copy of the subtree for every use.
  • blackboard declares each variable with a type and an optional default, and a custom node’s blackboard_reads and blackboard_writes declare the data flow. beetree validate checks the variables’ types and defaults, but not yet that a name under blackboard_reads or blackboard_writes is a declared variable, or that a reader comes after a writer: targt validates. Until it does, run the check above in a test.
  • beetree generate writes the declared reads and writes as a comment in each node’s stub (// Blackboard reads: target) and a typed blackboard class with one property per variable, the subtree’s included.
  • The simulator does not hold blackboard values: --override sets what each leaf returns, not what it writes. A subtree’s variables join the tree’s own; there is no per-subtree blackboard or port mapping.

Where it comes from

Damian Isla’s Handling Complexity in the Halo 2 AI (2005) describes the behavior DAG: reused behaviors with several parents, and the memory each use needs of its own. The BehaviorTree.CPP tutorial Blackboard and ports shows nodes that declare their inputs and outputs, so a tool can check the data flow, and Subtrees and port remapping the per-subtree blackboard. Epic’s Behavior Tree in Unreal Engine: Overview explains a blackboard asset with typed keys that every task and decorator names. More reading is on the Resources page.

Next, read Hybrids: utility, state machines and planners to see a tree share its decisions with other methods, read how to declare variables and the keys each node reads and writes in the tree format, or open the Build hub, paste the archer into the builder and use Step through to follow a tick into each copy of take_cover.