-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathBehaviorTree.cs
More file actions
579 lines (475 loc) · 14.1 KB
/
BehaviorTree.cs
File metadata and controls
579 lines (475 loc) · 14.1 KB
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
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
/*
* Best practices for serialization:
* - Don't use the `new` constructor
* - Instead use ScriptableObject.CreateInstance()
* - For initialization, use OnEnable() instead of the constructor
*
* Unity calls the constructor, deserializes the data (populating the object) and THEN calls OnEnable(),
* so the data is guaranteed to be there in this method.
*
*/
namespace Hivemind {
public enum Status
{
Success,
Failure,
Running,
Error
}
public class Context {
private Dictionary<string, object> context = new Dictionary<string, object>();
public Dictionary<string, object> All {
get { return context; }
}
public bool ContainsKey(string key) {
return context.ContainsKey(key);
}
public T Get<T>(string key) {
if (!context.ContainsKey(key)) {
throw new System.MissingMemberException(string.Format ("Key {0} not found in the current context", key));
}
T value = (T) context[key];
return value;
}
public T Get<T>(string key, T defaultValue) {
if (!context.ContainsKey(key)) {
Set<T>(key, defaultValue);
return defaultValue;
}
T value = (T) context[key];
return value;
}
public void Set<T>(string key, T value) {
context[key] = value;
}
public void Unset(string key) {
context.Remove (key);
}
}
[System.Serializable]
public class BehaviorTree : ScriptableObject {
public static string[] NodeTypes = {
"Action", "Inverter", "Parallel",
"RandomSelector", "Repeater", "Selector",
"Sequence", "Succeeder", "UntilSucceed"
};
public Root rootNode;
public List<Node> nodes = new List<Node>();
public bool debugMode = false;
public Node currentNode = null;
public int TotalTicks { get; private set; }
public delegate void NodeWillTick(Node node);
public delegate void NodeDidTick(Node node, Status result);
public NodeWillTick nodeWillTick;
public NodeDidTick nodeDidTick;
public void SetRoot(Root root) {
rootNode = root;
nodes.Add(root);
root.behaviorTree = this;
}
public T CreateNode<T>() where T : Node {
T node = (T) ScriptableObject.CreateInstance<T>();
node.behaviorTree = this;
return node;
}
// Lifecycle
public void OnEnable() {
hideFlags = HideFlags.HideAndDontSave;
}
public void OnDestroy() {
foreach (Node node in nodes) {
DestroyImmediate (node);
}
}
public Status Tick(GameObject agent, Context context) {
BehaviorTreeAgent btAgent = agent.GetComponent<BehaviorTreeAgent>();
if (btAgent) {
debugMode = btAgent.debugMode;
}
TotalTicks++;
Status result = rootNode.Tick(agent, context);
rootNode.lastStatus = result;
rootNode.lastTick = TotalTicks;
return result;
}
public Status Tick(Node node, GameObject agent, Context context) {
if (nodeWillTick != null && node != currentNode)
nodeWillTick(node);
Status result = node.Tick(agent, context);
if (nodeDidTick != null)
nodeDidTick(node, result);
currentNode = node;
node.lastStatus = result;
node.lastTick = TotalTicks;
return result;
}
public Node GetNodeByGUID(string GUID) {
foreach (Node node in nodes) {
if (node.GUID == GUID) return node;
}
return null;
}
}
[System.Serializable]
public class Node : ScriptableObject, System.IComparable {
// Editor settings
[SerializeField]
public Vector2 editorPosition;
// The Behavior Tree this node belongs too
public BehaviorTree behaviorTree;
// Used by the debugger to visually display the last status returned
public Status? lastStatus;
public int lastTick = 0;
// GUID
public string GUID;
// Child connections
public virtual void ConnectChild(Node child) {}
public virtual void DisconnectChild(Node child) {}
public virtual List<Node> Children { get { return null;} }
public virtual int ChildCount { get { return 0; } }
public virtual bool CanConnectChild { get { return false; } }
public virtual bool ContainsChild(Node child) { return false; }
// IComparable for sorting left-to-right in the visual editor
public int CompareTo(object other) {
Node otherNode = other as Node;
return editorPosition.x < otherNode.editorPosition.x ? -1 : 1;
}
// Parent connections
[SerializeField]
Node _parent;
public virtual Node parent {
get { return _parent; }
set {
if (value == null && _parent.ContainsChild(this)) {
throw new System.InvalidOperationException(string.Format ("Cannot set parent of {0} to null because {1} still contains it in its children", this, value));
} else if (value == null || (value != null && value.ContainsChild(this))) {
_parent = value;
} else {
throw new System.InvalidOperationException(string.Format ("{0} must contain {1} as a child before setting the child parent property", value, this));
}
}
}
public virtual void Unparent() {
if (_parent != null) {
_parent.DisconnectChild(this);
} else {
Debug.LogWarning(string.Format ("Attempted unparenting {0} while it has no parent"));
}
}
public List<Node> Ancestors() {
List<Node> ancestorNodes = new List<Node>();
if (parent != null) parent.Ancestors (ref ancestorNodes);
return ancestorNodes;
}
private void Ancestors(ref List<Node> ancestorNodes) {
ancestorNodes.Add (this);
if (parent != null) parent.Ancestors (ref ancestorNodes);
}
// All connections
public virtual void Disconnect() {
// Disconnect parent
if (parent != null) {
Unparent();
}
// Disconnect children
if (ChildCount > 0) {
for (int i = ChildCount - 1; i >= 0; i--) {
DisconnectChild(Children[i]);
}
}
}
// Lifecycle
public void OnEnable() {
hideFlags = HideFlags.HideAndDontSave;
}
// Runtime
public virtual Status Tick(GameObject agent, Context context) { return Status.Error; }
}
// Root ------------------------------------------------------------------------------------------------------------------------------------------------------
[System.Serializable]
public class Root : Node {
// Child connections
[SerializeField]
Node _child;
public override void ConnectChild(Node child) {
if (_child == null) {
_child = child;
child.parent = this;
} else {
throw new System.InvalidOperationException(string.Format ("{0} already has a connected child, cannot connect {1}", this, child));
}
}
public override void DisconnectChild(Node child) {
if (_child == child) {
_child = null;
child.parent = null;
} else {
throw new System.InvalidOperationException(string.Format ("{0} is not a child of {1}", child, this));
}
}
public override List<Node> Children {
get {
List<Node> nodeList = new List<Node>();
nodeList.Add(_child);
return nodeList;
}
}
public override int ChildCount {
get { return _child != null ? 1 : 0; }
}
public override bool CanConnectChild {
get { return _child == null; }
}
public override bool ContainsChild (Node child)
{
return _child == child;
}
// Parent Connections
public override Node parent {
get { return null; }
set { throw new System.InvalidOperationException("The Root node cannot have a parent connection"); }
}
public override void Unparent() {
throw new System.InvalidOperationException("The Root node cannot have a parent connection");
}
// Runtime
public override Status Tick(GameObject agent, Context context)
{
Status result = Status.Error;
if (_child != null) {
result = behaviorTree.Tick (_child, agent, context);
}
return result;
}
}
// Composite nodes ------------------------------------------------------------------------------------------------------------------------------------------------------
[System.Serializable]
public abstract class Composite : Node
{
// Child connections
[SerializeField]
List<Node> _children = new List<Node>();
public override void ConnectChild(Node child) {
_children.Add (child);
child.parent = this;
}
public override void DisconnectChild(Node child) {
if (_children.Contains(child)) {
_children.Remove (child);
child.parent = null;
} else {
throw new System.InvalidOperationException(string.Format ("{0} is not a child of {1}", child, this));
}
}
public void SortChildren() {
_children.Sort ();
}
public override List<Node> Children { get { return _children; } }
public override int ChildCount { get { return _children.Count; } }
public override bool CanConnectChild { get { return true; } }
public override bool ContainsChild(Node child) { return _children.Contains (child); }
// Runtime
public override abstract Status Tick(GameObject agent, Context context);
}
[System.Serializable]
public class Selector : Composite
{
[SerializeField]
int lastRunning = 0;
public bool rememberRunning = false;
public override Status Tick(GameObject agent, Context context)
{
int start = rememberRunning ? lastRunning : 0;
for (int i = start; i < ChildCount; i++)
{
Node node = Children[i];
Status status = behaviorTree.Tick(node, agent, context);
if (status != Status.Failure)
{
lastRunning = status == Status.Running ? i : 0;
return status;
}
}
return Status.Failure;
}
// Serialization
public void Serialize(ref XmlElement el) {
el.SetAttribute("remember", rememberRunning ? bool.TrueString : bool.FalseString);
}
// Deserialization
public void Deserialize(XmlElement el) {
rememberRunning = bool.Parse(el.GetAttribute("remember"));
}
}
[System.Serializable]
public class RandomSelector : Composite
{
public override Status Tick(GameObject agent, Context context)
{
throw new System.NotImplementedException ();
}
}
[System.Serializable]
public class Sequence : Composite
{
[SerializeField]
int lastRunning = 0;
public bool rememberRunning = false;
public override Status Tick(GameObject agent, Context context)
{
int start = rememberRunning ? lastRunning : 0;
for ( int i = start; i < ChildCount; i++)
{
Node node = Children[i];
Status status = behaviorTree.Tick(node, agent, context);
if (status != Status.Success)
{
lastRunning = status == Status.Running ? i : 0;
return status;
} else {
lastRunning = 0;
}
}
return Status.Success;
}
// Serialization
public void Serialize(ref XmlElement el) {
el.SetAttribute("remember", rememberRunning ? bool.TrueString : bool.FalseString);
}
// Deserialization
public void Deserialize(XmlElement el) {
rememberRunning = bool.Parse(el.GetAttribute("remember"));
}
}
[System.Serializable]
public class Parallel : Composite
{
public enum ResolutionStrategy {
FirstSuccess, FirstFailure, FirstResolved, AllResolved
}
public ResolutionStrategy strategy = ResolutionStrategy.FirstSuccess;
[SerializeField]
List<Node> stillRunning;
List<Status> results;
public override Status Tick(GameObject agent, Context context)
{
// Initialize stillRunning with all child nodes
// if (stillRunning == null) {
// results = new List<Status>();
// stillRunning = new List<Node>();
// for ( int i = 0; i < ChildCount; i++) {
// stillRunning.Add (Children[i]);
// }
// }
//
// foreach (Node node in stillRunning) {
// Status status = behaviorTree.Tick (node, agent, context);
// if (status != Status.Running) {
// stillRunning.Remove (node);
// }
// results.Add (status);
//
// if (strategy == ResolutionStrategy.FirstSuccess && status == Status.Success)
// return Status.Success;
// else if (strategy == ResolutionStrategy.FirstFailure && status == Status.Failure)
// return Status.Failure;
// else if (status == Status.Error)
// return Status.Error;
// }
//
// switch(strategy) {
// case ResolutionStrategy.FirstSuccess:
// break;
// }
return Status.Error;
}
}
// Decorator nodes ------------------------------------------------------------------------------------------------------------------------------------------------------
[System.Serializable]
public abstract class Decorator : Node
{
// Child connections
[SerializeField]
Node _child;
public override void ConnectChild(Node child) {
if (_child == null) {
_child = child;
child.parent = this;
} else {
throw new System.InvalidOperationException(string.Format ("{0} already has a connected child, cannot connect {1}", this, child));
}
}
public override void DisconnectChild(Node child) {
if (_child == child) {
_child = null;
child.parent = null;
} else {
throw new System.InvalidOperationException(string.Format ("{0} is not a child of {1}", child, this));
}
}
public override List<Node> Children {
get {
List<Node> nodeList = new List<Node>();
nodeList.Add(_child);
return nodeList;
}
}
public override int ChildCount {
get { return _child != null ? 1 : 0; }
}
public override bool CanConnectChild {
get { return _child == null; }
}
public override bool ContainsChild(Node child) {
return _child == child;
}
// Runtime
public override Status Tick(GameObject agent, Context context)
{
throw new System.NotImplementedException ();
}
}
[System.Serializable]
public class Repeater : Decorator
{
[SerializeField]
int _repetitions;
// Setting repetitions to zero will repeat forever
public void SetRepetitions(int repetitions) {
_repetitions = repetitions;
}
public int repetitions { get { return _repetitions; } }
public override Status Tick(GameObject agent, Context context)
{
throw new System.NotImplementedException ();
}
}
[System.Serializable]
public class UntilSucceed : Decorator
{
public override Status Tick(GameObject agent, Context context)
{
throw new System.NotImplementedException ();
}
}
[System.Serializable]
public class Inverter : Decorator
{
public override Status Tick(GameObject agent, Context context)
{
throw new System.NotImplementedException ();
}
}
[System.Serializable]
public class Succeeder : Decorator
{
public override Status Tick(GameObject agent, Context context)
{
throw new System.NotImplementedException ();
}
}
}