bulletml 0.2.1

BulletML library in Rust
Documentation
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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
use indextree::{Arena, Node, NodeId};
use std::collections::HashSet;
use std::ops::{Deref, DerefMut};

use crate::tree::{
    BulletML, BulletMLExpression, BulletMLNode, BulletMLType, DirectionType, HVType, SpeedType,
};

/// Set of data required during a BulletML run.
///
/// `D` is the type of the application data used in the [AppRunner](trait.AppRunner.html) callbacks.
pub struct RunnerData<'a, D: 'a> {
    pub bml: &'a BulletML,
    pub data: &'a mut D,
}

type Parameters = Vec<f64>;

/// State information that can be used to call
/// [Runner::new_from_state](struct.Runner.html#method.new_from_state) or
/// [Runner::init_from_state](struct.Runner.html#method.init_from_state) when creating new bullets.
///
/// See also [AppRunner::create_bullet](trait.AppRunner.html#tymethod.create_bullet).
pub struct State {
    bml_type: Option<BulletMLType>,
    nodes: Box<[NodeId]>,
    parameters: Parameters,
}

/// Elementary bullet runner. It is used either to run one single bullet or to run one or more "top"
/// actions.
pub struct Runner<R> {
    runners: Vec<RunnerImpl>,
    app_runner: R,
}

impl<'a, R> Runner<R> {
    /// Creates a new runner for all the "top" actions of the provided BulletML document.
    ///
    /// `app_runner` is the application runner which contains all the specific behaviours.
    ///
    /// `bml` is the parsed BulletML document to be used by the runner until the bullet dies.
    pub fn new(app_runner: R, bml: &BulletML) -> Self {
        let bml_type = bml.get_type();
        let runners = bml
            .root
            .children(&bml.arena)
            .filter(|child| {
                let child_node = &bml.arena[*child];
                child_node.get().is_top_action()
            })
            .map(|action| {
                let state = State {
                    bml_type,
                    nodes: Box::new([action]),
                    parameters: Vec::new(),
                };
                RunnerImpl::new(state)
            })
            .collect();
        Runner {
            runners,
            app_runner,
        }
    }

    /// Reuses this runner for all the "top" actions of the provided BulletML document. It works
    /// the same way as [new](#method.new).
    ///
    /// `app_runner` is the application runner which contains all the specific behaviours.
    ///
    /// `bml` is the parsed BulletML document to be used by the runner until the bullet dies.
    pub fn init<D>(&mut self, bml: &BulletML)
    where
        R: AppRunner<D>,
    {
        let bml_type = bml.get_type();
        self.runners.clear();
        for action in bml.root.children(&bml.arena).filter(|child| {
            let child_node = &bml.arena[*child];
            child_node.get().is_top_action()
        }) {
            let state = State {
                bml_type,
                nodes: Box::new([action]),
                parameters: Vec::new(),
            };
            self.runners.push(RunnerImpl::new(state))
        }
        self.app_runner.init();
    }

    /// Creates a new runner from an existing state.
    ///
    /// `app_runner` is the application runner which contains all the specific behaviours.
    ///
    /// `state` is the state with which
    /// [AppRunner::create_bullet](trait.AppRunner.html#tymethod.create_bullet) is called.
    pub fn new_from_state(app_runner: R, state: State) -> Self {
        Runner {
            runners: vec![RunnerImpl::new(state)],
            app_runner,
        }
    }

    /// Reuses this runner from an existing state.  It works
    /// the same way as [new_from_state](#method.new_from_state) except that the application
    /// runner cannot change.
    ///
    /// `state` is the state with which
    /// [AppRunner::create_bullet](trait.AppRunner.html#tymethod.create_bullet) is called.
    pub fn init_from_state<D>(&mut self, state: State)
    where
        R: AppRunner<D>,
    {
        self.runners.clear();
        self.runners.push(RunnerImpl::new(state));
        self.app_runner.init();
    }

    /// Runs one iteration of this runner.
    ///
    /// `data` contains the application data used in the [AppRunner](trait.AppRunner.html) callbacks.
    pub fn run<D>(&mut self, data: &mut RunnerData<D>)
    where
        R: AppRunner<D>,
    {
        for runner in &mut self.runners {
            runner.run(data, &mut self.app_runner);
        }
    }

    /// Checks whether this runner is alive.
    pub fn is_end(&self) -> bool {
        for runner in &self.runners {
            if runner.is_end() {
                return true;
            }
        }
        false
    }
}

impl<R: Default> Default for Runner<R> {
    fn default() -> Self {
        Runner {
            runners: Vec::default(),
            app_runner: R::default(),
        }
    }
}

impl<R> Deref for Runner<R> {
    type Target = R;
    fn deref(&self) -> &Self::Target {
        &self.app_runner
    }
}

impl<R> DerefMut for Runner<R> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.app_runner
    }
}

/// Application specific BulletML runner trait.
pub trait AppRunner<D> {
    /// Initializes the runner.
    ///
    /// This function is called when a new [Runner](struct.Runner.html) is created/reused.
    fn init(&mut self) {}
    /// Gets this bullet's direction based on application data.
    fn get_bullet_direction(&self, data: &D) -> f64;
    /// Gets this bullet's aim direction based on application data.
    ///
    /// The "target" related to the "aim" notion is application specific.
    fn get_aim_direction(&self, data: &D) -> f64;
    /// Gets this bullet's speed based on application data.
    fn get_bullet_speed(&self, data: &D) -> f64;
    /// Gets the bullet default speed.
    fn get_default_speed(&self) -> f64;
    /// Gets the BulletML "rank", a value between 0 and 1 indicating the level of difficulty.
    /// The value is used in arithmetic expressions with `$rank`.
    fn get_rank(&self, data: &D) -> f64;
    /// Tells the application to create a bullet with the given `direction` and `speed`.
    ///
    /// The simple use case is to create a bullet whose direction and speed won't change until it
    /// disappears or hits the target.
    ///
    /// Nevertheless there could be more complex use cases which involve creating a new runner with
    /// the same BulletML document or even another one.
    fn create_simple_bullet(&mut self, data: &mut D, direction: f64, speed: f64);
    /// Tells the application to create a bullet based on the given `state`, initial `direction`
    /// and initial `speed`.
    ///
    /// The typical use case is to create a new runner with the same BulletML document. See
    /// [Runner::new_from_state](struct.Runner.html#method.new_from_state) and
    /// [Runner::init_from_state](struct.Runner.html#method.init_from_state).
    fn create_bullet(&mut self, data: &mut D, state: State, direction: f64, speed: f64);
    /// Gets the current iteration number.
    fn get_turn(&self, data: &D) -> u32;
    /// Tells the application to make this bullet vanish.
    fn do_vanish(&mut self, data: &mut D);
    fn do_change_direction(&mut self, _data: &mut D, _direction: f64) {}
    /// Tells the application to make this bullet change speed.
    fn do_change_speed(&mut self, _data: &mut D, _speed: f64) {}
    /// Tells the application to make this bullet accelerate.
    fn do_accel_x(&mut self, _: f64) {}
    /// Tells the application to make this bullet accelerate.
    fn do_accel_y(&mut self, _: f64) {}
    /// Gets this bullet's X speed.
    fn get_bullet_speed_x(&self) -> f64 {
        0.
    }
    /// Gets this bullet's Y speed.
    fn get_bullet_speed_y(&self) -> f64 {
        0.
    }
    /// Gets a new random value. The random number generator is managed by the application.
    fn get_rand(&self, data: &mut D) -> f64;
    #[cfg(test)]
    fn log(&mut self, _data: &mut D, _node: &BulletMLNode) {}
}

struct Validatable<T: Copy> {
    value: T,
    valid: bool,
}

impl<T: Copy> Validatable<T> {
    fn get(&self) -> T {
        self.value
    }

    fn is_valid(&self) -> bool {
        self.valid
    }

    fn set(&mut self, value: T) {
        self.value = value;
        self.valid = true;
    }

    fn invalidate(&mut self) {
        self.valid = false;
    }
}

impl<T: Copy + Default> Default for Validatable<T> {
    fn default() -> Self {
        Validatable {
            value: T::default(),
            valid: false,
        }
    }
}

struct LinearFunc<X, Y> {
    first_x: X,
    last_x: X,
    first_y: Y,
    last_y: Y,
    gradient: Y,
}

impl<X, Y> LinearFunc<X, Y>
where
    X: Copy + PartialOrd + std::ops::Sub<Output = X> + Into<Y>,
    Y: Copy
        + Default
        + std::ops::Add<Output = Y>
        + std::ops::Sub<Output = Y>
        + std::ops::Mul<Output = Y>
        + std::ops::Div<Output = Y>,
{
    fn new(first_x: X, last_x: X, first_y: Y, last_y: Y) -> Self {
        Self {
            first_x,
            last_x,
            first_y,
            last_y,
            gradient: (last_y - first_y) / (last_x - first_x).into(),
        }
    }

    fn get_value(&self, x: X) -> Y {
        self.first_y + self.gradient * (x - self.first_x).into()
    }

    fn is_last(&self, x: X) -> bool {
        x >= self.last_x
    }

    fn get_last(&self) -> Y {
        self.last_y
    }
}

struct StackedRef {
    ref_id: NodeId,
    prev: NodeId,
    prev_parameters: Parameters,
}

pub struct RunnerImpl {
    bml_type: Option<BulletMLType>,
    nodes: Box<[NodeId]>,
    root_nodes: HashSet<NodeId>,
    change_dir: Option<LinearFunc<u32, f64>>,
    change_spd: Option<LinearFunc<u32, f64>>,
    accel_x: Option<LinearFunc<u32, f64>>,
    accel_y: Option<LinearFunc<u32, f64>>,
    spd: Validatable<f64>,
    prev_spd: Validatable<f64>,
    dir: Validatable<f64>,
    prev_dir: Validatable<f64>,
    act: Option<NodeId>,
    act_turn: Option<u32>,
    end_turn: u32,
    act_iter: usize,
    end: bool,
    parameters: Parameters,
    repeat_stack: Vec<RepeatElem>,
    ref_stack: Vec<StackedRef>,
}

impl RunnerImpl {
    fn new(state: State) -> Self {
        let act = Some(state.nodes[0]);
        let mut root_nodes = HashSet::new();
        for node in state.nodes.iter() {
            root_nodes.insert(*node);
        }
        RunnerImpl {
            bml_type: state.bml_type,
            nodes: state.nodes,
            root_nodes,
            change_dir: None,
            change_spd: None,
            accel_x: None,
            accel_y: None,
            spd: Validatable::default(),
            prev_spd: Validatable::default(),
            dir: Validatable::default(),
            prev_dir: Validatable::default(),
            act,
            act_turn: None,
            end_turn: 0,
            act_iter: 0,
            end: false,
            parameters: state.parameters,
            repeat_stack: Vec::new(),
            ref_stack: Vec::new(),
        }
    }

    fn run<D>(&mut self, data: &mut RunnerData<D>, runner: &mut dyn AppRunner<D>) {
        if self.is_end() {
            return;
        }
        self.changes(data, runner);
        self.end_turn = runner.get_turn(data.data);
        if self.act.is_none() {
            if !self.is_turn_end()
                && self.change_dir.is_none()
                && self.change_spd.is_none()
                && self.accel_x.is_none()
                && self.accel_y.is_none()
            {
                self.end = true;
            }
            return;
        }
        self.act = Some(self.nodes[self.act_iter]);
        if self.act_turn.is_none() {
            self.act_turn = Some(runner.get_turn(data.data));
        }
        self.run_sub(data, runner);
        match self.act {
            None => {
                self.act_iter += 1;
                if self.act_iter < self.nodes.len() {
                    self.act = Some(self.nodes[self.act_iter]);
                }
            }
            Some(act) => self.nodes[self.act_iter] = act,
        }
    }

    fn is_end(&self) -> bool {
        self.end
    }

    fn is_turn_end(&self) -> bool {
        self.is_end() || self.act_turn.unwrap_or(0) > self.end_turn
    }

    fn do_wait(&mut self, frame: u32) {
        if frame > 0 {
            self.act_turn = Some(self.act_turn.unwrap() + frame);
        }
    }

    fn changes<D>(&mut self, data: &mut RunnerData<D>, runner: &mut dyn AppRunner<D>) {
        let now = runner.get_turn(data.data);
        let reset = if let Some(change_dir) = &self.change_dir {
            if change_dir.is_last(now) {
                runner.do_change_direction(&mut data.data, change_dir.get_last());
                true
            } else {
                runner.do_change_direction(&mut data.data, change_dir.get_value(now));
                false
            }
        } else {
            false
        };
        if reset {
            self.change_dir = None;
        }
        let reset = if let Some(change_spd) = &self.change_spd {
            if change_spd.is_last(now) {
                runner.do_change_speed(&mut data.data, change_spd.get_last());
                true
            } else {
                runner.do_change_speed(&mut data.data, change_spd.get_value(now));
                false
            }
        } else {
            false
        };
        if reset {
            self.change_spd = None;
        }
        let reset = if let Some(accel_x) = &self.accel_x {
            if accel_x.is_last(now) {
                runner.do_accel_x(accel_x.get_last());
                true
            } else {
                runner.do_accel_x(accel_x.get_value(now));
                false
            }
        } else {
            false
        };
        if reset {
            self.accel_x = None;
        }
        let reset = if let Some(accel_y) = &self.accel_y {
            if accel_y.is_last(now) {
                runner.do_accel_y(accel_y.get_last());
                true
            } else {
                runner.do_accel_y(accel_y.get_value(now));
                false
            }
        } else {
            false
        };
        if reset {
            self.accel_y = None;
        }
    }

    fn run_sub<D>(&mut self, data: &mut RunnerData<D>, runner: &mut dyn AppRunner<D>) {
        let bml = data.bml;
        while let Some(act) = self.act {
            if self.is_turn_end() {
                break;
            }
            let mut prev = act;
            let mut prev_node = &bml.arena[act];
            let node = &bml.arena[act];
            #[cfg(test)]
            runner.log(&mut data.data, node.get());
            match node.get() {
                BulletMLNode::Bullet { .. } => self.run_bullet(data, runner),
                BulletMLNode::Action { .. } => self.run_action(node),
                BulletMLNode::Fire { .. } => self.run_fire(data, runner),
                BulletMLNode::ChangeDirection => self.run_change_direction(data, runner),
                BulletMLNode::ChangeSpeed => self.run_change_speed(data, runner),
                BulletMLNode::Accel => self.run_accel(data, runner),
                BulletMLNode::Wait(expr) => self.run_wait(*expr, data, runner),
                BulletMLNode::Repeat => self.run_repeat(act, data, runner),
                BulletMLNode::BulletRef(label) => {
                    self.run_ref(act, bml.bullet_refs[label], data, runner)
                }
                BulletMLNode::ActionRef(label) => {
                    self.run_ref(act, bml.action_refs[label], data, runner)
                }
                BulletMLNode::FireRef(label) => {
                    self.run_ref(act, bml.fire_refs[label], data, runner)
                }
                BulletMLNode::Vanish => self.run_vanish(data, runner),
                _ => (),
            }
            loop {
                if self.act.is_none() {
                    // Unstack reference if needed.
                    if self
                        .ref_stack
                        .last()
                        .map_or(false, |stacked| stacked.ref_id == prev)
                    {
                        let top = self.ref_stack.pop().unwrap();
                        prev = top.prev;
                        prev_node = &bml.arena[prev];
                        self.parameters = top.prev_parameters;
                    }

                    // Jump to next sibling if any.
                    if !self.root_nodes.contains(&prev) {
                        self.act = prev_node.next_sibling();
                    }
                }

                // Found something to run or hit a root node, break.
                if self.act.is_some() || self.root_nodes.contains(&prev) {
                    break;
                }

                // Go to parent unless it is an unfinished Repeat.
                let parent = prev_node.parent();
                let (new_act, new_act_node) = if let Some(parent) = parent {
                    let parent_node = &bml.arena[parent];
                    if let BulletMLNode::Repeat = parent_node.get() {
                        let rep = self.repeat_stack.last_mut().unwrap();
                        rep.iter += 1;
                        if rep.iter < rep.end {
                            // Unfinished Repeat, set act and break loop.
                            self.act = Some(rep.act);
                            break;
                        }
                        // Finished Repeat, pop.
                        self.repeat_stack.pop();
                    }
                    (parent, parent_node)
                } else {
                    panic!("A run node must have a parent");
                };

                prev = new_act;
                prev_node = new_act_node;
            }
        }
    }

    fn get_first_child_id_matching<M, N>(
        arena: &Arena<BulletMLNode>,
        parent: NodeId,
        m: M,
    ) -> Option<NodeId>
    where
        M: Fn(&BulletMLNode) -> Option<N>,
    {
        for child in parent.children(arena) {
            let child_node = &arena[child];
            if m(child_node.get()).is_some() {
                return Some(child);
            }
        }
        None
    }

    fn get_first_child_matching<M, N>(
        arena: &Arena<BulletMLNode>,
        parent: NodeId,
        m: M,
    ) -> Option<N>
    where
        M: Fn(&BulletMLNode) -> Option<N>,
    {
        for child in parent.children(arena) {
            let child_node = &arena[child];
            let n = m(child_node.get());
            if n.is_some() {
                return n;
            }
        }
        None
    }

    fn get_children_ids_matching<M, N>(
        arena: &Arena<BulletMLNode>,
        parent: NodeId,
        m: M,
    ) -> Vec<NodeId>
    where
        M: Fn(&BulletMLNode) -> Option<N>,
    {
        parent
            .children(arena)
            .filter(|child| {
                let child_node = &arena[*child];
                m(child_node.get()).is_some()
            })
            .collect()
    }

    fn shot_init(&mut self) {
        self.spd.invalidate();
        self.dir.invalidate();
    }

    fn get_direction<D>(
        &mut self,
        dir_type: Option<DirectionType>,
        expr: BulletMLExpression,
        data: &mut RunnerData<D>,
        runner: &dyn AppRunner<D>,
    ) -> f64 {
        let direction = self.get_number_contents(expr, data, runner);
        let (mut direction, aim) = match dir_type {
            None => (direction, true),
            Some(DirectionType::Aim) => (direction, true),
            Some(DirectionType::Absolute) => (
                if self.bml_type == Some(BulletMLType::Horizontal) {
                    direction - 90.
                } else {
                    direction
                },
                false,
            ),
            Some(DirectionType::Relative) => {
                (direction + runner.get_bullet_direction(data.data), false)
            }
            Some(DirectionType::Sequence) => {
                if !self.prev_dir.is_valid() {
                    (0., true)
                } else {
                    (direction + self.prev_dir.get(), false)
                }
            }
        };
        if aim {
            direction += runner.get_aim_direction(data.data);
        }
        while direction > 360. {
            direction -= 360.
        }
        while direction < 0. {
            direction += 360.
        }
        self.prev_dir.set(direction);
        direction
    }

    fn set_direction<D>(&mut self, data: &mut RunnerData<D>, runner: &dyn AppRunner<D>) {
        if let Some(act) = self.act {
            let direction =
                Self::get_first_child_matching(&data.bml.arena, act, BulletMLNode::match_direction);
            if let Some((dir_type, dir)) = direction {
                let direction = self.get_direction(dir_type, dir, data, runner);
                self.dir.set(direction);
            }
        }
    }

    fn get_speed<D>(
        &mut self,
        spd_type: Option<SpeedType>,
        expr: BulletMLExpression,
        data: &mut RunnerData<D>,
        runner: &dyn AppRunner<D>,
    ) -> f64 {
        let mut speed = self.get_number_contents(expr, data, runner);
        speed = match spd_type {
            None => speed,
            Some(SpeedType::Absolute) => speed,
            Some(SpeedType::Relative) => speed + runner.get_bullet_speed(data.data),
            Some(SpeedType::Sequence) => {
                if !self.prev_spd.is_valid() {
                    1.
                } else {
                    speed + self.prev_spd.get()
                }
            }
        };
        self.prev_spd.set(speed);
        speed
    }

    fn set_speed<D>(&mut self, data: &mut RunnerData<D>, runner: &dyn AppRunner<D>) {
        if let Some(act) = self.act {
            let speed =
                Self::get_first_child_matching(&data.bml.arena, act, BulletMLNode::match_speed);
            if let Some((spd_type, spd)) = speed {
                let speed = self.get_speed(spd_type, spd, data, runner);
                self.spd.set(speed);
            }
        }
    }

    fn run_bullet<D>(&mut self, data: &mut RunnerData<D>, runner: &mut dyn AppRunner<D>) {
        let arena = &data.bml.arena;
        self.set_speed(data, runner);
        self.set_direction(data, runner);
        if !self.spd.is_valid() {
            let default = runner.get_default_speed();
            self.spd.set(default);
            self.prev_spd.set(default);
        }
        if !self.dir.is_valid() {
            let default = runner.get_aim_direction(data.data);
            self.dir.set(default);
            self.prev_dir.set(default);
        }
        let all_actions = self.act.map_or_else(
            || Vec::new(),
            |act| Self::get_children_ids_matching(arena, act, BulletMLNode::match_any_action),
        );
        if all_actions.is_empty() {
            runner.create_simple_bullet(&mut data.data, self.dir.get(), self.spd.get());
        } else {
            let state = State {
                bml_type: self.bml_type,
                nodes: all_actions.into_boxed_slice(),
                parameters: self.parameters.clone(),
            };
            runner.create_bullet(&mut data.data, state, self.dir.get(), self.spd.get());
        }
        self.act = None;
    }

    fn run_fire<D>(&mut self, data: &mut RunnerData<D>, runner: &dyn AppRunner<D>) {
        self.shot_init();
        self.set_speed(data, runner);
        self.set_direction(data, runner);
        if let Some(act) = self.act {
            let arena = &data.bml.arena;
            let bullet =
                Self::get_first_child_id_matching(arena, act, BulletMLNode::match_any_bullet);
            if bullet.is_some() {
                self.act = bullet;
            }
        }
    }

    fn run_action(&mut self, node: &Node<BulletMLNode>) {
        self.act = node.first_child();
    }

    fn run_wait<D>(
        &mut self,
        expr: BulletMLExpression,
        data: &mut RunnerData<D>,
        runner: &dyn AppRunner<D>,
    ) {
        let frame = self.get_number_contents(expr, data, runner);
        self.do_wait(frame as u32);
        self.act = None;
    }

    fn run_repeat<D>(&mut self, act: NodeId, data: &mut RunnerData<D>, runner: &dyn AppRunner<D>) {
        let times = Self::get_first_child_matching(&data.bml.arena, act, BulletMLNode::match_times);
        if let Some(times) = times {
            let times = self.get_number_contents(times, data, runner) as usize;
            let arena = &data.bml.arena;
            let action =
                Self::get_first_child_id_matching(arena, act, BulletMLNode::match_any_action);
            self.repeat_stack.push(RepeatElem {
                iter: 0,
                end: times,
                act: action.unwrap(),
            });
            self.act = action;
        }
    }

    fn run_ref<D>(
        &mut self,
        act: NodeId,
        ref_id: NodeId,
        data: &mut RunnerData<D>,
        runner: &dyn AppRunner<D>,
    ) {
        let new_parameters = self.get_parameters(data, runner);
        let prev_parameters = std::mem::replace(&mut self.parameters, new_parameters);
        self.ref_stack.push(StackedRef {
            ref_id,
            prev: act,
            prev_parameters: prev_parameters,
        });
        self.act = Some(ref_id);
    }

    fn run_change_direction<D>(&mut self, data: &mut RunnerData<D>, runner: &dyn AppRunner<D>) {
        if let Some(act) = self.act {
            let arena = &data.bml.arena;
            let term = Self::get_first_child_matching(arena, act, BulletMLNode::match_term);
            if let Some(term) = term {
                let direction =
                    Self::get_first_child_matching(arena, act, BulletMLNode::match_direction);
                if let Some((dir_type, dir)) = direction {
                    let term = self.get_number_contents(term, data, runner) as u32;
                    let (dir, seq) = if let Some(DirectionType::Sequence) = dir_type {
                        (self.get_number_contents(dir, data, runner), true)
                    } else {
                        (self.get_direction(dir_type, dir, data, runner), false)
                    };
                    self.calc_change_direction(dir, term, seq, data, runner);
                }
            }
        }
        self.act = None;
    }

    fn calc_change_direction<D>(
        &mut self,
        direction: f64,
        term: u32,
        seq: bool,
        data: &RunnerData<D>,
        runner: &dyn AppRunner<D>,
    ) {
        let act_turn = self.act_turn.unwrap_or(0);
        let final_turn = act_turn + term;
        let dir_first = runner.get_bullet_direction(data.data);
        if seq {
            self.change_dir = Some(LinearFunc::new(
                act_turn,
                final_turn,
                dir_first,
                dir_first + direction * f64::from(term),
            ));
        } else {
            let dir_space1 = direction - dir_first;
            let dir_space2 = if dir_space1 > 0. {
                dir_space1 - 360.
            } else {
                dir_space1 + 360.
            };
            let dir_space = if f64::abs(dir_space1) < f64::abs(dir_space2) {
                dir_space1
            } else {
                dir_space2
            };
            self.change_dir = Some(LinearFunc::new(
                act_turn,
                final_turn,
                dir_first,
                dir_first + dir_space,
            ));
        }
    }

    fn run_change_speed<D>(&mut self, data: &mut RunnerData<D>, runner: &dyn AppRunner<D>) {
        if let Some(act) = self.act {
            let arena = &data.bml.arena;
            let term = Self::get_first_child_matching(arena, act, BulletMLNode::match_term);
            if let Some(term) = term {
                let speed = Self::get_first_child_matching(arena, act, BulletMLNode::match_speed);
                if let Some((spd_type, spd)) = speed {
                    let term = self.get_number_contents(term, data, runner) as u32;
                    let spd = if let Some(SpeedType::Sequence) = spd_type {
                        self.get_number_contents(spd, data, runner) * f64::from(term)
                            + runner.get_bullet_speed(data.data)
                    } else {
                        self.get_speed(spd_type, spd, data, runner)
                    };
                    self.calc_change_speed(spd, term, data, runner);
                }
            }
        }
        self.act = None;
    }

    fn calc_change_speed<D>(
        &mut self,
        speed: f64,
        term: u32,
        data: &RunnerData<D>,
        runner: &dyn AppRunner<D>,
    ) {
        let act_turn = self.act_turn.unwrap_or(0);
        let final_turn = act_turn + term;
        let spd_first = runner.get_bullet_speed(data.data);
        self.change_spd = Some(LinearFunc::new(act_turn, final_turn, spd_first, speed));
    }

    fn run_accel<D>(&mut self, data: &mut RunnerData<D>, runner: &dyn AppRunner<D>) {
        if let Some(act) = self.act {
            let arena = &data.bml.arena;
            let term = Self::get_first_child_matching(arena, act, BulletMLNode::match_term);
            if let Some(term) = term {
                let term = self.get_number_contents(term, data, runner) as u32;
                let horizontal =
                    Self::get_first_child_matching(arena, act, BulletMLNode::match_horizontal);
                let vertical =
                    Self::get_first_child_matching(arena, act, BulletMLNode::match_vertical);
                if self.bml_type == Some(BulletMLType::Horizontal) {
                    if let Some((v_type, v)) = vertical {
                        self.accel_x = self.calc_accel_xy(
                            runner.get_bullet_speed_x(),
                            self.get_number_contents(v, data, runner),
                            term,
                            v_type,
                        );
                    }
                    if let Some((h_type, h)) = horizontal {
                        self.accel_y = self.calc_accel_xy(
                            runner.get_bullet_speed_y(),
                            self.get_number_contents(h, data, runner),
                            term,
                            h_type,
                        );
                    }
                } else {
                    if let Some((h_type, h)) = horizontal {
                        self.accel_x = self.calc_accel_xy(
                            runner.get_bullet_speed_x(),
                            self.get_number_contents(h, data, runner),
                            term,
                            h_type,
                        );
                    }
                    if let Some((v_type, v)) = vertical {
                        self.accel_y = self.calc_accel_xy(
                            runner.get_bullet_speed_y(),
                            self.get_number_contents(v, data, runner),
                            term,
                            v_type,
                        );
                    }
                }
            }
        }
        self.act = None;
    }

    fn calc_accel_xy(
        &self,
        first_spd: f64,
        value: f64,
        term: u32,
        hv_type: HVType,
    ) -> Option<LinearFunc<u32, f64>> {
        let act_turn = self.act_turn.unwrap_or(0);
        let final_turn = act_turn + term;
        let final_spd = match hv_type {
            HVType::Sequence => first_spd + value * f64::from(term),
            HVType::Relative => first_spd + value,
            HVType::Absolute => value,
        };
        Some(LinearFunc::new(act_turn, final_turn, first_spd, final_spd))
    }

    fn run_vanish<D>(&mut self, data: &mut RunnerData<D>, runner: &mut dyn AppRunner<D>) {
        runner.do_vanish(&mut data.data);
        self.act = None;
    }

    fn get_parameters<D>(&self, data: &mut RunnerData<D>, runner: &dyn AppRunner<D>) -> Parameters {
        let children = self.act.unwrap().children(&data.bml.arena);
        let mut parameters = Vec::new();
        for child in children {
            let child_node = &data.bml.arena[child];
            if let BulletMLNode::Param(expr) = child_node.get() {
                parameters.push(self.get_number_contents(*expr, data, runner));
            }
        }
        parameters
    }

    fn get_number_contents<D>(
        &self,
        expr: BulletMLExpression,
        data: &mut RunnerData<D>,
        runner: &dyn AppRunner<D>,
    ) -> f64 {
        match expr {
            BulletMLExpression::Const(value) => value,
            BulletMLExpression::Expr(expr) => {
                let rank = runner.get_rank(&data.data);
                let expr_ref = expr.from(&data.bml.expr_slab.ps);
                use fasteval::Evaler;
                expr_ref
                    .eval(
                        &data.bml.expr_slab,
                        &mut |name: &str, args: Vec<f64>| match (name, args.as_slice()) {
                            ("v", &[i]) => Some(self.parameters[i as usize - 1]),
                            ("rank", &[]) => Some(rank),
                            ("rand", &[]) => Some(runner.get_rand(data.data)),
                            _ => None,
                        },
                    )
                    .unwrap()
            }
        }
    }
}

#[derive(Debug)]
struct RepeatElem {
    iter: usize,
    end: usize,
    act: NodeId,
}

#[cfg(test)]
mod test_runner {
    use super::{AppRunner, Runner, RunnerData, State};
    use crate::parse::BulletMLParser;
    use crate::tree::{BulletML, BulletMLNode};

    pub struct TestAppRunner {
        index: usize,
        turn: u32,
        new_runners: Vec<Runner<TestAppRunner>>,
    }

    impl From<Runner<TestAppRunner>> for TestAppRunner {
        fn from(runner: Runner<TestAppRunner>) -> Self {
            runner.app_runner
        }
    }

    struct TestLog {
        log: Vec<String>,
        pos: usize,
        var_name: String,
    }

    impl TestLog {
        fn new(var_name: String) -> Self {
            TestLog {
                log: Vec::new(),
                pos: 0,
                var_name,
            }
        }

        fn assert_log(&mut self, value: &str, times: usize) {
            if self.pos + times > self.log.len() {
                panic!("too far {} > {}", self.pos + times, self.log.len());
            }
            for val in &self.log[self.pos..(self.pos + times)] {
                assert_eq!(val, value);
            }
            self.pos += times;
        }

        fn assert_log_end(&mut self) {
            let mut pos = self.pos;
            if pos < self.log.len() {
                println!("{} at position {}", self.var_name, pos);
            }
            while pos < self.log.len() {
                let value = &self.log[pos];
                let mut count = 1;
                for val in &self.log[pos + 1..] {
                    if val == value {
                        count += 1;
                    } else {
                        break;
                    }
                }
                println!(
                    "    {}.assert_log(r#\"{}\"#, {});",
                    self.var_name, value, count
                );
                pos += count;
            }
            assert_eq!(self.pos, self.log.len());
            self.log.truncate(0);
        }
    }

    struct TestLogs(Vec<TestLog>);

    impl Drop for TestLogs {
        fn drop(&mut self) {
            for log in &mut self.0 {
                log.assert_log_end();
            }
        }
    }

    impl TestAppRunner {
        pub fn new(index: usize) -> Self {
            TestAppRunner {
                index,
                turn: 0,
                new_runners: Vec::new(),
            }
        }

        pub fn next_turn(&mut self) {
            self.turn += 1;
        }

        fn log_iteration(&mut self, iteration: u32, logs: &mut Vec<TestLog>) {
            if self.index >= logs.len() {
                logs.push(TestLog::new(format!("logs[{}]", self.index)));
            }
            logs[self.index].log.push(format!("=== {}", iteration));
        }
    }

    struct TestAppData<'a> {
        logs: &'a mut Vec<TestLog>,
    }

    impl<'a> AppRunner<TestAppData<'a>> for TestAppRunner {
        fn get_bullet_direction(&self, _data: &TestAppData<'a>) -> f64 {
            0.
        }

        fn get_aim_direction(&self, _data: &TestAppData<'a>) -> f64 {
            0.
        }

        fn get_bullet_speed(&self, _data: &TestAppData<'a>) -> f64 {
            1.
        }

        fn get_default_speed(&self) -> f64 {
            10.
        }

        fn get_rank(&self, _data: &TestAppData<'a>) -> f64 {
            1.
        }

        fn create_simple_bullet(&mut self, data: &mut TestAppData<'a>, direction: f64, speed: f64) {
            data.logs[self.index]
                .log
                .push(format!("create_simple_bullet({}, {})", direction, speed));
        }

        fn create_bullet(
            &mut self,
            data: &mut TestAppData<'a>,
            state: State,
            direction: f64,
            speed: f64,
        ) {
            data.logs[self.index]
                .log
                .push(format!("create_bullet({}, {})", direction, speed));
            let runner = Runner::new_from_state(TestAppRunner::new(0), state);
            self.new_runners.push(runner);
        }

        fn get_turn(&self, _data: &TestAppData<'a>) -> u32 {
            self.turn
        }

        fn do_vanish(&mut self, _data: &mut TestAppData<'a>) {}

        fn do_change_direction(&mut self, data: &mut TestAppData<'a>, direction: f64) {
            data.logs[self.index]
                .log
                .push(format!("do_change_direction({})", direction));
        }

        fn do_change_speed(&mut self, data: &mut TestAppData<'a>, speed: f64) {
            data.logs[self.index]
                .log
                .push(format!("do_change_speed({})", speed));
        }

        fn get_rand(&self, _data: &mut TestAppData<'a>) -> f64 {
            0.42
        }

        fn log(&mut self, data: &mut TestAppData<'a>, node: &BulletMLNode) {
            data.logs[self.index].log.push(format!("{:?}", node));
        }
    }

    struct TestManager {
        bml: BulletML,
        runners: Vec<Runner<TestAppRunner>>,
    }

    impl<'a> TestManager {
        fn new(bml: BulletML) -> Self {
            TestManager {
                bml,
                runners: Vec::new(),
            }
        }

        fn run(&mut self, iteration: u32, logs: &mut Vec<TestLog>) {
            let mut new_runners = Vec::new();
            for runner in &mut self.runners {
                if !runner.is_end() {
                    runner.app_runner.log_iteration(iteration, logs);
                    runner.run(&mut RunnerData {
                        bml: &self.bml,
                        data: &mut TestAppData { logs },
                    });
                    new_runners.extend(&mut runner.new_runners.drain(..));
                    runner.app_runner.next_turn();
                }
            }
            self.runners.reserve(new_runners.len());
            for mut runner in new_runners.drain(..) {
                runner.app_runner.index = self.runners.len();
                self.runners.push(runner);
            }
        }

        fn run_test(&mut self, max_iter: u32, logs: &mut Vec<TestLog>) {
            let runner = Runner::new(TestAppRunner::new(self.runners.len()), &self.bml);
            self.runners.push(runner);
            for i in 0..max_iter {
                self.run(i, logs);
            }
        }
    }

    #[test]
    fn test_mini() {
        let bml = BulletMLParser::new()
            .parse(
                r##"<?xml version="1.0" ?>
<!DOCTYPE bulletml SYSTEM "../../bulletml.dtd">
<bulletml>
<action label="top">
    <fire>
        <bullet />
    </fire>
</action>
</bulletml>"##,
            )
            .unwrap();
        let mut manager = TestManager::new(bml);
        let mut logs = Vec::new();
        manager.run_test(100, &mut logs);
        logs[0].assert_log(r#"=== 0"#, 1);
        logs[0].assert_log(r#"Action(Some("top"))"#, 1);
        logs[0].assert_log(r#"Fire(None)"#, 1);
        logs[0].assert_log(r#"Bullet(None)"#, 1);
        logs[0].assert_log(r#"create_simple_bullet(0, 10)"#, 1);
        logs[0].assert_log(r#"=== 1"#, 1);
        TestLogs(logs);
    }

    #[test]
    fn test_mini_aim() {
        let bml = BulletMLParser::new()
            .parse(
                r##"<?xml version="1.0" ?>
<!DOCTYPE bulletml SYSTEM "../../bulletml.dtd">
<bulletml>
<action label="top">
    <repeat>
        <times>1000</times>
        <action>
            <fire>
                <bullet>
                    <direction type="aim">0</direction>
                    <speed>1</speed>
                </bullet>
            </fire>
            <wait>100</wait>
        </action>
    </repeat>
</action>
</bulletml>"##,
            )
            .unwrap();
        let mut manager = TestManager::new(bml);
        let mut logs = Vec::new();
        manager.run_test(110000, &mut logs);
        logs[0].assert_log(r#"=== 0"#, 1);
        logs[0].assert_log(r#"Action(Some("top"))"#, 1);
        logs[0].assert_log(r#"Repeat"#, 1);
        for i in 0..1000 {
            logs[0].assert_log(r#"Action(None)"#, 1);
            logs[0].assert_log(r#"Fire(None)"#, 1);
            logs[0].assert_log(r#"Bullet(None)"#, 1);
            logs[0].assert_log(r#"create_simple_bullet(0, 1)"#, 1);
            logs[0].assert_log(r#"Wait(Const(100.0))"#, 1);
            for j in 0..100 {
                logs[0].assert_log(&format!(r#"=== {}"#, i * 100 + j + 1), 1);
            }
        }
        TestLogs(logs);
    }

    #[test]
    fn test_bulletsmorph_double_seduction() {
        let bml = BulletMLParser::with_capacities(12, 128)
            .parse(
                r##"<?xml version="1.0" ?>
    <!DOCTYPE bulletml SYSTEM "../bulletml.dtd">
    <bulletml type="vertical" xmlns="http://www.asahi-net.or.jp/~cs8k-cyu/bulletml">
    <action label="top">
        <fire>
            <direction type="aim">30</direction>
            <bulletRef label="parentbit">
                <param>1</param>
            </bulletRef>
        </fire>
        <fire>
            <direction type="aim">-30</direction>
            <bulletRef label="parentbit">
                <param>-1</param>
            </bulletRef>
        </fire>
        <wait>300</wait>
    </action>
    <bullet label="parentbit">
        <speed>2.0</speed>
        <action>
            <actionRef label="cross">
                <param>75</param>
                <param>0</param>
            </actionRef>
            <actionRef label="cross">
                <param>70</param>
                <param>0</param>
            </actionRef>
            <actionRef label="cross">
                <param>65</param>
                <param>0</param>
            </actionRef>
            <actionRef label="cross">
                <param>60</param>
                <param>0</param>
            </actionRef>
            <actionRef label="cross">
               <param>55</param>
                <param>0</param>
            </actionRef>
            <actionRef label="cross">
                <param>50</param>
                <param>0</param>
            </actionRef>
            <actionRef label="cross">
                <param>80</param>
                <param>15 * $1</param>
            </actionRef>
                <actionRef label="cross">
                <param>75</param>
                <param>10 * $1</param>
            </actionRef>
            <actionRef label="cross">
                <param>70</param>
                <param>6 * $1</param>
            </actionRef>
            <actionRef label="cross">
                <param>65</param>
                <param>3 * $1</param>
            </actionRef>
            <actionRef label="cross">
                <param>60</param>
                <param>1 * $1</param>
            </actionRef>
            <actionRef label="cross">
                <param>55</param>
                <param>0</param>
            </actionRef>
            <vanish/>
        </action>
    </bullet>
    <action label="cross">
        <fire>
            <direction type="absolute">0</direction>
            <bulletRef label="aimbit">
                <param>$1</param>
                <param>$2</param>
            </bulletRef>
        </fire>
        <fire>
            <direction type="absolute">90</direction>
            <bulletRef label="aimbit">
                <param>$1</param>
                <param>$2</param>
            </bulletRef>
        </fire>
        <fire>
            <direction type="absolute">180</direction>
            <bulletRef label="aimbit">
                <param>$1</param>
                <param>$2</param>
            </bulletRef>
        </fire>
        <fire>
            <direction type="absolute">270</direction>
            <bulletRef label="aimbit">
                <param>$1</param>
                <param>$2</param>
            </bulletRef>
        </fire>
        <wait>5</wait>
    </action>
    <bullet label="aimbit">
        <speed>0.6</speed>
        <action>
            <wait>$1</wait>
            <fire>
                <direction type="aim">$2</direction>
                <speed>1.6 * (0.5 + 0.5 * $rank)</speed>
                <bullet/>
            </fire>
            <repeat>
                <times>2 + 5 * $rank</times>
                <action>
                    <fire>
                        <direction type="sequence">0</direction>
                        <speed type="sequence">0.1</speed>
                        <bullet/>
                    </fire>
                </action>
            </repeat>
            <vanish/>
        </action>
    </bullet>
    </bulletml>"##,
            )
            .unwrap();
        let mut manager = TestManager::new(bml);
        let mut logs = Vec::new();
        manager.run_test(1000, &mut logs);
        logs[0].assert_log(r#"=== 0"#, 1);
        logs[0].assert_log(r#"Action(Some("top"))"#, 1);
        logs[0].assert_log(r#"Fire(None)"#, 1);
        logs[0].assert_log(r#"BulletRef("parentbit")"#, 1);
        logs[0].assert_log(r#"Bullet(Some("parentbit"))"#, 1);
        logs[0].assert_log(r#"create_bullet(30, 2)"#, 1);
        logs[0].assert_log(r#"Fire(None)"#, 1);
        logs[0].assert_log(r#"BulletRef("parentbit")"#, 1);
        logs[0].assert_log(r#"Bullet(Some("parentbit"))"#, 1);
        logs[0].assert_log(r#"create_bullet(330, 2)"#, 1);
        logs[0].assert_log(r#"Wait(Const(300.0))"#, 1);
        for i in 0..300 {
            logs[0].assert_log(&format!(r#"=== {}"#, i + 1), 1);
        }

        for i in 1..3 {
            logs[i].assert_log(r#"=== 1"#, 1);
            logs[i].assert_log(r#"Action(None)"#, 1);
            for j in 0..12 {
                logs[i].assert_log(r#"ActionRef("cross")"#, 1);
                logs[i].assert_log(r#"Action(Some("cross"))"#, 1);
                for k in 0..4 {
                    logs[i].assert_log(r#"Fire(None)"#, 1);
                    logs[i].assert_log(r#"BulletRef("aimbit")"#, 1);
                    logs[i].assert_log(r#"Bullet(Some("aimbit"))"#, 1);
                    logs[i].assert_log(&format!(r#"create_bullet({}, 0.6)"#, k * 90 % 360), 1);
                }
                logs[i].assert_log(r#"Wait(Const(5.0))"#, 1);
                for k in 0..5 {
                    logs[i].assert_log(&format!(r#"=== {}"#, j * 5 + k + 2), 1);
                }
            }
            logs[i].assert_log(r#"Vanish"#, 1);
            logs[i].assert_log(&format!(r#"=== {}"#, 62), 1);
        }

        let v1s = [75, 70, 65, 60, 55, 50, 80, 75, 70, 65, 60, 55];
        let v2_factors = [0, 0, 0, 0, 0, 0, 15, 10, 6, 3, 1, 0];
        for i in 3..99 {
            logs[i].assert_log(&format!(r#"=== {}"#, (i - 3) / 8 * 5 + 2), 1);
            let mut spd = 1.6;
            for j in 0..1 {
                logs[i].assert_log(r#"Action(None)"#, 1);
                logs[i].assert_log(r#"Wait(Expr(ExpressionI(27)))"#, 1);
                for k in 0..v1s[(i - 3) / 8 % 12] {
                    logs[i].assert_log(&format!(r#"=== {}"#, (i - 3) / 8 * 5 + k + 3), 1);
                }
                logs[i].assert_log(r#"Fire(None)"#, 1);
                logs[i].assert_log(r#"Bullet(None)"#, 1);
                let mut dir = v2_factors[j + (i - 3) / 8] * (((i - 3) % 8 / 4) as isize * -2 + 1);
                if dir > 360 {
                    dir -= 360;
                }
                if dir < 0 {
                    dir += 360;
                }
                logs[i].assert_log(&format!(r#"create_simple_bullet({}, {})"#, dir, spd), 1);
                logs[i].assert_log(r#"Repeat"#, 1);
                for _ in 0..7 {
                    logs[i].assert_log(r#"Action(None)"#, 1);
                    logs[i].assert_log(r#"Fire(None)"#, 1);
                    logs[i].assert_log(r#"Bullet(None)"#, 1);
                    spd += 0.1;
                    logs[i].assert_log(&format!(r#"create_simple_bullet({}, {})"#, dir, spd), 1);
                }
                logs[i].assert_log(r#"Vanish"#, 1);
            }
            logs[i].assert_log(
                &format!(r#"=== {}"#, (i - 3) / 8 * 5 + v1s[(i - 3) / 8 % 12] + 3),
                1,
            );
        }
        TestLogs(logs);
    }

    #[test]
    fn test_tt_morph_0to1() {
        let bml = BulletMLParser::new()
            .parse(
                r##"<?xml version="1.0" ?>
<!DOCTYPE bulletml SYSTEM "http://www.asahi-net.or.jp/~cs8k-cyu/bulletml/bulletml.dtd">

<bulletml type="vertical"
          xmlns="http://www.asahi-net.or.jp/~cs8k-cyu/bulletml">

<action label="top">
        <changeSpeed>
                <speed>0</speed>
                <term>1</term>
        </changeSpeed>
        <wait>1</wait>
        <changeSpeed>
                <speed>1</speed>
                <term>60-$rank*50</term>
        </changeSpeed>
        <wait>60-$rank*50</wait>
        <fire>
                <direction type="relative">0</direction>
                <bullet/>
        </fire>
</action>

</bulletml>"##,
            )
            .unwrap();
        let mut manager = TestManager::new(bml);
        let mut logs = Vec::new();
        manager.run_test(100, &mut logs);
        logs[0].assert_log(r#"=== 0"#, 1);
        logs[0].assert_log(r#"Action(Some("top"))"#, 1);
        logs[0].assert_log(r#"ChangeSpeed"#, 1);
        logs[0].assert_log(r#"Wait(Const(1.0))"#, 1);
        logs[0].assert_log(r#"=== 1"#, 1);
        logs[0].assert_log(r#"do_change_speed(0)"#, 1);
        logs[0].assert_log(r#"ChangeSpeed"#, 1);
        logs[0].assert_log(r#"Wait(Expr(ExpressionI(1)))"#, 1);
        logs[0].assert_log(r#"=== 2"#, 1);
        logs[0].assert_log(r#"do_change_speed(1)"#, 1);
        logs[0].assert_log(r#"=== 3"#, 1);
        logs[0].assert_log(r#"do_change_speed(1)"#, 1);
        logs[0].assert_log(r#"=== 4"#, 1);
        logs[0].assert_log(r#"do_change_speed(1)"#, 1);
        logs[0].assert_log(r#"=== 5"#, 1);
        logs[0].assert_log(r#"do_change_speed(1)"#, 1);
        logs[0].assert_log(r#"=== 6"#, 1);
        logs[0].assert_log(r#"do_change_speed(1)"#, 1);
        logs[0].assert_log(r#"=== 7"#, 1);
        logs[0].assert_log(r#"do_change_speed(1)"#, 1);
        logs[0].assert_log(r#"=== 8"#, 1);
        logs[0].assert_log(r#"do_change_speed(1)"#, 1);
        logs[0].assert_log(r#"=== 9"#, 1);
        logs[0].assert_log(r#"do_change_speed(1)"#, 1);
        logs[0].assert_log(r#"=== 10"#, 1);
        logs[0].assert_log(r#"do_change_speed(1)"#, 1);
        logs[0].assert_log(r#"=== 11"#, 1);
        logs[0].assert_log(r#"do_change_speed(1)"#, 1);
        logs[0].assert_log(r#"Fire(None)"#, 1);
        logs[0].assert_log(r#"Bullet(None)"#, 1);
        logs[0].assert_log(r#"create_simple_bullet(0, 10)"#, 1);
        logs[0].assert_log(r#"=== 12"#, 1);
        TestLogs(logs);
    }

    #[test]
    fn test_tt_morph_accelshot() {
        let bml = BulletMLParser::new()
            .parse(
                r##"<?xml version="1.0" ?>
<!DOCTYPE bulletml SYSTEM "http://www.asahi-net.or.jp/~cs8k-cyu/bulletml/bulletml.dtd">

<bulletml type="vertical"
          xmlns="http://www.asahi-net.or.jp/~cs8k-cyu/bulletml">

<action label="top">
        <fire>
                <direction type="relative">0</direction>
                <speed type="relative">-0.9</speed>
                <bulletRef label="accel"/>
        </fire>
        <repeat><times>$rank*1.7</times>
        <action>
                <wait>2</wait>
                <fire>
                        <direction type="relative">0</direction>
                        <speed type="sequence">0.3</speed>
                        <bulletRef label="accel"/>
                </fire>
        </action>
        </repeat>
        <vanish/>
</action>

<bullet label="accel">
        <action>
                <wait>3</wait>
                <changeSpeed>
                        <speed>1</speed>
                        <term>60</term>
                </changeSpeed>
        </action>
</bullet>

</bulletml>"##,
            )
            .unwrap();
        let mut manager = TestManager::new(bml);
        let mut logs = Vec::new();
        manager.run_test(100, &mut logs);
        logs[0].assert_log(r#"=== 0"#, 1);
        logs[0].assert_log(r#"Action(Some("top"))"#, 1);
        logs[0].assert_log(r#"Fire(None)"#, 1);
        logs[0].assert_log(r#"BulletRef("accel")"#, 1);
        logs[0].assert_log(r#"Bullet(Some("accel"))"#, 1);
        logs[0].assert_log(r#"create_bullet(0, 0.09999999999999998)"#, 1);
        logs[0].assert_log(r#"Repeat"#, 1);
        logs[0].assert_log(r#"Action(None)"#, 1);
        logs[0].assert_log(r#"Wait(Const(2.0))"#, 1);
        logs[0].assert_log(r#"=== 1"#, 1);
        logs[0].assert_log(r#"=== 2"#, 1);
        logs[0].assert_log(r#"Fire(None)"#, 1);
        logs[0].assert_log(r#"BulletRef("accel")"#, 1);
        logs[0].assert_log(r#"Bullet(Some("accel"))"#, 1);
        logs[0].assert_log(r#"create_bullet(0, 0.39999999999999997)"#, 1);
        logs[0].assert_log(r#"Vanish"#, 1);
        logs[0].assert_log(r#"=== 3"#, 1);

        logs[1].assert_log(r#"=== 1"#, 1);
        logs[1].assert_log(r#"Action(None)"#, 1);
        logs[1].assert_log(r#"Wait(Const(3.0))"#, 1);
        logs[1].assert_log(r#"=== 2"#, 1);
        logs[1].assert_log(r#"=== 3"#, 1);
        logs[1].assert_log(r#"=== 4"#, 1);
        logs[1].assert_log(r#"ChangeSpeed"#, 1);
        for i in 0..60 {
            logs[1].assert_log(&format!(r#"=== {}"#, i + 5), 1);
            logs[1].assert_log(r#"do_change_speed(1)"#, 1);
        }

        logs[2].assert_log(r#"=== 3"#, 1);
        logs[2].assert_log(r#"Action(None)"#, 1);
        logs[2].assert_log(r#"Wait(Const(3.0))"#, 1);
        logs[2].assert_log(r#"=== 4"#, 1);
        logs[2].assert_log(r#"=== 5"#, 1);
        logs[2].assert_log(r#"=== 6"#, 1);
        logs[2].assert_log(r#"ChangeSpeed"#, 1);
        for i in 0..60 {
            logs[2].assert_log(&format!(r#"=== {}"#, i + 7), 1);
            logs[2].assert_log(r#"do_change_speed(1)"#, 1);
        }
        TestLogs(logs);
    }

    #[test]
    fn test_tt_morph_twin() {
        let bml = BulletMLParser::new()
            .parse(
                r##"<?xml version="1.0" ?>
<!DOCTYPE bulletml SYSTEM "http://www.asahi-net.or.jp/~cs8k-cyu/bulletml/bulletml.dtd">

<bulletml type="vertical"
          xmlns="http://www.asahi-net.or.jp/~cs8k-cyu/bulletml">


 <action label="top">
  <wait>1</wait>
  <fire>
   <bullet>
        <direction type="relative">0</direction>
        <speed type="relative">$rank</speed>
    <actionRef label="ofs">
     <param>90</param>
    </actionRef>
   </bullet>
  </fire>
  <fire>
   <bullet>
        <direction type="relative">0</direction>
        <speed type="relative">$rank</speed>
    <actionRef label="ofs">
     <param>-90</param>
    </actionRef>
   </bullet>
  </fire>
  <vanish/>
 </action>

<action label="ofs">
  <changeDirection>
   <direction type="relative">$1</direction>
   <term>1</term>
  </changeDirection>
  <wait>1</wait>
  <changeDirection>
   <direction type="relative">0-$1</direction>
   <term>1</term>
  </changeDirection>
  <wait>1</wait>
  <fire>
        <direction type="relative">0</direction>
        <speed type="relative">-$rank</speed>
        <bullet/>
  </fire>
  <vanish/>
</action>

</bulletml>"##,
            )
            .unwrap();
        let mut manager = TestManager::new(bml);
        let mut logs = Vec::new();
        manager.run_test(100, &mut logs);
        logs[0].assert_log(r#"=== 0"#, 1);
        logs[0].assert_log(r#"Action(Some("top"))"#, 1);
        logs[0].assert_log(r#"Wait(Const(1.0))"#, 1);
        logs[0].assert_log(r#"=== 1"#, 1);
        logs[0].assert_log(r#"Fire(None)"#, 1);
        logs[0].assert_log(r#"Bullet(None)"#, 1);
        logs[0].assert_log(r#"create_bullet(0, 2)"#, 1);
        logs[0].assert_log(r#"Fire(None)"#, 1);
        logs[0].assert_log(r#"Bullet(None)"#, 1);
        logs[0].assert_log(r#"create_bullet(0, 2)"#, 1);
        logs[0].assert_log(r#"Vanish"#, 1);
        logs[0].assert_log(r#"=== 2"#, 1);

        logs[1].assert_log(r#"=== 2"#, 1);
        logs[1].assert_log(r#"ActionRef("ofs")"#, 1);
        logs[1].assert_log(r#"Action(Some("ofs"))"#, 1);
        logs[1].assert_log(r#"ChangeDirection"#, 1);
        logs[1].assert_log(r#"Wait(Const(1.0))"#, 1);
        logs[1].assert_log(r#"=== 3"#, 1);
        logs[1].assert_log(r#"do_change_direction(90)"#, 1);
        logs[1].assert_log(r#"ChangeDirection"#, 1);
        logs[1].assert_log(r#"Wait(Const(1.0))"#, 1);
        logs[1].assert_log(r#"=== 4"#, 1);
        logs[1].assert_log(r#"do_change_direction(-90)"#, 1);
        logs[1].assert_log(r#"Fire(None)"#, 1);
        logs[1].assert_log(r#"Bullet(None)"#, 1);
        logs[1].assert_log(r#"create_simple_bullet(0, 0)"#, 1);
        logs[1].assert_log(r#"Vanish"#, 1);
        logs[1].assert_log(r#"=== 5"#, 1);

        logs[2].assert_log(r#"=== 2"#, 1);
        logs[2].assert_log(r#"ActionRef("ofs")"#, 1);
        logs[2].assert_log(r#"Action(Some("ofs"))"#, 1);
        logs[2].assert_log(r#"ChangeDirection"#, 1);
        logs[2].assert_log(r#"Wait(Const(1.0))"#, 1);
        logs[2].assert_log(r#"=== 3"#, 1);
        logs[2].assert_log(r#"do_change_direction(-90)"#, 1);
        logs[2].assert_log(r#"ChangeDirection"#, 1);
        logs[2].assert_log(r#"Wait(Const(1.0))"#, 1);
        logs[2].assert_log(r#"=== 4"#, 1);
        logs[2].assert_log(r#"do_change_direction(90)"#, 1);
        logs[2].assert_log(r#"Fire(None)"#, 1);
        logs[2].assert_log(r#"Bullet(None)"#, 1);
        logs[2].assert_log(r#"create_simple_bullet(0, 0)"#, 1);
        logs[2].assert_log(r#"Vanish"#, 1);
        logs[2].assert_log(r#"=== 5"#, 1);
        TestLogs(logs);
    }

    #[test]
    fn test_tt_morph_wedge_half() {
        let bml = BulletMLParser::new()
            .parse(
                r##"<?xml version="1.0" ?>
<!DOCTYPE bulletml SYSTEM "http://www.asahi-net.or.jp/~cs8k-cyu/bulletml/bulletml.dtd">

<bulletml type="vertical"
          xmlns="http://www.asahi-net.or.jp/~cs8k-cyu/bulletml">

 <action label="top">
  <wait>1</wait>
  <fire>
   <bullet>
        <direction type="relative">0</direction>
        <speed type="relative">$rank*0.4+0.2</speed>
    <actionRef label="ofs">
     <param>0</param>
     <param>-0.08</param>
    </actionRef>
   </bullet>
  </fire>
  <fire>
   <bullet>
        <direction type="relative">0</direction>
        <speed type="relative">$rank*0.4+0.2</speed>
    <actionRef label="ofs">
     <param>-120</param>
     <param>0.08</param>
    </actionRef>
   </bullet>
  </fire>
  <vanish/>
 </action>

<action label="ofs">
  <changeDirection>
   <direction type="relative">$1</direction>
   <term>1</term>
  </changeDirection>
  <wait>1</wait>
  <changeDirection>
   <direction type="relative">0-$1</direction>
   <term>1</term>
  </changeDirection>
  <wait>1</wait>
  <fire>
        <direction type="relative">0</direction>
        <speed type="relative">$2-$rank*0.4-0.2</speed>
        <bullet/>
  </fire>
  <vanish/>
</action>

</bulletml>"##,
            )
            .unwrap();
        let mut manager = TestManager::new(bml);
        let mut logs = Vec::new();
        manager.run_test(100, &mut logs);
        logs[0].assert_log(r#"=== 0"#, 1);
        logs[0].assert_log(r#"Action(Some("top"))"#, 1);
        logs[0].assert_log(r#"Wait(Const(1.0))"#, 1);
        logs[0].assert_log(r#"=== 1"#, 1);
        logs[0].assert_log(r#"Fire(None)"#, 1);
        logs[0].assert_log(r#"Bullet(None)"#, 1);
        logs[0].assert_log(r#"create_bullet(0, 1.6)"#, 1);
        logs[0].assert_log(r#"Fire(None)"#, 1);
        logs[0].assert_log(r#"Bullet(None)"#, 1);
        logs[0].assert_log(r#"create_bullet(0, 1.6)"#, 1);
        logs[0].assert_log(r#"Vanish"#, 1);
        logs[0].assert_log(r#"=== 2"#, 1);

        logs[1].assert_log(r#"=== 2"#, 1);
        logs[1].assert_log(r#"ActionRef("ofs")"#, 1);
        logs[1].assert_log(r#"Action(Some("ofs"))"#, 1);
        logs[1].assert_log(r#"ChangeDirection"#, 1);
        logs[1].assert_log(r#"Wait(Const(1.0))"#, 1);
        logs[1].assert_log(r#"=== 3"#, 1);
        logs[1].assert_log(r#"do_change_direction(0)"#, 1);
        logs[1].assert_log(r#"ChangeDirection"#, 1);
        logs[1].assert_log(r#"Wait(Const(1.0))"#, 1);
        logs[1].assert_log(r#"=== 4"#, 1);
        logs[1].assert_log(r#"do_change_direction(0)"#, 1);
        logs[1].assert_log(r#"Fire(None)"#, 1);
        logs[1].assert_log(r#"Bullet(None)"#, 1);
        logs[1].assert_log(r#"create_simple_bullet(0, 0.31999999999999995)"#, 1);
        logs[1].assert_log(r#"Vanish"#, 1);
        logs[1].assert_log(r#"=== 5"#, 1);

        logs[2].assert_log(r#"=== 2"#, 1);
        logs[2].assert_log(r#"ActionRef("ofs")"#, 1);
        logs[2].assert_log(r#"Action(Some("ofs"))"#, 1);
        logs[2].assert_log(r#"ChangeDirection"#, 1);
        logs[2].assert_log(r#"Wait(Const(1.0))"#, 1);
        logs[2].assert_log(r#"=== 3"#, 1);
        logs[2].assert_log(r#"do_change_direction(-120)"#, 1);
        logs[2].assert_log(r#"ChangeDirection"#, 1);
        logs[2].assert_log(r#"Wait(Const(1.0))"#, 1);
        logs[2].assert_log(r#"=== 4"#, 1);
        logs[2].assert_log(r#"do_change_direction(120)"#, 1);
        logs[2].assert_log(r#"Fire(None)"#, 1);
        logs[2].assert_log(r#"Bullet(None)"#, 1);
        logs[2].assert_log(r#"create_simple_bullet(0, 0.48)"#, 1);
        logs[2].assert_log(r#"Vanish"#, 1);
        logs[2].assert_log(r#"=== 5"#, 1);
        TestLogs(logs);
    }
}