forked from BehaviorTree/BehaviorTree.CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree_node.cpp
495 lines (429 loc) · 11.7 KB
/
tree_node.cpp
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
/* Copyright (C) 2015-2018 Michele Colledanchise - All Rights Reserved
* Copyright (C) 2018-2022 Davide Faconti, Eurecat - All Rights Reserved
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "behaviortree_cpp/tree_node.h"
#include <cstring>
#include <array>
namespace BT
{
struct TreeNode::PImpl
{
PImpl(std::string name, NodeConfig config):
name(std::move(name)),
config(std::move(config))
{}
const std::string name;
NodeStatus status = NodeStatus::IDLE;
std::condition_variable state_condition_variable;
mutable std::mutex state_mutex;
StatusChangeSignal state_change_signal;
NodeConfig config;
std::string registration_ID;
PreTickCallback substitution_callback;
PostTickCallback post_condition_callback;
std::mutex callback_injection_mutex;
std::shared_ptr<WakeUpSignal> wake_up;
std::array<ScriptFunction, size_t(PreCond::COUNT_)> pre_parsed;
std::array<ScriptFunction, size_t(PostCond::COUNT_)> post_parsed;
};
TreeNode::TreeNode(std::string name, NodeConfig config) :
_p(new PImpl(std::move(name), std::move(config)))
{
}
TreeNode::TreeNode(TreeNode &&other) noexcept
{
this->_p = std::move(other._p);
}
TreeNode &TreeNode::operator=(TreeNode &&other) noexcept
{
this->_p = std::move(other._p);
return *this;
}
TreeNode::~TreeNode() {}
NodeStatus TreeNode::executeTick()
{
auto new_status = _p->status;
// a pre-condition may return the new status.
// In this case it override the actual tick()
if (auto precond = checkPreConditions())
{
new_status = precond.value();
}
else
{
// injected pre-callback
bool substituted = false;
if(!isStatusCompleted(_p->status))
{
PreTickCallback callback;
{
std::unique_lock lk(_p->callback_injection_mutex);
callback = _p->substitution_callback;
}
if(callback)
{
auto override_status = callback(*this);
if(isStatusCompleted(override_status))
{
// don't execute the actual tick()
substituted = true;
new_status = override_status;
}
}
}
// Call the ACTUAL tick
if(!substituted){
new_status = tick();
}
}
checkPostConditions(new_status);
// injected post callback
if(isStatusCompleted(new_status))
{
PostTickCallback callback;
{
std::unique_lock lk(_p->callback_injection_mutex);
callback = _p->post_condition_callback;
}
if(callback)
{
auto override_status = callback(*this, new_status);
if(isStatusCompleted(override_status))
{
new_status = override_status;
}
}
}
// preserve the IDLE state if skipped, but communicate SKIPPED to parent
if(new_status != NodeStatus::SKIPPED) {
setStatus(new_status);
}
return new_status;
}
void TreeNode::haltNode()
{
halt();
const auto& parse_executor = _p->post_parsed[size_t(PostCond::ON_HALTED)];
if (parse_executor)
{
Ast::Environment env = {config().blackboard, config().enums};
parse_executor(env);
}
}
void TreeNode::setStatus(NodeStatus new_status)
{
if (new_status == NodeStatus::IDLE)
{
throw RuntimeError("Node [", name(),
"]: you are not allowed to set manually the status to IDLE. "
"If you know what you are doing (?) use resetStatus() instead.");
}
NodeStatus prev_status;
{
std::unique_lock<std::mutex> UniqueLock(_p->state_mutex);
prev_status = _p->status;
_p->status = new_status;
}
if (prev_status != new_status)
{
_p->state_condition_variable.notify_all();
_p->state_change_signal.notify(std::chrono::high_resolution_clock::now(), *this,
prev_status, new_status);
}
}
TreeNode::PreScripts &TreeNode::preConditionsScripts() {
return _p->pre_parsed;
}
TreeNode::PostScripts &TreeNode::postConditionsScripts() {
return _p->post_parsed;
}
Expected<NodeStatus> TreeNode::checkPreConditions()
{
Ast::Environment env = {config().blackboard, config().enums};
// check the pre-conditions
for (size_t index = 0; index < size_t(PreCond::COUNT_); index++)
{
const auto& parse_executor = _p->pre_parsed[index];
if (!parse_executor)
{
continue;
}
const PreCond preID = PreCond(index);
// Some preconditions are applied only when the node state is IDLE or SKIPPED
if (_p->status == NodeStatus::IDLE ||
_p->status == NodeStatus::SKIPPED)
{
// what to do if the condition is true
if (parse_executor(env).cast<bool>())
{
if (preID == PreCond::FAILURE_IF)
{
return NodeStatus::FAILURE;
}
else if (preID == PreCond::SUCCESS_IF)
{
return NodeStatus::SUCCESS;
}
else if (preID == PreCond::SKIP_IF)
{
return NodeStatus::SKIPPED;
}
}
// if the conditions is false
else if(preID == PreCond::WHILE_TRUE)
{
return NodeStatus::SKIPPED;
}
}
else if(_p->status == NodeStatus::RUNNING && preID == PreCond::WHILE_TRUE)
{
// what to do if the condition is false
if (!parse_executor(env).cast<bool>())
{
haltNode();
return NodeStatus::SKIPPED;
}
}
}
return nonstd::make_unexpected(""); // no precondition
}
void TreeNode::checkPostConditions(NodeStatus status)
{
auto ExecuteScript = [this](const PostCond& cond) {
const auto& parse_executor = _p->post_parsed[size_t(cond)];
if (parse_executor)
{
Ast::Environment env = {config().blackboard, config().enums};
parse_executor(env);
}
};
if (status == NodeStatus::SUCCESS)
{
ExecuteScript(PostCond::ON_SUCCESS);
}
else if (status == NodeStatus::FAILURE)
{
ExecuteScript(PostCond::ON_FAILURE);
}
ExecuteScript(PostCond::ALWAYS);
}
void TreeNode::resetStatus()
{
NodeStatus prev_status;
{
std::unique_lock<std::mutex> lock(_p->state_mutex);
prev_status = _p->status;
_p->status = NodeStatus::IDLE;
}
if (prev_status != NodeStatus::IDLE)
{
_p->state_condition_variable.notify_all();
_p->state_change_signal.notify(std::chrono::high_resolution_clock::now(), *this,
prev_status, NodeStatus::IDLE);
}
}
NodeStatus TreeNode::status() const
{
std::lock_guard<std::mutex> lock(_p->state_mutex);
return _p->status;
}
NodeStatus TreeNode::waitValidStatus()
{
std::unique_lock<std::mutex> lock(_p->state_mutex);
while (isHalted())
{
_p->state_condition_variable.wait(lock);
}
return _p->status;
}
const std::string& TreeNode::name() const
{
return _p->name;
}
bool TreeNode::isHalted() const
{
return _p->status == NodeStatus::IDLE;
}
TreeNode::StatusChangeSubscriber
TreeNode::subscribeToStatusChange(TreeNode::StatusChangeCallback callback)
{
return _p->state_change_signal.subscribe(std::move(callback));
}
void TreeNode::setPreTickFunction(PreTickCallback callback)
{
std::unique_lock lk(_p->callback_injection_mutex);
_p->substitution_callback = callback;
}
void TreeNode::setPostTickFunction(PostTickCallback callback)
{
std::unique_lock lk(_p->callback_injection_mutex);
_p->post_condition_callback = callback;
}
uint16_t TreeNode::UID() const
{
return _p->config.uid;
}
const std::string &TreeNode::fullPath() const
{
return _p->config.path;
}
const std::string& TreeNode::registrationName() const
{
return _p->registration_ID;
}
const NodeConfig &TreeNode::config() const
{
return _p->config;
}
NodeConfig &TreeNode::config()
{
return _p->config;
}
StringView TreeNode::getRawPortValue(const std::string& key) const
{
auto remap_it = _p->config.input_ports.find(key);
if (remap_it == _p->config.input_ports.end())
{
remap_it = _p->config.output_ports.find(key);
if (remap_it == _p->config.output_ports.end())
{
throw std::logic_error(StrCat("[", key, "] not found"));
}
}
return remap_it->second;
}
bool TreeNode::isBlackboardPointer(StringView str, StringView* stripped_pointer)
{
if (str.size() < 3)
{
return false;
}
// strip leading and following spaces
size_t front_index = 0;
size_t last_index = str.size()-1;
while(str[front_index] == ' ' && front_index <= last_index)
{
front_index++;
}
while(str[last_index] == ' ' && front_index <= last_index)
{
last_index--;
}
const auto size = (last_index-front_index) + 1;
auto valid = size >= 3 && str[front_index] == '{' && str[last_index] == '}';
if(valid && stripped_pointer)
{
*stripped_pointer = StringView( &str[front_index+1], size-2);
}
return valid;
}
StringView TreeNode::stripBlackboardPointer(StringView str)
{
StringView out;
if(isBlackboardPointer(str, &out))
{
return out;
}
return {};
}
Expected<StringView> TreeNode::getRemappedKey(StringView port_name,
StringView remapped_port)
{
if (remapped_port == "=")
{
return {port_name};
}
StringView stripped;
if (isBlackboardPointer(remapped_port, &stripped))
{
return {stripped};
}
return nonstd::make_unexpected("Not a blackboard pointer");
}
void TreeNode::emitWakeUpSignal()
{
if (_p->wake_up)
{
_p->wake_up->emitSignal();
}
}
bool TreeNode::requiresWakeUp() const
{
return bool(_p->wake_up);
}
void TreeNode::setRegistrationID(StringView ID)
{
_p->registration_ID.assign(ID.data(), ID.size());
}
void TreeNode::setWakeUpInstance(std::shared_ptr<WakeUpSignal> instance)
{
_p->wake_up = instance;
}
void TreeNode::modifyPortsRemapping(const PortsRemapping& new_remapping)
{
for (const auto& new_it : new_remapping)
{
auto it = _p->config.input_ports.find(new_it.first);
if (it != _p->config.input_ports.end())
{
it->second = new_it.second;
}
it = _p->config.output_ports.find(new_it.first);
if (it != _p->config.output_ports.end())
{
it->second = new_it.second;
}
}
}
template <>
std::string toStr<PreCond>(const PreCond& pre)
{
switch (pre)
{
case PreCond::SUCCESS_IF:
return "_successIf";
case PreCond::FAILURE_IF:
return "_failureIf";
case PreCond::SKIP_IF:
return "_skipIf";
case PreCond::WHILE_TRUE:
return "_while";
default:
return "Undefined";
}
}
template <>
std::string toStr<PostCond>(const PostCond& pre)
{
switch (pre)
{
case PostCond::ON_SUCCESS:
return "_onSuccess";
case PostCond::ON_FAILURE:
return "_onFailure";
case PostCond::ALWAYS:
return "_post";
case PostCond::ON_HALTED:
return "_onHalted";
default:
return "Undefined";
}
}
AnyPtrLocked BT::TreeNode::getLockedPortContent(const std::string &key)
{
if(auto remapped_key = getRemappedKey(key, getRawPortValue(key)))
{
return _p->config.blackboard->getAnyLocked(std::string(*remapped_key));
}
return {};
}
} // namespace BT