arora_behavior/lib.rs
1//! Behavior interpreters: the executors the Arora runtime ticks each step.
2//!
3//! Two things share the word "behavior", and this crate is about only one of
4//! them:
5//!
6//! - A **behavior** (the noun) is an *authored, editable representation* of what
7//! a device should do — a behavior tree, a node graph — produced in a visual
8//! editor (Studio, the Vizij Workspace) and shipped as data.
9//! - A [`BehaviorInterpreter`] is the *runtime-level executor* that runs one of
10//! those: a behavior-tree interpreter, a node-graph interpreter. It is the
11//! thing the runtime actually ticks.
12//!
13//! The runtime holds one `Box<dyn BehaviorInterpreter>` and ticks it — swapping
14//! the interpreter replaces the behavior. The behavior tree is one interpreter
15//! (`arora-behavior-tree`'s [`BehaviorTreeInterpreter`]); a Vizij node graph is
16//! another. Adding a new *kind of authored behavior* means adding a new
17//! interpreter here. Hand-implementing the trait to hard-code a single behavior
18//! in Rust is possible, but it is a corner case — the promoted path is to author
19//! a behavior in an editor and let an interpreter run it.
20//!
21//! An authored behavior is a [`graph::Graph`] — nodes bound to functions, with
22//! typed I/Os and links — and interpreters are edited by
23//! [`apply`](BehaviorInterpreter::apply)ing a [`graph::GraphDiff`]. Loading a
24//! behavior is applying a diff onto an empty graph. See [`graph`] for the model.
25//!
26//! Each tick an interpreter gets a [`BehaviorContext`]: the shared
27//! [`DataStore`](arora_types::data::DataStore) (read inputs, write intent /
28//! outputs) and a [`CallBridge`](arora_types::call::CallBridge) (so a
29//! module-calling interpreter like the behavior tree can reach the engine). An
30//! interpreter uses whichever it needs — a graph reads/writes the store; the
31//! tree drives the caller.
32//!
33//! Timing is not a tick argument. The runtime publishes the frame's clock into
34//! the store under the [`built_in`] keys before it ticks, so an interpreter that
35//! needs `dt` or elapsed time reads it from the store like any other slot.
36
37use arora_types::call::CallBridge;
38use arora_types::data::DataStore;
39
40pub mod built_in;
41pub mod graph;
42pub mod interpreter_module;
43
44pub use graph::{Graph, GraphDiff};
45
46/// Whether an interpreter wants to be ticked again — and, when it does not, how
47/// it ended.
48///
49/// Liveness is one bit: [`Running`](Self::Running) or terminal
50/// ([`Done`](Self::Done)). The terminal case carries a `Result` — `Ok(())` for a
51/// clean stop, `Err` for a fault the run could not recover from.
52///
53/// This is the interpreter's *scheduling* status, not an application outcome. A
54/// behavior does not *return* a value — it writes its outputs to store keys — so
55/// the terminal `Ok` is `()`, never a payload. A run's success / failure / errno
56/// is likewise an application value on its status key, not here: one [`tick`] may
57/// drive many runs, so a single return cannot speak for each. What the runtime
58/// must act on is only liveness and, at termination, whether the run stopped
59/// cleanly or faulted.
60///
61/// [`tick`]: BehaviorInterpreter::tick
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum BehaviorStatus {
64 /// Not terminal: tick me again next step (a node graph; a tree still
65 /// running).
66 Running,
67 /// Terminal: I reached a terminal state and the runtime drops me. `Ok(())`
68 /// is a clean stop; `Err(_)` is a fault the run could not recover from — its
69 /// reason is surfaced (like an `Err` from [`tick`](BehaviorInterpreter::tick))
70 /// but, unlike a transient `Err`, a run that ends `Done(Err(_))` is dropped,
71 /// *not* retried.
72 Done(Result<(), BehaviorError>),
73}
74
75/// What a [`BehaviorInterpreter`] receives each
76/// [`tick`](BehaviorInterpreter::tick).
77pub struct BehaviorContext<'a> {
78 /// The shared blackboard: read inputs, write intent / outputs.
79 pub store: &'a dyn DataStore,
80 /// The module-call bridge (the engine), for interpreters that call modules.
81 pub call_bridge: &'a mut dyn CallBridge,
82}
83
84/// An interpreter failed to tick.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct BehaviorError {
87 /// Human-readable description.
88 pub message: String,
89}
90
91impl std::fmt::Display for BehaviorError {
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 f.write_str(&self.message)
94 }
95}
96
97impl std::error::Error for BehaviorError {}
98
99/// A behavior *executor*: something the Arora runtime ticks once per step to run
100/// an authored behavior.
101///
102/// Implemented by the behavior tree (`arora-behavior-tree`'s
103/// [`BehaviorTreeInterpreter`]) and by other interpreters such as a Vizij
104/// node-graph interpreter. The runtime holds one `Box<dyn BehaviorInterpreter>`
105/// and ticks it without knowing which is which.
106///
107/// Implement this to add a new *kind of executor* (a new authored-behavior
108/// representation the runtime can run), not to hand-code one particular
109/// behavior — authored behaviors come from the visual editors, run by an
110/// existing interpreter.
111///
112/// Not `Send`: the runtime is a single-owner, single-thread step loop.
113pub trait BehaviorInterpreter {
114 /// Advance one step. Return [`BehaviorStatus::Running`] to be ticked again,
115 /// or [`BehaviorStatus::Done`] to be dropped — `Done(Ok(()))` for a clean
116 /// stop, `Done(Err(e))` for a terminal fault whose reason `e` is surfaced.
117 ///
118 /// An `Err` from `tick` is different from `Ok(Done(Err(..)))`: an `Err` is a
119 /// *transient* failure — the runtime keeps the interpreter installed and
120 /// ticks it again next step (a momentary lowering or call-bridge hiccup),
121 /// only raising the reason on the standing error watch. `Done(Err(..))` is
122 /// *terminal*: the run has ended and will not be retried.
123 fn tick(&mut self, ctx: &mut BehaviorContext) -> Result<BehaviorStatus, BehaviorError>;
124
125 /// Edit the running behavior by applying a [`GraphDiff`](graph::GraphDiff):
126 /// add/remove nodes and links, set/override predetermined keys. **Loading** a
127 /// behavior is applying a diff onto an empty graph.
128 ///
129 /// The default rejects edition — override it in interpreters that carry an
130 /// editable [`graph::Graph`] (the behavior tree does). A hand-coded,
131 /// non-graph interpreter (the corner case above) can leave this as-is.
132 ///
133 /// `apply` validates and stores the edit; an implementation may defer
134 /// re-lowering its runtime form to the next [`tick`](Self::tick) (which
135 /// carries the store in its context), so a lowering problem can surface
136 /// there rather than here. This keeps `apply` callable from anywhere a
137 /// [`GraphDiff`](graph::GraphDiff) arrives — notably the interpreter's
138 /// engine-registered edit function, which holds no store.
139 fn apply(&mut self, diff: graph::GraphDiff) -> Result<(), BehaviorError> {
140 let _ = diff;
141 Err(BehaviorError {
142 message: "this interpreter does not support graph edition".to_string(),
143 })
144 }
145
146 /// Replace the running behavior with `graph`, whole. Like
147 /// [`apply`](Self::apply) it is store-less — an implementation may defer
148 /// lowering to the next [`tick`](Self::tick) — so it is callable from the
149 /// interpreter's engine-registered load function. The default rejects
150 /// loading, for hand-coded interpreters that carry no graph.
151 fn load(&mut self, graph: graph::Graph) -> Result<(), BehaviorError> {
152 let _ = graph;
153 Err(BehaviorError {
154 message: "this interpreter does not support loading a graph".to_string(),
155 })
156 }
157}