behaviortree-core 0.1.0

Core implementaion of behaviortree
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// Copyright © 2025 Stephan Kunz
//! A [`BehaviorTree`](crate::tree::tree::BehaviorTree) element.

use databoard::Databoard;
use tinyscript::SharedRuntime;

use crate::{
	BehaviorPtr, BehaviorResult, BehaviorState, ConstString, FAILURE_IF, ON_FAILURE, ON_SUCCESS, POST, SKIP_IF, SUCCESS_IF,
	WHILE,
	behavior_data::BehaviorData,
	error::Error,
	pre_post_conditions::{Conditions, PostConditions, PreConditions},
	tree::{
		tree_element_list::BehaviorTreeElementList,
		tree_iter::{TreeIter, TreeIterMut},
	},
};

#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
/// The different kinds of a [`BehaviorTreeElement`]
pub enum TreeElementKind {
	/// A behavior tree leaf.
	Leaf,
	/// A behavior tree node.
	Node,
	/// A behavior subtree.
	SubTree,
}

/// A tree elements.
pub struct BehaviorTreeElement {
	/// Kind of the element.
	kind: TreeElementKind,
	/// The behavior of that element.
	behavior: BehaviorPtr,
	/// Data of the Behavior.
	data: BehaviorData,
	/// Children of the element.
	children: BehaviorTreeElementList,
	/// Tuple of pre- and post-conditions, checked before and after a tick.
	conditions: Conditions,
}

impl BehaviorTreeElement {
	/// Construct a [`BehaviorTreeElement`].
	#[must_use]
	pub fn create(kind: TreeElementKind, behavior: BehaviorPtr, data: BehaviorData) -> Self {
		Self {
			kind,
			behavior,
			data,
			children: BehaviorTreeElementList::default(),
			conditions: Conditions::default(),
		}
	}

	/// Construct a [`BehaviorTreeElement`].
	#[must_use]
	pub fn new(
		kind: TreeElementKind,
		behavior: BehaviorPtr,
		data: BehaviorData,
		children: BehaviorTreeElementList,
		conditions: Conditions,
	) -> Self {
		Self {
			kind,
			behavior,
			data,
			children,
			conditions,
		}
	}

	/// Get the uid.
	#[must_use]
	pub const fn uid(&self) -> u16 {
		self.data.uid()
	}

	/// Get the id.
	#[must_use]
	pub const fn id(&self) -> &ConstString {
		self.data.description().id()
	}

	/// Returns the name of the behavior.
	#[must_use]
	pub const fn name(&self) -> &ConstString {
		self.data.description().name()
	}

	/// Returns a reference to the [`BehaviorData`].
	#[must_use]
	pub const fn data(&self) -> &BehaviorData {
		&self.data
	}

	/// Returns a mutable reference to the [`BehaviorData`].
	#[must_use]
	pub const fn data_mut(&mut self) -> &mut BehaviorData {
		&mut self.data
	}

	/// Returns a reference to the behavior.
	#[must_use]
	pub const fn behavior(&self) -> &BehaviorPtr {
		&self.behavior
	}

	/// Returns a mutable reference to the behavior.
	#[must_use]
	pub const fn behavior_mut(&mut self) -> &mut BehaviorPtr {
		&mut self.behavior
	}

	/// Returns a reference to the blackboard.
	#[must_use]
	pub const fn blackboard(&self) -> &Databoard {
		self.data().blackboard()
	}

	/// Returns a reference to the blackboard.
	#[must_use]
	pub const fn blackboard_mut(&mut self) -> &mut Databoard {
		self.data_mut().blackboard_mut()
	}

	/// Returns the children.
	#[must_use]
	pub const fn children(&self) -> &BehaviorTreeElementList {
		&self.children
	}

	/// Returns the children mutable.
	#[must_use]
	pub const fn children_mut(&mut self) -> &mut BehaviorTreeElementList {
		&mut self.children
	}

	/// Returns the pre conditions.
	#[must_use]
	pub const fn pre_conditions(&self) -> &PreConditions {
		&self.conditions.pre
	}

	/// Returns the pre condition mutables.
	#[must_use]
	pub const fn pre_conditions_mut(&mut self) -> &mut PreConditions {
		&mut self.conditions.pre
	}

	/// Returns the post conditions.
	#[must_use]
	pub const fn post_conditions(&self) -> &PostConditions {
		&self.conditions.post
	}

	/// Returns the post conditions mutable.
	#[must_use]
	pub const fn post_conditions_mut(&mut self) -> &mut PostConditions {
		&mut self.conditions.post
	}

	/// Halts the element and all its children considering postconditions.
	/// # Errors
	pub fn halt(&mut self, runtime: &SharedRuntime) -> Result<(), Error> {
		if self.data.state() != BehaviorState::Idle {
			let state = self
				.behavior
				.halt(&mut self.data, &mut self.children, runtime)?;
			self.data.set_state(state);
			if let Some(script) = self.conditions.post.get("_onHalted") {
				let _ = runtime
					.lock()
					.run(script, self.data.blackboard_mut())?;
			}
		}
		Ok(())
	}

	/// Ticks the element considering pre- and postconditions.
	/// # Errors
	pub async fn tick(&mut self, runtime: &SharedRuntime) -> BehaviorResult {
		// A pre-condition may return the next state which will override the current tick().
		let old_state = self.data.state();
		let state = if let Some(result) = self.check_pre_conditions(runtime)? {
			result
		} else if old_state == BehaviorState::Idle {
			self.behavior
				.start(&mut self.data, &mut self.children, runtime)
				.await?
		} else {
			self.behavior
				.tick(&mut self.data, &mut self.children, runtime)
				.await?
		};

		self.check_post_conditions(state, runtime)?;

		// Preserve the last state if skipped, but communicate `Skipped` to parent
		if state != BehaviorState::Skipped {
			self.data.set_state(state);
			// } else {
			//     self.data.set_state(old_state);
		}

		Ok(state)
	}

	/// Halts child at `index`.
	/// # Errors
	/// - if index is out of childrens bounds.
	pub fn halt_child_at(&mut self, index: usize, runtime: &SharedRuntime) -> Result<(), Error> {
		self.children.halt_at(index, runtime)
	}

	/// Halt all children at and beyond `index`.
	/// # Errors
	/// - if index is out of childrens bounds.
	pub fn halt_children_from(&mut self, index: usize, runtime: &SharedRuntime) -> Result<(), Error> {
		self.children.halt_from(index, runtime)
	}

	/// Halt all children at and beyond `index`.
	/// # Errors
	/// - if index is out of childrens bounds.
	pub fn halt_children(&mut self, runtime: &SharedRuntime) -> Result<(), Error> {
		self.children.halt(runtime)
	}

	/// Reset state of element.
	pub fn reset_state(&mut self) {
		// let prev_state = self.data.state();
		self.data.set_state(BehaviorState::Idle);
		// if prev_state != BehaviorState::Idle {
		// 	// @TODO: tree_node.cpp TreeNode::resetStatus()
		// 	todo!()
		// }
	}

	/// Add a pre state change callback with the given name.
	/// The name is not unique, which is important when removing callback.
	pub fn add_pre_state_change_callback<T>(&mut self, name: ConstString, callback: T)
	where
		T: Fn(&BehaviorData, &mut BehaviorState) + Send + Sync + 'static,
	{
		self.data
			.add_pre_state_change_callback(name, callback);
	}

	/// Remove any pre state change callback with the given name.
	pub fn remove_pre_state_change_callback(&mut self, name: &str) {
		self.data.remove_pre_state_change_callback(name);
	}

	/// Return an iterator over the children.
	#[must_use]
	pub fn children_iter(&self) -> impl DoubleEndedIterator<Item = &Self> {
		self.children().iter()
	}

	/// Return a mutable iterator over the children.
	#[must_use]
	pub fn children_iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut Self> {
		self.children_mut().iter_mut()
	}

	/// Get an iterator over the tree element.
	pub fn iter(&self) -> impl Iterator<Item = &Self> {
		TreeIter::new(self)
	}

	/// Get a mutable iterator over the tree element.
	pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Self> {
		TreeIterMut::new(self)
	}

	pub const fn kind(&self) -> TreeElementKind {
		self.kind
	}

	fn check_pre_conditions(&mut self, runtime: &SharedRuntime) -> Result<Option<BehaviorState>, Error> {
		if self.conditions.pre.is_some() {
			// Preconditions only applied when the node state is `Idle` or `Skipped`
			if self.data.state() == BehaviorState::Idle || self.data.state() == BehaviorState::Skipped {
				if let Some(script) = self.conditions.pre.get(FAILURE_IF) {
					let res = runtime
						.lock()
						.run(script, self.data.blackboard_mut())?;
					if bool::try_from(res)? {
						return Ok(Some(BehaviorState::Failure));
					}
				}
				if let Some(script) = self.conditions.pre.get(SUCCESS_IF) {
					let res = runtime
						.lock()
						.run(script, self.data.blackboard_mut())?;
					if bool::try_from(res)? {
						return Ok(Some(BehaviorState::Success));
					}
				}
				if let Some(script) = self.conditions.pre.get(SKIP_IF) {
					let res = runtime
						.lock()
						.run(script, self.data.blackboard_mut())?;
					if bool::try_from(res)? {
						return Ok(Some(BehaviorState::Skipped));
					}
				}
				if let Some(script) = self.conditions.pre.get(WHILE) {
					let res = runtime
						.lock()
						.run(script, self.data.blackboard_mut())?;
					if bool::try_from(res)? {
						return Ok(Some(BehaviorState::Skipped));
					}
				}
			} else
			// Preconditions only applied when the node state is `Running`
			if self.data.state() == BehaviorState::Running
				&& let Some(script) = self.conditions.pre.get(WHILE)
			{
				let res = runtime
					.lock()
					.run(script, self.data.blackboard_mut())?;
				// if not true halt element and return `Skipped`
				if bool::try_from(res)? {
					let _res = self.halt(runtime);
					return Ok(Some(BehaviorState::Skipped));
				}
			}
		}
		Ok(None)
	}

	fn check_post_conditions(&mut self, state: BehaviorState, runtime: &SharedRuntime) -> Result<(), Error> {
		if self.conditions.post.is_some() {
			match state {
				BehaviorState::Failure => {
					if let Some(script) = self.conditions.post.get(ON_FAILURE) {
						let _ = runtime
							.lock()
							.run(script, self.data.blackboard_mut())?;
					}
				}
				BehaviorState::Success => {
					if let Some(script) = self.conditions.post.get(ON_SUCCESS) {
						let _ = runtime
							.lock()
							.run(script, self.data.blackboard_mut())?;
					}
				}
				// rest is ignored
				_ => {}
			}
			if let Some(script) = self.conditions.post.get(POST) {
				let _ = runtime
					.lock()
					.run(script, self.data.blackboard_mut())?;
			}
		}
		Ok(())
	}

	/// Returns the Groot2 style 'path' of the element.
	#[must_use]
	pub const fn groot2_path(&self) -> &ConstString {
		self.data.description().groot2_path()
	}

	/// Returns the current state of the element.
	#[must_use]
	pub const fn state(&self) -> BehaviorState {
		self.data.state()
	}

	/// Adds a child to the elements children list.
	pub fn add_child(&mut self, child: Self) {
		self.children.push(child);
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::{
		behavior_data::BehaviorData,
		behavior_description::BehaviorDescription,
		behavior_state::BehaviorState,
		behaviors::mock_behavior::{MockBehavior, MockBehaviorConfig},
		pre_post_conditions::Conditions,
	};
	use databoard::Databoard;

	/// Covers `BehaviorTreeElement::new()` constructor (lines 60-74).
	/// Uses internal types (`Conditions`, `BehaviorTreeElementList`) since we are in the crate.
	#[test]
	fn new_constructor_covers_all_lines() {
		let behavior: BehaviorPtr = alloc::boxed::Box::new(MockBehavior::new(MockBehaviorConfig {
			return_state: BehaviorState::Success,
			..Default::default()
		}));
		let data = BehaviorData::create(
			42,
			Databoard::default(),
			BehaviorDescription::new("test_node", "test_node", false),
		);
		let children = BehaviorTreeElementList::default();
		let conditions = Conditions::default();

		let element = BehaviorTreeElement::new(TreeElementKind::Node, behavior, data, children, conditions);

		assert_eq!(element.uid(), 42);
		assert_eq!(element.name().as_ref(), "test_node");
		assert!(matches!(element.kind(), TreeElementKind::Node));
		assert_eq!(element.children().len(), 0);
	}
}