stackbt_behavior_tree 0.1.2

Behavior Trees for StackBT
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
use behavior_tree_node::Statepoint;
use serial_node::{Enumerable, SerialDecider, NontermDecision, TermDecision};
use parallel_node::ParallelDecider;
use std::marker::PhantomData;

/// Runs all nodes in sequence, one at a time, regardless of how they resolve 
/// in the end. 
pub struct SerialRunner<E, I, N, T> where E: Enumerable {
    _who_cares: PhantomData<(E, I, N, T)>
}

impl<E, I, N, T> SerialDecider for SerialRunner<E, I, N, T> where 
    E: Enumerable
{
    type Enum = E;
    type Input = I;
    type Nonterm = N;
    type Term = T;
    type Exit = ();

    fn on_nonterminal(_input: &I, _ordinal: E, statept: N) -> NontermDecision<E, N, ()> {
        NontermDecision::Step(statept)
    }

    fn on_terminal(_input: &I, ordinal: E, statept: T) -> TermDecision<E, T, ()> {
        match ordinal.successor() {
            Option::Some(e) => {
                TermDecision::Trans(e, statept)
            },
            Option::None => TermDecision::Exit(())
        }
    }
}

/// Runs nodes in sequence until one resolves into an Option::Some, which 
/// depending on context may be either success or failure. 
pub struct SerialSelector<E, I, N, T> where E: Enumerable {
    _who_cares: PhantomData<(E, I, N, T)>
}

impl<E, I, N, T> SerialDecider for SerialSelector<E, I, N, T> where 
    E: Enumerable
{
    type Enum = E;
    type Input = I;
    type Nonterm = N;
    type Term = Option<T>;
    type Exit = Option<(E, T)>;

    fn on_nonterminal(_input: &I, _ord: E, statept: N) -> NontermDecision<E, N, 
        Option<(E, T)>> 
    {
        NontermDecision::Step(statept)
    }

    fn on_terminal(_input: &I, ord: E, statept: Option<T>) -> TermDecision<E, Option<T>, 
        Option<(E, T)>> 
    {
        match statept {
            Option::Some(t) => TermDecision::Exit(Option::Some((ord, t))),
            Option::None => match ord.successor() {
                Option::Some(e) => TermDecision::Trans(e, Option::None),
                Option::None => TermDecision::Exit(Option::None)
            }
        }
    }
}

/// Runs nodes in parallel until at some point, they all terminate or 
/// enter a trap state indicated by returning a statepoint terminal 
/// as the nonterminal. 
pub struct ParallelRunner<I, N, R, T> {
    _who_cares: PhantomData<(I, N, R, T)>
}

impl<I, N, R, T> ParallelDecider for ParallelRunner<I, N, R, T> where 
    I: 'static,
    N: 'static,
    R: 'static,
    T: 'static
{
    type Input = I;
    type Nonterm = Statepoint<N, R>;
    type Term = T;
    type Exit = Box<[Statepoint<R, T>]>;

    #[inline]
    fn each_step(_input: &I, states: Box<[Statepoint<Statepoint<N, R>, T>]>) -> 
        Statepoint<Box<[Statepoint<Self::Nonterm, T>]>, Self::Exit> 
    {
        if states.iter().any(|val| match val {
            Statepoint::Nonterminal(Statepoint::Nonterminal(_)) => true,
            _ => false 
        }) {
            Statepoint::Nonterminal(states)
        } else {
            let vec = states.into_vec().into_iter().map(|val| 
                match val {
                    Statepoint::Nonterminal(v) => match v {
                        Statepoint::Terminal(k) => Statepoint::Nonterminal(k),
                        _ => unreachable!("No currently pending nodes")
                    },
                    Statepoint::Terminal(k) => Statepoint::Terminal(k)
                }
            ).collect::<Vec<_>>();
            Statepoint::Terminal(vec.into_boxed_slice())
        }
    }
}

/// Runs nodes until one terminates, resolving to a tuple of the terminating
/// index and its terminal state when it does. 
pub struct ParallelRacer<I, N, T>  {
    _who_cares: PhantomData<(I, N, T)>
}

impl<I, N, T> ParallelDecider for ParallelRacer<I, N, T> where 
    I: 'static,
    N: 'static,
    T: 'static + Clone
{
    type Input = I;
    type Nonterm = N;
    type Term = T;
    type Exit = (usize, T);

    #[inline]
    fn each_step(_input: &I, states: Box<[Statepoint<N, T>]>) -> 
        Statepoint<Box<[Statepoint<N, T>]>, (usize, T)> 
    {
        let mut retval = Option::None;
        for value in states.iter().enumerate() {
            if let Statepoint::Terminal(val) = value.1 {
                retval = Option::Some((value.0, val.clone()));
                break;
            }
        };
        match retval {
            Option::None => Statepoint::Nonterminal(states),
            Option::Some(v) => Statepoint::Terminal(v)
        }

    }
}

#[cfg(test)]
mod tests {
    use base_nodes::MachineWrapper;
    use behavior_tree_node::{BehaviorTreeNode, NodeResult, Statepoint};
    use stackbt_automata_impl::automaton::Automaton;
    use stackbt_automata_impl::internal_state_machine::{InternalTransition,
        InternalStateMachine};
    use stackbt_automata_impl::ref_state_machine::{ReferenceTransition,
        RefStateMachine};
    use serial_node::{Enumerable, EnumNode};
    use map_wrappers::{OutputNodeMap, OutputMappedNode};
    use control_wrappers::{NodeGuard, GuardedNode};
    use node_runner::NodeRunner;
    use std::marker::PhantomData;

    #[derive(Copy, Clone, Default)]
    struct IndefiniteIncrement;

    impl InternalTransition for IndefiniteIncrement {
        type Input = i64;
        type Internal = i64;
        type Action = Statepoint<i64, i64>;

        fn step(input: &i64, state: &mut i64) -> Statepoint<i64, i64> {
            if *input >= 0 {
                *state += 1;
                Statepoint::Nonterminal(*state)
            } else {
                Statepoint::Terminal(*state)
            }
        }
    }


    #[derive(Copy, Clone, PartialEq, Eq, Debug)]
    enum IndexEnum {
        First,
        Second
    }
    
    impl Enumerable for IndexEnum {
        fn zero() -> Self {
            IndexEnum::First
        }

        fn successor(self) -> Option<Self> {
            match self {
                IndexEnum::First => Option::Some(IndexEnum::Second),
                IndexEnum::Second => Option::None
            }
        }
    }

    enum MultiMachine {
        First(MachineWrapper<InternalStateMachine<'static, 
            IndefiniteIncrement>, i64, i64>),
        Second(MachineWrapper<InternalStateMachine<'static, 
            IndefiniteIncrement>, i64, i64>)
    }

    impl BehaviorTreeNode for MultiMachine {
        type Input = i64;
        type Nonterminal = i64;
        type Terminal = i64;

        fn step(self, input: &i64) -> NodeResult<i64, i64, Self> {
            match self {
                MultiMachine::First(n) => {
                    match n.step(input) {
                        NodeResult::Nonterminal(r, m) => NodeResult::Nonterminal(
                            r,
                            MultiMachine::First(m)
                        ),
                        NodeResult::Terminal(t) => NodeResult::Terminal(t)
                    }
                },
                MultiMachine::Second(n) => {
                    match n.step(input) {
                        NodeResult::Nonterminal(r, m) => NodeResult::Nonterminal(
                            r,
                            MultiMachine::Second(m)
                        ),
                        NodeResult::Terminal(t) => NodeResult::Terminal(t)
                    }
                }
            }
        }
    }
    
    impl EnumNode for MultiMachine {

        type Discriminant = IndexEnum;

        fn new(thing: IndexEnum) -> MultiMachine {
            match thing {
                IndexEnum::First => MultiMachine::First(
                    MachineWrapper::default()
                ),
                IndexEnum::Second => MultiMachine::Second(
                    MachineWrapper::default()
                )
            }
        }

        fn discriminant(&self) -> IndexEnum {
            match self {
                MultiMachine::First(_) => IndexEnum::First,
                MultiMachine::Second(_) => IndexEnum::Second
            }
        }
    }

    #[test]
    fn serial_runner_test() {
        use serial_node::{SerialBranchNode, NontermReturn};
        use node_compositions::SerialRunner;
        let test_node = SerialBranchNode::<MultiMachine, SerialRunner<_, _, _, _>, ()>
            ::default();
        let test_node_1 = match test_node.step(&3) {
            NodeResult::Nonterminal(ret, n) => {
                match ret {
                    NontermReturn::Nonterminal(e, v) => {
                        assert_eq!(e, IndexEnum::First);
                        assert_eq!(v, 1);
                    },
                    _ => unreachable!("Expected subordinate nonterminal transition")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let test_node_2 = match test_node_1.step(&3) {
            NodeResult::Nonterminal(ret, n) => {
                match ret {
                    NontermReturn::Nonterminal(e, v) => {
                        assert_eq!(e, IndexEnum::First);
                        assert_eq!(v, 2);
                    },
                    _ => unreachable!("Expected subordinate nonterminal transition")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let test_node_3 = match test_node_2.step(&-1) {
            NodeResult::Nonterminal(ret, n) => {
                match ret {
                    NontermReturn::Terminal(e, v) => {
                        assert_eq!(e, IndexEnum::First);
                        assert_eq!(v, 2);
                    },
                    _ => unreachable!("Expected subordinate nonterminal transition")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let test_node_4 = match test_node_3.step(&3) {
            NodeResult::Nonterminal(ret, n) => {
                match ret {
                    NontermReturn::Nonterminal(e, v) => {
                        assert_eq!(e, IndexEnum::Second);
                        assert_eq!(v, 1);
                    },
                    _ => unreachable!("Expected subordinate nonterminal transition")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        match test_node_4.step(&-3) {
            NodeResult::Terminal(_) => (),
            _ => unreachable!("Expected terminal transition")
        };
    }

    struct ValSep;

    impl OutputNodeMap for ValSep {
        type NontermIn = i64;
        type NontermOut = i64;
        type TermIn = i64;
        type TermOut = Option<i64>;

        fn nonterminal_transform(inval: i64) -> i64 {
            inval
        }

        fn terminal_transform(inval: i64) -> Option<i64> {
            if inval >= 2 {
                Option::Some(inval)
            } else {
                Option::None
            }
        }
    }

    enum WrappedMachine {
        First(OutputMappedNode<MachineWrapper<InternalStateMachine<'static, 
            IndefiniteIncrement>, i64, i64>, ValSep>),
        Second(OutputMappedNode<MachineWrapper<InternalStateMachine<'static, 
            IndefiniteIncrement>, i64, i64>, ValSep>)
    }

    impl BehaviorTreeNode for WrappedMachine {
        type Input = i64;
        type Nonterminal = i64;
        type Terminal = Option<i64>;

        fn step(self, input: &i64) -> NodeResult<i64, Option<i64>, Self> {
            match self {
                WrappedMachine::First(n) => {
                    match n.step(input) {
                        NodeResult::Nonterminal(r, m) => NodeResult::Nonterminal(
                            r,
                            WrappedMachine::First(m)
                        ),
                        NodeResult::Terminal(t) => NodeResult::Terminal(t)
                    }
                },
                WrappedMachine::Second(n) => {
                    match n.step(input) {
                        NodeResult::Nonterminal(r, m) => NodeResult::Nonterminal(
                            r,
                            WrappedMachine::Second(m)
                        ),
                        NodeResult::Terminal(t) => NodeResult::Terminal(t)
                    }
                }
            }
        }
    }
    
    impl EnumNode for WrappedMachine {
        type Discriminant = IndexEnum;

        fn new(thing: IndexEnum) -> WrappedMachine {
            match thing {
                IndexEnum::First => WrappedMachine::First(
                    OutputMappedNode::default()
                ),
                IndexEnum::Second => WrappedMachine::Second(
                    OutputMappedNode::default()
                )
            }
        }

        fn discriminant(&self) -> IndexEnum {
            match self {
                WrappedMachine::First(_) => IndexEnum::First,
                WrappedMachine::Second(_) => IndexEnum::Second
            }
        }
    }

    #[test]
    fn serial_selector_test() {
        use serial_node::{SerialBranchNode, NontermReturn};
        use node_compositions::SerialSelector;
        let test_node = SerialBranchNode::<WrappedMachine, SerialSelector<_, _, _, _>, 
            Option<_>>::default();
        let test_node_1 = match test_node.step(&3) {
            NodeResult::Nonterminal(ret, n) => {
                match ret {
                    NontermReturn::Nonterminal(e, v) => {
                        assert_eq!(e, IndexEnum::First);
                        assert_eq!(v, 1);
                    },
                    _ => unreachable!("Expected subordinate nonterminal transition")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let test_node_2 = match test_node_1.step(&-1) {
            NodeResult::Nonterminal(ret, n) => {
                match ret {
                    NontermReturn::Terminal(e, v) => {
                        assert_eq!(e, IndexEnum::First);
                        match v {
                            Option::None => (),
                            _ => unreachable!("Expected subordinate failure")
                        }
                    },
                    _ => unreachable!("Expected subordinate nonterminal transition")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let test_node_3 = match test_node_2.step(&3) {
            NodeResult::Nonterminal(ret, n) => {
                match ret {
                    NontermReturn::Nonterminal(e, v) => {
                        assert_eq!(e, IndexEnum::Second);
                        assert_eq!(v, 1);
                    },
                    _ => unreachable!("Expected subordinate nonterminal transition")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let test_node_4 = match test_node_3.step(&3) {
            NodeResult::Nonterminal(ret, n) => {
                match ret {
                    NontermReturn::Nonterminal(e, v) => {
                        assert_eq!(e, IndexEnum::Second);
                        assert_eq!(v, 2);
                    },
                    _ => unreachable!("Expected subordinate nonterminal transition")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let test_node_5 = match test_node_4.step(&3) {
            NodeResult::Nonterminal(ret, n) => {
                match ret {
                    NontermReturn::Nonterminal(e, v) => {
                        assert_eq!(e, IndexEnum::Second);
                        assert_eq!(v, 3);
                    },
                    _ => unreachable!("Expected subordinate nonterminal transition")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        match test_node_5.step(&-3) {
            NodeResult::Terminal(t) => {
                match t {
                    Option::Some(k) => assert_eq!(k, (IndexEnum::Second, 3)),
                    _ => unreachable!("Expected return with success")
                }
            },
            _ => unreachable!("Expected terminal transition")
        };

    }

    #[derive(Copy, Clone)]
    enum TwoCycler {
        First, 
        Second
    }

    impl Default for TwoCycler {
        fn default() -> TwoCycler {
            TwoCycler::First
        }
    }
    
    impl ReferenceTransition for TwoCycler {
        type Input = ();
        type Action = Statepoint<(), ()>;
        fn step(self, input: &()) -> (Self::Action, Self) {
            match self {
                TwoCycler::First => (Statepoint::Nonterminal(()), TwoCycler::Second),
                TwoCycler::Second => (Statepoint::Terminal(()), TwoCycler::First)
            }
        }
    }

    #[derive(Copy, Clone)]
    enum ThreeCycler {
        First,
        Second, 
        Third
    }

    impl Default for ThreeCycler {
        fn default() -> ThreeCycler {
            ThreeCycler::First
        }
    }

    impl ReferenceTransition for ThreeCycler {
        type Input = ();
        type Action = Statepoint<(), ()>;
        fn step(self, input: &()) -> (Self::Action, Self) {
            match self {
                ThreeCycler::First => (Statepoint::Nonterminal(()), ThreeCycler::Second),
                ThreeCycler::Second => (Statepoint::Nonterminal(()), ThreeCycler::Third),
                ThreeCycler::Third => (Statepoint::Terminal(()), ThreeCycler::First)
            }
        }
    }

    #[derive(Copy, Clone)]
    struct ParMachine {
        first: RefStateMachine<'static, TwoCycler>,
        second: RefStateMachine<'static, ThreeCycler>
    }

    impl Default for ParMachine {
        fn default() -> ParMachine {
            ParMachine {
                first: RefStateMachine::new(TwoCycler::default()),
                second: RefStateMachine::new(ThreeCycler::default())
            }
        }
    }

    #[derive(Copy, Clone, Default)]
    struct ParMachineController;

    impl InternalTransition for ParMachineController {
        type Input = ();
        type Internal = ParMachine;
        type Action = Box<[Statepoint<Statepoint<(), ()>, ()>]>;

        fn step(input: &(), mach: &mut ParMachine) -> Box<[Statepoint<
            Statepoint<(), ()>, ()>]> 
        {
            let thing = vec![
                Statepoint::Nonterminal(mach.first.transition(input)), 
                Statepoint::Nonterminal(mach.second.transition(input))
            ];
            thing.into_boxed_slice()
        }
    }

    #[test]
    fn parallel_runner_test() {
        use parallel_node::ParallelBranchNode;
        use node_compositions::ParallelRunner;
        let test_node = ParallelBranchNode::<InternalStateMachine<
            ParMachineController>, ParallelRunner<_, _, _, _>>::default();
        let test_node_1 = match test_node.step(&()) {
            NodeResult::Nonterminal(v, n) => match v.as_ref() {
                [
                    Statepoint::Nonterminal(Statepoint::Nonterminal(())),
                    Statepoint::Nonterminal(Statepoint::Nonterminal(()))
                ] => n,
                _ => unreachable!("Expected only (nonterminal, nonterminal)")
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let test_node_2 = match test_node_1.step(&()) {
            NodeResult::Nonterminal(v, n) => match v.as_ref() {
                [
                    Statepoint::Nonterminal(Statepoint::Terminal(())),
                    Statepoint::Nonterminal(Statepoint::Nonterminal(()))
                ] => n,
                _ => unreachable!("Expected only (terminal, nonterminal)")
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let test_node_3 = match test_node_2.step(&()) {
            NodeResult::Nonterminal(v, n) => match v.as_ref() {
                [
                    Statepoint::Nonterminal(Statepoint::Nonterminal(())),
                    Statepoint::Nonterminal(Statepoint::Terminal(()))
                ] => n,
                _ => unreachable!("Expected only (nonterminal, terminal)")
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let test_node_4 = match test_node_3.step(&()) {
            NodeResult::Nonterminal(v, n) => match v.as_ref() {
                [
                    Statepoint::Nonterminal(Statepoint::Terminal(())),
                    Statepoint::Nonterminal(Statepoint::Nonterminal(()))
                ] => n,
                _ => unreachable!("Expected only (terminal, nonterminal)")
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let test_node_5 = match test_node_4.step(&()) {
            NodeResult::Nonterminal(v, n) => match v.as_ref() {
                [
                    Statepoint::Nonterminal(Statepoint::Nonterminal(())),
                    Statepoint::Nonterminal(Statepoint::Nonterminal(()))
                ] => n,
                _ => unreachable!("Expected only (nonterminal, nonterminal)")
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        match test_node_5.step(&()) {
            NodeResult::Terminal(_) => (),
            _ => unreachable!("Expected terminal transition")
        };
    }

    #[derive(Default, Copy, Clone)]
    struct WrapParMachineController;

    impl InternalTransition for WrapParMachineController {
        type Input = ();
        type Internal = ParMachine;
        type Action = Box<[Statepoint<(), ()>]>;

        fn step(input: &(), mach: &mut ParMachine) -> Box<[Statepoint<(), ()>]> {
            let thing = vec![
                mach.first.transition(input), 
                mach.second.transition(input)
            ];
            thing.into_boxed_slice()
        }
    }

    #[test]
    fn parallel_racer_test() {
        use parallel_node::ParallelBranchNode;
        use node_compositions::ParallelRacer;
        let test_node = ParallelBranchNode::<InternalStateMachine<
            WrapParMachineController>, ParallelRacer<_, _, _>>::default();
        let test_node_1 = match test_node.step(&()) {
            NodeResult::Nonterminal(_, n) => n,
            _ => unreachable!("Expected nonterminal transition")
        };
        match test_node_1.step(&()) {
            NodeResult::Terminal(_) => (),
            _ => unreachable!("Expected terminal transition")
        };
    }
}