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
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
//! The deterministic client core: game state, the behaviour contract and the tick.
//!
//! No I/O and no clock here: the connection feeds decoded [`Inbound`] packets and the time
//! in, and takes the [`Outbound`] packets out, so the tick order can be tested without a
//! socket.
//!
//! # Tick model
//!
//! Mirrors 1.8.9 `MinecraftClient.tick` as recorded in vanilla-client packet traces (and is the same
//! in 1.16.5):
//!
//! 1. inbound packets that arrived since the last tick have been applied (on arrival, like
//! vanilla's per-frame task queue; keep-alives, teleports and window confirms are
//! answered then);
//! 2. [`Behavior::tick`] runs. Actions (`chat`, `select_slot`, `swing`, `respawn`, …) are
//! written immediately, in call order, before this tick's movement packet;
//! [`TickContext::set_aim`] / [`TickContext::set_controls`] only record intent;
//! 3. held slot sync → rotation step (whole mouse counts) → movement step → sprint change →
//! sneak change → exactly one movement packet.
//!
//! The server therefore judges this tick's actions with the *previous* tick's sent pose
//! ([`TickContext::sent`]).
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::common::{
Abilities, ChatMessage, ClientSettings, Controls, GameMode, Health, Inbound, MovePacket,
Outbound, Pose, Vec3,
};
use crate::hands::{self, BlockHit, Buttons, DigFactors, Hands, HandsIo};
use crate::interest::Interests;
use crate::rotation::Rotation;
use crate::sim::{Crosshair, PickQuery, Sim, WorldView};
use crate::version::{Capabilities, GameVersion};
/// Pending chat messages kept for the behaviour; more are dropped (and counted) while the
/// behaviour is not ticking.
const MAX_PENDING_CHAT: usize = 512;
/// A bot behaviour: the code that decides what the player does each tick.
///
/// Behaviours never see packets or versions: they read a [`TickContext`] and call its
/// actions. A panic in a behaviour stops that behaviour (its [`Behavior::stop`] is called with
/// `"panic"`) but not the connection: the player keeps standing and answering the server.
pub trait Behavior {
/// Name for logs.
fn name(&self) -> &str {
"behavior"
}
/// Optional packet groups this behaviour needs. Read every tick; a change updates the
/// packet filter. Everything not asked for is dropped before it is decoded.
fn interests(&self) -> Interests {
Interests::NONE
}
/// Extra clientbound play packet ids (of `version`) to copy undecoded into
/// [`TickEvents::raw`], including packets the core consumes itself (the core's handling
/// does not change). Read every tick like [`Behavior::interests`]; a change updates the
/// packet filter. Decoding is the behaviour's job (`ghast::protocol::v1_8::play::clientbound`
/// / `v1_16_5`).
fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
let _ = version;
std::borrow::Cow::Borrowed(&[])
}
/// Called on the first tick the player is in the world, before that tick's
/// [`Behavior::tick`] (both see the same events).
fn start(&mut self, ctx: &mut TickContext<'_>) {
let _ = ctx;
}
/// Called every tick while the player is in the world and the server is answering.
fn tick(&mut self, ctx: &mut TickContext<'_>);
/// Whether the behaviour still wants ticks. Once it returns `false` the behaviour is done:
/// it is not ticked again (the player keeps standing and answering the server) and
/// [`Behavior::stop`] still runs when the session ends. Read after every start / tick.
fn running(&self) -> bool {
true
}
/// Called after every tick's movement step (also while the behaviour is on hold or has
/// finished), with a read-only view of what the server now has: the pose sent this tick,
/// the world, entities and inventory. For observers (a viewer, a recorder); it cannot act.
/// Default: nothing.
///
/// ```
/// use ghast_client::{Behavior, TickContext, TickView};
///
/// /// Logs where the server has the player, once a second.
/// struct Tracker;
///
/// impl Behavior for Tracker {
/// fn tick(&mut self, _ctx: &mut TickContext<'_>) {}
///
/// fn after_tick(&mut self, view: &TickView<'_>) {
/// if view.tick() % 20 == 0 {
/// let p = view.sent();
/// println!("{} {:?} in {}", view.tick(), p.pos, view.dimension());
/// }
/// }
/// }
/// ```
fn after_tick(&mut self, view: &TickView<'_>) {
let _ = view;
}
/// Called once when the session ends (or the behaviour panicked).
fn stop(&mut self, reason: &str) {
let _ = reason;
}
/// 26.1+: a dialog the server shows during the configuration state, before the player is in
/// the world (behaviours do not tick there). Called only with [`Interests::DIALOGS`]; the
/// client sends the returned answer at once, as vanilla would for that button (see
/// [`crate::dialog`]); `None` leaves the dialog open. A dialog the answer opens is offered
/// next. Play-state dialogs come through [`TickContext::dialog`] instead. Default: `None`.
fn configuration_dialog(
&mut self,
dialog: &crate::dialog::Dialog,
) -> Option<crate::dialog::DialogAnswer> {
let _ = dialog;
None
}
}
/// A boxed behaviour is a behaviour (a runner can pick one from its config at run time).
impl<B: Behavior + ?Sized> Behavior for Box<B> {
fn name(&self) -> &str {
(**self).name()
}
fn interests(&self) -> Interests {
(**self).interests()
}
fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
(**self).raw_packets(version)
}
fn start(&mut self, ctx: &mut TickContext<'_>) {
(**self).start(ctx);
}
fn tick(&mut self, ctx: &mut TickContext<'_>) {
(**self).tick(ctx);
}
fn running(&self) -> bool {
(**self).running()
}
fn after_tick(&mut self, view: &TickView<'_>) {
(**self).after_tick(view);
}
fn stop(&mut self, reason: &str) {
(**self).stop(reason);
}
fn configuration_dialog(
&mut self,
dialog: &crate::dialog::Dialog,
) -> Option<crate::dialog::DialogAnswer> {
(**self).configuration_dialog(dialog)
}
}
/// Why [`TickContext::click`] (or opening / closing a window) sent nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClickRefused {
/// The player is turning: click only while still.
Turning,
/// The inventory refused it.
Inventory(ghast_inventory::ClickError),
/// The player is dead (vanilla's death screen takes the input until the respawn).
Dead,
}
impl std::fmt::Display for ClickRefused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ClickRefused::Turning => f.write_str("the player is turning"),
ClickRefused::Inventory(e) => write!(f, "{e}"),
ClickRefused::Dead => f.write_str("the player is dead"),
}
}
}
impl std::error::Error for ClickRefused {}
/// A click that was sent: match it with [`TickEvents::inventory`]'s `clicks` on a later tick
/// (window id and action number, as the server's confirm carries them).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ClickTicket {
/// Window id the click was sent for; -1 when no [`ghast_inventory::ClickResult`] will
/// follow (the 26.x creative inventory screen, whose packets the server applies as sent).
pub window_id: i32,
/// Its action number.
pub action: i16,
}
impl ClickTicket {
/// Whether `r` is the result of this click.
#[must_use]
pub fn matches(&self, r: &ghast_inventory::ClickResult) -> bool {
r.window_id == self.window_id && r.action == self.action
}
}
/// A behaviour that does nothing (the player stands still).
#[derive(Debug, Clone, Copy, Default)]
pub struct Idle;
impl Behavior for Idle {
fn name(&self) -> &str {
"idle"
}
fn tick(&mut self, _ctx: &mut TickContext<'_>) {}
}
/// A clientbound play packet copied for the behaviour ([`Behavior::raw_packets`]).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RawInbound {
/// Packet id (version-specific).
pub id: i32,
/// The body after the id, undecoded (a cheap reference-counted copy).
pub body: bytes::Bytes,
/// When the frame was decoded from the socket (frames read together share it).
pub at: Instant,
}
/// A server teleport / correction (`position`) with the poses around it.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct TeleportEvent {
/// The packet's values as received: absolute or relative per
/// [`crate::common::teleport_flags`] in `flags`.
pub teleport: crate::common::Teleport,
/// What the server had from us just before ([`TickContext::sent`] before the overwrite):
/// compare with [`TeleportEvent::after`] to see what the server moved / turned us by.
pub sent_before: Pose,
/// The client pose just before (it may be ahead of `sent_before` within a tick).
pub pose_before: Pose,
/// The pose after applying it (relative fields resolved).
pub after: Pose,
}
/// Most teleports kept between two behaviour ticks.
const MAX_PENDING_TELEPORTS: usize = 64;
/// Most raw packets kept between two behaviour ticks.
const MAX_PENDING_RAW: usize = 4096;
/// Most dialog events kept between two behaviour ticks (the open dialog is always current).
const MAX_PENDING_DIALOGS: usize = 64;
/// What happened since the behaviour's previous tick.
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct TickEvents {
/// Chat messages in arrival order (only with [`Interests::CHAT`]).
pub chat: Vec<ChatMessage>,
/// Chat messages dropped because too many piled up while the behaviour was not ticking.
pub chat_dropped: usize,
/// The server teleported / corrected the player.
pub teleported: bool,
/// Every teleport in arrival order, with the sent pose before it (at most 64 per tick).
pub teleports: Vec<TeleportEvent>,
/// A join game packet arrived (first join or a proxy server switch).
pub joined: bool,
/// The player respawned or changed dimension.
pub respawned: bool,
/// The player died (health reached 0).
pub died: bool,
/// Health, food or saturation changed.
pub health_changed: bool,
/// The game mode changed.
pub game_mode_changed: bool,
/// Inventory / window changes and click results (ghast-inventory).
pub inventory: ghast_inventory::Events,
/// Block changes in arrival order (only with [`Interests::BLOCK_UPDATES`]): position and
/// the version's raw block state (1.8 `id << 4 | meta`, 1.16 the global palette id).
/// The world already holds them when the behaviour ticks.
pub block_updates: Vec<(ghast_protocol::BlockPos, u32)>,
/// Block changes dropped because too many piled up between two behaviour ticks.
pub block_updates_dropped: usize,
/// The packets asked for with [`Behavior::raw_packets`], in arrival order (kept while the
/// behaviour is on hold, like chat).
pub raw: Vec<RawInbound>,
/// Raw packets dropped because more than 4096 piled up between two behaviour ticks.
pub raw_dropped: usize,
}
impl TickEvents {
fn clear(&mut self) {
self.chat.clear();
self.chat_dropped = 0;
self.teleported = false;
self.teleports.clear();
self.joined = false;
self.respawned = false;
self.died = false;
self.health_changed = false;
self.game_mode_changed = false;
self.inventory = ghast_inventory::Events::default();
self.block_updates.clear();
self.block_updates_dropped = 0;
self.raw.clear();
self.raw_dropped = 0;
}
}
/// Tunables of the core.
#[derive(Debug, Clone)]
pub(crate) struct CoreOptions {
pub name: Arc<str>,
/// The version's capability row (the core asks it instead of comparing versions).
pub caps: &'static Capabilities,
pub settings: ClientSettings,
pub brand: Option<String>,
pub sensitivity: f32,
pub silent_hold: Duration,
pub inventory: ghast_inventory::Version,
/// Keep the look still on a tick that dug / placed when the turn would take the
/// crosshair off the clicked block (Grim RotationPlace re-checks with the next look).
pub hold_turn_on_action: bool,
/// Accept server resource packs the server requires (optional ones are declined).
pub accept_required_packs: bool,
/// Entities push the player (vanilla: on; off is the non-vanilla opt-in of
/// [`crate::Client::entity_push`]).
pub entity_push: bool,
}
/// Client state shared by the connection and the behaviour context.
#[derive(Debug)]
pub(crate) struct Core {
opts: CoreOptions,
tick: u64,
entity_id: i32,
joined: bool,
teleported_once: bool,
ready: bool,
pose: Pose,
sent: Pose,
rotation: Rotation,
aimed: bool,
controls: Controls,
health: Health,
/// The world's clocks (`update_time`) and the network id of the dimension's day clock.
clocks: crate::common::Clocks,
day_clock: Option<i32>,
dead: bool,
abilities: Abilities,
game_mode: GameMode,
held_slot: u8,
sent_slot: u8,
open_window: i32,
dimension: String,
respawn_screen: bool,
pending: TickEvents,
current: TickEvents,
out: Vec<Outbound>,
last_inbound: Option<Instant>,
silent: bool,
quit: Option<String>,
status: String,
hands: Hands,
buttons: Buttons,
/// Inventory and windows (ghast-inventory).
inv: ghast_inventory::Inventory,
/// The look changed in the last movement step (window clicks need a still player).
turned: bool,
/// Our active status effects: id → amplifier.
effects: std::collections::BTreeMap<i8, i8>,
/// Aqua affinity on the helmet (dig speed under water).
aqua_affinity: bool,
/// Blocks broken on the client this tick (predicted air until the server answers).
broken_now: Vec<ghast_protocol::BlockPos>,
/// The crosshair pick's entity list (kept to reuse the allocation).
pick: PickList,
/// Flight wanted by the behaviour this tick ([`TickContext::set_flying`]).
want_flying: Option<bool>,
/// Turns held back because they would have moved the crosshair off a clicked block.
held_turns: u64,
/// Arm swings (main and off hand) written in finished ticks.
swings: u64,
/// 1.21.4+ level loading: the server said the level's chunks are coming (game event 13).
level_load_started: bool,
/// 1.21.4+: `player_loaded` was sent for the current level.
client_loaded: bool,
/// 1.19.3+ signed chat: a chat session is ready to be announced (`setKeyPair`).
chat_session_due: bool,
/// 1.21.4+: this tick sent `player_loaded` (no mouse turn on it).
gate_tick: bool,
/// Test hook: the level-load gate's "section compiled" / "timed out" inputs.
#[cfg(test)]
test_gate: Option<(bool, bool)>,
/// Ticks spent waiting for the level (vanilla lets the player in after 30 s).
load_wait: u32,
/// Consecutive ticks the 3x3 columns around the player have been loaded (vanilla compiles
/// the player's section only then, and sees it compiled a tick later at the earliest).
near_loaded: u8,
/// Time origin for nanosecond timestamps (chunk batch timing).
origin: Instant,
/// Entities push the player ([`TickContext::set_entity_push`]).
entity_push: bool,
/// The switch as the sim has it.
entity_push_sim: bool,
/// The dialog open now (26.1+ `show_dialog`).
dialog: Option<Arc<crate::dialog::Dialog>>,
/// Dialog events since the behaviour's last tick, and those of its current tick (kept out
/// of [`TickEvents`]: almost always empty, they cost nothing per tick this way).
dialogs_pending: Vec<crate::dialog::DialogEvent>,
dialogs: Vec<crate::dialog::DialogEvent>,
/// The wire's block-prediction sequence after the last packets written (1.19+).
sequence: Option<i32>,
/// Test hook: this tick's look, set instead of a rotation step.
#[cfg(test)]
forced_look: Option<(f32, f32)>,
}
/// Behaviour bookkeeping of the engine.
#[derive(Debug, Default)]
struct BehaviorState {
started: bool,
failed: bool,
/// The behaviour reported [`Behavior::running`] `false`.
done: bool,
}
/// The core plus the behaviour's lifecycle.
#[derive(Debug)]
pub(crate) struct Engine<S> {
pub core: Core,
pub sim: S,
state: BehaviorState,
}
impl Core {
fn new(opts: CoreOptions) -> Self {
let rotation = Rotation::new(opts.sensitivity);
// a version module exists only with its feature, which enables its inventory
let inv = ghast_inventory::Inventory::new(opts.inventory)
.expect("the version's feature enables its ghast-inventory feature");
let entity_push = opts.entity_push;
Core {
opts,
tick: 0,
entity_id: 0,
joined: false,
teleported_once: false,
ready: false,
pose: Pose::default(),
sent: Pose::default(),
rotation,
aimed: false,
controls: Controls::default(),
health: Health::default(),
clocks: crate::common::Clocks::default(),
day_clock: None,
dead: false,
abilities: Abilities::default(),
game_mode: GameMode::default(),
held_slot: 0,
sent_slot: 0,
open_window: 0,
dimension: String::new(),
respawn_screen: true,
pending: TickEvents::default(),
current: TickEvents::default(),
out: Vec::with_capacity(16),
last_inbound: None,
silent: false,
quit: None,
status: String::new(),
hands: Hands::default(),
buttons: Buttons::default(),
inv,
turned: false,
effects: std::collections::BTreeMap::new(),
aqua_affinity: false,
broken_now: Vec::new(),
pick: PickList::default(),
want_flying: None,
held_turns: 0,
swings: 0,
level_load_started: false,
client_loaded: false,
chat_session_due: false,
gate_tick: false,
#[cfg(test)]
test_gate: None,
load_wait: 0,
near_loaded: 0,
origin: Instant::now(),
entity_push,
entity_push_sim: entity_push,
dialog: None,
dialogs_pending: Vec::new(),
dialogs: Vec::new(),
sequence: None,
#[cfg(test)]
forced_look: None,
}
}
/// A new client player entity (join, respawn): `lastReported*` zero, nothing held down,
/// waiting for the server's position.
fn reset_player(&mut self, why: &str) {
self.teleported_once = false;
self.ready = false;
self.pose = Pose::default();
self.sent = Pose::default();
self.controls = Controls::default();
self.aimed = false;
self.open_window = 0;
self.dead = false;
self.hands.reset();
self.buttons = Buttons::default();
self.effects.clear();
// A new level waits for its chunks again (1.21.4+ LevelLoadTracker).
self.level_load_started = false;
self.client_loaded = false;
self.load_wait = 0;
self.near_loaded = 0;
log::debug!(
"[{}] t{} {why}: waiting for the server position",
self.opts.name,
self.tick
);
}
/// The last inbound time in nanoseconds from the core's origin.
fn now_nanos(&self) -> i64 {
self.last_inbound.map_or(0, |t| {
t.saturating_duration_since(self.origin).as_nanos() as i64
})
}
fn column_loaded(&self, world: &dyn WorldView) -> bool {
// BlockPos(posX, 0, posZ) floors the coordinates.
let cx = (self.pose.pos.x.floor() as i64 >> 4) as i32;
let cz = (self.pose.pos.z.floor() as i64 >> 4) as i32;
world.is_column_loaded(cx, cz)
}
/// The player's column and its 8 neighbours are loaded (`RenderSection.hasAllNeighbors`:
/// the condition for vanilla's first compile of the player's section).
fn neighbourhood_loaded(&self, world: &dyn WorldView) -> bool {
let cx = (self.pose.pos.x.floor() as i64 >> 4) as i32;
let cz = (self.pose.pos.z.floor() as i64 >> 4) as i32;
(-1..=1).all(|dx| (-1..=1).all(|dz| world.is_column_loaded(cx + dx, cz + dz)))
}
}
/// The held stack's dig / use facts.
fn held_item<W: Sim + ?Sized>(
inv: &ghast_inventory::Inventory,
sim: &W,
) -> Option<hands::HeldItem> {
let s = inv.held()?;
let id = u16::try_from(s.id()).ok()?;
let count = u8::try_from(s.count().clamp(0, 255)).unwrap_or(0);
Some(sim.item_use_facts(s, false, sim.held_item(id, count, efficiency(s))))
}
/// Whether rays hit the entity (`Entity.collides`): living entities, players,
/// paintings and the solid objects (boats, minecarts, TNT, falling blocks, item frames, armor
/// stands, leash knots, end crystals); not items, orbs, projectiles.
fn collidable(e: &ghast_entity::Entity) -> bool {
use ghast_entity::{EntityClass, EntityType};
match e.class() {
EntityClass::Player | EntityClass::Mob | EntityClass::Painting => true,
EntityClass::Item | EntityClass::ExperienceOrb => false,
EntityClass::Object => match e.entity_type() {
// 63: the large fireball (`EntityFireball.canBeCollidedWith`; small fireballs and
// wither skulls are not).
EntityType::LegacyObject(t) => {
matches!(t, 1 | 10 | 50 | 51 | 63 | 70 | 71 | 77 | 78)
}
#[cfg(feature = "v1_16_5")]
EntityType::Registry(_) => {
ghast_entity::v1_16_5::info(e.entity_type()).is_some_and(|i| {
matches!(
i.name,
"boat"
| "fireball"
| "tnt"
| "end_crystal"
| "falling_block"
| "item_frame"
| "leash_knot"
| "armor_stand"
| "shulker_bullet"
) || i.name.contains("minecart")
})
}
_ => false,
},
// A class added for a newer version: not targetable until it is classified here.
_ => false,
}
}
/// 1.8 – 1.16.5: whether the crosshair pick can hit `e` (rays hit it, not a spectator) and its
/// targeting margin from the type's size table.
pub(crate) fn legacy_pick_margin(
ents: &ghast_entity::Entities,
e: &ghast_entity::Entity,
) -> Option<f32> {
let spectator = e.is_player()
&& ents
.player_info(&e.uuid())
.is_some_and(|p| p.game_mode == 3);
(collidable(e) && !spectator).then(|| e.targeting_margin())
}
/// The pickable entities near the eyes as the oracle-proven crosshair pick takes them, with
/// each one's id and position alongside (empty without an entity tracker).
#[derive(Debug, Default)]
struct PickList {
entities: Vec<ghast_physics::pick::PickEntity>,
ids: Vec<(i32, Vec3)>,
}
impl PickList {
/// Fills the list: tracked entities within 16 blocks of `eyes` (vanilla's search box only
/// drops entities the ray cannot hit, so this radius loses none) that the version's pick can
/// hit ([`Sim::pick_margin`]), not ourselves.
fn fill(&mut self, w: &(impl Sim + ?Sized), caps: &Capabilities, eyes: Vec3) {
self.entities.clear();
self.ids.clear();
if let Some(ents) = w.entities() {
self.fill_from(w, ents, caps, eyes);
}
}
#[inline(never)]
fn fill_from(
&mut self,
w: &(impl Sim + ?Sized),
ents: &ghast_entity::Entities,
caps: &Capabilities,
eyes: Vec3,
) {
use ghast_entity::Entity;
let me = ents.self_id();
let root = |mut id: i32| {
for _ in 0..16 {
match ents.get(id).and_then(Entity::vehicle) {
Some(v) => id = v,
None => break,
}
}
id
};
let riding = ents.me().and_then(Entity::vehicle);
let my_root = me.map(root);
for e in ents.within([eyes.x, eyes.y, eyes.z], 16.0) {
if Some(e.id()) == me {
continue;
}
let Some(pick_radius) = w.pick_margin(e) else {
continue;
};
let Some(b) = e.bounding_box() else {
continue;
};
// 1.8: the vehicle we sit on; 1.9+: anything with our root vehicle.
let same_root_vehicle = if caps.entity_pick_root_vehicle {
my_root.is_some_and(|r| root(e.id()) == r)
} else {
riding == Some(e.id())
};
self.entities.push(ghast_physics::pick::PickEntity {
bb: ghast_physics::math::Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5]),
pick_radius,
same_root_vehicle,
});
let p = e.position();
self.ids.push((e.id(), Vec3::new(p[0], p[1], p[2])));
}
}
/// The pick result as the hands take it: the block (none when an entity is in front or
/// beyond the 3-block limit) and the entity.
fn split(&self, t: Crosshair, eyes: Vec3) -> (Option<BlockHit>, Option<hands::EntityHit>) {
match t {
Crosshair::Block(b) => (b, None),
Crosshair::Entity { index, hit } => {
let (id, entity_pos) = self.ids[index];
let d = [hit.x - eyes.x, hit.y - eyes.y, hit.z - eyes.z];
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
(
None,
Some(hands::EntityHit {
id,
hit,
entity_pos,
distance,
}),
)
}
}
}
}
/// The player's box at `pos` for the pick's entity search (standing 0.6 x 1.8: the search
/// box only filters out entities the ray cannot reach, so the pose's exact box is not needed).
fn pick_box(pos: Vec3) -> ghast_physics::math::Aabb {
let h = f64::from(0.6f32 / 2.0);
ghast_physics::math::Aabb::new(
pos.x - h,
pos.y,
pos.z - h,
pos.x + h,
pos.y + f64::from(1.8f32),
pos.z + h,
)
}
/// The off-hand stack's facts (1.9+).
fn off_held_item<W: Sim + ?Sized>(
inv: &ghast_inventory::Inventory,
sim: &W,
) -> Option<hands::HeldItem> {
let s = inv.offhand()?;
let id = u16::try_from(s.id()).ok()?;
let count = u8::try_from(s.count().clamp(0, 255)).unwrap_or(0);
Some(sim.item_use_facts(s, true, sim.held_item(id, count, 0)))
}
/// Efficiency level of a stack (see [`enchant_level`]).
fn efficiency(s: &ghast_inventory::Stack) -> u8 {
enchant_level(s, 32, "minecraft:efficiency")
}
/// An enchantment level from the stack NBT: the 1.8 `ench` list with numeric ids, or the 1.13+
/// `Enchantments` list with names. Parsed only when the stack has NBT.
fn enchant_level(s: &ghast_inventory::Stack, id_1_8: i32, name: &str) -> u8 {
use ghast_protocol::nbt::Tag;
let Some(root) = s.nbt().and_then(|n| n.parse().ok().flatten()) else {
return 0;
};
let Some(c) = root.tag.as_compound() else {
return 0;
};
let num = |t: Option<&Tag>| match t {
Some(Tag::Short(v)) => i32::from(*v),
Some(Tag::Int(v)) => *v,
Some(Tag::Byte(v)) => i32::from(*v),
_ => -1,
};
for key in ["ench", "Enchantments"] {
if let Some(Tag::List(l)) = c.get(key) {
for e in l.items.iter().filter_map(Tag::as_compound) {
let hit = match e.get("id") {
Some(Tag::String(n)) => n == name,
other => num(other) == id_1_8,
};
if hit {
return u8::try_from(num(e.get("lvl")).clamp(0, 255)).unwrap_or(0);
}
}
}
}
0
}
impl<S: Sim> Engine<S> {
pub(crate) fn new(opts: CoreOptions, mut sim: S) -> Self {
sim.set_entity_push(opts.entity_push);
Engine {
core: Core::new(opts),
sim,
state: BehaviorState::default(),
}
}
/// A chat session was started in the wire layer: announce it on the next tick, from the
/// connection tick like vanilla (`ClientPacketListener.tick` → `setKeyPair`).
pub(crate) fn request_chat_session(&mut self) {
self.core.chat_session_due = true;
}
/// A join game arrived and no reconfiguration dropped the level since.
pub(crate) fn joined(&self) -> bool {
self.core.joined
}
/// Bytes arrived from the server (liveness for the silent-server guard).
pub(crate) fn note_inbound(&mut self, now: Instant) {
self.core.last_inbound = Some(now);
}
/// Time of the last inbound bytes.
pub(crate) fn last_inbound(&self) -> Option<Instant> {
self.core.last_inbound
}
/// The wire layer's prediction sequence after writing packets.
pub(crate) fn note_sequence(&mut self, sequence: Option<i32>) {
self.core.sequence = sequence;
}
/// After a world packet: a prediction answer that moved the player back
/// ([`Sim::take_snap`]) moves the engine's pose with it.
#[inline]
pub(crate) fn sync_snap(&mut self) {
if let Some(p) = self.sim.take_snap() {
log::debug!(
"[{}] t{} moved back to {:.3} {:.3} {:.3}: a restored block holds the player",
self.core.opts.name,
self.core.tick,
p.x,
p.y,
p.z
);
self.core.pose.pos = p;
}
}
/// The bot's name (for logs).
pub(crate) fn name(&self) -> &str {
&self.core.opts.name
}
/// Queues a raw packet copy for the behaviour's next tick.
pub(crate) fn push_raw(&mut self, p: RawInbound) {
let ev = &mut self.core.pending;
if ev.raw.len() < MAX_PENDING_RAW {
ev.raw.push(p);
} else {
ev.raw_dropped += 1;
}
}
/// The raw packet ids the behaviour wants (none once it failed or finished).
pub(crate) fn raw_packets<B: Behavior>(&self, b: &B) -> std::borrow::Cow<'static, [i32]> {
if self.state.failed || self.state.done {
std::borrow::Cow::Borrowed(&[])
} else {
b.raw_packets(self.core.opts.caps.version)
}
}
/// The inventory (the connection feeds it its packets).
pub(crate) fn inventory_mut(&mut self) -> &mut ghast_inventory::Inventory {
&mut self.core.inv
}
/// 1.8 – 1.16.5: the inventory has just opened the mount screen of entity `entity_id`; its
/// slot rules are read off the tracked entity when the sim can (a behaviour's
/// `TickContext::set_mount_rules` later still wins).
pub(crate) fn mount_screen_opened(&mut self, entity_id: i32) {
if let Some(r) = self.sim.mount_rules(entity_id) {
self.core.inv.set_mount_rules(Some(r));
}
}
/// Outbound packets produced since the last call, in send order.
pub(crate) fn outbound(&mut self) -> &mut Vec<Outbound> {
&mut self.core.out
}
/// Set when the behaviour asked to disconnect.
pub(crate) fn quit_requested(&self) -> Option<&str> {
self.core.quit.as_deref()
}
pub(crate) fn core_name(&self) -> &str {
&self.core.opts.name
}
/// [`crate::Client::accept_required_resource_packs`].
pub(crate) fn accept_required_packs(&self) -> bool {
self.core.opts.accept_required_packs
}
pub(crate) fn tick_count(&self) -> u64 {
self.core.tick
}
/// Applies one inbound packet (except disconnect and compression, which the connection
/// handles).
pub(crate) fn handle(&mut self, p: Inbound) {
let c = &mut self.core;
let sim = &mut self.sim;
match p {
Inbound::KeepAlive(id) => c.out.push(Outbound::KeepAlive(id)),
Inbound::JoinGame(j) => {
c.entity_id = j.entity_id;
// LocalPlayer's main arm comes from the client option.
sim.set_main_arm_left(c.opts.settings.main_hand == 0);
c.game_mode = j.game_mode;
c.respawn_screen = j.respawn_screen;
// A join always creates a new client world (the world itself was cleared by
// the world packet routing).
c.dimension = j.dimension;
c.joined = true;
c.pending.joined = true;
// The level's loading screen replaces any dialog.
c.dialog = None;
c.health = Health::default();
c.abilities = Abilities::default();
c.reset_player("join game");
sim.reset_player();
sim.spectator(c.game_mode == GameMode::Spectator);
// ClientPlayNetworkHandler.onGameJoin: settings, then the brand (1.20.2+ sends
// both in the configuration state instead).
if !c.opts.caps.configuration_state {
c.out.push(Outbound::Settings(c.opts.settings.clone()));
if let Some(brand) = &c.opts.brand {
c.out.push(Outbound::Brand(brand.clone()));
}
}
log::info!(
"[{}] joined: entity {} {:?} dimension {}",
c.opts.name,
c.entity_id,
c.game_mode,
c.dimension
);
}
Inbound::Respawn {
dimension,
game_mode,
keep,
} => {
if dimension != c.dimension {
c.dimension = dimension;
}
c.game_mode = game_mode;
c.pending.respawned = true;
c.reset_player("respawn");
sim.respawn_player(keep);
sim.spectator(c.game_mode == GameMode::Spectator);
}
Inbound::Teleport(t) => {
if c.teleported_once {
log::debug!(
"[{}] t{} teleport {:?} {:?} {:?} yaw {:?} pitch {:?} flags {}; we had sent \
{:?} {:?} {:?} yaw {:?} pitch {:?} ground {}",
c.opts.name,
c.tick,
t.x,
t.y,
t.z,
t.yaw,
t.pitch,
t.flags,
c.sent.pos.x,
c.sent.pos.y,
c.sent.pos.z,
c.sent.yaw,
c.sent.pitch,
c.sent.on_ground
);
}
let (sent_before, pose_before) = (c.sent, c.pose);
sim.teleport(&mut c.pose, &t);
sim.teleport_sequence(c.sequence);
if c.pending.teleports.len() < MAX_PENDING_TELEPORTS {
c.pending.teleports.push(TeleportEvent {
teleport: t,
sent_before,
pose_before,
after: c.pose,
});
}
if let Some(id) = t.teleport_id {
c.out.push(Outbound::TeleportConfirm(id));
}
c.out.push(Outbound::Move(MovePacket::PositionLook {
horizontal_collision: false,
pos: c.pose.pos,
yaw: c.pose.yaw,
pitch: c.pose.pitch,
on_ground: false,
}));
// The server now has this pose; vanilla's lastReported* are not touched.
c.sent = Pose {
on_ground: false,
..c.pose
};
if !c.teleported_once {
log::debug!(
"[{}] t{} spawn position {:.3} {:.3} {:.3}",
c.opts.name,
c.tick,
c.pose.pos.x,
c.pose.pos.y,
c.pose.pos.z
);
}
c.teleported_once = true;
c.pending.teleported = true;
}
Inbound::Chat(m) => {
if c.pending.chat.len() < MAX_PENDING_CHAT {
c.pending.chat.push(m);
} else {
c.pending.chat_dropped += 1;
}
}
Inbound::Time(t) => {
c.clocks.apply(&t);
// the dimension's day clock (26.x: by its world clock registry id)
c.day_clock = sim.day_clock();
}
Inbound::Health(h) => {
let was_dead = c.dead;
c.health = h;
sim.food(h.food);
// isAlive(): a dead player does not wait for its section (26.1 load gate).
sim.player_alive(h.health > 0.0);
c.pending.health_changed = true;
if h.health <= 0.0 && !was_dead {
c.dead = true;
c.pending.died = true;
log::info!("[{}] t{} died", c.opts.name, c.tick);
}
}
Inbound::Died { entity_id } => {
if entity_id == c.entity_id && !c.respawn_screen {
// 1.16 immediate respawn: the client respawns without a death screen.
c.out.push(Outbound::Respawn);
}
}
Inbound::Abilities(a) => {
c.abilities = a;
c.pose.flying = a.flying();
sim.abilities(a);
}
Inbound::HeldSlot(s) => {
if (0..9).contains(&s) {
// Only the inventory's selection changes; the controller's copy does not,
// so the next sync echoes it (as vanilla does).
if c.held_slot != s as u8 {
c.hands.stop_using();
}
c.held_slot = s as u8;
}
}
Inbound::GameState { reason, value } => match reason {
// Weather (the 26.1 riptide reads the rain).
1 | 2 | 7 => sim.weather(reason, value),
3 => {
c.game_mode = GameMode::from_wire(value as u8);
sim.spectator(c.game_mode == GameMode::Spectator);
// 26.x ServerPlayer.setGameMode(SPECTATOR) calls stopUsingItem and the living
// flags clear the client's use: stopping at once stands in for that. 1.8.9 –
// 1.16.5 stop nothing (the use runs until release or finish).
if c.game_mode == GameMode::Spectator && c.opts.caps.spectator_switch_stops_use
{
c.hands.stop_using();
}
c.pending.game_mode_changed = true;
}
// 1.15+: "immediate respawn" gamerule (1 = no respawn screen).
11 if c.opts.caps.immediate_respawn_rule => c.respawn_screen = value == 0.0,
// 1.21.4+ LEVEL_CHUNKS_LOAD_START: the level's chunks are on their way.
13 if c.opts.caps.player_loaded_gate => {
c.level_load_started = true;
sim.level_load_start();
}
_ => {}
},
// Window confirms are answered by the inventory (exactly once).
Inbound::Transaction { .. } => {}
Inbound::OpenWindow(id) => c.open_window = id,
Inbound::CloseWindow(_) => c.open_window = 0,
Inbound::Velocity { entity_id, motion } => {
if entity_id == c.entity_id {
sim.velocity(motion, false);
}
}
Inbound::ExplosionPush(motion) => sim.velocity(motion, true),
Inbound::MovementSpeed {
entity_id,
base,
modifiers,
} => {
if entity_id == c.entity_id {
log::debug!(
"[{}] t{} movement speed base {base:?} modifiers {modifiers:?}",
c.opts.name,
c.tick
);
let mods: Vec<(u128, f64, u8)> = modifiers
.iter()
.map(|&(id, amount, op)| (id.as_u128(), amount, op as u8))
.collect();
sim.movement_speed(base, &mods);
}
}
Inbound::Effect {
entity_id,
id,
amplifier,
} => {
if entity_id == c.entity_id {
c.effects.insert(id, amplifier);
sim.status_effects(&c.effects);
}
}
Inbound::EffectRemoved { entity_id, id } => {
if entity_id == c.entity_id {
c.effects.remove(&id);
sim.status_effects(&c.effects);
}
}
Inbound::EntityStatus { entity_id, status } => {
// 9: the server finished our item use (eating, drinking).
if entity_id == c.entity_id && status == 9 {
c.hands.stop_using();
}
}
Inbound::Attributes {
entity_id,
attributes,
} => {
if entity_id == c.entity_id {
sim.attributes(&attributes);
}
}
Inbound::Ping(id) => c.out.push(Outbound::Pong(id)),
Inbound::ChunkBatchStart => sim.chunk_batch_start(c.now_nanos()),
Inbound::ChunkBatchFinished(size) => {
let per_tick = sim.chunk_batch_finished(size, c.now_nanos());
c.out.push(Outbound::ChunkBatchReceived(per_tick));
}
Inbound::StartConfiguration => {
// Vanilla drops the level and the player until the next join.
c.joined = false;
c.dialog = None;
c.reset_player("reconfiguration");
sim.drop_level();
}
Inbound::ResourcePackPush { id, required } => {
// A client that never shows the prompt: optional packs are declined; required
// ones are accepted (and reported loaded) when allowed, as the server would
// otherwise disconnect.
if required && c.opts.accept_required_packs {
for result in [3, 4, 0] {
c.out.push(Outbound::ResourcePackStatus { id, result });
}
} else {
c.out.push(Outbound::ResourcePackStatus { id, result: 1 });
}
}
Inbound::CookieRequest(key) => {
// The wire layer fills in a stored value.
c.out.push(Outbound::CookieResponse { key, value: None });
}
Inbound::StoreCookie { .. } => {}
// The session driver ends the session (or follows the transfer).
Inbound::Transfer { .. } => {}
Inbound::Rotate {
yaw,
pitch,
relative_yaw,
relative_pitch,
} => {
// ClientPacketListener.handleRotatePlayer: set (or add), answer with a look.
let yaw = if relative_yaw { c.pose.yaw + yaw } else { yaw };
let pitch = if relative_pitch {
c.pose.pitch + pitch
} else {
pitch
};
c.pose.yaw = yaw;
c.pose.pitch = pitch.clamp(-90.0, 90.0);
c.rotation.reset(c.pose.yaw, c.pose.pitch);
c.out.push(Outbound::LookAnswer {
yaw: c.pose.yaw,
pitch: c.pose.pitch,
});
c.sent.yaw = c.pose.yaw;
c.sent.pitch = c.pose.pitch;
}
Inbound::ShowDialog(d) => {
log::debug!("[{}] t{} dialog \"{}\"", c.opts.name, c.tick, d.title);
c.dialog = Some(d.clone());
if c.dialogs_pending.len() < MAX_PENDING_DIALOGS {
c.dialogs_pending.push(crate::dialog::DialogEvent::Shown(d));
}
}
Inbound::ClearDialog => {
if c.dialog.take().is_some() && c.dialogs_pending.len() < MAX_PENDING_DIALOGS {
c.dialogs_pending.push(crate::dialog::DialogEvent::Cleared);
}
}
Inbound::Disconnect(_) | Inbound::SetCompression(_) => {}
}
}
/// The interests of the behaviour (the packet filter follows them).
pub(crate) fn interests<B: Behavior>(&self, b: &B) -> Interests {
if self.state.failed {
Interests::NONE
} else {
b.interests()
}
}
/// Ends the behaviour (session over).
pub(crate) fn stop<B: Behavior>(&mut self, b: &mut B, reason: &str) {
if self.state.started && !self.state.failed {
self.state.failed = true;
let name = self.core.opts.name.clone();
if catch_unwind(AssertUnwindSafe(|| b.stop(reason))).is_err() {
log::error!("[{name}] behaviour {} panicked in stop", b.name());
}
}
}
/// One client tick at `now` (dialog commands never parse: no command tree).
#[cfg(test)]
#[allow(dead_code, reason = "the engine tests need every version feature")]
pub(crate) fn tick<B: Behavior>(&mut self, b: &mut B, now: Instant) {
self.tick_with(b, now, &|_| crate::dialog::CommandCheck::ParseErrors);
}
/// One client tick at `now`; `commands` checks a dialog's command like vanilla's
/// `verifyCommand` (the wire layer's command tree).
pub(crate) fn tick_with<B: Behavior>(
&mut self,
b: &mut B,
now: Instant,
commands: &dyn Fn(&str) -> crate::dialog::CommandCheck,
) {
let c = &mut self.core;
c.tick += 1;
// `ClientLevel.tickTime`: the game time and the clocks move on between updates.
c.clocks.tick();
// Per-tick packet-order guard and click timeout of the inventory.
c.inv.tick();
let was_ready = c.ready;
// 1.21.4+ (`LocalPlayer.tick` without the old `hasChunkAt` check): once the level
// loaded, the player ticks in an unloaded column too (its blocks read as void air).
c.ready = c.teleported_once
&& ((c.opts.caps.player_loaded_gate && c.client_loaded) || c.column_loaded(&self.sim));
if c.ready != was_ready {
if c.ready {
log::info!(
"[{}] t{} in the world at {:.3} {:.3} {:.3}",
c.opts.name,
c.tick,
c.pose.pos.x,
c.pose.pos.y,
c.pose.pos.z
);
} else {
log::debug!(
"[{}] t{} player column not loaded: not ticking",
c.opts.name,
c.tick
);
}
}
if c.chat_session_due && c.joined {
// ClientPacketListener.tick: the key pair future finished → chat_session_update,
// before the level-load check.
c.chat_session_due = false;
c.out.push(Outbound::ChatSessionUpdate);
}
if c.opts.caps.player_loaded_gate && c.joined && !c.client_loaded {
// 1.21.4+ LevelLoadTracker: after the server's "chunks load start" the level is
// ready once the player's section is compiled and visible
// (`isSectionCompiledAndVisible`; spectators and dead players at once); after 30 s
// it lets the player in anyway. The first compile needs the 3x3 columns around the
// player (`hasAllNeighbors`) and happens in a frame after the tick that received
// them, so the earliest ready tick is the next one (a nearby section has no
// fade-in). `player_loaded` goes out from the connection tick, before the key
// handling and the player tick.
c.load_wait += 1;
let near = c.neighbourhood_loaded(&self.sim);
c.near_loaded = if near {
c.near_loaded.saturating_add(1)
} else {
0
};
// The oracle-proven gate (ghast_physics::modern::LoadGate) decides (dead players,
// spectators and feet outside the build height included); "section compiled" is
// ours: the nine columns on two consecutive ticks.
let (compiled, timed_out) = (c.ready && c.near_loaded >= 2, c.load_wait >= 600);
#[cfg(test)]
let (compiled, timed_out) = c.test_gate.unwrap_or((compiled, timed_out));
if self.sim.load_gate_tick(compiled, timed_out) {
c.client_loaded = true;
c.gate_tick = true;
c.out.push(Outbound::PlayerLoaded);
log::debug!("[{}] t{} player loaded", c.opts.name, c.tick);
}
}
if !c.ready || (c.opts.caps.player_loaded_gate && !c.client_loaded) {
// The client player does not tick outside a loaded column (1.16 vanilla; on 1.8
// the bot waits for its column as well) nor before its level loaded (1.21.4+).
if c.opts.caps.sends_tick_end && c.joined {
c.out.push(Outbound::TickEnd);
}
// Behind the level-load gate only the player's entity tick counter runs.
if c.opts.caps.player_loaded_gate && c.joined && !c.client_loaded {
self.sim.tick_unloaded();
}
self.sim.tick_entities(&mut c.pose);
return;
}
let silent_for = c.last_inbound.map(|t| now.saturating_duration_since(t));
let silent = silent_for.is_some_and(|d| d > c.opts.silent_hold);
if silent != c.silent {
c.silent = silent;
if silent {
log::warn!(
"[{}] t{} server silent for {} ms: behaviour on hold",
c.opts.name,
c.tick,
silent_for.unwrap_or_default().as_millis()
);
} else {
log::info!(
"[{}] t{} server answering again: behaviour resumes",
c.opts.name,
c.tick
);
}
}
if silent {
// Freeze: release the keys, keep only the vanilla movement packet.
c.controls = Controls::default();
c.aimed = false;
} else if !self.state.failed && !self.state.done {
std::mem::swap(&mut c.pending, &mut c.current);
c.pending.clear();
if !c.dialogs.is_empty() || !c.dialogs_pending.is_empty() {
c.dialogs.clear();
std::mem::swap(&mut c.dialogs, &mut c.dialogs_pending);
}
c.current.inventory = c.inv.drain_events();
c.current.block_updates_dropped =
self.sim.drain_block_updates(&mut c.current.block_updates);
if c.current.inventory.player_changed {
// Armour enchantments that change movement / digging.
let ench = |a: usize, id: i32, name: &str| {
c.inv.armor(a).map_or(0, |s| enchant_level(s, id, name))
};
let depth = ench(3, 8, "minecraft:depth_strider");
let soul = ench(3, -1, "minecraft:soul_speed");
c.aqua_affinity = ench(0, 6, "minecraft:aqua_affinity") > 0;
self.sim.boots(depth, soul);
self.sim.feet_item(c.inv.armor(3).map(|s| s.id()));
}
// what the open screen sent by itself while the server's packets were applied (the
// 1.16.5 anvil's rename_item), before this tick's actions
for o in c.inv.take_screen_packets() {
c.out.push(Outbound::Inventory(o));
}
let started = self.state.started;
self.state.started = true;
if !started {
c.rotation.reset(c.pose.yaw, c.pose.pitch);
}
let name = c.opts.name.clone();
let result = catch_unwind(AssertUnwindSafe(|| {
let held = held_item(&c.inv, &self.sim);
let mut ctx = TickContext {
core: c,
world: &self.sim,
held,
crosshair: std::cell::OnceCell::new(),
commands,
};
if !started {
b.start(&mut ctx);
}
b.tick(&mut ctx);
b.running()
}));
match result {
Ok(true) => {}
Ok(false) => {
self.state.done = true;
log::info!("[{name}] behaviour {} finished", b.name());
}
Err(_) => {
log::error!("[{name}] behaviour {} panicked: stopped", b.name());
self.stop(b, "panic");
}
}
}
let c = &mut self.core;
// The behaviour may have switched entity pushes for this tick's entity ticks.
if c.entity_push != c.entity_push_sim {
c.entity_push_sim = c.entity_push;
self.sim.set_entity_push(c.entity_push);
}
// ClientPlayerInteractionManager.tick (syncSelectedSlot) runs before the key
// processing: a held slot the server changed is echoed before any click.
if c.held_slot != c.sent_slot {
c.sent_slot = c.held_slot;
c.out.push(Outbound::HeldSlot(i16::from(c.sent_slot)));
}
// MinecraftClient.tick key processing (a GUI takes the mouse: buttons up).
{
// The screen as the inventory models it (vanilla: a window the client has no
// screen for opens none; a window the client closed is gone at once).
let gui = c.inv.gui_open();
// 26.1: the riptide strength of the held tridents, while it can matter.
if self.sim.modern_inputs() && ((c.buttons.right && !gui) || c.hands.using_item()) {
self.sim.held_use_inputs(&mut c.inv);
}
let eye = if c.pose.sneaking {
c.opts.caps.sneak_eye_height
} else {
c.opts.caps.eye_height
};
let eyes = Vec3::new(c.pose.pos.x, c.pose.pos.y + eye, c.pose.pos.z);
let sim = &self.sim;
let blocks = |x: i32, y: i32, z: i32| sim.block_query(x, y, z);
let blocked = |p: ghast_protocol::BlockPos, f: crate::common::Face, id: u16| {
sim.place_suppressed(p, f, id)
};
let look = hands::look_vector(c.pose.yaw, c.pose.pitch);
let held_id = c.inv.held().and_then(|s| u16::try_from(s.id()).ok());
// The death screen takes the input too, until the respawn.
let (left, right) = (
c.buttons.left && !gui && !c.dead,
c.buttons.right && !gui && !c.dead,
);
// GameRenderer.updateTargetedEntity before the key handling: one oracle-proven
// pick for the block and the entity. With both buttons up the hands never read it
// (no click, and the dig is reset whatever the target), so it is only computed
// when a button is down — here, at the vanilla pick point, from this state.
let (target, entity) = if left || right {
c.pick.fill(sim, c.opts.caps, eyes);
let crosshair = sim.crosshair_target(&PickQuery {
eyes,
rotation: (c.pose.yaw, c.pose.pitch),
look,
held: held_id,
now: true,
creative: c.game_mode == GameMode::Creative,
player_bb: pick_box(c.pose.pos),
entities: &c.pick.entities,
});
c.pick.split(crosshair, eyes)
} else {
(None, None)
};
let in_water = blocks(
eyes.x.floor() as i32,
eyes.y.floor() as i32,
eyes.z.floor() as i32,
)
.is_some_and(|b| b.water);
let held = held_item(&c.inv, sim);
let mut placed = false;
let first = c.out.len();
let mut io = HandsIo {
blocks: &blocks,
target,
held,
held_stack: c.inv.held().cloned(),
food: c.health.food,
modern: c.opts.caps.combat_1_9,
off_held: off_held_item(&c.inv, sim),
off_stack: c.inv.offhand().cloned(),
entity,
factors: DigFactors {
on_ground: c.pose.on_ground,
in_water,
aqua_affinity: c.aqua_affinity,
haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
},
sneaking: c.pose.sneaking,
out: &mut c.out,
broken: &mut c.broken_now,
placed: &mut placed,
spectator: c.game_mode == GameMode::Spectator,
spectator_swings: c.opts.caps.spectator_block_click_swings,
place_blocked: &blocked,
};
c.hands.tick(left, right, &mut io);
// Other placements: the server's set_slot brings the new count of the held stack.
let _ = placed;
predict_planting(c, sim, first);
}
// The tick's dig packets (behaviour actions and buttons): broken blocks turn to air
// and the version keeps its records of them for the server's answers.
if c.hands.dug || !c.hands.placing.is_empty() {
// Only 1.16.5 records the digs that broke nothing.
if !c.broken_now.is_empty() || !c.hands.placing.is_empty() || self.sim.records_digs() {
sent_predictions(c, &mut self.sim);
}
c.hands.dug = false;
c.hands.placing.clear();
}
// ClientPlayerEntity.tickMovement: a flight toggle is told to the server before the move.
if let Some(f) = c.want_flying.take() {
let first = c.out.len();
self.sim.set_flying(f, &mut c.out);
if c.out.len() > first {
c.pose.flying = f;
} else if f && !c.pose.flying {
log::debug!(
"[{}] t{} set_flying(true) refused: flight not allowed",
c.opts.name,
c.tick
);
}
}
// Rotation runs only on ticks the behaviour aimed (budgets untouched otherwise).
c.turned = false;
#[cfg(test)]
if let Some((yaw, pitch)) = c.forced_look.take() {
c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
c.pose.yaw = yaw;
c.pose.pitch = pitch;
c.aimed = false;
}
// The gate tick keeps the look (the loading screen held the mouse); an aim set on it
// turns from the next tick.
let gate_tick = std::mem::take(&mut c.gate_tick);
if c.aimed && !gate_tick {
let (yaw, pitch) = c.rotation.step(c.pose.yaw, c.pose.pitch);
if c.opts.hold_turn_on_action && !post_look_ok(c, yaw, pitch) {
// Grim RotationPlace re-checks a dig / place with the look of the movement
// packet that follows it: keep the mouse still on the clicked block this tick.
c.held_turns += 1;
} else {
c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
c.pose.yaw = yaw;
c.pose.pitch = pitch;
}
c.aimed = false;
}
let first = c.out.len();
// 26.1 per-tick inputs: updatingUsingItem, the glider (the other versions' sims do
// nothing here).
// 26.1 per-tick inputs, only when something can need them: a use, a release, a jump
// press, attached rockets.
if self.sim.modern_inputs()
&& (c.hands.using_item()
|| c.hands.released_use().is_some()
|| c.controls.jump
|| self.sim.pre_tick_wanted())
{
let pre = crate::sim::PreTick {
using: c.hands.use_item(),
released: c.hands.released_use(),
controls: c.controls,
look: (c.pose.yaw, c.pose.pitch),
};
if !self.sim.pre_tick(&c.inv, &pre) {
c.hands.stop_using();
}
}
let using = c.hands.using_item();
self.sim
.step(&mut c.pose, c.controls, using, c.entity_id, &mut c.out);
// ClientLevel.tickEntities: after this tick's pick and key handling, and after the
// player (the first entity in the client's tick list): the other entities' ticks see
// the moved player and push it (1.12.2, 26.1+).
self.sim.tick_entities(&mut c.pose);
c.hands.count_use_tick();
for o in &c.out[first..] {
let Outbound::Move(m) = o else { continue };
match *m {
MovePacket::Position { pos, .. } => c.sent.pos = pos,
MovePacket::Look { yaw, pitch, .. } => {
c.sent.yaw = yaw;
c.sent.pitch = pitch;
}
MovePacket::PositionLook {
pos, yaw, pitch, ..
} => {
c.sent.pos = pos;
c.sent.yaw = yaw;
c.sent.pitch = pitch;
}
MovePacket::Flying { .. } => {}
}
if matches!(
m,
MovePacket::Position { .. } | MovePacket::PositionLook { .. }
) {
c.sent.motion = c.pose.motion;
}
}
c.sent.on_ground = c.pose.on_ground;
c.sent.sneaking = c.pose.sneaking;
c.sent.sprinting = c.pose.sprinting;
c.sent.flying = c.pose.flying;
c.swings += count_swings(&c.out);
// Minecraft.tick's screen check: a dead player without a screen gets the death screen
// or, with the immediate-respawn rule (1.15+, `respawn_screen` off), asks to respawn,
// every tick until the server's respawn arrives (also when it joined already dead,
// which brings no death event). With the death screen the behaviour decides
// (`TickContext::respawn`).
if c.dead && c.joined && !c.respawn_screen && !c.inv.gui_open() {
c.out.push(Outbound::Respawn);
}
// Minecraft.tick ends with `tick_end` (1.21.2+), after the player's packets.
if c.opts.caps.sends_tick_end {
c.out.push(Outbound::TickEnd);
}
if self.state.started && !self.state.failed {
let name = c.opts.name.clone();
let view = TickView {
core: &self.core,
world: &self.sim,
};
if catch_unwind(AssertUnwindSafe(|| b.after_tick(&view))).is_err() {
log::error!(
"[{name}] behaviour {} panicked in after_tick: stopped",
b.name()
);
self.stop(b, "panic");
}
}
}
}
/// Arm swings (main or off hand) in a packet list.
fn count_swings(out: &[Outbound]) -> u64 {
out.iter()
.filter(|o| matches!(o, Outbound::Swing | Outbound::SwingOffHand))
.count() as u64
}
/// A read-only view after the movement step ([`Behavior::after_tick`]).
pub struct TickView<'a> {
core: &'a Core,
world: &'a dyn WorldView,
}
impl std::fmt::Debug for TickView<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TickView")
.field("tick", &self.core.tick)
.field("sent", &self.core.sent)
.finish_non_exhaustive()
}
}
impl TickView<'_> {
/// Ticks since the session started.
#[must_use]
pub fn tick(&self) -> u64 {
self.core.tick
}
/// The protocol version.
#[must_use]
pub fn version(&self) -> GameVersion {
self.core.opts.caps.version
}
/// The client pose after this tick's movement step.
#[must_use]
pub fn pose(&self) -> &Pose {
&self.core.pose
}
/// What the server has after this tick's movement packet (position, look, flags).
#[must_use]
pub fn sent(&self) -> &Pose {
&self.core.sent
}
/// The world.
#[must_use]
pub fn world(&self) -> &dyn WorldView {
self.world
}
/// The tracked entities (with [`Interests::ENTITIES`]).
#[must_use]
pub fn entities(&self) -> Option<&ghast_entity::Entities> {
self.world.entities()
}
/// The inventory and the open window.
#[must_use]
pub fn inventory(&self) -> &ghast_inventory::Inventory {
&self.core.inv
}
/// What the behaviour saw this tick (the events of [`TickContext::events`]).
#[must_use]
pub fn events(&self) -> &TickEvents {
&self.core.current
}
/// Our entity id.
#[must_use]
pub fn entity_id(&self) -> i32 {
self.core.entity_id
}
/// Health, food and saturation.
#[must_use]
pub fn health(&self) -> Health {
self.core.health
}
/// The world's time: game time and the dimension's time of day (`update_time`, counted on
/// between the server's updates); `None` before the first update.
#[must_use]
pub fn world_time(&self) -> Option<crate::common::WorldTime> {
self.core.clocks.world_time(self.core.day_clock)
}
/// Game mode.
#[must_use]
pub fn game_mode(&self) -> GameMode {
self.core.game_mode
}
/// The selected hotbar slot.
#[must_use]
pub fn held_slot(&self) -> u8 {
self.core.held_slot
}
/// The block being broken and its progress 0 … 1.
#[must_use]
pub fn mining(&self) -> Option<(ghast_protocol::BlockPos, f32)> {
self.core.hands.mining()
}
/// Arm swings sent so far (see [`TickContext::swings`]).
#[must_use]
pub fn swings(&self) -> u64 {
self.core.swings
}
/// Blocks broken so far.
#[must_use]
pub fn broken(&self) -> u64 {
self.core.hands.broken
}
/// The current dimension (`"0"` / `"-1"` / `"1"` on 1.8, the world name on 1.16), as
/// [`TickContext::dimension`].
#[must_use]
pub fn dimension(&self) -> &str {
&self.core.dimension
}
/// Using the held item (eating, blocking, drawing a bow): movement input is slowed. As
/// [`TickContext::using_item`].
#[must_use]
pub fn using_item(&self) -> bool {
self.core.hands.using_item()
}
/// The serverbound packets of this tick in write order (its actions, the movement
/// packet, `tick_end`), plus the answers to packets that arrived just before it; written
/// to the socket right after [`Behavior::after_tick`]. A dig shows as
/// [`Outbound::Dig`](crate::common::Outbound::Dig) with its status, block and face. The
/// wire layer adds per-protocol details when it writes them (sequence numbers:
/// [`TickView::prediction_sequence`]).
#[must_use]
pub fn outbound(&self) -> &[Outbound] {
&self.core.out
}
/// [`TickContext::prediction_sequence`] (before this tick's packets are written).
#[must_use]
pub fn prediction_sequence(&self) -> Option<i32> {
self.core.sequence
}
}
#[cfg(all(test, feature = "v1_8"))]
impl Core {
/// Test hook: the held slot as both the client and the server have it (no sync packet).
pub(crate) fn test_set_slot(&mut self, slot: u8) {
self.held_slot = slot;
self.sent_slot = slot;
self.inv.select(slot);
}
/// Test hook: the pose and the sent pose.
pub(crate) fn test_poses(&mut self) -> (&mut Pose, &mut Pose) {
(&mut self.pose, &mut self.sent)
}
/// Test hook: turns held back by the post-look check.
pub(crate) fn test_held_turns(&self) -> u64 {
self.held_turns
}
}
#[cfg(all(test, feature = "v1_8"))]
impl TickContext<'_> {
/// Test hook: this tick's look without a rotation step.
pub(crate) fn test_force_look(&mut self, yaw: f32, pitch: f32) {
self.core.forced_look = Some((yaw, pitch));
}
/// Test hook: the rotation controller (to predict a step).
pub(crate) fn test_rotation(&self) -> Rotation {
self.core.rotation
}
}
/// Hands the tick's dig and block-item placement packets to the sim in packet order
/// ([`Sim::dig_sent`], [`Sim::place_sent`]): whether each dig broke its block on the client,
/// each packet's 1.19+ prediction sequence (counted from the wire's last sequence the way the
/// wire will number this tick's predicting packets: dig start / finish, place, use item) and
/// the player's position before the tick's movement.
#[cold]
#[inline(never)]
fn sent_predictions<S: Sim>(c: &mut Core, sim: &mut S) {
use crate::common::DigStatus;
let player = c.pose.pos;
let mut sequence = c.sequence.unwrap_or(0);
let mut broken = 0;
let mut placing = c.hands.placing.iter().copied().peekable();
let any_item = c.inv.held().is_some() || c.inv.offhand().is_some();
// items used by predicted placements: main hand, off hand
let mut used = [0u8; 2];
for (i, o) in c.out.iter().enumerate() {
match *o {
Outbound::Dig { status, pos, .. } => {
let predicting = matches!(status, DigStatus::Start | DigStatus::Finish);
if predicting {
sequence = sequence.wrapping_add(1);
} else if status != DigStatus::Abort {
continue;
}
let b = predicting && c.broken_now.get(broken) == Some(&pos);
if b {
broken += 1;
}
sim.dig_sent(pos, status, b, sequence, player);
}
Outbound::Place {
pos,
face,
ref held,
off_hand,
..
} => {
sequence = sequence.wrapping_add(1);
while placing.next_if(|&p| (p as usize) < i).is_some() {}
if placing.next_if_eq(&(i as u32)).is_some()
&& sim.place_sent(&crate::sim::predict::PlaceSent {
pos,
face,
held: held.as_ref(),
sneaking: c.pose.sneaking,
any_item,
game_mode: c.game_mode,
sequence,
player,
})
&& crate::sim::predict::placing_uses_item(c.game_mode)
{
used[usize::from(off_hand)] = used[usize::from(off_hand)].saturating_add(1);
}
}
Outbound::UseItem { .. } => {
sequence = sequence.wrapping_add(1);
}
_ => {}
}
}
debug_assert_eq!(
broken,
c.broken_now.len(),
"a broken block without its dig packet"
);
for p in &c.broken_now[broken..] {
sim.predict_air(p.x, p.y, p.z);
}
c.broken_now.clear();
if used[0] > 0 {
c.inv.consume_held(used[0]);
}
if used[1] > 0 {
c.inv.consume_offhand(used[1]);
}
}
/// 1.8 `SeedItem.use` / `CropItem.use` on the client: planting on the top of
/// its soil with air above uses one item at once (the server's set_slot follows later; it
/// sends none when the count already agrees). Applied to the `block_place` packets written
/// from `first` on. Other placements wait for the server's set_slot: predicting them needs
/// vanilla's full placement rules, and a wrong prediction would never be corrected.
fn predict_planting(c: &mut Core, world: &dyn WorldView, first: usize) {
if !c.opts.caps.seed_planting_prediction || c.game_mode == GameMode::Creative {
return;
}
let mut uses = 0u8;
for o in &c.out[first..] {
let Outbound::Place {
pos,
face: crate::common::Face::Up,
held: Some(held),
off_hand: false,
..
} = o
else {
continue;
};
// Seed item → its soil (wheat, pumpkin, melon seeds, carrot, potato: farmland;
// nether wart: soul sand).
let soil = match held.id() {
295 | 361 | 362 | 391 | 392 => 60,
372 => 88,
_ => continue,
};
let id = |y: i32| world.raw_block(pos.x, y, pos.z).map(|s| s >> 4);
if held.count() > i32::from(uses) && id(pos.y) == Some(soil) && id(pos.y + 1) == Some(0) {
uses += 1;
}
}
if uses > 0 {
c.inv.consume_held(uses);
}
}
/// Whether the look `yaw`/`pitch` still points at every block dug or placed this tick (its
/// full cube, from the sent and the current feet, standing or sneaking eyes, with the old or the
/// new yaw) — the post-look check that keeps Grim's RotationPlace check satisfied.
fn post_look_ok(c: &Core, yaw: f32, pitch: f32) -> bool {
let looks = [
hands::look_vector(c.pose.yaw, pitch),
hands::look_vector(yaw, pitch),
];
let heights = [c.opts.caps.eye_height, c.opts.caps.sneak_eye_height];
c.out
.iter()
.filter_map(|o| match o {
Outbound::Dig {
status: crate::common::DigStatus::Start | crate::common::DigStatus::Finish,
pos,
..
}
| Outbound::Place { pos, .. } => Some(*pos),
_ => None,
})
.all(|t| {
[c.sent.pos, c.pose.pos].iter().all(|o| {
heights.iter().any(|h| {
let eyes = Vec3::new(o.x, o.y + *h, o.z);
looks
.iter()
.any(|l| hands::ray_hits_cube(eyes, *l, t, ACTION_LOOK_REACH))
})
})
})
}
/// Reach of the post-look check (6 blocks).
const ACTION_LOOK_REACH: f64 = 6.0;
/// The behaviour's view of the client during one tick.
///
/// Reading is free; actions are written to the server in call order before this tick's
/// movement packet.
pub struct TickContext<'a> {
core: &'a mut Core,
world: &'a dyn Sim,
held: Option<hands::HeldItem>,
/// The sent-pose crosshair, picked on the first ask: nothing a behaviour does during its
/// tick changes the sent pose, the game mode or the world.
crosshair: std::cell::OnceCell<(Option<BlockHit>, Option<hands::EntityHit>)>,
/// Vanilla's check of a dialog command (`verifyCommand`).
commands: &'a dyn Fn(&str) -> crate::dialog::CommandCheck,
}
impl std::fmt::Debug for TickContext<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TickContext")
.field("tick", &self.core.tick)
.field("pose", &self.core.pose)
.finish_non_exhaustive()
}
}
impl TickContext<'_> {
/// Ticks since the connection entered the play state.
#[must_use]
pub fn tick(&self) -> u64 {
self.core.tick
}
/// The protocol version of this connection.
#[must_use]
pub fn version(&self) -> GameVersion {
self.core.opts.caps.version
}
/// The client pose now (start of the tick, before this tick's rotation and movement).
#[must_use]
pub fn pose(&self) -> &Pose {
&self.core.pose
}
/// The last pose written to the server: what it judges this tick's actions against.
#[must_use]
pub fn sent(&self) -> &Pose {
&self.core.sent
}
/// Eye position of `pose` (standing or sneaking eye height of this version).
#[must_use]
pub fn eyes(&self, pose: &Pose) -> Vec3 {
let v = self.core.opts.caps;
pose.eyes(if pose.sneaking {
v.sneak_eye_height
} else {
v.eye_height
})
}
/// The world (loaded chunk columns and their blocks).
#[must_use]
pub fn world(&self) -> &dyn WorldView {
self.world
}
/// 26.1: the client player's complete movement state as the physics holds it now (start of
/// the tick): the attributes the server sent (movement speed, step height, jump strength,
/// scale, ...), effects, abilities and the level's build height. Clone it to simulate
/// ahead with `ghast_physics::modern::tick`. `None` on the other versions.
#[cfg(ghast_modern)]
#[must_use]
pub fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
self.world.modern_player()
}
/// What happened since the previous tick.
#[must_use]
pub fn events(&self) -> &TickEvents {
&self.core.current
}
/// Our entity id.
#[must_use]
pub fn entity_id(&self) -> i32 {
self.core.entity_id
}
/// Arm swings (main and off hand) written so far in the session: every `arm_animation`,
/// whether from [`TickContext::swing`], an action (place, dig, attack) or the held buttons
/// (digging swings every tick). Includes this tick's written so far.
#[must_use]
pub fn swings(&self) -> u64 {
self.core.swings + count_swings(&self.core.out)
}
/// Health, food and saturation.
#[must_use]
pub fn health(&self) -> Health {
self.core.health
}
/// The world's time: game time and the dimension's time of day (`update_time`, counted on
/// between the server's updates); `None` before the first update.
#[must_use]
pub fn world_time(&self) -> Option<crate::common::WorldTime> {
self.core.clocks.world_time(self.core.day_clock)
}
/// The player is dead (waiting for [`TickContext::respawn`]).
#[must_use]
pub fn is_dead(&self) -> bool {
self.core.dead
}
/// Game mode.
#[must_use]
pub fn game_mode(&self) -> GameMode {
self.core.game_mode
}
/// Abilities as the server sent them.
#[must_use]
pub fn abilities(&self) -> Abilities {
self.core.abilities
}
/// The server allows flight.
#[must_use]
pub fn can_fly(&self) -> bool {
self.core.abilities.may_fly()
}
/// The selected hotbar slot (0 … 8).
#[must_use]
pub fn held_slot(&self) -> u8 {
self.core.held_slot
}
/// Id of the open container window, if the server opened one.
#[must_use]
pub fn open_window(&self) -> Option<i32> {
(self.core.open_window != 0).then_some(self.core.open_window)
}
/// The current dimension (`"0"` / `"-1"` / `"1"` on 1.8, the world name on 1.16).
#[must_use]
pub fn dimension(&self) -> &str {
&self.core.dimension
}
/// The movement controls recorded for this tick.
#[must_use]
pub fn controls(&self) -> Controls {
self.core.controls
}
/// The rotation target.
#[must_use]
pub fn aim(&self) -> (f32, f32) {
self.core.rotation.target()
}
// ---- actions: written now, before this tick's movement packet ----
/// Sends a chat line or command (truncated to the version's limit, 100 / 256 UTF-16
/// units, like vanilla).
pub fn chat(&mut self, text: impl Into<String>) {
self.core.out.push(Outbound::Chat(text.into()));
}
/// Asks the server to respawn the player. Only sent while dead; returns whether it was.
pub fn respawn(&mut self) -> bool {
if self.core.dead {
self.core.out.push(Outbound::Respawn);
true
} else {
false
}
}
/// Selects a hotbar slot (0 … 8); sends `held_item_slot` when it changes. Out-of-range
/// slots are ignored.
pub fn select_slot(&mut self, slot: u8) {
if slot < 9 {
if self.core.held_slot != slot {
self.core.hands.stop_using();
self.core.hands.ticks_since_swing = 0;
}
self.core.held_slot = slot;
self.core.inv.select(slot);
if self.core.sent_slot != slot {
self.core.sent_slot = slot;
self.core.out.push(Outbound::HeldSlot(i16::from(slot)));
}
}
}
/// Swings the arm (`arm_animation`).
pub fn swing(&mut self) {
self.core.out.push(Outbound::Swing);
}
/// The drop key outside a screen (`MinecraftClient.handleInputEvents`): a `player_action`
/// that drops one item of the held stack, or the whole stack with `whole_stack` (the key
/// with control held), written now. It goes out with an empty hand too, like vanilla.
/// 1.16.5 and 26.x predict it as vanilla does (`ClientPlayerEntity.dropSelectedItem`,
/// `LocalPlayer.drop`): the item leaves the held slot at once (the server's `set_slot`
/// then confirms or corrects it) and, when one did, the main arm swings (`arm_animation`
/// after the drop); a use of the held item ends with its stack. 1.8.9 and 1.12.2 send the
/// drop alone and wait for the server's slot update. Refused (nothing sent, `false`) while
/// a screen is open (a window, the player inventory, a dialog: vanilla's keys then go to
/// the screen), while dead, or in spectator mode.
pub fn drop_held(&mut self, whole_stack: bool) -> bool {
if !self.keys_reach_player() {
return false;
}
let c = &mut *self.core;
c.out.push(Outbound::Dig {
status: if whole_stack {
crate::common::DigStatus::DropStack
} else {
crate::common::DigStatus::DropItem
},
pos: ghast_protocol::BlockPos::new(0, 0, 0),
face: crate::common::Face::Down,
});
if c.opts.caps.drop_prediction && c.inv.drop_held(whole_stack) {
if c.inv.held().is_none() && c.hands.use_item().is_some_and(|(off, _)| !off) {
// tickActiveItemStack / updatingUsingItem: the used stack is gone.
c.hands.stop_using();
}
c.out.push(Outbound::Swing);
// A dig or place later in this tick sees the new hand, as in vanilla's key order.
self.held = held_item(&self.core.inv, self.world);
}
true
}
/// The swap-hands key outside a screen (1.9+): a `player_action` that swaps the main- and
/// off-hand stacks, written now. Like vanilla the client predicts nothing: both stacks
/// come back in the server's slot updates (1.16.5: a use of the main or off hand then ends
/// unless that hand still holds the used item). Sent while an item is in use too, as
/// vanilla does. Refused (nothing sent, `false`) on 1.8.9 (no off hand), while a screen is
/// open, while dead, or in spectator mode.
pub fn swap_hands(&mut self) -> bool {
if !self.core.opts.caps.combat_1_9 || !self.keys_reach_player() {
return false;
}
self.core.out.push(Outbound::Dig {
status: crate::common::DigStatus::SwapHands,
pos: ghast_protocol::BlockPos::new(0, 0, 0),
face: crate::common::Face::Down,
});
true
}
/// Vanilla handles the drop and swap keys only without a screen and for a living,
/// non-spectator player.
fn keys_reach_player(&self) -> bool {
let c = &*self.core;
!c.inv.gui_open() && c.dialog.is_none() && !c.dead && c.game_mode != GameMode::Spectator
}
/// Escape hatch: queues a serverbound play packet the behaviour encoded itself (`id` and
/// `body` of this session's protocol version, see [`TickContext::version`]), written as
/// given in call order with the other actions, before this tick's movement packet.
/// **You are responsible for protocol correctness**: the client does not look at it, so a
/// packet that changes state it models (movement, held slot, windows, digging) makes the
/// client and the server disagree.
pub fn send_raw(&mut self, id: i32, body: impl Into<bytes::Bytes>) {
self.core
.out
.push(Outbound::Raw(ghast_protocol::RawPacket::new(
id,
body.into(),
)));
}
/// [`TickContext::send_raw`] with a generated packet type (e.g. from
/// `ghast::protocol::v26_2::play::serverbound`); it must belong to this session's version.
/// Refused (nothing queued) unless it is a serverbound play packet.
pub fn send_packet<P: ghast_protocol::Packet>(
&mut self,
packet: &P,
) -> Result<(), ghast_protocol::EncodeError> {
if P::STATE != ghast_protocol::State::Play
|| P::DIRECTION != ghast_protocol::Direction::Serverbound
{
return Err(ghast_protocol::EncodeError::Invalid(
"not a serverbound play packet",
));
}
let mut body = bytes::BytesMut::new();
packet.encode(&mut body)?;
self.send_raw(P::ID, body.freeze());
Ok(())
}
/// Ends the session after this tick's packets are written.
pub fn disconnect(&mut self, reason: impl Into<String>) {
self.core.quit = Some(reason.into());
}
// ---- intent for this tick's movement step ----
/// Rotation target for this tick: the client turns toward it in whole mouse counts
/// (at most 14° yaw / 10.5° pitch per tick). Call it every tick you want to turn.
pub fn set_aim(&mut self, yaw: f32, pitch: f32) {
self.core.rotation.set_target(yaw, pitch);
self.core.aimed = true;
}
/// Movement keys from now on (kept until changed); the physics turns them into movement
/// like vanilla's `Input` (sneaking scales walking by 0.3).
pub fn set_controls(&mut self, controls: Controls) {
self.core.controls = controls;
}
/// The inventory: player slots, cursor, the open window, the pending click.
#[must_use]
pub fn inventory(&self) -> &ghast_inventory::Inventory {
&self.core.inv
}
/// Clicks in the open screen (`window_click`, written now). Refused (nothing sent) while
/// the player is dead ([`ClickRefused::Dead`]), while the player is turning (the look changed in the last movement step or an aim is set for
/// this tick: clicks only while still) or when the inventory refuses it (one click in
/// flight, same-tick packet order, unpredictable result, …). The result arrives in
/// [`TickEvents::inventory`] on a later tick.
pub fn click(&mut self, click: ghast_inventory::Click) -> Result<ClickTicket, ClickRefused> {
if self.core.dead {
return Err(ClickRefused::Dead);
}
if self.core.turned || self.core.aimed {
return Err(ClickRefused::Turning);
}
let o = self
.core
.inv
.click(click)
.map_err(ClickRefused::Inventory)?;
// the screen's own packets of this click (1.16.5 anvil rename_item) go first
for s in self.core.inv.take_screen_packets() {
self.core.out.push(Outbound::Inventory(s));
}
let ticket = match &o {
ghast_inventory::Outgoing::Click(p) => ClickTicket {
window_id: i32::from(p.window_id),
action: p.action,
},
// 26.x: no confirm exists; the inventory reports the click under ghast's own
// action number once it settled (or the server corrected it).
ghast_inventory::Outgoing::ContainerClick(p) => ClickTicket {
window_id: p.window_id,
action: p.action,
},
// the 26.x creative screen's packets: applied at once, no result will follow
_ => ClickTicket {
window_id: -1,
action: -1,
},
};
self.core.out.push(Outbound::Inventory(o));
Ok(ticket)
}
/// Renames the item in the open anvil (26.1 `rename_item`, written now; nothing is sent
/// when the name did not change or the input slot is empty). An empty name removes a
/// custom name.
pub fn anvil_rename(&mut self, name: &str) -> Result<(), ClickRefused> {
if let Some(o) = self
.core
.inv
.anvil_rename(name)
.map_err(ClickRefused::Inventory)?
{
self.core.out.push(Outbound::Inventory(o));
}
Ok(())
}
/// Selects a banner pattern in the open loom (26.1 `container_button_click`, written now;
/// nothing is sent for a pattern the loom does not offer).
pub fn select_loom_pattern(&mut self, index: i32) -> Result<(), ClickRefused> {
#[cfg(ghast_modern)]
if let Some(o) = self
.core
.inv
.select_loom_pattern_modern(index)
.map_err(ClickRefused::Inventory)?
{
self.core.out.push(Outbound::Inventory(o));
}
#[cfg(not(ghast_modern))]
let _ = index;
Ok(())
}
/// 1.8 – 1.16.5: what the open mount screen's saddle and armor slots take, read off the
/// mount entity (see [`ghast_inventory::Inventory::set_mount_rules`]); until then clicks that
/// need them (a saddle, horse armor or carpet into those slots) are refused. Nothing is sent.
pub fn set_mount_rules(&mut self, rules: Option<ghast_inventory::MountRules>) {
self.core.inv.set_mount_rules(rules);
}
/// 1.16.5: presses a menu button the way its screen does (stonecutter recipe, loom pattern,
/// lectern page / take book; `enchant_item` written now when the menu takes it). The
/// stonecutter and the loom update their result like the client.
pub fn click_button(&mut self, index: i32) -> Result<(), ClickRefused> {
if let Some(o) = self
.core
.inv
.click_button(index)
.map_err(ClickRefused::Inventory)?
{
self.core.out.push(Outbound::Inventory(o));
}
Ok(())
}
/// Selects a trade in the open villager screen (1.8 / 1.12 `MC|TrSel`, 1.16.5 / 26.1
/// `select_trade`, written now; the output is looked up again for that offer and, from
/// 1.16.5 on, the payment slots are refilled like the real screen).
pub fn select_trade(&mut self, index: i32) -> Result<(), ClickRefused> {
let o = self
.core
.inv
.select_trade(index)
.map_err(ClickRefused::Inventory)?;
self.core.out.push(Outbound::Inventory(o));
Ok(())
}
/// Opens the player inventory GUI (1.8: the "open inventory" client command; 1.16: nothing
/// is sent). Window 0 clicks need it open. Refused while the player is dead.
pub fn open_inventory(&mut self) -> Result<(), ClickRefused> {
if self.core.dead {
return Err(ClickRefused::Dead);
}
if let Some(o) = self
.core
.inv
.open_inventory()
.map_err(ClickRefused::Inventory)?
{
self.core.out.push(Outbound::Inventory(o));
}
Ok(())
}
/// Closes the open GUI (`close_window` with its id; 0 for the player inventory).
pub fn close_window(&mut self) -> Result<(), ClickRefused> {
let o = self.core.inv.close().map_err(ClickRefused::Inventory)?;
self.core.out.push(Outbound::Inventory(o));
// Vanilla closeHandledScreen: the container ends on the client too.
self.core.open_window = 0;
Ok(())
}
/// Mouse buttons from now on (kept until changed; released by a join, a respawn or an
/// open window). Left held mines what the crosshair is on, right held uses / places
/// (vanilla's key processing, after the behaviour and before the movement packet).
///
/// **Entities are invisible without entity tracking** ([`Interests::ENTITIES`] or
/// [`Interests::ENTITY_TRACKING`]): the crosshair then sees blocks only (a player or mob in
/// front of the block does not stop the dig and cannot be attacked) and nothing pushes the
/// bot. Ask for one of the interests when other entities matter.
pub fn set_buttons(&mut self, buttons: Buttons) {
self.core.buttons = buttons;
}
/// **Not vanilla when off**: whether other entities push the player from now on (default
/// on, see [`crate::Client::entity_push`]). Takes effect on this tick's entity ticks; a
/// no-op without entity tracking ([`Interests::ENTITIES`] or
/// [`Interests::ENTITY_TRACKING`]: no entities are known, so nothing pushes) and on 1.8.9,
/// whose client never pushes the player.
pub fn set_entity_push(&mut self, on: bool) {
self.core.entity_push = on;
}
/// Whether other entities push the player ([`TickContext::set_entity_push`]).
#[must_use]
pub fn entity_push(&self) -> bool {
self.core.entity_push
}
/// The dialog the server has open now (26.1+, only with [`Interests::DIALOGS`]; see
/// [`crate::dialog`]).
#[must_use]
pub fn dialog(&self) -> Option<&crate::dialog::Dialog> {
self.core.dialog.as_deref()
}
/// Dialogs the server showed and closed since the behaviour's previous tick, in arrival
/// order (26.1+, only with [`Interests::DIALOGS`]; [`TickContext::dialog`] is the one open
/// now). Like [`TickContext::events`], kept while the behaviour is on hold.
#[must_use]
pub fn dialog_events(&self) -> &[crate::dialog::DialogEvent] {
&self.core.dialogs
}
/// Answers the open dialog the way vanilla does for that button (or Escape): the packets
/// vanilla sends are written now, in call order with the other actions (`chat_command`
/// for a command that needs no confirmation, `custom_click_action` for a custom action;
/// client-only actions send nothing), and the dialog closes, stays or is replaced as its
/// `after_action` and the action say.
pub fn answer_dialog(
&mut self,
answer: &crate::dialog::DialogAnswer,
) -> Result<crate::dialog::DialogOutcome, crate::dialog::DialogRefused> {
use crate::dialog::{CommandCheck, DialogOutcome, DialogRefused, DialogSent, Effect, Next};
let d = self.core.dialog.clone().ok_or(DialogRefused::NoDialog)?;
let (effect, mut next) = crate::dialog::resolve(&d, answer)?;
let sent = match effect {
Effect::Nothing => DialogSent::Nothing,
Effect::Custom { id, payload } => {
self.core.out.push(Outbound::CustomClickAction {
id: id.clone(),
payload: crate::dialog::payload_nbt(payload.as_ref()),
});
DialogSent::Custom(id)
}
Effect::Command(command) => match ((self.commands)(&command), answer.confirms()) {
(CommandCheck::NoIssues, _)
| (CommandCheck::ParseErrors | CommandCheck::PermissionsRequired, true) => {
self.core.out.push(Outbound::DialogCommand(command.clone()));
DialogSent::Command(command)
}
(CommandCheck::SignatureRequired, true) => {
// "Suggest command": the player sends it from the chat line.
self.core.out.push(Outbound::Chat(format!("/{command}")));
DialogSent::Command(command)
}
(check, _) => {
// The confirmation screen returns to the dialog when cancelled.
next = Next::Stay;
DialogSent::CommandHeld { command, check }
}
},
};
let (open, waiting) = match next {
Next::Stay => (Some(d.clone()), false),
Next::Closed => (None, false),
Next::Waiting => (None, true),
Next::Open(n) => (Some(n), false),
};
if let Some(n) = &open
&& !Arc::ptr_eq(n, &d)
{
self.core
.dialogs_pending
.push(crate::dialog::DialogEvent::Shown(n.clone()));
}
self.core.dialog = open.clone();
Ok(DialogOutcome {
sent,
open,
waiting,
})
}
/// The buttons held.
#[must_use]
pub fn buttons(&self) -> Buttons {
self.core.buttons
}
/// The crosshair as the server judges it: vanilla's pick (block at the game mode's reach,
/// then the entity ray) along the **sent** look from the sent eyes.
fn sent_crosshair(&self) -> (Option<BlockHit>, Option<hands::EntityHit>) {
*self.crosshair.get_or_init(|| self.pick_sent())
}
fn pick_sent(&self) -> (Option<BlockHit>, Option<hands::EntityHit>) {
let s = &self.core.sent;
let v = self.core.opts.caps;
let eye = if s.sneaking {
v.sneak_eye_height
} else {
v.eye_height
};
let eyes = Vec3::new(s.pos.x, s.pos.y + eye, s.pos.z);
let mut list = PickList::default();
list.fill(self.world, v, eyes);
let t = self.world.crosshair_target(&PickQuery {
eyes,
rotation: (s.yaw, s.pitch),
look: hands::look_vector(s.yaw, s.pitch),
held: None,
now: false,
creative: self.core.game_mode == GameMode::Creative,
player_bb: pick_box(s.pos),
entities: &list.entities,
});
list.split(t, eyes)
}
/// The block the crosshair is on as the server judges it (from the sent pose): `None` when
/// nothing is in reach or an entity is in front of it.
///
/// **Entities count only with [`Interests::ENTITIES`]:** without entity tracking this is a
/// block pick that looks through players and mobs (and nothing pushes the bot).
#[must_use]
pub fn target(&self) -> Option<BlockHit> {
self.sent_crosshair().0
}
/// The tracked entities (behaviours that ask for [`Interests::ENTITIES`]).
#[must_use]
pub fn entities(&self) -> Option<&ghast_entity::Entities> {
self.world.entities()
}
/// The entity the crosshair is on as the server judges it (from the sent pose; vanilla's
/// pick: within 3 blocks outside creative, nearer than the block hit, boxes grown by the
/// type's targeting margin).
#[must_use]
pub fn target_entity(&self) -> Option<hands::EntityHit> {
self.sent_crosshair().1
}
/// Attacks `entity` (`use_entity` attack and the arm swing in the version's order; 1.16
/// resets the attack cooldown). Refused (`false`, nothing sent) while dead and unless the
/// sent crosshair is on that entity.
pub fn attack(&mut self, entity: i32) -> bool {
if self.core.dead || self.target_entity().is_none_or(|e| e.id != entity) {
return false;
}
let world = self.world;
let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
let blocked = |p: ghast_protocol::BlockPos, f: crate::common::Face, id: u16| {
world.place_suppressed(p, f, id)
};
let c = &mut *self.core;
let modern = c.opts.caps.combat_1_9;
let mut placed = false;
let mut io = HandsIo {
blocks: &blocks,
target: None,
held: self.held,
held_stack: None,
food: c.health.food,
modern,
off_held: None,
off_stack: None,
entity: None,
factors: DigFactors::default(),
sneaking: c.pose.sneaking,
out: &mut c.out,
broken: &mut c.broken_now,
placed: &mut placed,
spectator: c.game_mode == GameMode::Spectator,
spectator_swings: c.opts.caps.spectator_block_click_swings,
place_blocked: &blocked,
};
if !modern {
io.out.push(Outbound::Swing);
}
c.hands.attack(entity, &mut io);
if modern {
c.out.push(Outbound::Swing);
}
true
}
/// 1.16 attack strength 0 … 1 for an attack speed (4.0 for an empty hand, swords 1.6,
/// axes 0.8–1.0); 1.0 on 1.8 (no cooldown).
#[must_use]
pub fn attack_strength(&self, attack_speed: f64) -> f32 {
if self.core.opts.caps.combat_1_9 {
self.core.hands.attack_strength(attack_speed)
} else {
1.0
}
}
/// The block being broken with the left button and its progress 0 … 1.
#[must_use]
pub fn mining(&self) -> Option<(ghast_protocol::BlockPos, f32)> {
self.core.hands.mining()
}
/// Blocks broken so far (finish sent).
#[must_use]
pub fn broken(&self) -> u64 {
self.core.hands.broken
}
/// Using the held item (eating, blocking, drawing a bow): movement input is slowed.
#[must_use]
pub fn using_item(&self) -> bool {
self.core.hands.using_item()
}
/// 1.19+ (26.1, 26.2): the block-prediction sequence number of the last predicting packet
/// written so far (`block_dig` start / finish, `block_place`, `use_item` each take the
/// next one; it restarts at 0 in a new level), the number the server's
/// `block_changed_ack` answers with (the client then restores the blocks it broke in those
/// predictions to the server's state). `None` on 1.8.9 – 1.16.5. The packets this tick
/// writes are not counted yet ([`TickView::outbound`] lists them).
#[must_use]
pub fn prediction_sequence(&self) -> Option<i32> {
self.core.sequence
}
/// The vehicle the player rides (26.1 boats and rafts; 1.16.5, 1.12.2 and 1.8.9 boats with
/// entity tracking: boarded when the server's `set_passengers` (1.8.9: `attach_entity`)
/// names the player, e.g. after a right click on the boat with the crosshair on it; the
/// client then moves the boat with the movement keys). Leave it with the sneak key (on
/// 1.12.2 and 1.8.9 the server takes the player off). `None` when not riding.
#[must_use]
pub fn vehicle(&self) -> Option<crate::common::Vehicle> {
self.world.vehicle()
}
/// Riding a vehicle ([`TickContext::vehicle`]).
#[must_use]
pub fn is_riding(&self) -> bool {
self.world.vehicle().is_some()
}
/// Gliding with an elytra (1.12.2, 1.16.5, 26.x; shared flag 7: set by the client when a
/// glide starts (on 1.12.2 by the server, after the client asked), cleared by the server on
/// landing, in water or when the elytra breaks).
#[must_use]
pub fn is_gliding(&self) -> bool {
self.world.gliding()
}
/// Starts gliding the way a player does (1.12.2, 1.16.5, 26.x): presses jump for this tick
/// (the controls' `jump`, as [`TickContext::set_controls`] would; release it on the next
/// tick). The client starts a glide on a fresh jump press in the air with an elytra
/// equipped (not on the ground, not flying, not in water, not on a climbable): jump must
/// have been released on the tick before (a held key is not a press). Nothing happens when
/// those conditions do not hold. 1.12.2 only asks (`start_fall_flying`, while falling); the
/// server starts the glide. On 1.12.2 / 1.16.5 the server's glide flag and the rockets it
/// attaches are read from the first such press with an elytra on.
pub fn start_gliding(&mut self) {
self.core.controls.jump = true;
}
/// The version facts of an item stack (tool speeds, block item, food, usable), as the
/// hands use them for the held stack. `None` for ids outside the item id range.
///
/// ```no_run
/// # fn f(ctx: &ghast_client::TickContext<'_>) {
/// if let Some(s) = ctx.inventory().hotbar(0) {
/// let food = ctx.item_facts(s).is_some_and(|f| f.food);
/// }
/// # }
/// ```
#[must_use]
pub fn item_facts(&self, stack: &ghast_inventory::Stack) -> Option<hands::HeldItem> {
let id = u16::try_from(stack.id()).ok()?;
let count = u8::try_from(stack.count().clamp(0, 255)).unwrap_or(0);
Some(crate::sim::held_item_facts(
self.core.opts.caps.data,
id,
count,
efficiency(stack),
))
}
/// Break progress per tick (vanilla `calcBlockBreakingData`) of the block at `pos` dug
/// with `stack` (`None` = empty hand), with the factors the left button uses now: on
/// ground, eyes in water, aqua affinity, haste / mining fatigue. The block breaks once the
/// progress sums to 1, so it takes about `ceil(1 / speed)` ticks; 0 = unbreakable.
/// Creative mode breaks every block at once and is not reflected here. `None` when the
/// column is not loaded.
///
/// ```no_run
/// # fn f(ctx: &ghast_client::TickContext<'_>, pos: ghast_client::BlockPos) {
/// // The hotbar slot that digs `pos` fastest.
/// let best = (0..9u8).max_by(|a, b| {
/// let s = |k: u8| ctx.dig_speed(pos, ctx.inventory().hotbar(k.into())).unwrap_or(0.0);
/// s(*a).total_cmp(&s(*b))
/// });
/// # }
/// ```
#[must_use]
pub fn dig_speed(
&self,
pos: ghast_protocol::BlockPos,
stack: Option<&ghast_inventory::Stack>,
) -> Option<f32> {
let b = self.world.block_query(pos.x, pos.y, pos.z)?;
if b.air {
return Some(0.0);
}
let c = &*self.core;
let eyes = self.eyes(&c.pose);
let in_water = self
.world
.block_query(
eyes.x.floor() as i32,
eyes.y.floor() as i32,
eyes.z.floor() as i32,
)
.is_some_and(|b| b.water);
let held = stack.and_then(|s| self.item_facts(s));
let factors = DigFactors {
on_ground: c.pose.on_ground,
in_water,
aqua_affinity: c.aqua_affinity,
haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
};
Some(hands::relative_hardness(&b, held.as_ref(), factors))
}
/// Starts digging `pos` on `face` (`block_dig` start, then an arm swing), breaking it at
/// once when it is instant for the held item. Refused (nothing sent, `false`) unless the
/// crosshair from the sent pose is on exactly that block face, and while the player is dead.
pub fn dig(&mut self, pos: ghast_protocol::BlockPos, face: crate::common::Face) -> bool {
if self.core.dead
|| !self
.target()
.is_some_and(|t| t.pos == pos && t.face == face)
{
return false;
}
let world = self.world;
let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
let blocked = |p: ghast_protocol::BlockPos, f: crate::common::Face, id: u16| {
world.place_suppressed(p, f, id)
};
let c = &mut *self.core;
let mut placed = false;
let mut io = HandsIo {
blocks: &blocks,
target: None,
held: self.held,
held_stack: c.inv.held().cloned(),
food: c.health.food,
modern: c.opts.caps.combat_1_9,
off_held: None,
off_stack: None,
entity: None,
factors: DigFactors {
on_ground: c.pose.on_ground,
in_water: false,
aqua_affinity: c.aqua_affinity,
haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
},
sneaking: c.pose.sneaking,
out: &mut c.out,
broken: &mut c.broken_now,
placed: &mut placed,
spectator: c.game_mode == GameMode::Spectator,
spectator_swings: c.opts.caps.spectator_block_click_swings,
place_blocked: &blocked,
};
c.hands.click_block(pos, face, &mut io);
c.out.push(Outbound::Swing);
true
}
/// Right-clicks `support`'s `face` at the absolute point `hit` (`block_place`, then an arm
/// swing): places the held block or activates the block. Refused (nothing sent, `false`)
/// while the player is dead (until the respawn the server would drop it without an answer,
/// and vanilla's death screen takes the input), unless the crosshair from the sent pose is
/// on exactly that block face, and on 1.8.9 /
/// 1.12.2 when the vanilla client would write no packet because the held block cannot go
/// there (the spot next to the face is not replaceable, or the block would overlap the
/// player).
pub fn place(
&mut self,
support: ghast_protocol::BlockPos,
face: crate::common::Face,
hit: Vec3,
) -> bool {
if self.core.dead {
return false;
}
let Some(t) = self.target().filter(|t| t.pos == support && t.face == face) else {
return false;
};
let world = self.world;
let Some(b) = world.block_query(support.x, support.y, support.z) else {
return false;
};
let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
let blocked = |p: ghast_protocol::BlockPos, f: crate::common::Face, id: u16| {
world.place_suppressed(p, f, id)
};
let c = &mut *self.core;
let mut placed = false;
let first = c.out.len();
let mut io = HandsIo {
blocks: &blocks,
target: None,
held: self.held,
held_stack: c.inv.held().cloned(),
food: c.health.food,
modern: c.opts.caps.combat_1_9,
off_held: None,
off_stack: None,
entity: None,
factors: DigFactors::default(),
sneaking: c.pose.sneaking,
out: &mut c.out,
broken: &mut c.broken_now,
placed: &mut placed,
spectator: c.game_mode == GameMode::Spectator,
spectator_swings: c.opts.caps.spectator_block_click_swings,
place_blocked: &blocked,
};
c.hands
.right_click_block(BlockHit { hit, ..t }, &b, &mut io);
let _ = placed;
if c.out.len() == first {
// 1.8.9 / 1.12.2: the vanilla client would write no block packet (the block item
// cannot go there): nothing is sent.
return false;
}
predict_planting(c, world, first);
c.out.push(Outbound::Swing);
true
}
/// When the last inbound bytes arrived (a gap before a setback means lag).
#[must_use]
pub fn last_inbound(&self) -> Option<Instant> {
self.core.last_inbound
}
/// The yaw / pitch this tick's movement step will use, from this tick's
/// [`TickContext::set_aim`] and the digs / places written so far (incl. the turn held by
/// [`crate::Client::hold_turn_on_action`]). Computed on a copy: the rotation's carried
/// budget does not change. Clicks of held buttons, which run after the behaviour, are not
/// seen. Without an aim this tick: the current look.
#[must_use]
pub fn planned_look(&self) -> (f32, f32) {
let c = &*self.core;
let now = (c.pose.yaw, c.pose.pitch);
#[cfg(test)]
if let Some(l) = c.forced_look {
return l;
}
if !c.aimed {
return now;
}
let mut r = c.rotation;
let (yaw, pitch) = r.step(c.pose.yaw, c.pose.pitch);
if c.opts.hold_turn_on_action && !post_look_ok(c, yaw, pitch) {
now
} else {
(yaw, pitch)
}
}
/// Starts or stops creative-style flight: the `abilities` packet goes out before this
/// tick's movement step, like a double-tapped jump (but without the jump). Starting needs
/// the server's "may fly" ability; asking for the current state sends nothing.
pub fn set_flying(&mut self, flying: bool) {
self.core.want_flying = Some(flying);
}
/// Turns held back so far because they would have taken the crosshair off a block dug or
/// placed on the same tick (see [`crate::Client::hold_turn_on_action`]).
#[must_use]
pub fn held_turns(&self) -> u64 {
self.core.held_turns
}
/// Behaviour status line (logged when it changes).
pub fn status(&mut self, text: &str) {
if self.core.status != text {
text.clone_into(&mut self.core.status);
log::info!(
"[{}] t{} status: {text}",
self.core.opts.name,
self.core.tick
);
}
}
}
/// The engine replays of the modern versions' oracle goldens (`engine_modern_tests.rs`), compiled
/// once per version with that version's modules.
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_26_1.rs"]
mod tests_26_1;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1",
feature = "v26_2"
))]
#[path = "engine_tests_26_2.rs"]
mod tests_26_2;
/// Resource packs and the drop / swap actions on 1.8 – 1.16 (`engine_tests_actions.rs`).
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_actions.rs"]
mod tests_actions;
/// Mount screen rules read off the tracked entity (`engine_tests_mounts.rs`).
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "engine_tests_mounts.rs"]
mod tests_mounts;
/// The world's time on the legacy versions (`engine_tests_time.rs`).
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "engine_tests_time.rs"]
mod tests_time;
/// The legacy special menus through the open-window path (`engine_tests_menus.rs`).
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
#[path = "engine_tests_menus.rs"]
mod tests_menus;
/// `Client::record` on every version (`engine_tests_record.rs`).
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_record.rs"]
mod tests_record;
/// The engine replay of the 1.12.2 entity goldens (`engine_tests_1_12.rs`).
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_1_12.rs"]
mod tests_1_12;
/// The engine replay of the 1.8.9 boat goldens (`engine_tests_1_8.rs`).
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_1_8.rs"]
mod tests_1_8;
/// The engine replay of the 1.16.5 entity goldens (`engine_tests_1_16_5.rs`).
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_1_16_5.rs"]
mod tests_1_16_5;
/// Block predictions and the server's answers (26.x acks, 1.16.5 dig answers).
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
#[path = "engine_tests_predict.rs"]
mod tests_predict;
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
mod tests {
use super::*;
use crate::common::Teleport;
use crate::common::{ChatPosition, EntityAction, JoinGame};
use ghast_protocol::RawPacket;
pub(super) fn opts(version: GameVersion) -> CoreOptions {
CoreOptions {
name: "test".into(),
caps: version.caps(),
settings: ClientSettings::default(),
brand: Some("vanilla".into()),
sensitivity: 0.5,
silent_hold: Duration::from_millis(1500),
hold_turn_on_action: true,
accept_required_packs: true,
entity_push: true,
inventory: match version.instance() {
GameVersion::V1_8_9 => ghast_inventory::Version::V1_8,
GameVersion::V1_12_2 => ghast_inventory::Version::V1_12,
GameVersion::V26_1 => ghast_inventory::Version::V26_1,
#[cfg(feature = "v26_2")]
GameVersion::V26_2 => ghast_inventory::Version::V26_2,
_ => ghast_inventory::Version::V1_16_5,
},
}
}
/// A 1.8.9 engine (physics) or a 1.16.5 one (stand-still mover).
pub(super) fn engine(version: GameVersion) -> Engine<Box<dyn Sim>> {
let sim: Box<dyn Sim> = match version.instance() {
GameVersion::V1_8_9 => Box::new(crate::sim::Sim18::new()),
GameVersion::V1_12_2 => Box::new(crate::sim::Sim12::new()),
GameVersion::V26_1 => Box::new(crate::sim::Sim26::test_overworld()),
#[cfg(feature = "v26_2")]
GameVersion::V26_2 => Box::new(crate::sim::Sim262::test_overworld()),
_ => Box::new(crate::sim::Sim16::new()),
};
Engine::new(opts(version), sim)
}
/// Loads the column of chunk (x, z) the way the connection does.
pub(super) fn load(e: &mut Engine<Box<dyn Sim>>, x: i32, z: i32) {
let raw = match e.core.opts.caps.version.instance() {
GameVersion::V1_8_9 => crate::sim::test_chunks::v1_8(x, z),
GameVersion::V1_12_2 => crate::sim::test_chunks::v1_12_2(x, z),
GameVersion::V26_1 => crate::sim::test_chunks::v26_1(x, z),
#[cfg(feature = "v26_2")]
GameVersion::V26_2 => crate::sim::test_chunks::v26_2(x, z),
_ => crate::sim::test_chunks::v1_16_5(x, z),
};
e.sim.world_packet(&raw).unwrap();
}
pub(super) fn join(e: &mut Engine<Box<dyn Sim>>) {
e.handle(Inbound::JoinGame(JoinGame {
entity_id: 7,
game_mode: GameMode::Survival,
dimension: "0".into(),
hardcore: false,
dimension_nbt: None,
respawn_screen: true,
}));
// The player's column and its neighbours (1.21.4+ loads the level only with all nine).
for x in -1..=1 {
for z in -1..=1 {
load(e, x, z);
}
}
e.handle(Inbound::Teleport(Teleport {
x: 8.5,
y: 64.0,
z: 8.5,
yaw: 90.0,
pitch: 0.0,
flags: 0,
teleport_id: None,
..Default::default()
}));
// 1.21.4+: the server says the level's chunks are coming (game event 13).
e.handle(Inbound::GameState {
reason: 13,
value: 0.0,
});
// The nine columns arrived before the previous tick: the level loads on the next one.
e.core.near_loaded = 1;
e.outbound().clear();
}
/// Records the tick's packets as names.
pub(super) fn names(out: &mut Vec<Outbound>) -> Vec<&'static str> {
let v = out
.iter()
.map(|o| match o {
Outbound::Move(m) => m.trace_id(),
Outbound::Chat(_) => "chat",
Outbound::HeldSlot(_) => "held_slot",
Outbound::Swing => "swing",
Outbound::EntityAction { .. } => "entity_action",
Outbound::KeepAlive(_) => "keep_alive",
Outbound::Transaction { .. } => "transaction",
Outbound::TeleportConfirm(_) => "teleport_confirm",
Outbound::Respawn => "respawn",
Outbound::Settings(_) => "settings",
Outbound::Brand(_) => "brand",
Outbound::Abilities { .. } => "abilities",
Outbound::Dig { .. } => "block_dig",
Outbound::Place { .. } | Outbound::UseItem { .. } => "block_place",
Outbound::SwingOffHand => "swing_off",
Outbound::UseEntity { .. } => "use_entity",
Outbound::Inventory(_) => "inventory",
Outbound::PlayerInput(_) => "player_input",
Outbound::TickEnd => "tick_end",
Outbound::PlayerLoaded => "player_loaded",
Outbound::ChatSessionUpdate => "chat_session_update",
Outbound::ChunkBatchReceived(_) => "chunk_batch_received",
Outbound::Pong(_) => "pong",
Outbound::ResourcePackStatus { .. } => "resource_pack",
Outbound::CookieResponse { .. } => "cookie_response",
Outbound::LookAnswer { .. } => "C05",
Outbound::VehicleMove { .. } => "vehicle_move",
Outbound::SteerBoat { .. } => "steer_boat",
Outbound::SteerVehicle { .. } => "steer_vehicle",
Outbound::CustomClickAction { .. } => "custom_click_action",
Outbound::DialogCommand(_) => "chat_command",
Outbound::Raw(_) => "raw",
})
.collect();
out.clear();
v
}
pub(super) struct Script<F: FnMut(&mut TickContext<'_>)>(pub(super) F);
impl<F: FnMut(&mut TickContext<'_>)> Behavior for Script<F> {
fn tick(&mut self, ctx: &mut TickContext<'_>) {
(self.0)(ctx);
}
}
#[test]
fn join_sends_settings_then_brand() {
let mut e = engine(GameVersion::V1_8_9);
e.handle(Inbound::JoinGame(JoinGame {
entity_id: 1,
game_mode: GameMode::Creative,
dimension: "0".into(),
hardcore: false,
dimension_nbt: None,
respawn_screen: true,
}));
assert_eq!(names(e.outbound()), ["settings", "brand"]);
}
#[test]
fn nothing_before_the_first_teleport() {
let mut e = engine(GameVersion::V1_8_9);
let mut b = Idle;
let t0 = Instant::now();
load(&mut e, 0, 0);
e.outbound().clear();
for i in 0..5 {
e.tick(&mut b, t0 + Duration::from_millis(50 * i));
}
assert!(e.outbound().is_empty());
}
#[test]
fn teleport_reply_per_version() {
let mut e = engine(GameVersion::V1_16_5);
e.handle(Inbound::Teleport(Teleport {
x: 1.0,
y: 2.0,
z: 3.0,
yaw: 450.0,
pitch: 100.0,
flags: 0,
teleport_id: Some(5),
..Default::default()
}));
let out = std::mem::take(e.outbound());
assert_eq!(out[0], Outbound::TeleportConfirm(5));
match out[1] {
Outbound::Move(MovePacket::PositionLook {
yaw,
pitch,
on_ground,
..
}) => {
assert_eq!((yaw, pitch, on_ground), (90.0, 90.0, false));
}
ref o => panic!("unexpected {o:?}"),
}
let mut e = engine(GameVersion::V1_8_9);
e.handle(Inbound::Teleport(Teleport {
x: 1.0,
y: 2.0,
z: 3.0,
yaw: 450.0,
pitch: 100.0,
flags: 0,
teleport_id: None,
..Default::default()
}));
let out = std::mem::take(e.outbound());
assert_eq!(out.len(), 1);
// 1.8 does not clamp the pitch.
assert!(matches!(
out[0],
Outbound::Move(MovePacket::PositionLook {
yaw: 90.0,
pitch: 100.0,
..
})
));
}
/// The crosshair is one pick (`ghast_physics::pick::v1_8::pick_target`, oracle-proven on
/// `tests/golden/1.8.9/picks.jsonl.gz`) over the tracked entities: a zombie in front is the
/// target and hides the block; one hit beyond 3 blocks but before the block leaves neither
/// (vanilla's miss), so the block behind it is not dug either.
#[test]
fn entity_pick_uses_the_tracker_and_the_proven_pick() {
use ghast_protocol::v1_8::play::clientbound::id;
use std::cell::Cell;
let raw = |id: i32, b: Vec<u8>| RawPacket {
id,
body: bytes::Bytes::from(b),
};
let zombie = |eid: u8, x: f64| {
let mut b = vec![eid, 54];
for v in [x, 64.0, 8.5] {
b.extend(((v * 32.0) as i32).to_be_bytes());
}
b.extend([0, 0, 0, 0, 0, 0, 0, 0, 0, 0x7f]);
raw(id::SPAWN_ENTITY_LIVING, b)
};
let mut e = engine(GameVersion::V1_8_9);
let mut login = 7i32.to_be_bytes().to_vec();
login.extend([0, 0, 2, 20, 7]);
login.extend(b"default");
login.push(0);
e.sim.world_packet(&raw(id::LOGIN, login)).unwrap();
e.sim.set_entities(Some(ghast_entity::Config::default()));
join(&mut e);
// Stone at (4, 65, 8): its east face is 3.5 blocks west of the eyes (8.5, 65.62, 8.5),
// which look west (yaw 90).
let pos: i64 = (4 << 38) | (65 << 26) | 8;
let mut b = pos.to_be_bytes().to_vec();
b.push(1 << 4);
e.sim.world_packet(&raw(id::BLOCK_CHANGE, b)).unwrap();
let t0 = Instant::now();
e.note_inbound(t0);
let seen = Cell::new((None, None));
let look = |e: &mut Engine<Box<dyn Sim>>| {
let mut b = Script(|ctx: &mut TickContext<'_>| {
seen.set((
ctx.target_entity().map(|h| (h.id, h.distance)),
ctx.target().map(|t| (t.pos, t.face)),
));
});
e.tick(&mut b, t0);
seen.get()
};
assert_eq!(
look(&mut e),
(
None,
Some((ghast_protocol::BlockPos::new(4, 65, 8), crate::Face::East))
)
);
// A zombie 2 blocks west: its box (0.6 wide) grown by the 1.8 margin 0.1 is hit at
// x = 6.9, 1.6 away; the block behind is not the target.
e.sim.world_packet(&zombie(50, 6.5)).unwrap();
let (ent, block) = look(&mut e);
let (eid, d) = ent.unwrap();
assert_eq!(eid, 50);
assert!((d - 1.6).abs() < 1e-6, "{d}");
assert_eq!(block, None);
// Gone, and one at x = 5.0 instead: hit at 5.4, 3.1 away (> 3) but before the block.
e.sim
.world_packet(&raw(id::ENTITY_DESTROY, vec![1, 50]))
.unwrap();
e.sim.world_packet(&zombie(51, 5.0)).unwrap();
assert_eq!(look(&mut e), (None, None));
}
#[test]
fn actions_precede_the_single_movement_packet() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Script(|ctx: &mut TickContext<'_>| {
if ctx.tick() == 2 {
ctx.select_slot(3);
ctx.chat("hello");
ctx.swing();
ctx.set_controls(Controls {
sneak: true,
..Controls::default()
});
}
});
e.tick(&mut b, t0);
assert_eq!(names(e.outbound()), ["C06"]);
e.tick(&mut b, t0);
assert_eq!(
names(e.outbound()),
["held_slot", "chat", "swing", "entity_action", "C03"]
);
for _ in 0..100 {
e.tick(&mut b, t0);
let n = names(e.outbound());
assert_eq!(n.len(), 1, "one movement packet per tick: {n:?}");
}
}
/// Raw packets go out in call order with the other actions, before the movement packet,
/// and the wire writes them as given (the same frame as the typed packet).
#[test]
fn raw_packets_keep_the_call_order() {
use crate::version::ClientVersion;
for v in [GameVersion::V1_8_9, GameVersion::V26_1] {
let mut e = engine(v);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut refused = None;
let mut b = Script(|ctx: &mut TickContext<'_>| {
if ctx.tick() == 3 {
ctx.swing();
ctx.send_raw(0x7f, vec![1, 2, 3]);
ctx.send_packet(&ghast_protocol::v26_1::play::serverbound::ArmAnimation {
hand: ghast_protocol::v26_1::play::serverbound::ArmAnimationHand::OFF_HAND,
})
.unwrap();
refused = Some(ctx.send_packet(
&ghast_protocol::v26_1::play::clientbound::KeepAlive { keep_alive_id: 1 },
));
ctx.chat("after");
}
});
for _ in 0..2 {
e.tick(&mut b, t0);
}
e.outbound().clear();
e.tick(&mut b, t0);
let out = e.outbound().clone();
let n = names(e.outbound());
assert_eq!(n[..4], ["swing", "raw", "raw", "chat"], "{v:?} {n:?}");
let movement = n.iter().position(|x| {
x.starts_with('C') || x.contains("position") || *x == "flying" || *x == "look"
});
assert!(movement.is_none_or(|m| m > 3), "{v:?} {n:?}");
assert!(refused.unwrap().is_err());
// The wire writes the raw packet as the typed one.
let typed = ghast_protocol::v26_1::play::serverbound::ArmAnimation {
hand: ghast_protocol::v26_1::play::serverbound::ArmAnimationHand::OFF_HAND,
};
let mut want = ghast_protocol::FrameEncoder::new();
want.write_packet(&typed).unwrap();
let mut got = ghast_protocol::FrameEncoder::new();
let mut wire = crate::version::Wire26_1::default();
crate::version::V26_1::write_play(&mut got, &out[2], &mut wire).unwrap();
assert_eq!(got.take(), want.take());
}
}
#[test]
fn standing_bot_packets() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let mut b = Idle;
let t0 = Instant::now();
e.note_inbound(t0);
// First tick: the position differs from the fresh player's lastReported (origin).
e.tick(&mut b, t0);
let out = std::mem::take(e.outbound());
assert!(matches!(
out[..],
[Outbound::Move(MovePacket::PositionLook {
on_ground: false,
..
})]
));
// Then flying (on ground) with a position refresh every 21st tick.
let mut kinds = Vec::new();
for _ in 0..42 {
e.tick(&mut b, t0);
kinds.extend(names(e.outbound()));
}
assert_eq!(kinds.iter().filter(|k| **k == "C04").count(), 2);
assert_eq!(kinds.iter().filter(|k| **k == "C03").count(), 40);
assert_eq!((kinds[20], kinds[41]), ("C04", "C04"));
assert!(e.core.sent.on_ground);
}
#[test]
fn silent_server_freezes_behaviour() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut ticks = 0;
let mut b = Script(|ctx: &mut TickContext<'_>| {
ticks += 1;
ctx.set_controls(Controls {
sneak: true,
..Controls::default()
});
});
e.tick(&mut b, t0 + Duration::from_millis(100));
e.tick(&mut b, t0 + Duration::from_millis(1600));
// Frozen: keys released, so the sneak stops; still one movement packet.
let n = names(e.outbound());
assert_eq!(n, ["entity_action", "C06", "entity_action", "C03"]);
e.note_inbound(t0 + Duration::from_millis(1700));
e.tick(&mut b, t0 + Duration::from_millis(1700));
let _ = b;
assert_eq!(ticks, 2);
}
#[test]
fn keepalive_answered_transactions_left_to_the_inventory() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
e.handle(Inbound::KeepAlive(42));
// The engine never answers confirms: the inventory does (exactly once), see the
// fake-server test.
e.handle(Inbound::Transaction {
window_id: 0,
action: -5,
accepted: false,
});
assert_eq!(std::mem::take(e.outbound()), [Outbound::KeepAlive(42)]);
}
#[test]
fn panicking_behaviour_does_not_stop_the_tick() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
let mut b = Script(|ctx: &mut TickContext<'_>| {
if ctx.tick() == 2 {
panic!("boom");
}
});
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
for _ in 0..5 {
e.tick(&mut b, t0);
}
std::panic::set_hook(hook);
assert!(e.state.failed);
assert_eq!(names(e.outbound()).len(), 5);
}
#[test]
fn chat_events_reach_the_behaviour_once() {
let mut e = engine(GameVersion::V1_16_5);
join(&mut e);
e.handle(Inbound::Chat(ChatMessage {
rendered: None,
json: r#"{"text":"hi"}"#.into(),
position: ChatPosition::System,
sender: None,
}));
let mut seen = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
seen.extend(ctx.events().chat.iter().map(ChatMessage::plain));
});
let t0 = Instant::now();
e.tick(&mut b, t0);
e.tick(&mut b, t0);
let _ = b;
assert_eq!(seen, ["hi"]);
}
/// Joining already dead (health 0, no death event): with the immediate-respawn rule the
/// tick asks to respawn (vanilla's screen check) until the respawn arrives; with the
/// death screen nothing is sent, the behaviour sees `died` and may call `respawn`.
#[test]
fn joining_dead_respawns_like_vanilla() {
let mut versions = vec![
(GameVersion::V1_8_9, false),
(GameVersion::V1_12_2, false),
(GameVersion::V1_16_5, true),
(GameVersion::V26_1, true),
];
#[cfg(feature = "v26_2")]
versions.push((GameVersion::V26_2, true));
for (v, rule) in versions {
for immediate in [false, true] {
let mut e = engine(v);
join(&mut e);
if rule {
e.handle(Inbound::GameState {
reason: 11,
value: if immediate { 1.0 } else { 0.0 },
});
}
e.handle(Inbound::Health(crate::common::Health {
health: 0.0,
food: 20,
saturation: 5.0,
}));
let t0 = Instant::now();
e.note_inbound(t0);
let mut died = false;
let mut b = Script(|ctx: &mut TickContext<'_>| died |= ctx.events().died);
let mut respawns = 0;
for _ in 0..3 {
e.tick(&mut b, t0);
respawns += e
.outbound()
.iter()
.filter(|o| matches!(o, Outbound::Respawn))
.count();
e.outbound().clear();
}
let _ = b;
assert!(died, "{v:?}");
let want = if rule && immediate { 3 } else { 0 };
assert_eq!(respawns, want, "{v:?} immediate {immediate}");
}
}
}
#[test]
fn immediate_respawn_1_16() {
let mut e = engine(GameVersion::V1_16_5);
join(&mut e);
e.handle(Inbound::GameState {
reason: 11,
value: 1.0,
});
e.handle(Inbound::Died { entity_id: 7 });
assert_eq!(e.outbound().as_slice(), [Outbound::Respawn]);
}
/// Left button on the floor: START, swings, FINISH, all before the tick's movement
/// packet; the broken block is predicted air and the player falls into the hole.
#[test]
fn dig_with_the_left_button() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Script(|ctx: &mut TickContext<'_>| {
ctx.set_aim(90.0, 89.5);
let down = ctx.target().is_some_and(|t| {
t.pos == ghast_protocol::BlockPos::new(8, 63, 8) && t.face == crate::Face::Up
});
ctx.set_buttons(Buttons {
left: down,
right: false,
});
});
let mut ticks = Vec::new();
for _ in 0..200 {
e.tick(&mut b, t0);
let n = names(e.outbound());
assert_eq!(n.iter().filter(|x| x.starts_with('C')).count(), 1, "{n:?}");
assert!(n.last().unwrap().starts_with('C'), "movement last: {n:?}");
ticks.push(n);
}
let flat: Vec<&str> = ticks.iter().flatten().copied().collect();
assert_eq!(
flat.iter().filter(|x| **x == "block_dig").count(),
2,
"start + finish"
);
assert!(e.core.hands.broken == 1);
// Stone by hand: not harvestable, 1 / 1.5 / 100 per tick -> 151 damage ticks.
let start = ticks.iter().position(|t| t.contains(&"block_dig")).unwrap();
let finish = ticks
.iter()
.rposition(|t| t.contains(&"block_dig"))
.unwrap();
assert_eq!(finish - start, 150);
assert!(e.sim.block_query(8, 63, 8).unwrap().air);
assert!(
e.core.pose.pos.y < 64.0,
"falls into the hole: {:?}",
e.core.pose.pos
);
}
/// `TickView::outbound` lists the tick's packets (the left button's dig start among them,
/// ahead of the movement packet); `prediction_sequence` is what the wire reports, and the
/// modern wire counts the predicting packets.
#[test]
fn outbound_visible_to_the_behaviour() {
use crate::version::ClientVersion;
struct Watch {
seen: Vec<Vec<Outbound>>,
seq: Vec<Option<i32>>,
}
impl Behavior for Watch {
fn tick(&mut self, ctx: &mut TickContext<'_>) {
self.seq.push(ctx.prediction_sequence());
ctx.set_aim(90.0, 89.5);
let down = ctx.target().is_some_and(|t| t.face == crate::Face::Up);
ctx.set_buttons(Buttons {
left: down,
right: false,
});
}
fn after_tick(&mut self, view: &TickView<'_>) {
self.seen.push(view.outbound().to_vec());
assert_eq!(view.prediction_sequence(), *self.seq.last().unwrap());
}
}
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Watch {
seen: Vec::new(),
seq: Vec::new(),
};
for t in 0..20 {
e.note_sequence(Some(t));
e.tick(&mut b, t0);
assert_eq!(*e.outbound(), *b.seen.last().unwrap());
e.outbound().clear();
}
assert_eq!(b.seq.last(), Some(&Some(19)));
let dig = b
.seen
.iter()
.find(|o| o.iter().any(|p| matches!(p, Outbound::Dig { .. })))
.expect("a dig start");
assert!(matches!(
dig.iter()
.find(|p| matches!(p, Outbound::Dig { .. }))
.unwrap(),
Outbound::Dig {
status: crate::common::DigStatus::Start,
face: crate::Face::Up,
..
}
));
assert!(matches!(dig.last(), Some(Outbound::Move(_))));
// 26.1's wire: start and finish take a new number, abort does not.
let mut wire = crate::version::Wire26_1::default();
let mut enc = ghast_protocol::FrameEncoder::new();
let dig = |status| Outbound::Dig {
status,
pos: ghast_protocol::BlockPos::new(1, 2, 3),
face: crate::Face::Up,
};
use crate::common::DigStatus;
assert_eq!(crate::version::V26_1::prediction_sequence(&wire), Some(0));
for (s, want) in [
(DigStatus::Start, 1),
(DigStatus::Abort, 1),
(DigStatus::Start, 2),
(DigStatus::Finish, 3),
] {
crate::version::V26_1::write_play(&mut enc, &dig(s), &mut wire).unwrap();
assert_eq!(
crate::version::V26_1::prediction_sequence(&wire),
Some(want)
);
}
assert_eq!(crate::version::V1_8::prediction_sequence(&()), None);
}
/// `dig_speed` is the left button's per-tick progress; `item_facts` the hands' facts.
#[test]
fn dig_speed_and_item_facts() {
// 1.16.5 facts by name (its test chunk is empty).
let mut e = engine(GameVersion::V1_16_5);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Script(|ctx: &mut TickContext<'_>| {
let id = |n: &str| i32::from(ghast_data::v1_16_5::Item::from_name(n).unwrap().id());
let bread = ctx.item_facts(&ghast_inventory::Stack::new(id("bread"), 3, 0));
assert!(bread.is_some_and(|f| f.food && f.usable && !f.places_block && f.count == 3));
let dirt = ctx.item_facts(&ghast_inventory::Stack::new(id("dirt"), 1, 0));
assert!(dirt.is_some_and(|f| f.places_block && !f.food));
});
e.tick(&mut b, t0);
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
e.note_inbound(t0);
let got = std::cell::Cell::new(None);
let mut b = Script(|ctx: &mut TickContext<'_>| {
let stone = ghast_protocol::BlockPos::new(8, 63, 8);
let pick = ghast_inventory::Stack::new(278, 1, 0);
let facts = ctx.item_facts(&pick).unwrap();
assert!(!facts.places_block && !facts.food);
got.set(Some((
ctx.dig_speed(stone, None),
ctx.dig_speed(stone, Some(&pick)),
ctx.dig_speed(ghast_protocol::BlockPos::new(8, 64, 8), None),
ctx.dig_speed(ghast_protocol::BlockPos::new(500, 63, 8), None),
)));
});
// Land first (in the air the progress is ÷5).
for _ in 0..40 {
e.tick(&mut b, t0);
}
assert!(e.core.pose.on_ground, "{:?}", e.core.pose);
let (hand, pick, air, unloaded) = got.get().expect("ticked");
// Stone by hand: not harvestable, 1 / 1.5 / 100 per tick (the 150 ticks of
// `dig_with_the_left_button`).
assert_eq!(hand, Some(1.0 / 1.5 / 100.0));
// Diamond pickaxe: speed 8, harvestable: 8 / 1.5 / 30.
assert_eq!(pick, Some(8.0 / 1.5 / 30.0));
assert_eq!(air, Some(0.0));
assert_eq!(unloaded, None);
}
/// `place` is refused unless the sent look is on the face; then C08 + C0A before the
/// movement packet.
#[test]
fn place_needs_the_sent_look() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let floor = ghast_protocol::BlockPos::new(8, 63, 8);
let mut results = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
ctx.set_aim(90.0, 89.5);
results.push(ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)));
});
// Torches in the selected hotbar slot (window 0 slot 36): a full block would go into
// the player's own box, which the 1.8 client does not even send.
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
let mut placed_tick = None;
for i in 0..20 {
e.tick(&mut b, t0);
let n = names(e.outbound());
if n.contains(&"block_place") {
assert_eq!(n[..2], ["block_place", "swing"], "{n:?}");
placed_tick.get_or_insert(i);
}
}
let _ = b;
let first = results.iter().position(|r| *r).unwrap();
assert!(first > 3, "refused while still turning");
assert_eq!(placed_tick, Some(first));
assert_eq!(e.core.inv.held().map(|s| s.id()), Some(50));
}
#[test]
fn sneak_action_order() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let mut b = Script(|ctx: &mut TickContext<'_>| {
ctx.set_controls(Controls {
sneak: true,
..Controls::default()
});
});
e.tick(&mut b, Instant::now());
let out = std::mem::take(e.outbound());
assert_eq!(
out[0],
Outbound::EntityAction {
entity_id: 7,
action: EntityAction::StartSneaking
}
);
assert!(matches!(out[1], Outbound::Move(_)));
}
/// Block changes reach the behaviour once, in arrival order, only when asked for.
#[test]
fn block_updates_per_version() {
use ghast_protocol::BlockPos;
for &v in GameVersion::ALL {
let mut e = engine(v);
join(&mut e);
e.sim.collect_block_updates(true);
let t0 = Instant::now();
e.note_inbound(t0);
let raws = match v.instance() {
GameVersion::V1_8_9 => {
use ghast_protocol::v1_8::play::clientbound as cb;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 59 << 4 | 7,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_x: 0,
chunk_z: 0,
records: vec![cb::MultiBlockChangeRecords {
horizontal_pos: 5 << 4 | 6,
y: 62,
block_id: 60 << 4 | 7,
}],
})
.unwrap(),
]
}
GameVersion::V1_12_2 => {
use ghast_protocol::v1_12_2::play::clientbound as cb;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 59 << 4 | 7,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_x: 0,
chunk_z: 0,
records: vec![cb::MultiBlockChangeRecords {
horizontal_pos: 5 << 4 | 6,
y: 62,
block_id: 60 << 4 | 7,
}],
})
.unwrap(),
]
}
GameVersion::V26_1 => {
use ghast_protocol::v26_1::play::clientbound as cb;
// Section y = -1 (20-bit two's complement), local x 5 z 6 y 14.
let local = (5 << 8 | 6 << 4 | 14) as i64;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 1,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
x: 0,
z: 0,
y: -1,
},
records: vec![9 << 12 | local],
})
.unwrap(),
]
}
#[cfg(feature = "v26_2")]
GameVersion::V26_2 => {
use ghast_protocol::v26_2::play::clientbound as cb;
// Section y = -1 (20-bit two's complement), local x 5 z 6 y 14.
let local = (5 << 8 | 6 << 4 | 14) as i64;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 1,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
x: 0,
z: 0,
y: -1,
},
records: vec![9 << 12 | local],
})
.unwrap(),
]
}
_ => {
use ghast_protocol::v1_16_5::play::clientbound as cb;
// Section y = -1 (20-bit two's complement), local x 5 z 6 y 14.
let local = (5 << 8 | 6 << 4 | 14) as i64;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 1,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
x: 0,
z: 0,
y: 0xF_FFFF,
},
not_trust_edges: false,
records: vec![9 << 12 | local],
})
.unwrap(),
]
}
};
for raw in &raws {
e.sim.world_packet(raw).unwrap();
}
let mut seen = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
seen.push(ctx.events().block_updates.clone());
});
e.tick(&mut b, t0);
e.tick(&mut b, t0);
let _ = b;
let want = match v.instance() {
GameVersion::V1_8_9 | GameVersion::V1_12_2 => vec![
(BlockPos::new(3, 63, 4), 59 << 4 | 7),
(BlockPos::new(5, 62, 6), 60 << 4 | 7),
],
_ => vec![(BlockPos::new(3, 63, 4), 1), (BlockPos::new(5, -2, 6), 9)],
};
assert_eq!(seen, [want, Vec::new()], "{v:?}");
// Not collected when not asked for.
e.sim.collect_block_updates(false);
e.sim.world_packet(&raws[0]).unwrap();
let mut n = usize::MAX;
let mut b = Script(|ctx: &mut TickContext<'_>| n = ctx.events().block_updates.len());
e.tick(&mut b, t0);
let _ = b;
assert_eq!(n, 0);
}
}
/// `set_flying` sends the abilities packet before the move, only when allowed and changed.
#[test]
fn set_flying_needs_may_fly() {
for &v in GameVersion::ALL {
let mut e = engine(v);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
// In the air (flight ends on landing, like vanilla).
e.handle(Inbound::Teleport(Teleport {
x: 8.5,
y: 70.0,
z: 8.5,
yaw: 90.0,
pitch: 0.0,
flags: 0,
teleport_id: Some(2),
..Default::default()
}));
e.outbound().clear();
let mut b = Script(|ctx: &mut TickContext<'_>| ctx.set_flying(true));
e.tick(&mut b, t0);
assert!(!names(e.outbound()).contains(&"abilities"), "{v:?}");
assert!(!e.core.pose.flying);
e.handle(Inbound::Abilities(Abilities {
flags: 4,
..Abilities::default()
}));
e.tick(&mut b, t0);
let out = std::mem::take(e.outbound());
assert_eq!(
out[0],
Outbound::Abilities {
flags: 6,
flying_speed: 0.05,
walking_speed: 0.1
},
"{v:?}"
);
assert!(matches!(out[1], Outbound::Move(_)), "{out:?}");
assert!(e.core.pose.flying && e.core.sent.flying);
// Already flying: nothing more.
e.tick(&mut b, t0);
assert!(!names(e.outbound()).contains(&"abilities"));
let _ = b;
}
}
/// 1.12.2 runs the vanilla-exact physics: the player is added to its chunk on the first
/// tick (nothing sent), then walks on the stone floor and sends its moves; standing still
/// sends no idle on-ground packets (1.9+).
#[test]
fn v1_12_2_walks_with_physics() {
let mut e = engine(GameVersion::V1_12_2);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut idle = Script(|_: &mut TickContext<'_>| {});
e.tick(&mut idle, t0);
assert!(
!names(e.outbound())
.iter()
.any(|n| matches!(*n, "C04" | "C06"))
);
for _ in 0..5 {
e.tick(&mut idle, t0);
}
e.outbound().clear();
let start = e.core.pose.pos;
assert!(e.core.pose.on_ground, "{:?}", e.core.pose);
let mut walk = Script(|ctx: &mut TickContext<'_>| {
ctx.set_controls(crate::common::Controls {
forward: true,
..Default::default()
});
});
for _ in 0..10 {
e.tick(&mut walk, t0);
}
let _ = walk;
let moved = names(e.outbound());
assert!(
moved.iter().any(|n| matches!(*n, "C04" | "C06")),
"{moved:?}"
);
// Yaw 90 faces -X.
assert!(e.core.pose.pos.x < start.x - 0.5, "{:?}", e.core.pose.pos);
assert_eq!(e.core.pose.pos.y, 64.0);
let mut stop = Script(|ctx: &mut TickContext<'_>| {
ctx.set_controls(crate::common::Controls::default());
});
for _ in 0..30 {
e.tick(&mut stop, t0);
}
e.outbound().clear();
for _ in 0..5 {
e.tick(&mut stop, t0);
}
let _ = (idle, stop);
// No idle on-ground packets; at most the position refresh every 20 ticks.
let still = names(e.outbound());
assert!(still.len() <= 1 && !still.contains(&"C03"), "{still:?}");
}
/// A behaviour that reports `running() == false` is not ticked again.
#[test]
fn finished_behaviour_is_not_ticked() {
struct Three(std::rc::Rc<std::cell::Cell<u32>>);
impl Behavior for Three {
fn tick(&mut self, _ctx: &mut TickContext<'_>) {
self.0.set(self.0.get() + 1);
}
fn running(&self) -> bool {
self.0.get() < 3
}
}
let ticks = std::rc::Rc::new(std::cell::Cell::new(0));
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b: Box<dyn Behavior> = Box::new(Three(ticks.clone()));
for _ in 0..10 {
e.tick(&mut b, t0);
// The player keeps sending its movement packet.
let out = std::mem::take(e.outbound());
assert!(
out.iter().any(|o| matches!(o, Outbound::Move(_))),
"{out:?}"
);
}
assert_eq!(
ticks.get(),
3,
"not ticked after running() == false (through the Box)"
);
}
/// A turn that would take the crosshair off a block placed this tick waits one tick.
#[test]
fn turn_held_on_a_place_tick() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
let floor = ghast_protocol::BlockPos::new(8, 63, 8);
let mut tick = 0;
let mut placed_at = None;
let mut pitches = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
tick += 1;
if placed_at.is_none() {
ctx.set_aim(90.0, 89.5);
if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
placed_at = Some(tick);
// Look up on the same tick: held back.
ctx.set_aim(90.0, -60.0);
}
} else {
ctx.set_aim(90.0, -60.0);
}
pitches.push(ctx.pose().pitch);
});
for _ in 0..30 {
e.tick(&mut b, t0);
e.outbound().clear();
}
let _ = b;
let p = placed_at.expect("placed");
assert_eq!(e.core.held_turns, 1);
// Pose at the start of the tick after the place: still the place look.
assert_eq!(pitches[p], pitches[p - 1], "{pitches:?}");
assert!(pitches[p + 1] < pitches[p], "{pitches:?}");
}
/// `click` returns the ticket its confirm carries.
#[test]
fn click_ticket_matches_the_confirm() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
let mut ticket = None;
let mut n = 0;
let mut b = Script(|ctx: &mut TickContext<'_>| {
n += 1;
if n == 1 {
ctx.open_inventory().unwrap();
} else if ticket.is_none() {
ticket = ctx
.click(ghast_inventory::Click::Pickup {
slot: 36,
right: false,
})
.ok();
}
});
for _ in 0..3 {
e.tick(&mut b, t0);
}
let _ = b;
let t = ticket.expect("click sent");
assert_eq!(t.window_id, 0);
assert!(t.matches(&ghast_inventory::ClickResult::new(
0,
t.action,
ghast_inventory::ClickOutcome::Accepted,
)));
}
/// 1.8 planting uses the seed at once (vanilla `SeedItem.use` on the client); a
/// torch place waits for the server.
#[test]
fn planting_uses_the_seed_at_once() {
use ghast_protocol::v1_8::play::clientbound as cb;
for (soil, item, used) in [
(60 << 4 | 7, 295, true),
(1 << 4, 295, false),
(60 << 4, 50, false),
] {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let floor = ghast_protocol::BlockPos::new(8, 63, 8);
let raw = RawPacket::from_packet(&cb::BlockChange {
location: floor,
r#type: soil,
})
.unwrap();
e.sim.world_packet(&raw).unwrap();
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(item, 64, 0)));
let mut done = false;
let mut b = Script(|ctx: &mut TickContext<'_>| {
ctx.set_aim(90.0, 89.5);
if !done {
done = ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5));
}
});
let mut sent = None;
for _ in 0..20 {
e.tick(&mut b, t0);
for o in e.outbound().drain(..) {
if let Outbound::Place { held, .. } = o {
sent = held.map(|h| h.count());
}
}
}
let _ = b;
assert_eq!(sent, Some(64), "the packet carries the stack before use");
let left = e.core.inv.held().map(|s| s.count());
assert_eq!(
left,
Some(if used { 63 } else { 64 }),
"soil {soil} item {item}"
);
}
}
/// `planned_look` is the look the movement step then uses: a plain turn, a turn held on a
/// place tick, no aim; and it leaves the rotation's budget alone.
#[test]
fn planned_look_is_the_next_look() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
let floor = ghast_protocol::BlockPos::new(8, 63, 8);
let mut n = 0;
let mut placed = false;
let mut plans: Vec<(f32, f32)> = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
n += 1;
if n % 5 == 0 {
// No aim this tick: the current look.
} else if !placed {
ctx.set_aim(90.0, 89.5);
if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
placed = true;
ctx.set_aim(90.0, -60.0);
}
} else {
ctx.set_aim(150.0, -60.0);
}
// Asking twice changes nothing.
let p = ctx.planned_look();
assert_eq!(p, ctx.planned_look());
plans.push(p);
});
let mut looks = Vec::new();
for _ in 0..40 {
e.tick(&mut b, t0);
e.outbound().clear();
looks.push((e.core.pose.yaw, e.core.pose.pitch));
}
let _ = b;
assert!(placed);
assert_eq!(e.core.test_held_turns(), 1);
assert_eq!(plans, looks);
}
/// A teleport event keeps the sent pose from before the overwrite, the raw values and the
/// resolved pose.
#[test]
fn teleport_event_has_the_sent_pose_before() {
for &v in GameVersion::ALL {
let mut e = engine(v);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut seen = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
seen.extend(ctx.events().teleports.iter().copied());
});
e.tick(&mut b, t0);
let sent = e.core.sent;
// Relative yaw +30, absolute position.
let tp = Teleport {
x: 10.5,
y: 64.0,
z: 8.5,
yaw: 30.0,
pitch: 0.0,
flags: crate::common::teleport_flags::YAW,
teleport_id: Some(9),
relative: crate::common::teleport_flags::YAW as u32,
..Default::default()
};
e.handle(Inbound::Teleport(tp));
e.tick(&mut b, t0);
e.tick(&mut b, t0);
let _ = b;
// The spawn position first (join), then ours, each once.
assert_eq!(seen.len(), 2, "{v:?}");
let ev = seen[1];
assert_eq!(ev.teleport, tp);
assert_eq!(ev.sent_before, sent);
assert_eq!(ev.after.pos, Vec3::new(10.5, 64.0, 8.5));
assert_eq!(ev.after.yaw, sent.yaw + 30.0, "{v:?}");
}
}
/// A container the server opened and the behaviour closed (`close_window`) no longer
/// holds the mouse: the left button digs again (both versions). While it is open the
/// buttons are up.
#[test]
fn closed_window_frees_the_buttons() {
for &v in GameVersion::ALL {
let mut e = engine(v);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
if v.instance() == GameVersion::V1_16_5 {
// The 1.16 test chunk is all air: put a stone floor under the player.
use ghast_protocol::v1_16_5::play::clientbound as cb;
let raw = RawPacket::from_packet(&cb::BlockChange {
location: ghast_protocol::BlockPos::new(8, 63, 8),
r#type: 1,
})
.unwrap();
e.sim.world_packet(&raw).unwrap();
}
e.core.inv.on_open_window(
5,
Some(ghast_inventory::WindowKind::Chest { rows: 3 }),
"Vault".into(),
);
e.handle(Inbound::OpenWindow(5));
// Something on the cursor: vanilla's client-side close drops it (the server
// throws it out), so the client forgets it too.
e.core
.inv
.on_set_slot(-1, -1, Some(ghast_inventory::Stack::new(1, 3, 0)));
let mut n = 0;
let mut closed_at = None;
let mut b = Script(|ctx: &mut TickContext<'_>| {
n += 1;
ctx.set_aim(90.0, 89.5);
ctx.set_buttons(Buttons {
left: true,
right: false,
});
if n == 15 {
assert!(ctx.inventory().cursor().is_some());
ctx.close_window().unwrap();
assert_eq!(ctx.open_window(), None);
let inv = ctx.inventory();
assert!(!inv.gui_open() && inv.window().is_none() && inv.cursor().is_none());
closed_at = Some(n);
}
});
let mut first_dig = None;
for i in 1..=30 {
e.tick(&mut b, t0);
let out = std::mem::take(e.outbound());
if first_dig.is_none()
&& out.iter().any(|o| {
matches!(
o,
Outbound::Dig {
status: crate::common::DigStatus::Start,
..
}
)
})
{
first_dig = Some(i);
}
}
let _ = b;
assert_eq!(closed_at, Some(15));
let d = first_dig.unwrap_or_else(|| panic!("{v:?}: no dig after the close"));
// The hands run after the behaviour: the closing tick already digs.
assert!(d >= 15, "{v:?}: dug at tick {d} with the window open");
}
}
/// `swings` counts every arm swing: the behaviour's, an action's and the held button's.
#[test]
fn swings_count_every_arm_swing() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut n = 0;
let mut seen = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
n += 1;
ctx.set_aim(90.0, 89.5);
if n == 1 {
ctx.swing();
ctx.swing();
}
if n == 20 {
// Hold the left button on the stone floor: a swing every tick while digging.
ctx.set_buttons(Buttons {
left: true,
right: false,
});
}
seen.push(ctx.swings());
});
let mut sent = 0u64;
for _ in 0..30 {
e.tick(&mut b, t0);
sent += count_swings(&std::mem::take(e.outbound()));
}
let _ = b;
assert_eq!(seen[0], 2, "this tick's own swings count at once");
assert!(sent > 10, "the held button swings: {sent}");
// The last reading misses only the hands' swing of the last tick.
assert_eq!(*seen.last().unwrap() + 1, sent);
assert_eq!(e.core.swings, sent);
}
/// `WorldView::column` gives the stored column; light and biomes only when configured.
#[test]
fn column_view_and_world_config() {
for config in [
None,
Some(
ghast_world::WorldConfig::default()
.with_biomes(true)
.with_light(true),
),
] {
let sim = crate::sim::Sim18::with(&crate::sim::SimOptions {
world: config,
..crate::sim::SimOptions::default()
});
let mut e = Engine::new(opts(GameVersion::V1_8_9), Box::new(sim) as Box<dyn Sim>);
join(&mut e);
let w: &dyn WorldView = &e.sim;
let col = w.column(0, 0).expect("loaded");
assert_eq!(u32::from(col.raw(8, 63, 8)), w.raw_block(8, 63, 8).unwrap());
assert_eq!(col.raw(8, 63, 8), 1 << 4);
assert!(w.column(5, 5).is_none());
let light = col.sky_light(8, 63, 8);
assert_eq!(light.is_some(), config.is_some(), "{config:?}");
let biomes = !matches!(col.biomes(), ghast_world::Biomes::None);
assert_eq!(biomes, config.is_some(), "{config:?}");
}
}
/// `after_tick` runs after the movement step with the sent pose, also once the behaviour
/// finished; a panic there stops the behaviour only.
#[test]
fn after_tick_sees_the_sent_pose() {
struct Obs {
n: u32,
views: Vec<(u64, Pose, u64)>,
}
impl Behavior for Obs {
fn tick(&mut self, ctx: &mut TickContext<'_>) {
self.n += 1;
ctx.set_aim(150.0, 10.0);
ctx.set_controls(Controls {
forward: true,
..Controls::default()
});
}
fn running(&self) -> bool {
self.n < 5
}
fn after_tick(&mut self, view: &TickView<'_>) {
self.views.push((view.tick(), *view.sent(), view.swings()));
assert!(view.world().is_column_loaded(0, 0));
assert_eq!(view.version(), GameVersion::V1_8_9);
}
}
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Obs {
n: 0,
views: Vec::new(),
};
let mut sent = Vec::new();
for _ in 0..10 {
e.tick(&mut b, t0);
e.outbound().clear();
sent.push(e.core.sent);
}
assert_eq!(b.n, 5);
assert_eq!(b.views.len(), 10, "also after the behaviour finished");
for (i, (_, p, _)) in b.views.iter().enumerate() {
assert_eq!(*p, sent[i]);
}
assert_ne!(
b.views[0].1.yaw, b.views[4].1.yaw,
"the view follows the turn"
);
}
/// With block entities on, a 1.8 sign update reaches the column (and the packet passes the
/// filter); off by default.
#[test]
fn block_entities_follow_the_world_config() {
use ghast_protocol::v1_8::play::clientbound as cb;
for on in [false, true] {
let sim = crate::sim::Sim18::with(&crate::sim::SimOptions {
world: on.then(|| ghast_world::WorldConfig::default().with_block_entities(true)),
..crate::sim::SimOptions::default()
});
assert_eq!(sim.world_packet_ids().contains(&cb::id::UPDATE_SIGN), on);
let mut e = Engine::new(opts(GameVersion::V1_8_9), Box::new(sim) as Box<dyn Sim>);
join(&mut e);
let raw = RawPacket::from_packet(&cb::UpdateSign {
location: ghast_protocol::BlockPos::new(3, 64, 4),
text1: "\"Hello\"".into(),
text2: "\"\"".into(),
text3: "\"\"".into(),
text4: "\"\"".into(),
})
.unwrap();
e.sim.world_packet(&raw).unwrap();
let w: &dyn WorldView = &e.sim;
let be = w.column(0, 0).unwrap().block_entity(3, 64, 4);
assert_eq!(be.is_some(), on, "{be:?}");
}
}
}