forked from arvidsson/BrainTree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BrainTree.h
600 lines (479 loc) · 14.4 KB
/
BrainTree.h
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
// BrainTree - C++ behavior tree single header library
// Copyright 2017 Pär Arvidsson. All rights reserved.
// Licensed under the MIT license (https://github.com/arvidsson/BrainTree/blob/master/LICENSE).
#pragma once
#include <memory>
#include <vector>
#include <string>
#include <unordered_map>
#include <cassert>
namespace BrainTree
{
class Node
{
public:
enum class Status
{
Invalid,
Success,
Failure,
Running,
};
virtual ~Node() {}
virtual Status update() = 0;
virtual void initialize() {}
virtual void terminate(Status s) {}
Status tick()
{
if (status != Status::Running) {
initialize();
}
status = update();
if (status != Status::Running) {
terminate(status);
}
return status;
}
bool isSuccess() const { return status == Status::Success; }
bool isFailure() const { return status == Status::Failure; }
bool isRunning() const { return status == Status::Running; }
bool isTerminated() const { return isSuccess() || isFailure(); }
void reset() { status = Status::Invalid; }
using Ptr = std::shared_ptr<Node>;
protected:
Status status = Status::Invalid;
};
class Composite : public Node
{
public:
Composite() : it(children.begin()) {}
virtual ~Composite() {}
void addChild(Node::Ptr child) { children.push_back(child); }
bool hasChildren() const { return !children.empty(); }
protected:
std::vector<Node::Ptr> children;
std::vector<Node::Ptr>::iterator it;
};
class Decorator : public Node
{
public:
virtual ~Decorator() {}
void setChild(Node::Ptr node) { child = node; }
bool hasChild() const { return child != nullptr; }
protected:
Node::Ptr child = nullptr;
};
class Blackboard
{
public:
void setBool(std::string key, bool value) { bools[key] = value; }
bool getBool(std::string key)
{
if (bools.find(key) == bools.end()) {
bools[key] = false;
}
return bools[key];
}
bool hasBool(std::string key) const { return bools.find(key) != bools.end(); }
void setInt(std::string key, int value) { ints[key] = value; }
int getInt(std::string key)
{
if (ints.find(key) == ints.end()) {
ints[key] = 0;
}
return ints[key];
}
bool hasInt(std::string key) const { return ints.find(key) != ints.end(); }
void setFloat(std::string key, float value) { floats[key] = value; }
float getFloat(std::string key)
{
if (floats.find(key) == floats.end()) {
floats[key] = 0.0f;
}
return floats[key];
}
bool hasFloat(std::string key) const { return floats.find(key) != floats.end(); }
void setDouble(std::string key, double value) { doubles[key] = value; }
double getDouble(std::string key)
{
if (doubles.find(key) == doubles.end()) {
doubles[key] = 0.0f;
}
return doubles[key];
}
bool hasDouble(std::string key) const { return doubles.find(key) != doubles.end(); }
void setString(std::string key, std::string value) { strings[key] = value; }
std::string getString(std::string key)
{
if (strings.find(key) == strings.end()) {
strings[key] = "";
}
return strings[key];
}
bool hasString(std::string key) const { return strings.find(key) != strings.end(); }
using Ptr = std::shared_ptr<Blackboard>;
protected:
std::unordered_map<std::string, bool> bools;
std::unordered_map<std::string, int> ints;
std::unordered_map<std::string, float> floats;
std::unordered_map<std::string, double> doubles;
std::unordered_map<std::string, std::string> strings;
};
class Leaf : public Node
{
public:
Leaf() {}
virtual ~Leaf() {}
Leaf(Blackboard::Ptr blackboard) : blackboard(blackboard) {}
virtual Status update() = 0;
protected:
Blackboard::Ptr blackboard;
};
class BehaviorTree : public Node
{
public:
BehaviorTree() : blackboard(std::make_shared<Blackboard>()) {}
BehaviorTree(const Node::Ptr &rootNode) : BehaviorTree() { root = rootNode; }
Status update() { return root->tick(); }
void setRoot(const Node::Ptr &node) { root = node; }
Blackboard::Ptr getBlackboard() const { return blackboard; }
private:
Node::Ptr root = nullptr;
Blackboard::Ptr blackboard = nullptr;
};
template <class Parent>
class DecoratorBuilder;
template <class Parent>
class CompositeBuilder
{
public:
CompositeBuilder(Parent* parent, Composite* node) : parent(parent), node(node) {}
template <class NodeType, typename... Args>
CompositeBuilder<Parent> leaf(Args... args)
{
auto child = std::make_shared<NodeType>((args)...);
node->addChild(child);
return *this;
}
template <class CompositeType, typename... Args>
CompositeBuilder<CompositeBuilder<Parent>> composite(Args... args)
{
auto child = std::make_shared<CompositeType>((args)...);
node->addChild(child);
return CompositeBuilder<CompositeBuilder<Parent>>(this, (CompositeType*)child.get());
}
template <class DecoratorType, typename... Args>
DecoratorBuilder<CompositeBuilder<Parent>> decorator(Args... args)
{
auto child = std::make_shared<DecoratorType>((args)...);
node->addChild(child);
return DecoratorBuilder<CompositeBuilder<Parent>>(this, (DecoratorType*)child.get());
}
Parent& end()
{
return *parent;
}
private:
Parent * parent;
Composite* node;
};
template <class Parent>
class DecoratorBuilder
{
public:
DecoratorBuilder(Parent* parent, Decorator* node) : parent(parent), node(node) {}
template <class NodeType, typename... Args>
DecoratorBuilder<Parent> leaf(Args... args)
{
auto child = std::make_shared<NodeType>((args)...);
node->setChild(child);
return *this;
}
template <class CompositeType, typename... Args>
CompositeBuilder<DecoratorBuilder<Parent>> composite(Args... args)
{
auto child = std::make_shared<CompositeType>((args)...);
node->setChild(child);
return CompositeBuilder<DecoratorBuilder<Parent>>(this, (CompositeType*)child.get());
}
template <class DecoratorType, typename... Args>
DecoratorBuilder<DecoratorBuilder<Parent>> decorator(Args... args)
{
auto child = std::make_shared<DecoratorType>((args)...);
node->setChild(child);
return DecoratorBuilder<DecoratorBuilder<Parent>>(this, (DecoratorType*)child.get());
}
Parent& end()
{
return *parent;
}
private:
Parent * parent;
Decorator* node;
};
class Builder
{
public:
template <class NodeType, typename... Args>
Builder leaf(Args... args)
{
root = std::make_shared<NodeType>((args)...);
return *this;
}
template <class CompositeType, typename... Args>
CompositeBuilder<Builder> composite(Args... args)
{
root = std::make_shared<CompositeType>((args)...);
return CompositeBuilder<Builder>(this, (CompositeType*)root.get());
}
template <class DecoratorType, typename... Args>
DecoratorBuilder<Builder> decorator(Args... args)
{
root = std::make_shared<DecoratorType>((args)...);
return DecoratorBuilder<Builder>(this, (DecoratorType*)root.get());
}
Node::Ptr build()
{
assert(root != nullptr && "The Behavior Tree is empty!");
auto tree = std::make_shared<BehaviorTree>();
tree->setRoot(root);
return tree;
}
private:
Node::Ptr root;
};
// The Selector composite ticks each child node in order.
// If a child succeeds or runs, the selector returns the same status.
// In the next tick, it will try to run each child in order again.
// If all children fails, only then does the selector fail.
class Selector : public Composite
{
public:
void initialize() override
{
it = children.begin();
}
Status update() override
{
assert(hasChildren() && "Composite has no children");
while (it != children.end()) {
auto status = (*it)->tick();
if (status != Status::Failure) {
return status;
}
it++;
}
return Status::Failure;
}
};
// The Sequence composite ticks each child node in order.
// If a child fails or runs, the sequence returns the same status.
// In the next tick, it will try to run each child in order again.
// If all children succeeds, only then does the sequence succeed.
class Sequence : public Composite
{
public:
void initialize() override
{
it = children.begin();
}
Status update() override
{
assert(hasChildren() && "Composite has no children");
while (it != children.end()) {
auto status = (*it)->tick();
if (status != Status::Success) {
return status;
}
it++;
}
return Status::Success;
}
};
// The StatefulSelector composite ticks each child node in order, and remembers what child it prevously tried to tick.
// If a child succeeds or runs, the stateful selector returns the same status.
// In the next tick, it will try to run the next child or start from the beginning again.
// If all children fails, only then does the stateful selector fail.
class StatefulSelector : public Composite
{
public:
Status update() override
{
assert(hasChildren() && "Composite has no children");
while (it != children.end()) {
auto status = (*it)->tick();
if (status != Status::Failure) {
return status;
}
it++;
}
it = children.begin();
return Status::Failure;
}
};
// The StatefulSequence composite ticks each child node in order, and remembers what child it prevously tried to tick.
// If a child fails or runs, the stateful sequence returns the same status.
// In the next tick, it will try to run the next child or start from the beginning again.
// If all children succeeds, only then does the stateful sequence succeed.
class MemSequence : public Composite
{
public:
Status update() override
{
assert(hasChildren() && "Composite has no children");
while (it != children.end()) {
auto status = (*it)->tick();
if (status != Status::Success) {
return status;
}
it++;
}
it = children.begin();
return Status::Success;
}
};
class ParallelSequence : public Composite
{
public:
ParallelSequence(bool successOnAll = true, bool failOnAll = true) : useSuccessFailPolicy(true), successOnAll(successOnAll), failOnAll(failOnAll) {}
ParallelSequence(int minSuccess, int minFail) : minSuccess(minSuccess), minFail(minFail) {}
Status update() override
{
assert(hasChildren() && "Composite has no children");
int minimumSuccess = minSuccess;
int minimumFail = minFail;
if (useSuccessFailPolicy) {
if (successOnAll) {
minimumSuccess = children.size();
}
else {
minimumSuccess = 1;
}
if (failOnAll) {
minimumFail = children.size();
}
else {
minimumFail = 1;
}
}
int total_success = 0;
int total_fail = 0;
for (auto &child : children) {
auto status = child->tick();
if (status == Status::Success) {
total_success++;
}
if (status == Status::Failure) {
total_fail++;
}
}
if (total_success >= minimumSuccess) {
return Status::Success;
}
if (total_fail >= minimumFail) {
return Status::Failure;
}
return Status::Running;
}
private:
bool useSuccessFailPolicy = false;
bool successOnAll = true;
bool failOnAll = true;
int minSuccess = 0;
int minFail = 0;
};
// The Succeeder decorator returns success, regardless of what happens to the child.
class Succeeder : public Decorator
{
public:
Status update() override
{
child->tick();
return Status::Success;
}
};
// The Failer decorator returns failure, regardless of what happens to the child.
class Failer : public Decorator
{
public:
Status update() override
{
child->tick();
return Status::Failure;
}
};
// The Inverter decorator inverts the child node's status, i.e. failure becomes success and success becomes failure.
// If the child runs, the Inverter returns the status that it is running too.
class Inverter : public Decorator
{
public:
Status update() override
{
auto s = child->tick();
if (s == Status::Success) {
return Status::Failure;
}
else if (s == Status::Failure) {
return Status::Success;
}
return s;
}
};
// The Repeater decorator repeats infinitely or to a limit until the child returns success.
class Repeater : public Decorator
{
public:
Repeater(int limit = 0) : limit(limit) {}
void initialize() override
{
counter = 0;
}
Status update() override
{
while (1) {
auto s = child->tick();
if (s == Status::Running) {
return Status::Running;
}
if (s == Status::Failure) {
return Status::Failure;
}
if (limit > 0 && ++counter == limit) {
return Status::Success;
}
child->reset();
}
}
protected:
int limit;
int counter = 0;
};
// The UntilSuccess decorator repeats until the child returns success and then returns success.
class UntilSuccess : public Decorator
{
public:
Status update() override
{
while (1) {
auto status = child->tick();
if (status == Status::Success) {
return Status::Success;
}
}
}
};
// The UntilFailure decorator repeats until the child returns fail and then returns success.
class UntilFailure : public Decorator
{
public:
Status update() override
{
while (1) {
auto status = child->tick();
if (status == Status::Failure) {
return Status::Success;
}
}
}
};
} // namespace BrainTree