behaviortree 0.7.4

A #![no_std] compatible behavior tree library similar to 'BehaviorTree.CPP'.
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
// Copyright © 2025 Stephan Kunz

//! XML parser for the [`BehaviorTreeFactory`]

#[doc(hidden)]
#[cfg(feature = "std")]
extern crate std;

use alloc::{
	boxed::Box,
	string::{String, ToString},
};
// region:      --- modules
use crate::{
	ACTION, BEHAVIORTREE, CONDITION, CONTROL, ConstString, DECORATOR, DEFAULT, EMPTY_STR, ID, NAME, SUBTREE, TREENODESMODEL,
	behavior::{BehaviorDataCollection, BehaviorKind, BehaviorPtr, pre_post_conditions::Conditions},
	factory::registry::{BehaviorRegistry, TreeNodesModelEntry},
	port::{PortDirection, is_allowed_port_name},
	tree::{BehaviorTreeElement, BehaviorTreeElementList},
	xml::error::Error,
};
use databoard::{Databoard, RemappingList, strip_board_pointer};
use roxmltree::{Document, Node, NodeType};
#[cfg(feature = "std")]
use std::path::PathBuf;
// endregion:   --- modules

// region:		--- helper
fn create_data_collection_from_xml<'a>(
	registry: &'a BehaviorRegistry,
	path: &str,
	element: &'a Node,
	uid: u16,
	blackboard: Option<&Databoard>,
	is_root: bool,
) -> Result<Box<BehaviorDataCollection<'a>>, Error> {
	let (behavior_id, behavior_kind) = {
		let tag_name = element.tag_name().name();
		match tag_name {
			BEHAVIORTREE => {
				if let Some(id) = element.attribute(ID) {
					(id, SUBTREE)
				} else {
					return Err(Error::MissingId { tag: tag_name.into() });
				}
			}
			ACTION | CONDITION | CONTROL | DECORATOR | SUBTREE => {
				if let Some(id) = element.attribute(ID) {
					(id, tag_name)
				} else {
					return Err(Error::MissingId { tag: tag_name.into() });
				}
			}
			_ => (tag_name, EMPTY_STR),
		}
	};
	let is_subtree = behavior_kind == SUBTREE;

	// if behavior has no assigned name, use beavior id
	let behavior_name = element
		.attribute(NAME)
		.map_or_else(|| behavior_id.to_string(), ToString::to_string);
	let mut path = String::from(path) + "/" + &behavior_name;
	// in case no explicit name was given, we extend the node_name with the uid
	if element.attribute(NAME).is_none() {
		path.push_str("::");
		path.push_str(&uid.to_string());
	}

	// look for the behavior in the `BehaviorRegistry`
	#[cfg(feature = "mock_behavior")]
	let res = if is_subtree {
		registry.fetch_behavior(SUBTREE, &path)
	} else {
		registry.fetch_behavior(behavior_id, &path)
	};
	#[cfg(not(feature = "mock_behavior"))]
	let res = if is_subtree {
		registry.fetch_behavior(SUBTREE)
	} else {
		registry.fetch_behavior(behavior_id)
	};
	let Ok((mut bhvr_desc, bhvr)) = res else {
		return Err(Error::NotRegistered {
			behavior: behavior_id.into(),
		});
	};
	bhvr_desc.set_name(&behavior_name);
	bhvr_desc.set_path(&path);

	let (autoremap, mut remappings, conditions) = handle_attributes(registry, behavior_id, behavior_kind, &bhvr, element)?;

	let blackboard = blackboard.map_or_else(Databoard::new, |blackboard| {
		if is_subtree && !is_root {
			// A SubTree gets a new Blackboard with parent and remappings.
			let mut new_remappings = RemappingList::default();
			core::mem::swap(&mut new_remappings, &mut remappings);
			Databoard::with(Some(blackboard.clone()), Some(new_remappings), autoremap)
		} else {
			blackboard.clone()
		}
	});

	Ok(Box::new(BehaviorDataCollection {
		behavior_name,
		path,
		bhvr_desc,
		blackboard,
		bhvr,
		remappings,
		conditions,
		uid,
		registry,
	}))
}

#[allow(clippy::too_many_lines)]
fn handle_attributes(
	registry: &BehaviorRegistry,
	behavior_id: &str,
	behavior_kind: &str,
	bhvr: &BehaviorPtr,
	node: &Node,
) -> Result<
	(
		/*autoremap:*/ bool,
		/*remappings:*/ RemappingList,
		/*pre&post conditions:*/ Conditions,
	),
	Error,
> {
	let mut autoremap = false;
	let mut remappings = RemappingList::default();
	let mut conditions = Conditions::default();
	// let mut preconditions = PreConditions::default();
	// let mut postconditions = PostConditions::default();

	// port list is needed twice:
	// - for checking port names in given attributes
	// - to add default values
	let port_list = bhvr.static_provided_ports();

	// first check for default values given in port definition.
	// this value can later be overwritten by default values given by xml attribute
	for port_definition in port_list.iter() {
		if let Some(default_value) = port_definition.default_value() {
			match remappings.add(port_definition.name(), default_value.clone()) {
				Ok(()) => {}
				Err(err) => {
					return Err(Error::Databoard {
						key: port_definition.name().into(),
						source: err,
					});
				}
			}
		}
	}

	// second fill in remappings from available TreeNodesModel's
	for entry in registry.tree_nodes_models() {
		if entry.0.contains(behavior_id) {
			match remappings.add(entry.1.key.clone(), entry.1.remapping.clone()) {
				Ok(()) => {}
				Err(err) => {
					return Err(Error::Databoard {
						key: entry.1.key.clone(),
						source: err,
					});
				}
			}
		}
	}

	// third handle attributes
	for attribute in node.attributes() {
		let key = attribute.name();
		let value = attribute.value();
		if key == NAME {
			// port "name" is always available
		} else if key == ID {
			// ignore as it is not a Port
		} else if key.starts_with('_') {
			// these are special attributes
			match key {
				crate::AUTOREMAP => {
					autoremap = match attribute.value().parse::<bool>() {
						Ok(val) => val,
						Err(_) => return Err(Error::WrongAutoremap),
					};
				}
				// preconditions
				crate::FAILURE_IF | crate::SKIP_IF | crate::SUCCESS_IF | crate::WHILE => {
					match conditions.pre.set(key, value) {
						Ok(()) => {}
						Err(err) => {
							return Err(Error::Condition {
								key: key.into(),
								source: err,
							});
						}
					}
				}
				// postconditions
				crate::ON_FAILURE | crate::ON_HALTED | crate::ON_SUCCESS | crate::POST => {
					match conditions.post.set(key, value) {
						Ok(()) => {}
						Err(err) => {
							return Err(Error::Condition {
								key: key.into(),
								source: err,
							});
						}
					}
				}
				_ => return Err(Error::UnknownAttribute { key: key.into() }),
			}
		} else {
			// for a subtree we cannot check against a port list
			if behavior_kind == SUBTREE {
				match remappings.overwrite(key, value) {
					Ok(res) => res,
					Err(err) => {
						return Err(Error::Databoard {
							key: key.into(),
							source: err,
						});
					}
				}
			} else {
				// check key against list of provided ports
				match port_list.find(key) {
					Some(_port) => {
						match strip_board_pointer(value) {
							Some(stripped) => {
								if stripped == "=" {
									if is_allowed_port_name(key) {
										let bb_pointer = String::from("{") + key + "}";
										match remappings.overwrite(key, bb_pointer) {
											Ok(res) => res,
											Err(err) => {
												return Err(Error::Databoard {
													key: key.into(),
													source: err,
												});
											}
										}
									} else {
										return Err(Error::NameNotAllowed { key: key.into() });
									}
								} else {
									// check if 'value' contains a valid BB pointer
									if is_allowed_port_name(stripped) {
										match remappings.overwrite(key, value) {
											Ok(res) => res,
											Err(err) => {
												return Err(Error::Databoard {
													key: key.into(),
													source: err,
												});
											}
										}
									} else {
										return Err(Error::NameNotAllowed { key: key.into() });
									}
								}
							}
							// Normal string, representing a const assignment
							None => match remappings.overwrite(key, value) {
								Ok(res) => res,
								Err(err) => {
									return Err(Error::Databoard {
										key: key.into(),
										source: err,
									});
								}
							},
						}
					}
					None => {
						return Err(Error::PortInvalid {
							port: key.into(),
							behavior: behavior_id.into(),
						});
					}
				}
			}
		}
	}
	remappings.shrink();
	Ok((autoremap, remappings, conditions))
}
// endregion:	--- helper

// region:      --- XmlParser
#[derive(Default)]
pub struct XmlParser {
	uid: u16,
}

impl XmlParser {
	/// Returns the root element for a [`BehaviorTree`](crate::tree::BehaviorTree).
	/// If an external blackboard is given, it will be used as a root blackboard.
	/// # Errors
	/// - if a needed behavior is not registered.
	/// - if an [`Action`] or [`Condition`] has children.
	/// - if a [`Decorator`] or [`SubTree`] has more than one child.
	/// - if a [`SubTree`] has no `ID` attribute given.
	pub(crate) fn create_tree_from_definition(
		&mut self,
		name: &str,
		registry: &BehaviorRegistry,
		external_blackboard: Option<&Databoard>,
	) -> Result<BehaviorTreeElement, Error> {
		registry.find_tree_definition(name).map_or_else(
			|| Err(Error::DefinitionNotFound { id: name.into() }),
			|(definition, range)| {
				let doc = Box::new(Document::parse(&definition[range])?);
				let element = Box::new(doc.root_element());
				let data = create_data_collection_from_xml(
					registry,
					EMPTY_STR,
					&element,
					self.next_uid(),
					external_blackboard,
					true,
				)?;
				// for tree root "path" is empty
				let children = self.build_children(&data, &element)?;
				if children.len() > 1 {
					return Err(Error::OneChild { behavior: name.into() });
				}
				let behaviortree = BehaviorTreeElement::create_subtree(data, children);
				Ok(behaviortree)
			},
		)
	}

	/// Registers the behavior (sub)tree definitions contained in the XML description.
	/// In `std` environments the file path of the XML description is used for
	/// implementation of the `<include path="..."/>` tags.
	/// # Errors
	/// - if the XML document is invalid.
	/// - if the XML has nested root elements.
	/// - if a behavior is already registered.
	pub(crate) fn register_document(
		registry: &mut BehaviorRegistry,
		xml: impl Into<ConstString>,
		#[cfg(feature = "std")] path: &ConstString,
	) -> Result<(), Error> {
		let xml = xml.into();
		// general checks
		let doc = Box::new(Document::parse(&xml)?);
		let root = Box::new(doc.root_element());
		if root.tag_name().name() != "root" {
			return Err(Error::WrongRootName);
		}
		if let Some(format) = root.attribute("BTCPP_format")
			&& format != "4"
		{
			return Err(Error::BtCppFormat);
		}

		// handle the attribute 'main_tree_to_execute`
		if let Some(name) = root.attribute("main_tree_to_execute") {
			registry.set_main_tree_id(name);
		}
		#[cfg(feature = "std")]
		Self::register_document_root(registry, &root, &xml, path)?;
		#[cfg(not(feature = "std"))]
		Self::register_document_root(registry, &root, &xml)?;
		Ok(())
	}

	/// Registers the content of documents root element.
	/// # Errors
	/// - if the XML document is invalid.
	/// - if the XML has nested root elements.
	/// - if a behavior is already registered.
	fn register_document_root(
		registry: &mut BehaviorRegistry,
		root: &Node,
		// the source is referenced multiple times, thats why it is passed in as &ConstString
		source: &ConstString,
		// the path is only necessary when loading xml from files
		#[cfg(feature = "std")] path: &ConstString,
	) -> Result<(), Error> {
		for element in root.children() {
			match element.node_type() {
				NodeType::Comment | NodeType::Text => {} // ignore
				NodeType::Root => return Err(Error::InvalidRootElement),
				NodeType::Element => {
					// only 'BehaviorTree' or 'TreeNodesModel' are valid
					let name = element.tag_name().name();
					match name {
						TREENODESMODEL => {
							Self::register_tree_nodes_model(registry, &element)?;
						}
						BEHAVIORTREE => {
							// check for tree ID
							if let Some(id) = element.attribute(ID) {
								// if no explicit main tree id is given, the first found id will be used for main tree
								if registry.main_tree_id().is_none() {
									registry.set_main_tree_id(id);
								}
								match registry.add_tree_defintion(id, source.clone(), element.range()) {
									Ok(()) => {}
									Err(err) => {
										return Err(Error::Factory {
											behavior: id.into(),
											source: err,
										});
									}
								}
							} else {
								return Err(Error::MissingId {
									tag: element.tag_name().name().into(),
								});
							}
						}
						#[cfg(feature = "std")]
						"include" => {
							let mut file_path: PathBuf;
							if let Some(path_attr) = element.attribute("path") {
								file_path = PathBuf::from(path_attr);
								if file_path.is_relative() {
									// use the given path
									file_path = PathBuf::from(path.as_ref());
									file_path.push(path_attr);
								}
							} else {
								return Err(Error::MissingPath {
									tag: element.tag_name().name().into(),
								});
							}
							match std::fs::read_to_string(&file_path) {
								Ok(xml) => {
									if let Some(cur_path) = file_path.parent() {
										let path = cur_path.to_string_lossy().into();
										Self::register_document(registry, xml, &path)?;
									} else {
										return Err(Error::ReadFile {
											name: file_path.to_string_lossy().into(),
											cause: "no parent".into(),
										});
									}
								}
								Err(err) => {
									return Err(Error::ReadFile {
										name: file_path.to_string_lossy().into(),
										cause: err.to_string().into(),
									});
								}
							}
						}
						_ => {
							return Err(Error::UnsupportedElement {
								tag: element.tag_name().name().into(),
							});
						}
					}
				}
				NodeType::PI => {
					return Err(Error::UnsupportedElement {
						tag: element.tag_name().name().into(),
					});
				}
			}
		}
		Ok(())
	}

	/// Registers the behavior definitions contained in the `TreeNodesModel` tag.
	fn register_tree_nodes_model(registry: &mut BehaviorRegistry, model: &Node) -> Result<(), Error> {
		for element in model.children() {
			match element.node_type() {
				NodeType::Root => return Err(Error::InvalidRootElement),
				NodeType::Element => {
					// an entry in the tree nodes model
					let behavior_type = element.tag_name().name();
					let mut behavior_id = behavior_type;
					for attribute in element.attributes() {
						match attribute.name() {
							"ID" => {
								behavior_id = attribute.value();
							}
							"editable" => { /* ignore */ }
							value => {
								return Err(Error::UnknownAttribute { key: value.into() });
							}
						}
					}
					for child in element.children() {
						match child.node_type() {
							NodeType::Root => return Err(Error::InvalidRootElement),
							NodeType::Element => {
								let port_type = child.tag_name().name();
								if let Some(port_name) = child.attribute(NAME)
									&& let Some(port_default) = child.attribute(DEFAULT)
								{
									let key = String::from(behavior_id) + port_name;
									let Ok(port_type) = PortDirection::try_from(port_type) else {
										return Err(Error::PortType { value: port_type.into() });
									};
									let entry = TreeNodesModelEntry {
										_port_type: port_type,
										key: port_name.into(),
										remapping: port_default.into(),
									};
									match registry.add_tree_nodes_model_entry(key.into(), entry) {
										Ok(()) => {}
										Err(err) => {
											return Err(Error::Factory {
												behavior: behavior_id.into(),
												source: err,
											});
										}
									}
								}
							}
							NodeType::PI => {
								return Err(Error::UnsupportedElement {
									tag: element.tag_name().name().into(),
								});
							}
							NodeType::Comment | NodeType::Text => {}
						}
					}
				}
				NodeType::PI => {
					return Err(Error::UnsupportedElement {
						tag: element.tag_name().name().into(),
					});
				}
				NodeType::Comment | NodeType::Text => {}
			}
		}
		Ok(())
	}

	/// Returns a list of all child behavior tree elements.
	/// # Errors
	/// - if a needed behavior is not registered.
	/// - if an [`Action`] or [`Condition`] has children.
	/// - if a [`Decorator`] or [`SubTree`] has more than one child.
	/// - if a [`SubTree`] has no `ID` attribute given.
	fn build_children(
		&mut self,
		parent_data: &BehaviorDataCollection,
		parent_element: &Node,
	) -> Result<BehaviorTreeElementList, Error> {
		// @TODO: improve error messages with parent element & current element
		let mut children = BehaviorTreeElementList::default();
		for child_element in parent_element.children() {
			match child_element.node_type() {
				NodeType::Comment | NodeType::Text => {} // ignore
				NodeType::Root => {
					// this should not happen
					return Err(Error::InvalidRootElement);
				}
				NodeType::Element => {
					let new_child = {
						let child_data = create_data_collection_from_xml(
							parent_data.registry,
							&parent_data.path,
							&child_element,
							self.next_uid(),
							Some(&parent_data.blackboard),
							false,
						)?;
						match child_data.bhvr_desc.kind() {
							BehaviorKind::Action | BehaviorKind::Condition => {
								if child_element.has_children() {
									return Err(Error::ChildrenNotAllowed {
										behavior: child_data.behavior_name.into(),
									});
								}
								BehaviorTreeElement::create_leaf(child_data)
							}
							BehaviorKind::Control | BehaviorKind::Decorator => {
								let children = self.build_children(&child_data, &child_element)?;
								if child_data.bhvr_desc.kind() == BehaviorKind::Decorator && children.len() != 1 {
									return Err(Error::OneChild {
										behavior: child_element.tag_name().name().into(),
									});
								}
								BehaviorTreeElement::create_node(child_data, children)
							}
							BehaviorKind::SubTree => {
								if let Some(id) = child_element.attribute(ID) {
									match child_data.registry.find_tree_definition(id) {
										Some((definition, range)) => {
											let doc = Box::new(Document::parse(&definition[range])?);
											let children = self.build_children(&child_data, &doc.root_element())?;
											if children.len() > 1 {
												return Err(Error::OneChild { behavior: id.into() });
											}
											BehaviorTreeElement::create_subtree(child_data, children)
										}
										None => {
											return Err(Error::DefinitionNotFound {
												id: child_data.behavior_name.into(),
											});
										}
									}
								} else {
									return Err(Error::MissingId {
										tag: child_element.tag_name().name().into(),
									});
								}
							}
						}
					};
					children.push(new_child);
				}
				NodeType::PI => {
					return Err(Error::UnsupportedElement {
						tag: child_element.tag_name().name().into(),
					});
				}
			}
		}
		Ok(children)
	}

	/// Get the next uid for a [`BehaviorTreeElement`].
	/// The maximum allowed number of behaviors in a tree is 65535!
	/// # Panics
	/// - if more than 65535 [`BehaviorTreeElement`]s are created for a [`BehaviorTree`](crate::tree::BehaviorTree)
	const fn next_uid(&mut self) -> u16 {
		let next = self.uid;
		self.uid += 1;
		next
	}
}
// endregion:   --- XmlParser