-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbehaviourtree.lua
827 lines (645 loc) · 20.2 KB
/
behaviourtree.lua
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
require("class")
SUCCESS = "SUCCESS"
FAILED = "FAILED"
READY = "READY"
RUNNING = "RUNNING"
---------------------------------------------------------------------------------------
BT = Class(function(self, inst, root)
self.inst = inst
self.root = root
end)
function BT:ForceUpdate()
self.forceupdate = true
end
function BT:Update()
self.root:Visit()
self.root:SaveStatus()
self.root:Step()
self.forceupdate = false
end
function BT:Reset()
self.root:Reset()
end
function BT:Stop()
self.root:Stop()
end
function BT:GetSleepTime()
if self.forceupdate then
return 0
end
return self.root:GetTreeSleepTime()
end
function BT:__tostring()
return self.root:GetTreeString()
end
---------------------------------------------------------------------------------------
local NODE_COUNT = 0
BehaviourNode = Class(function (self, name, children)
self.name = name or ""
self.children = children
self.status = READY
self.lastresult = READY
self.nextupdatetick = 0
--jcheng: this is for imgui to have an id to use
self.id = NODE_COUNT
NODE_COUNT = NODE_COUNT + 1
if children then
for i,k in pairs(children) do
k.parent = self
end
end
end)
function BehaviourNode:DoToParents(fn)
if self.parent then
fn(self.parent)
return self.parent:DoToParents(fn)
end
end
function BehaviourNode:GetTreeString(indent)
indent = indent or ""
local str = string.format("%s%s>%2.2f\n", indent, self:GetString(), self:GetTreeSleepTime() or 0)
if self.children then
for k, v in ipairs(self.children) do
-- uncomment this to see only the "active" part of the tree. handy for pigbrain.
--if v.status == RUNNING or v.status == SUCCESS or v.lastresult == RUNNING or v.lastresult == SUCCESS then
str = str .. v:GetTreeString(indent .. " >")
--end
end
end
return str
end
function BehaviourNode:DBString()
return ""
end
function BehaviourNode:Sleep(t)
self.nextupdatetime = GetTime() + t
end
function BehaviourNode:GetSleepTime()
if self.status == RUNNING and not self.children and not self:is_a(ConditionNode) then
if self.nextupdatetime then
local time_to = self.nextupdatetime - GetTime()
if time_to < 0 then
time_to = 0
end
return time_to
end
return 0
end
return nil
end
function BehaviourNode:GetTreeSleepTime()
local sleeptime = nil
if self.children then
for k,v in ipairs(self.children) do
if v.status == RUNNING then
local t = v:GetTreeSleepTime()
if t and (not sleeptime or sleeptime > t) then
sleeptime = t
end
end
end
end
local my_t = self:GetSleepTime()
if my_t and (not sleeptime or sleeptime > my_t) then
sleeptime = my_t
end
return sleeptime
end
function BehaviourNode:GetString()
local str = ""
if self.status == RUNNING then
str = self:DBString()
end
return string.format([[%s - %s <%s> (%s)]], self.name, self.status or "UNKNOWN", self.lastresult or "?", str)
end
function BehaviourNode:Visit()
self.status = FAILED
end
function BehaviourNode:SaveStatus()
self.lastresult = self.status
if self.children then
for k,v in pairs(self.children) do
v:SaveStatus()
end
end
end
function BehaviourNode:Step()
if self.status ~= RUNNING then
self:Reset()
elseif self.children then
for k, v in ipairs(self.children) do
v:Step()
end
end
end
function BehaviourNode:Reset()
if self.status ~= READY then
self.status = READY
if self.children then
for idx, child in ipairs(self.children) do
child:Reset()
end
end
end
end
function BehaviourNode:Stop()
if self.OnStop then
self:OnStop()
end
if self.children then
for idx, child in ipairs(self.children) do
child:Stop()
end
end
end
---------------------------------------------------------------------------------------
DecoratorNode = Class(BehaviourNode, function(self, name, child)
BehaviourNode._ctor(self, name or "Decorator", {child})
end)
---------------------------------------------------------------------------------------
ConditionNode = Class(BehaviourNode, function(self, fn, name)
BehaviourNode._ctor(self, name or "Condition")
self.fn = fn
end)
function ConditionNode:Visit()
if self.fn() then
self.status = SUCCESS
else
self.status = FAILED
end
end
---------------------------------------------------------------------------------------
MultiConditionNode = Class(BehaviourNode, function(self, start, continue, name)
BehaviourNode._ctor(self, name or "Condition")
self.start = start
self.continue = continue
end)
function MultiConditionNode:Visit()
if not self.running then
self.running = self.start()
else
self.running = self.continue()
end
if self.running then
self.status = SUCCESS
else
self.status = FAILED
end
end
---------------------------------------------------------------------------------------
ConditionWaitNode = Class(BehaviourNode, function(self, fn, name)
BehaviourNode._ctor(self, name or "Wait")
self.fn = fn
end)
function ConditionWaitNode:Visit()
if self.fn() then
self.status = SUCCESS
else
self.status = RUNNING
end
end
---------------------------------------------------------------------------------------
ActionNode = Class(BehaviourNode, function(self, action, name)
BehaviourNode._ctor(self, name or "ActionNode")
self.action = action
end)
function ActionNode:Visit()
self.action()
self.status = SUCCESS
end
---------------------------------------------------------------------------------------
WaitNode = Class(BehaviourNode, function(self, time)
BehaviourNode._ctor(self, "Wait")
self.wait_time = time
end)
function WaitNode:DBString()
local w = self.wake_time - GetTime()
return string.format("%2.2f", w)
end
function WaitNode:Visit()
local current_time = GetTime()
if self.status ~= RUNNING then
self.wake_time = current_time + FunctionOrValue(self.wait_time)
self.status = RUNNING
end
if self.status == RUNNING then
if current_time >= self.wake_time then
self.status = SUCCESS
else
self:Sleep(current_time - self.wake_time)
end
end
end
---------------------------------------------------------------------------------------
SequenceNode = Class(BehaviourNode, function(self, children)
BehaviourNode._ctor(self, "Sequence", children)
self.idx = 1
end)
function SequenceNode:DBString()
return tostring(self.idx)
end
function SequenceNode:Reset()
self._base.Reset(self)
self.idx = 1
end
function SequenceNode:Visit()
if self.status ~= RUNNING then
self.idx = 1
end
while self.idx <= #self.children do
local child = self.children[self.idx]
child:Visit()
if child.status == RUNNING or child.status == FAILED then
self.status = child.status
return
end
self.idx = self.idx + 1
end
self.status = SUCCESS
end
---------------------------------------------------------------------------------------
SelectorNode = Class(BehaviourNode, function(self, children)
BehaviourNode._ctor(self, "Selector", children)
self.idx = 1
end)
function SelectorNode:DBString()
return tostring(self.idx)
end
function SelectorNode:Reset()
self._base.Reset(self)
self.idx = 1
end
function SelectorNode:Visit()
if self.status ~= RUNNING then
self.idx = 1
end
local done = false
while self.idx <= #self.children do
local child = self.children[self.idx]
child:Visit()
if child.status == RUNNING or child.status == SUCCESS then
self.status = child.status
return
end
self.idx = self.idx + 1
end
self.status = FAILED
end
---------------------------------------------------------------------------------------
NotDecorator = Class(DecoratorNode, function(self, child)
DecoratorNode._ctor(self, "Not", child)
end)
function NotDecorator:Visit()
local child = self.children[1]
child:Visit()
if child.status == SUCCESS then
self.status = FAILED
elseif child.status == FAILED then
self.status = SUCCESS
else
self.status = child.status
end
end
---------------------------------------------------------------------------------------
FailIfRunningDecorator = Class(DecoratorNode, function(self, child)
DecoratorNode._ctor(self, "FailIfRunning", child)
end)
function FailIfRunningDecorator:Visit()
local child = self.children[1]
child:Visit()
if child.status == RUNNING then
self.status = FAILED
else
self.status = child.status
end
end
---------------------------------------------------------------------------------------
-- Useful to make a prioritynode move to the next element whether a child succeeds or fails
FailIfSuccessDecorator = Class(DecoratorNode, function(self, child)
DecoratorNode._ctor(self, "FailIfSuccess", child)
end)
function FailIfSuccessDecorator:Visit()
local child = self.children[1]
child:Visit()
if child.status == SUCCESS then
self.status = FAILED
else
self.status = child.status
end
end
---------------------------------------------------------------------------------------
LoopNode = Class(BehaviourNode, function(self, children, maxreps)
BehaviourNode._ctor(self, "Sequence", children)
self.idx = 1
self.maxreps = maxreps
self.rep = 0
end)
function LoopNode:DBString()
return tostring(self.idx)
end
function LoopNode:Reset()
self._base.Reset(self)
self.idx = 1
self.rep = 0
end
function LoopNode:Visit()
if self.status ~= RUNNING then
self.idx = 1
self.rep = 0
end
local done = false
while self.idx <= #self.children do
local child = self.children[self.idx]
child:Visit()
if child.status == RUNNING or child.status == FAILED then
if child.status == FAILED then
--print("EXIT LOOP ON FAIL")
end
self.status = child.status
return
end
self.idx = self.idx + 1
end
self.idx = 1
self.rep = self.rep + 1
if self.maxreps and self.rep >= self.maxreps then
--print("DONE LOOP")
self.status = SUCCESS
else
for k,v in ipairs(self.children) do
v:Reset()
end
end
end
---------------------------------------------------------------------------------------
RandomNode = Class(BehaviourNode, function(self, children)
BehaviourNode._ctor(self, "Random", children)
end)
function RandomNode:Reset()
self._base.Reset(self)
self.idx = nil
end
function RandomNode:Visit()
local done = false
if self.status == READY then
--pick a new child
self.idx = math.random(#self.children)
local start = self.idx
while true do
local child = self.children[self.idx]
child:Visit()
if child.status ~= FAILED then
self.status = child.status
return
end
self.idx = self.idx + 1
if self.idx > #self.children then
self.idx = 1
end
if self.idx == start then
self.status = FAILED
return
end
end
else
local child = self.children[self.idx]
child:Visit()
self.status = child.status
end
end
---------------------------------------------------------------------------------------
PriorityNode = Class(BehaviourNode, function(self, children, period, noscatter)
BehaviourNode._ctor(self, "Priority", children)
self.period = period or 1
if not noscatter then
self.lasttime = self.period * 0.5 + (self.period * math.random())
end
end)
function PriorityNode:GetSleepTime()
if self.status == RUNNING then
if not self.period then
return 0
end
local time_to = 0
if self.lasttime then
time_to = self.lasttime + self.period - GetTime()
if time_to < 0 then
time_to = 0
end
end
return time_to
elseif self.status == READY then
return 0
end
return nil
end
function PriorityNode:DBString()
local time_till = 0
if self.period then
time_till = (self.lasttime or 0) + self.period - GetTime()
end
return string.format("execute %d, eval in %2.2f", self.idx or -1, time_till)
end
function PriorityNode:Reset()
self._base.Reset(self)
self.idx = nil
end
function PriorityNode:Visit()
local time = GetTime()
local do_eval = not self.lasttime or not self.period or self.lasttime + self.period < time
local oldidx = self.idx
if do_eval then
local old_event = nil
if self.idx and self.children[self.idx]:is_a(EventNode) then
old_event = self.children[self.idx]
end
self.lasttime = time
local found = false
for idx, child in ipairs(self.children) do
local should_test_anyway = old_event and child:is_a(EventNode) and old_event.priority <= child.priority
if not found or should_test_anyway then
if child.status == FAILED or child.status == SUCCESS then
child:Reset()
end
child:Visit()
local cs = child.status
if cs == SUCCESS or cs == RUNNING then
if should_test_anyway and self.idx ~= idx then
self.children[self.idx]:Reset()
end
self.status = cs
found = true
self.idx = idx
end
else
child:Reset()
end
end
if not found then
self.status = FAILED
end
else
if self.idx then
local child = self.children[self.idx]
if child.status == RUNNING then
child:Visit()
self.status = child.status
if self.status ~= RUNNING then
self.lasttime = nil
end
end
end
end
end
---------------------------------------------------------------------------------------
ParallelNode = Class(BehaviourNode, function(self, children, name)
BehaviourNode._ctor(self, name or "Parallel", children)
end)
function ParallelNode:Step()
if self.status ~= RUNNING then
self:Reset()
elseif self.children then
for k, v in ipairs(self.children) do
if v.status == SUCCESS and v:is_a(ConditionNode) then
v:Reset()
end
end
end
end
function ParallelNode:Visit()
local done = true
local any_done = false
for idx, child in ipairs(self.children) do
if child:is_a(ConditionNode) then
child:Reset()
end
if child.status ~= SUCCESS then
child:Visit()
if child.status == FAILED then
self.status = FAILED
return
end
end
if child.status == RUNNING then
done = false
else
any_done = true
end
end
if done or (self.stoponanycomplete and any_done) then
self.status = SUCCESS
else
self.status = RUNNING
end
end
ParallelNodeAny = Class(ParallelNode, function(self, children)
ParallelNode._ctor(self, children, "Parallel(Any)")
self.stoponanycomplete = true
end)
---------------------------------------------------------------------------------------
EventNode = Class(BehaviourNode, function(self, inst, event, child, priority)
BehaviourNode._ctor(self, "Event("..event..")", {child})
self.inst = inst
self.event = event
self.priority = priority or 0
self.eventfn = function(inst, data) self:OnEvent(data) end
self.inst:ListenForEvent(self.event, self.eventfn)
--print(self.inst, "EventNode()", self.event)
end)
function EventNode:OnStop()
--print(self.inst, "EventNode:OnStop()", self.event)
if self.eventfn then
self.inst:RemoveEventCallback(self.event, self.eventfn)
self.eventfn = nil
end
end
function EventNode:OnEvent(data)
--print(self.inst, "EventNode:OnEvent()", self.event)
if self.status == RUNNING then
self.children[1]:Reset()
end
self.triggered = true
self.data = data
if self.inst.brain then
self.inst.brain:ForceUpdate()
end
self:DoToParents(function(node) if node:is_a(PriorityNode) then node.lasttime = nil end end)
--wake the parent!
end
function EventNode:Step()
self._base.Step(self)
self.triggered = false
end
function EventNode:Reset()
self.triggered = false
self._base.Reset(self)
end
function EventNode:Visit()
if self.status == READY and self.triggered then
self.status = RUNNING
end
if self.status == RUNNING then
if self.children and #self.children == 1 then
local child = self.children[1]
child:Visit()
self.status = child.status
else
self.status = FAILED
end
end
end
---------------------------------------------------------------
-- WhileNode: The While condition will be checked on every update,
-- so subsequent nodes will be interrupted if they change the result
-- of that condition.
function WhileNode(cond, name, node)
return ParallelNode
{
ConditionNode(cond, name),
node
}
end
---------------------------------------------------------------
-- IfNode: Once the If condition passes, the brain will move on to
-- the subsequent node, and continue executing it until that node succeeds or fails.
-- The If condition will not be checked again until that time.
function IfNode(cond, name, node)
return SequenceNode
{
ConditionNode(cond, name),
node
}
end
---------------------------------------------------------------
function IfThenDoWhileNode(ifcond, whilecond, name, node)
return ParallelNode
{
MultiConditionNode(ifcond, whilecond, name),
node
}
end
---------------------------------------------------------------
LatchNode = Class(BehaviourNode, function(self, inst, latchduration, child)
BehaviourNode._ctor(self, "Latch ("..tostring(latchduration)..")", {child})
self.inst = inst
self.latchduration = latchduration
self.currentlatchduration = 0
self.lastlatchtime = -math.huge
end)
function LatchNode:Visit()
if self.status == READY then
if GetTime() > self.currentlatchduration + self.lastlatchtime then
--print("GONNA GO!", GetTime(), self.currentlatchduration, "----", GetTime()+self.currentlatchduration, ">", self.lastlatchtime)
self.lastlatchtime = GetTime()
self.currentlatchduration = FunctionOrValue(self.latchduration, self.inst)
--print("New vals:", self.currentlatchduration , self.lastlatchtime)
self.status = RUNNING
else
self.status = FAILED
end
end
if self.status == RUNNING then
self.children[1]:Visit()
self.status = self.children[1].status
end
end