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
//! 1.8.9: the chunk store and the vanilla-exact physics.
use ghast_protocol::{BlockPos, RawPacket};
use super::*;
use crate::common::{Abilities, Controls, Outbound, Pose, Teleport, Vec3};
use crate::hands::{BlockQuery, HeldItem};
/// Block-local `[min, max]` of a physics box.
fn arr(b: &ghast_physics::math::Aabb) -> [f64; 6] {
[b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z]
}
/// The 1.8 ray shape at a position (ghast-physics: vanilla's bounds after
/// `Block.setBoundingBox`, neighbour-dependent shapes and the stairs passes):
/// `(selection, stairs passes)`.
fn ray_1_8(w: &ghast_world::v1_8::World, x: i32, y: i32, z: i32) -> RayBox {
use ghast_physics::v1_8::RayShape;
match ghast_physics::v1_8::ray_shape(w, x, y, z, false) {
RayShape::None => (None, None),
RayShape::Bounds(b) => (Some(arr(&b)), None),
RayShape::Stairs(p) => (None, Some(p.boxes().map(|b| b.as_ref().map(arr)))),
}
}
/// A ray shape as the hands take it.
type RayBox = (Option<[f64; 6]>, Option<[Option<[f64; 6]>; 8]>);
// ---- 1.8.9: ghast-physics ---------------------------------------------------------------
/// 1.8.9: the chunk store and the vanilla-exact physics.
pub(crate) struct Sim18 {
world: ghast_world::v1_8::World,
pub(super) player: ghast_physics::v1_8::PlayerState,
packets: ghast_physics::Packets,
rec: Option<crate::record::Recorder>,
force_step_position: ForceStepPosition,
entities: Option<ghast_entity::v1_8::Tracker>,
/// Block changes since the last drain (position, version raw state), when collected.
updates: BlockUpdates,
/// The session's last join and respawn packets: a tracker started mid-session replays
/// them to learn our entity id and dimension.
session: SessionPackets,
/// The world keeps block entities (signs, tile entity NBT).
block_entities: bool,
/// The boat we ride (the 1.8 client simulates it; with entity tracking).
ride: Option<Box<Ride18>>,
/// Our entity id (join game).
own_id: Option<i32>,
/// Test hook: the dimension's water vaporizes (an oracle case's).
#[cfg(test)]
vaporizes: bool,
/// The flags byte (entity data index 0) the server last sent for our entity.
server_flags: Option<u8>,
/// The absorption the server last sent for our entity (player entity data; 0 before any).
absorption: f32,
/// `absorption` changed since the engine last took it.
absorption_dirty: bool,
/// Blocks pistons move (the client runs the piston itself on a block-action packet).
pistons: ghast_physics::v1_8::Pistons,
/// World changes of the pistons, applied right away (kept to reuse the allocation).
piston_edits: ghast_physics::v1_8::Edits,
/// An unmodelled piston condition in the last movement step or the packets since
/// ([`super::WorldView::piston_uncertain`]): the player's `ticks_alive` when it was raised (it
/// holds while that counter has not moved on, so the plain tick never touches it).
piston_uncertain_at: Option<i32>,
/// The moving blocks' half of this tick is still to run, after the other entities' ticks
/// ([`Sim18::tick_piston_phase`], from `tick_entities`; with entity tracking).
piston_phase: bool,
/// A tick since the last crosshair ray of [`Sim18::step_pistons`] went without the ray
/// while a piston head may have been within its reach (riding): the heads' shared bounds'
/// history is not known. Plain ticks never set it: they are only taken while no head is
/// loaded or none is within reach ([`Sim18::heads_near`]), when the ray cannot change the
/// bounds.
ray_missed: bool,
/// Piston heads may be loaded in the client world (seen in a chunk's palette, a block
/// change or a piston's write; cleared with the world): the ticks then check the heads'
/// distance ([`Sim18::heads_near`]).
head_watch: bool,
/// The piston heads around [`Sim18::heads_center`] ([`Sim18::update_ray_need`]).
heads: Vec<[i32; 3]>,
heads_center: Option<[i32; 3]>,
/// Boats we boarded (`onEntityAttach` naming us clears vanilla's empty flag): their client
/// tick runs `Entity.move` from then on, even after we leave, until another entity boards
/// them ([`Sim18::bounds_movers`]).
boarded: Vec<i32>,
/// The horses and pigs the client watches (with entity tracking), from their spawn packets
/// on: the interpolation, body clock and rearing animation the player boards
/// ([`watched_packet`](Sim18::watched_packet)).
watched: Vec<(i32, ghast_physics::v1_8::Mount)>,
/// The entity tracker started (or restarted) after the join: entities spawned before are
/// not known until the next join or a respawn into another dimension.
tracker_late: bool,
/// Test hook: the JVM's `Math.sin` / `Math.cos` of the next boat tick (argument bits, sine,
/// cosine), from an oracle record.
#[cfg(test)]
trig: Vec<(u64, f64, f64)>,
/// The player's horse jump bar (it outlives a ride).
jump_bar: ghast_physics::v1_8::JumpBar,
}
/// Test hook: `Math.sin` / `Math.cos` from a table, the platform's for other arguments.
#[cfg(test)]
struct TableTrig<'a>(&'a [(u64, f64, f64)]);
#[cfg(test)]
impl ghast_physics::v1_8::JavaTrig for TableTrig<'_> {
fn sin(&self, x: f64) -> f64 {
self.0
.iter()
.find(|e| e.0 == x.to_bits())
.map_or_else(|| x.sin(), |e| e.1)
}
fn cos(&self, x: f64) -> f64 {
self.0
.iter()
.find(|e| e.0 == x.to_bits())
.map_or_else(|| x.cos(), |e| e.2)
}
}
/// The boat the player rides: its entity id and its client-side state.
#[derive(Debug)]
struct Ride18 {
id: i32,
seat: Seat18,
}
/// The boat the 1.8 client simulates, or the minecart or living mount the server moves.
#[derive(Debug)]
enum Seat18 {
Boat(ghast_physics::v1_8::Boat),
Cart(ghast_physics::v1_8::Minecart),
Mount(ghast_physics::v1_8::Mount),
}
/// One client tick of every horse and pig the client watches (`Mount::tick` without a rider);
/// one another entity rides is no longer modelled.
#[cold]
#[inline(never)]
fn tick_watched_mounts(
watched: &mut Vec<(i32, ghast_physics::v1_8::Mount)>,
t: &ghast_entity::v1_8::Tracker,
ridden: Option<i32>,
) {
let me = t.self_id();
watched.retain(|(id, _)| {
t.get(*id)
.is_some_and(|e| e.vehicle().is_none() && e.passengers().iter().all(|&p| Some(p) == me))
});
for (id, m) in watched.iter_mut() {
if ridden != Some(*id) {
m.tick(None);
}
}
}
/// A living mount (horse kinds, pig) as the client has it when we board it: the tracker's
/// drawn position and interpolation, rotation, head yaw, ground flag and entity data index 16
/// (without entity data a horse counts as saddled). The body clock starts as a fresh spawn's.
fn mount_of(e: &ghast_entity::Entity, kind: ghast_physics::v1_8::MountKind) -> Seat18 {
use ghast_entity::MetaValue;
let (yaw, pitch) = e.drawn_rotation();
let mut m = ghast_physics::v1_8::Mount::new(kind, e.drawn_position(), yaw, pitch);
m.tracked = e.position().map(|v| (v * 32.0).round() as i32);
if let Some((target, steps)) = e.interpolation() {
m.set_interpolation(target, e.yaw(), e.pitch(), i32::from(steps));
}
m.head_yaw = e.head_yaw();
m.body_yaw = m.head_yaw;
m.on_ground = e.drawn_on_ground();
match e.metadata().get(16) {
Some(MetaValue::Int(f)) => m.set_flags(*f),
Some(MetaValue::Byte(b)) => m.set_flags(i32::from(*b)),
_ => {
log::warn!(
"riding {kind:?} {} without its entity data (the metadata store is off): its \
saddle / rearing flags are unknown, taken as saddled and not rearing",
e.id()
);
m.set_flags(ghast_physics::v1_8::HORSE_SADDLED | 1);
}
}
Seat18::Mount(m)
}
impl std::fmt::Debug for Sim18 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Sim18")
.field("world", &self.world)
.field("pos", &self.player.pos)
.finish_non_exhaustive()
}
}
#[cfg(test)]
impl Sim18 {
/// Test hook: the physics player.
pub(crate) fn test_player(&self) -> &ghast_physics::v1_8::PlayerState {
&self.player
}
/// Test hook: the JVM's sine / cosine values of the next boat ticks (argument bits, sine,
/// cosine).
#[cfg(all(feature = "v1_12_2", feature = "v1_16_5", feature = "v26_1"))]
pub(crate) fn test_set_trig(&mut self, t: Vec<(u64, f64, f64)>) {
self.trig = t;
}
/// Test hook: replaces the physics player and syncs `pose`.
pub(crate) fn test_set_player(&mut self, pose: &mut Pose, p: ghast_physics::v1_8::PlayerState) {
self.player = p;
self.piston_uncertain_at = None;
self.pistons.forget_shared_bounds();
sync_pose(pose, &self.player);
}
/// Test hook: sets one block.
#[cfg(all(test, feature = "v1_12_2", feature = "v1_16_5"))]
pub(crate) fn test_set_block(
&mut self,
x: i32,
y: i32,
z: i32,
s: ghast_data::v1_8::BlockState,
) {
let old = self.world.block_state(x, y, z);
self.head_change(x, y, z, old, s.block().id() == 34);
self.world.set_block_state(x, y, z, s);
}
/// Test hook: the chunk store.
pub(crate) fn test_world(&self) -> &ghast_world::v1_8::World {
&self.world
}
}
impl Sim18 {
pub(crate) fn new() -> Self {
Sim18 {
world: ghast_world::v1_8::World::new(config()),
player: ghast_physics::v1_8::PlayerState::new([0.0; 3], 0.0, 0.0),
packets: ghast_physics::Packets::new(),
rec: None,
force_step_position: ForceStepPosition::Off,
entities: None,
updates: BlockUpdates::default(),
session: SessionPackets::default(),
block_entities: false,
ride: None,
own_id: None,
#[cfg(test)]
vaporizes: false,
server_flags: None,
absorption: 0.0,
absorption_dirty: false,
pistons: ghast_physics::v1_8::Pistons::new(),
piston_edits: ghast_physics::v1_8::Edits::new(),
piston_uncertain_at: None,
piston_phase: false,
ray_missed: false,
head_watch: false,
heads: Vec::new(),
heads_center: None,
boarded: Vec::new(),
watched: Vec::new(),
tracker_late: false,
#[cfg(test)]
trig: Vec::new(),
jump_bar: ghast_physics::v1_8::JumpBar::default(),
}
}
/// A sim with options (recording, Grim compatibility).
pub(crate) fn with(opts: &SimOptions) -> Self {
let mut s = Self::new();
s.force_step_position = opts.force_step_position;
s.entities = opts.entities.map(ghast_entity::v1_8::Tracker::new);
if let Some(c) = opts.world {
s.world = ghast_world::v1_8::World::new(c);
s.block_entities = c.block_entities;
}
if opts.shared_chunks.is_some() {
log::debug!("shared chunks are not used on 1.8.9; every section stays owned");
}
if let Some(p) = opts.record.as_deref() {
match crate::record::Recorder::create(p) {
Ok(r) => s.rec = Some(r),
Err(e) => log::warn!("cannot record to {}: {e}", p.display()),
}
}
s
}
}
impl Sim18 {
/// `block_action`: a piston's extend / retract runs the client's piston.
fn block_action(&mut self, raw: &RawPacket) -> Result<(), SimError> {
use ghast_protocol::v1_8::play::clientbound as cb;
let p: cb::BlockAction = raw.decode_as()?;
let block = p.block_id & 4095;
if block != 29 && block != 33 {
return Ok(());
}
self.piston_edits.clear();
self.pistons.block_event(
&self.world,
[p.location.x, p.location.y, p.location.z],
block as u8,
p.byte1,
p.byte2,
&mut self.piston_edits,
);
self.apply_piston_edits();
Ok(())
}
/// The player's tick while blocks move (kept out of the plain tick's code).
#[cold]
#[inline(never)]
fn step_pistons(&mut self, input: &ghast_physics::TickInput) {
if let Some(r) = &mut self.rec {
r.note_once("moving pistons not representable");
}
// The shared bounds of slabs, stairs, fences, ... (moving boxes are built from them)
// are followed from here on, known once a query or ray sets them; ticks this model did
// not follow, or entities that move or trace rays of their own on the client, may
// have changed them.
self.pistons.begin_bounds_tick(self.player.ticks_alive);
// The crosshair ray before the world tick: a ray through a piston head leaves its plate
// in the head block's shared bounds, which moving heads' boxes are built from. Only
// traced here (while blocks move, the bounds are a plate or a head is within reach);
// plain ticks skip it, and are only taken while the ray cannot meet a head. The
// history starts known: a fresh client's head bounds are the full cube.
{
if std::mem::take(&mut self.ray_missed) {
// Ticks without the ray while a head was within its reach (riding): vanilla's
// ray may have left the plate of any head it passed in the shared bounds (a
// head that has moved, gone or been left behind since: any facing).
self.pistons.forget_head_bounds(0x3f);
}
let p = &self.player;
let eye_h = if p.input.sneak {
1.62f32 - 0.08
} else {
1.62f32
};
let eye = ghast_physics::pick::legacy::eye_position(p.pos, eye_h);
let reach = f64::from(if p.abilities.creative { 5.0f32 } else { 4.5f32 });
self.pistons.crosshair(
&self.world,
eye,
ghast_physics::pick::legacy::look_vector(p.yaw, input.pitch),
reach,
);
}
// Vanilla may tick such entities between the ray and the player.
self.forget_for_movers();
// The player's half; vanilla ticks the other entities between the player and the moving
// blocks, which push them too (with entity tracking the blocks' half runs from
// `tick_entities`).
let before = self.player.bb;
ghast_physics::v1_8::tick_player_among_pistons(
&mut self.player,
input,
&self.world,
&ghast_physics::v1_8::Options::default(),
&self.pistons,
&mut self.packets,
);
// The player's own collision with a moving head whose bounds may be a plate this model
// does not know.
let head_unknown = self.pistons.head_unknown_touching(&before, &self.player.bb);
self.pistons.end_bounds_tick(self.player.ticks_alive);
if self.entities.is_some() && !self.pistons.is_empty() {
self.piston_phase = true;
} else {
// ... and between the player and the moving blocks.
self.forget_for_movers();
self.piston_edits.clear();
self.pistons.tick_after_entities(
&mut self.player,
&self.world,
&ghast_physics::v1_8::Options::default(),
&mut self.piston_edits,
);
self.apply_piston_edits();
self.flag_untracked();
}
if head_unknown {
self.piston_uncertain_at = Some(self.player.ticks_alive);
}
self.heads_near();
}
/// Piston heads within the crosshair's reach keep the ray traced on every tick (the slow
/// path), so the heads' shared bounds stay known while the player is near them. The heads
/// around are listed by a scan when the player has moved away from the last one's centre
/// and kept up to date by the block changes and chunk loads since. Returns whether one is
/// near (its centre within 8 blocks of the eye; the ray reaches blocks whose centre is at
/// most 5 + 0.87 away, and a head missing from the list is at least 7.5 away on one axis).
#[cold]
#[inline(never)]
fn heads_near(&mut self) -> bool {
const SCAN: i32 = 10;
let p = self.player.pos;
let eye = [p[0], p[1] + 1.62, p[2]];
let at = eye.map(|v| v.floor() as i32);
let far = |c: [i32; 3]| (0..3).any(|k| (at[k] - c[k]).abs() > SCAN - 7);
if self.heads_center.is_none_or(far) {
self.heads.clear();
scan_heads(&self.world, at, SCAN, &mut self.heads);
self.heads_center = Some(at);
}
let near = self.heads.iter().any(|h| {
let d = (0..3)
.map(|k| (f64::from(h[k]) + 0.5 - eye[k]).powi(2))
.sum::<f64>();
d <= 8.0 * 8.0
});
self.pistons.set_ray_needed(near);
near
}
/// Nothing moves and the head bounds are the full cube, kept watched only because heads are
/// loaded ([`ghast_physics::v1_8::Pistons::watch_only`]), and none is within the crosshair's
/// reach from this tick's eye: the plain tick applies (its ray cannot meet a head, and its
/// collision queries leave the full cube the bounds already are).
#[cold]
#[inline(never)]
fn heads_out_of_reach(&mut self) -> bool {
if !self.pistons.watch_only() || self.heads_near() {
return false;
}
// Other entities' queries and rays still meet the loaded heads on this tick.
if self.bounds_movers() {
self.pistons.forget_head_bounds(0x3f);
}
true
}
/// Piston heads may now be loaded ([`Sim18::head_watch`]).
#[cold]
#[inline(never)]
fn watch_heads(&mut self) {
self.head_watch = true;
self.pistons.set_heads_loaded(true);
}
/// Columns `(cx, cz)` were loaded or replaced: a head in their sections' palettes starts the
/// watch ([`Sim18::head_watch`]); while it runs, the list of the heads around is rescanned
/// when a column meets its cube.
fn columns_loaded(&mut self, cols: impl Iterator<Item = (i32, i32)>) {
for (cx, cz) in cols {
if let Some(c) = self.heads_center {
const R: i32 = 10;
let meets = |v: i32, at: i32| v * 16 <= at + R && v * 16 + 15 >= at - R;
if meets(cx, c[0]) && meets(cz, c[2]) {
self.heads_center = None;
}
}
if self.head_watch {
continue;
}
let Some(col) = self.world.column(cx, cz) else {
continue;
};
if (0..16).any(|i| {
col.section(i)
.is_some_and(|s| s.any_state(|r| r >> 4 == 34))
}) {
self.watch_heads();
}
}
}
/// The world was cleared or replaced (login, respawn): with no column left no head is loaded.
fn world_replaced(&mut self) {
self.heads.clear();
self.heads_center = None;
if self.world.columns().is_empty() {
self.head_watch = false;
self.pistons.set_heads_loaded(false);
self.pistons.set_ray_needed(false);
}
}
/// A block at `(x, y, z)` changes from `old` to `new` (packets, the pistons' writes): the
/// list of the heads around ([`Sim18::update_ray_need`]) follows it.
#[inline]
fn head_change(
&mut self,
x: i32,
y: i32,
z: i32,
old: Option<ghast_data::v1_8::BlockState>,
new_is_head: bool,
) {
if new_is_head && !self.head_watch {
self.watch_heads();
}
if head_facing(old) == 0 && !new_is_head {
return;
}
if self.heads_center.is_some() {
self.heads.retain(|h| *h != [x, y, z]);
if new_is_head {
self.heads.push([x, y, z]);
}
}
}
/// `true` when the client world may hold an entity that vanilla moves (`Entity.move`) or
/// that traces block rays on the client: items, orbs, projectiles, falling blocks, TNT,
/// boats we boarded, ... Their collision queries and rays change the shared bounds of
/// slabs, stairs, fences, ... and of the piston head (anywhere in the loaded world: a query
/// that meets a static head leaves the full cube, a ray through one its plate), which
/// moving boxes are built from and this model does not follow. Players, mobs, armor stands,
/// paintings, item frames, leash knots, end crystals and minecarts do neither on the
/// client; nor does a boat whose empty flag is set (`BoatEntity.tick`: it only steps
/// toward the server's position), which holds until we board it. Without entity tracking,
/// or with a tracker that started after the join, the client view cannot rule such an
/// entity out: always `true`.
#[cold]
#[inline(never)]
fn bounds_movers(&self) -> bool {
use ghast_entity::EntityType;
self.tracker_late
|| self.entities.as_ref().is_none_or(|t| {
t.iter().any(|e| match e.entity_type() {
EntityType::Player
| EntityType::LegacyMob(_)
| EntityType::Painting
| EntityType::LegacyObject(10 | 51 | 71 | 77 | 78) => false,
EntityType::LegacyObject(1) => self.boarded.contains(&e.id()),
_ => true,
})
})
}
/// Other entities may tick here ([`Sim18::bounds_movers`]): the shared bounds of slabs,
/// stairs, fences, ... and the piston head bounds are not known until a query or ray of
/// this model sets them again.
#[cold]
#[inline(never)]
fn forget_for_movers(&mut self) {
if self.bounds_movers() {
self.pistons.forget_shared_bounds();
self.pistons.forget_head_bounds(0x3f);
}
}
/// Not modelled: moving boxes from bounds the model does not track next to the player;
/// a push that met an entity the view does not follow or whose outcome depends on head
/// bounds a ray on a tick without moving blocks may have left (plain ticks do not trace the
/// ray).
fn flag_untracked(&mut self) {
if self.pistons.take_unmodelled() | self.pistons.untracked_near(&self.player.bb) {
self.piston_uncertain_at = Some(self.player.ticks_alive);
}
}
/// The block-entity half of the client tick (`World.tickEntities` after every entity): the
/// moving blocks advance and push the player and the other entities the client view
/// follows (players, mobs, armor stands: it moves its copies itself; they interpolate on
/// toward the server's positions from there). A push that meets a boat, a minecart, another
/// solid object, a rider or a ridden entity is flagged ([`super::WorldView::piston_uncertain`]).
#[cold]
#[inline(never)]
fn tick_piston_phase(&mut self, pose: &mut Pose) {
use ghast_entity::EntityType;
use ghast_physics::math::Aabb;
use ghast_physics::v1_8 as phys;
self.piston_phase = false;
// Vanilla ticks the other entities before the moving blocks.
self.forget_for_movers();
let mut others: Vec<(i32, phys::PistonEntity)> = Vec::new();
let mut solids: Vec<(Aabb, [i32; 3])> = Vec::new();
if let Some(t) = self.entities.as_ref().filter(|t| t.tracks_client_motion()) {
let me = t.self_id();
for e in t.iter() {
if Some(e.id()) == me {
continue;
}
let (Some(b), Some(o)) = (e.drawn_bounding_box(), e.search_order()) else {
continue;
};
let bb = Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5]);
let section = [o.0, o.2, o.1];
let ty = e.entity_type();
if ty == EntityType::LegacyObject(1) {
// A boat is solid for the others' moves (`getBox`).
solids.push((bb, section));
}
let living = matches!(
ty,
EntityType::Player | EntityType::LegacyMob(_) | EntityType::LegacyObject(78)
);
// Objects a piston moves on the client that the view does not follow (boats,
// minecarts, TNT, end crystals, fireballs, falling blocks); hanging entities do
// not move on the client, items, orbs and projectiles are not followed (their
// drawn position is the server's).
let solid_object =
matches!(ty, EntityType::LegacyObject(1 | 10 | 50 | 51 | 63 | 70));
if !living && !solid_object {
continue;
}
let spectator = ty == EntityType::Player && t.tab_game_mode(&e.uuid()) == Some(3);
let step_height = match ty {
EntityType::Player => 0.0,
// EndermanEntity 1.0, HorseBaseEntity 0.5 while not ridden (riders are not
// followed).
EntityType::LegacyMob(58) => 1.0,
EntityType::LegacyMob(100) => 0.5,
_ => phys::STEP_HEIGHT,
};
let p = e.drawn_position();
others.push((
e.id(),
phys::PistonEntity {
bb,
pos: p,
on_ground: e.drawn_on_ground(),
in_web: e.drawn_in_web(),
step_height,
sneaking: ty == EntityType::Player
&& ghast_entity::v1_8::flags(e) & 0x02 != 0,
moved: !spectator,
followed: living && e.vehicle().is_none() && e.passengers().is_empty(),
section,
},
));
}
}
let before: Vec<phys::PistonEntity> = others.iter().map(|o| o.1).collect();
let mut list: Vec<phys::PistonEntity> = others.iter().map(|o| o.1).collect();
self.piston_edits.clear();
if self.ride.is_some() {
self.pistons.tick_blocks_among(
&self.world,
&phys::Options::default(),
&mut list,
&solids,
&mut self.piston_edits,
);
} else {
self.pistons.tick_after_entities_among(
&mut self.player,
&self.world,
&phys::Options::default(),
&mut list,
&solids,
&mut self.piston_edits,
);
}
self.apply_piston_edits();
if let Some(t) = &mut self.entities {
for ((id, _), (a, b)) in others.iter().zip(list.iter().zip(&before)) {
if a != b {
let x = a.bb;
t.client_pushed(
*id,
a.pos,
[x.min_x, x.min_y, x.min_z, x.max_x, x.max_y, x.max_z],
a.on_ground,
a.in_web,
);
}
}
}
if self.ride.is_none() {
self.flag_untracked();
sync_pose(pose, &self.player);
} else if self.pistons.take_unmodelled() {
self.piston_uncertain_at = Some(self.player.ticks_alive);
}
}
/// The moving blocks' tick while the player rides (they do not push it here).
#[cold]
#[inline(never)]
fn tick_piston_blocks(&mut self) {
self.piston_edits.clear();
self.pistons
.tick_blocks(&self.world, &mut self.piston_edits);
self.apply_piston_edits();
}
/// Writes the pistons' world changes into the chunk store.
fn apply_piston_edits(&mut self) {
for k in 0..self.piston_edits.len() {
let ([x, y, z], s) = self.piston_edits[k];
let old = self.world.block_state(x, y, z);
self.head_change(x, y, z, old, s.block().id() == 34);
if self.world.set_block_state(x, y, z, s) {
self.updates
.push(BlockPos::new(x, y, z), u32::from(s.raw()));
}
}
}
/// After a packet changed blocks: a moving block whose block is no longer a moving-piston
/// block is gone (the client drops the block entity of a replaced block).
#[inline]
fn prune_pistons(&mut self) {
if !self.pistons.is_empty() {
self.prune_pistons_slow();
}
}
#[cold]
#[inline(never)]
fn prune_pistons_slow(&mut self) {
let w = &self.world;
self.pistons.retain(|m| {
w.block_state(m.pos[0], m.pos[1], m.pos[2])
.is_some_and(|s| s.block().id() == ghast_physics::v1_8::MOVING_PISTON)
});
}
/// `entity_metadata`: only our own entity's flags byte (index 0) is read. Vanilla's data
/// watcher writes it into the local player too (`NetHandlerPlayClient.handleEntityMetadata`):
/// the sprint bit sets the flag `isSprinting()` reads (`Entity.setFlag(3)`, not
/// `setSprinting`: the speed modifier stays until the client's own movement update changes
/// it). Sneaking is the input's on the 1.8 client (`isSneaking()`), the other bits are not
/// read by movement.
fn own_metadata(&mut self, raw: &RawPacket) -> Result<(), SimError> {
use ghast_protocol::defs::p47::types::EntityMetadataValue as V;
use ghast_protocol::v1_8::play::clientbound as cb;
let Some(own) = self.own_id else {
return Ok(());
};
let id = ghast_protocol::Reader::new(&raw.body).read_varint()?;
if let Some(r) = self.ride.as_deref_mut()
&& r.id == id
&& let Seat18::Mount(m) = &mut r.seat
{
// The mount's entity data index 16: horse flags (int), pig saddle (byte).
let p: cb::EntityMetadata = raw.decode_as()?;
for e in &p.metadata {
match (e.key, &e.value) {
(16, V::Int(f)) => m.set_flags(*f),
(16, V::Byte(b)) => m.set_flags(i32::from(*b)),
_ => {}
}
}
return Ok(());
}
if id != own {
return Ok(());
}
let p: cb::EntityMetadata = raw.decode_as()?;
for e in &p.metadata {
// PlayerEntity.setAbsorption: index 17.
if let (17, V::Float(a)) = (e.key, &e.value) {
self.absorption = *a;
self.absorption_dirty = true;
}
if let (0, V::Byte(b)) = (e.key, &e.value) {
let flags = *b as u8;
self.server_flags = Some(flags);
self.player.sprinting = flags & 0x08 != 0;
if let Some(r) = &mut self.rec {
r.note("own entity flags not representable");
}
}
}
Ok(())
}
/// The server's packets about the horses and pigs the client watches (not the one we ride):
/// a mob spawn of a mount type starts watching it (spawn position, angle bytes, entity data
/// index 16); moves, looks, head yaw and entity data follow; a removal ends it.
#[cold]
#[inline(never)]
fn watched_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
use ghast_protocol::defs::p47::types::EntityMetadataValue as V;
use ghast_protocol::v1_8::play::clientbound as cb;
let flags =
|m: &mut ghast_physics::v1_8::Mount,
list: &[ghast_protocol::defs::p47::types::EntityMetadataEntry]| {
for e in list {
match (e.key, &e.value) {
(16, V::Int(f)) => m.set_flags(*f),
(16, V::Byte(b)) => m.set_flags(i32::from(*b)),
_ => {}
}
}
};
if raw.id == cb::id::ENTITY_DESTROY {
let p: cb::EntityDestroy = raw.decode_as()?;
self.watched.retain(|w| !p.entity_ids.contains(&w.0));
return Ok(());
}
if raw.id == cb::id::SPAWN_ENTITY_LIVING {
let p: cb::SpawnEntityLiving = raw.decode_as()?;
self.watched.retain(|w| w.0 != p.entity_id);
if let Some(kind) = ghast_physics::v1_8::MountKind::of_mob_type(p.r#type) {
let mut m = ghast_physics::v1_8::Mount::spawned(
kind,
[p.x, p.y, p.z],
p.yaw,
p.pitch,
p.head_pitch,
);
flags(&mut m, &p.metadata);
self.watched.push((p.entity_id, m));
}
return Ok(());
}
let id = ghast_protocol::Reader::new(&raw.body).read_varint()?;
if self.ride.as_ref().is_some_and(|r| r.id == id) {
return Ok(());
}
let Some((_, m)) = self.watched.iter_mut().find(|w| w.0 == id) else {
return Ok(());
};
match raw.id {
cb::id::ENTITY_TELEPORT => {
let p: cb::EntityTeleport = raw.decode_as()?;
m.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch, p.on_ground);
}
cb::id::REL_ENTITY_MOVE => {
let p: cb::RelEntityMove = raw.decode_as()?;
m.server_update([p.d_x, p.d_y, p.d_z], None, p.on_ground);
}
cb::id::ENTITY_MOVE_LOOK => {
let p: cb::EntityMoveLook = raw.decode_as()?;
m.server_update([p.d_x, p.d_y, p.d_z], Some((p.yaw, p.pitch)), p.on_ground);
}
cb::id::ENTITY_LOOK => {
let p: cb::EntityLook = raw.decode_as()?;
m.server_update([0; 3], Some((p.yaw, p.pitch)), p.on_ground);
}
cb::id::ENTITY => m.server_update([0; 3], None, false),
cb::id::ENTITY_HEAD_ROTATION => {
let p: cb::EntityHeadRotation = raw.decode_as()?;
m.server_head_yaw(p.head_yaw);
}
cb::id::ENTITY_METADATA => {
let p: cb::EntityMetadata = raw.decode_as()?;
flags(m, &p.metadata);
}
_ => {}
}
Ok(())
}
/// The boat packets (with entity tracking): `attach_entity` naming us (boarding a tracked
/// boat, or leaving it with vehicle -1), and while riding the server's teleport, relative
/// moves, looks and velocity of that boat and its destruction (vanilla's
/// `World.removeEntity` takes the rider off).
#[cold]
#[inline(never)]
fn vehicle_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
use ghast_protocol::v1_8::play::clientbound as cb;
let Some(t) = &self.entities else {
return Ok(());
};
if raw.id == cb::id::ATTACH_ENTITY {
let p: cb::AttachEntity = raw.decode_as()?;
if p.leash {
return Ok(());
}
if t.self_id() != Some(p.entity_id) {
// Another entity boards a boat: vanilla sets its empty flag again.
self.boarded.retain(|&b| b != p.vehicle_id);
return Ok(());
}
if p.vehicle_id == -1 {
if let Some(r) = self.ride.take() {
log::debug!("left boat {}", r.id);
// A living mount: the client watches it again from where it is.
if let Seat18::Mount(m) = r.seat {
self.watched.retain(|w| w.0 != r.id);
self.watched.push((r.id, m));
}
}
return Ok(());
}
// onEntityAttach: a boat the client knows starts its physics; a minecart follows
// the server. The client's interpolation of either at rest ends at the server's
// last position.
let shadow = self
.watched
.iter()
.position(|w| w.0 == p.vehicle_id)
.map(|k| self.watched.swap_remove(k).1);
let seat = t.get(p.vehicle_id).and_then(|e| {
let fixed = e.position().map(|v| (v * 32.0).round() as i32);
let yaw = (e.yaw() * 256.0 / 360.0).round() as i32 as i8;
let pitch = (e.pitch() * 256.0 / 360.0).round() as i32 as i8;
match e.entity_type() {
ghast_entity::EntityType::LegacyObject(1) => Some(Seat18::Boat(
ghast_physics::v1_8::Boat::spawned(fixed, yaw, pitch),
)),
ghast_entity::EntityType::LegacyObject(10) => Some(Seat18::Cart(
ghast_physics::v1_8::Minecart::spawned(fixed, yaw, pitch),
)),
ghast_entity::EntityType::LegacyMob(id) => {
ghast_physics::v1_8::MountKind::of_mob_type(id).map(|k| match shadow {
// What the client held while it watched the mob: its
// interpolation, body clock, rearing animation and entity data.
Some(m) if m.kind == k => Seat18::Mount(m),
_ => mount_of(e, k),
})
}
_ => None,
}
});
if matches!(seat, Some(Seat18::Boat(_))) && !self.boarded.contains(&p.vehicle_id) {
// Vanilla clears the boat's empty flag ([`Sim18::bounds_movers`]).
self.boarded.push(p.vehicle_id);
}
match seat {
Some(seat) => {
log::debug!("riding {}", p.vehicle_id);
self.ride = Some(Box::new(Ride18 {
id: p.vehicle_id,
seat,
}));
}
None => {
self.ride = None;
log::debug!(
"riding {} (not simulated: not a boat, minecart, horse or pig)",
p.vehicle_id
);
}
}
return Ok(());
}
let Some(r) = self.ride.as_deref_mut() else {
return Ok(());
};
if let Seat18::Mount(m) = &mut r.seat {
let id = r.id;
match raw.id {
cb::id::ENTITY_TELEPORT => {
let p: cb::EntityTeleport = raw.decode_as()?;
if p.entity_id == id {
m.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch, p.on_ground);
}
}
cb::id::REL_ENTITY_MOVE => {
let p: cb::RelEntityMove = raw.decode_as()?;
if p.entity_id == id {
m.server_update([p.d_x, p.d_y, p.d_z], None, p.on_ground);
}
}
cb::id::ENTITY_MOVE_LOOK => {
let p: cb::EntityMoveLook = raw.decode_as()?;
if p.entity_id == id {
m.server_update([p.d_x, p.d_y, p.d_z], Some((p.yaw, p.pitch)), p.on_ground);
}
}
cb::id::ENTITY_LOOK => {
let p: cb::EntityLook = raw.decode_as()?;
if p.entity_id == id {
m.server_update([0; 3], Some((p.yaw, p.pitch)), p.on_ground);
}
}
cb::id::ENTITY => {
// The bare entity packet: no move, its ground flag is false.
let p: cb::Entity = raw.decode_as()?;
if p.entity_id == id {
m.server_update([0; 3], None, false);
}
}
cb::id::ENTITY_HEAD_ROTATION => {
let p: cb::EntityHeadRotation = raw.decode_as()?;
if p.entity_id == id {
m.server_head_yaw(p.head_yaw);
}
}
cb::id::ENTITY_DESTROY => {
let p: cb::EntityDestroy = raw.decode_as()?;
if p.entity_ids.contains(&id) {
log::debug!("mount {id} destroyed");
self.ride = None;
}
}
// A living mob's client motion does not move it.
_ => {}
}
return Ok(());
}
if let Seat18::Cart(c) = &mut r.seat {
let id = r.id;
match raw.id {
cb::id::ENTITY_TELEPORT => {
let p: cb::EntityTeleport = raw.decode_as()?;
if p.entity_id == id {
c.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch);
}
}
cb::id::REL_ENTITY_MOVE => {
let p: cb::RelEntityMove = raw.decode_as()?;
if p.entity_id == id {
c.server_update([p.d_x, p.d_y, p.d_z], None);
}
}
cb::id::ENTITY_MOVE_LOOK => {
let p: cb::EntityMoveLook = raw.decode_as()?;
if p.entity_id == id {
c.server_update([p.d_x, p.d_y, p.d_z], Some((p.yaw, p.pitch)));
}
}
cb::id::ENTITY_LOOK => {
let p: cb::EntityLook = raw.decode_as()?;
if p.entity_id == id {
c.server_update([0; 3], Some((p.yaw, p.pitch)));
}
}
cb::id::ENTITY => {
let p: cb::Entity = raw.decode_as()?;
if p.entity_id == id {
c.server_update([0; 3], None);
}
}
cb::id::ENTITY_DESTROY => {
let p: cb::EntityDestroy = raw.decode_as()?;
if p.entity_ids.contains(&id) {
log::debug!("minecart {id} destroyed");
self.ride = None;
}
}
// A minecart's client motion does not move it.
_ => {}
}
return Ok(());
}
let Seat18::Boat(b) = &mut r.seat else {
return Ok(());
};
match raw.id {
cb::id::ENTITY_TELEPORT => {
let p: cb::EntityTeleport = raw.decode_as()?;
if p.entity_id == r.id {
b.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch, p.on_ground);
}
}
cb::id::REL_ENTITY_MOVE => {
let p: cb::RelEntityMove = raw.decode_as()?;
if p.entity_id == r.id {
b.server_move([p.d_x, p.d_y, p.d_z], p.on_ground);
}
}
cb::id::ENTITY_MOVE_LOOK => {
let p: cb::EntityMoveLook = raw.decode_as()?;
if p.entity_id == r.id {
b.server_move([p.d_x, p.d_y, p.d_z], p.on_ground);
}
}
cb::id::ENTITY_LOOK => {
let p: cb::EntityLook = raw.decode_as()?;
if p.entity_id == r.id {
b.server_move([0; 3], p.on_ground);
}
}
cb::id::ENTITY => {
// The bare entity packet: no move, its ground flag is false.
let p: cb::Entity = raw.decode_as()?;
if p.entity_id == r.id {
b.server_move([0; 3], false);
}
}
cb::id::ENTITY_VELOCITY => {
let p: cb::EntityVelocity = raw.decode_as()?;
if p.entity_id == r.id {
let v = p.velocity;
let c = |x: i16| f64::from(x) / 8000.0;
b.server_velocity([c(v.x), c(v.y), c(v.z)]);
}
}
cb::id::ENTITY_DESTROY => {
let p: cb::EntityDestroy = raw.decode_as()?;
if p.entity_ids.contains(&r.id) {
log::debug!("boat {} destroyed", r.id);
self.ride = None;
}
}
_ => {}
}
Ok(())
}
/// A tick in the boat the 1.8 client simulates (`ghast_physics::v1_8::tick_boat`).
#[cold]
#[inline(never)]
fn step_ride(&mut self, input: &ghast_physics::TickInput) {
// The ride's ticks follow neither the ray nor the queries that set shared bounds.
self.pistons.forget_shared_bounds();
// The ride's ticks do not trace the crosshair ray.
if self.head_watch && self.heads_near() {
self.ray_missed = true;
}
// Other entities' queries and rays meet the loaded heads too.
if self.head_watch && self.bounds_movers() {
self.pistons.forget_head_bounds(0x3f);
}
let Some(r) = self.ride.as_deref_mut() else {
return;
};
let id = r.id;
let boat = match &mut r.seat {
Seat18::Boat(b) => b,
Seat18::Mount(m) => {
// The living mount the server moves (`ghast_physics::v1_8::tick_mount`).
ghast_physics::v1_8::tick_mount(
&mut self.player,
m,
&mut self.jump_bar,
input,
&self.world,
&ghast_physics::v1_8::Options::default(),
&mut self.packets,
);
return;
}
Seat18::Cart(c) => {
self.jump_bar.idle();
// The minecart the server moves (`ghast_physics::v1_8::tick_minecart`).
ghast_physics::v1_8::tick_minecart(
&mut self.player,
c,
input,
&self.world,
&ghast_physics::v1_8::Options::default(),
&mut self.packets,
);
return;
}
};
self.jump_bar.idle();
#[cfg(test)]
let still = ghast_physics::v1_8::tick_boat_with(
&mut self.player,
boat,
input,
&self.world,
&ghast_physics::v1_8::Options::default(),
&TableTrig(&self.trig),
&mut self.packets,
);
#[cfg(not(test))]
let still = ghast_physics::v1_8::tick_boat(
&mut self.player,
boat,
input,
&self.world,
&ghast_physics::v1_8::Options::default(),
&mut self.packets,
);
for &[x, y, z] in boat.broken_blocks() {
self.world
.set_block_state(x, y, z, ghast_data::v1_8::BlockState::AIR);
}
if !still {
log::debug!("boat {id} fell out of the world");
self.ride = None;
}
}
}
impl WorldView for Sim18 {
fn collisions(&self) -> (bool, bool) {
(
self.player.horizontal_collision,
self.player.vertical_collision,
)
}
fn piston_uncertain(&self) -> bool {
self.piston_uncertain_at == Some(self.player.ticks_alive)
}
fn column(&self, chunk_x: i32, chunk_z: i32) -> Option<&ghast_world::Column> {
self.world.column(chunk_x, chunk_z)
}
fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
self.world.is_column_loaded(chunk_x, chunk_z)
}
fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
self.world.block_state(x, y, z).map(|s| u32::from(s.raw()))
}
fn entities(&self) -> Option<&ghast_entity::Entities> {
self.entities.as_deref()
}
fn loaded_columns(&self) -> usize {
self.world.columns().len()
}
fn block_query(&self, x: i32, y: i32, z: i32) -> Option<BlockQuery> {
let s = self.world.block_state(x, y, z)?;
let b = s.block();
let info = b.info();
let ray = ray_1_8(&self.world, x, y, z);
Some(BlockQuery {
exact: Some(crate::hands::ExactDig::V1_8),
air: s.is_air(),
water: matches!(b.id(), 8 | 9),
block: u16::from(b.id()),
hardness: info.hardness.unwrap_or(-1.0),
dig_material: info.material,
harvest_tools: info.harvest_tools,
selection: ray.0,
stairs: ray.1,
activates: ACTIVATED_1_8.contains(&b.id()),
})
}
fn crosshair(
&self,
eyes: Vec3,
(yaw, pitch): (f32, f32),
_look: Vec3,
reach: f64,
) -> Option<crate::BlockHit> {
// The oracle-verified 1.8 pick (ghast_physics::pick::v1_8: vanilla's ray shapes,
// Entity.rayTrace with the float look vector).
use ghast_physics::pick::v1_8 as pick;
let eye = [eyes.x, eyes.y, eyes.z];
let hit = pick::pick(&self.world, eye, pick::look_vector(yaw, pitch), reach)?;
block_hit(&hit, eye)
}
}
impl Sim for Sim18 {
fn crosshair_target(&self, q: &PickQuery<'_>) -> Crosshair {
// The oracle-verified GameRenderer.updateTargetedEntity: block ray at the game
// mode's reach, then the entity ray.
use ghast_physics::pick::v1_8 as pick;
let eye = [q.eyes.x, q.eyes.y, q.eyes.z];
let look = pick::look_vector(q.rotation.0, q.rotation.1);
if q.entities.is_empty() {
// pick_target without entities is its block pick (`target` returns it as is).
let reach = if q.creative {
pick::CREATIVE_REACH
} else {
pick::REACH
};
return Crosshair::Block(
pick::pick(&self.world, eye, look, reach).and_then(|h| block_hit(&h, eye)),
);
}
let t = pick::pick_target(&self.world, eye, look, q.creative, &q.player_bb, q.entities);
legacy_crosshair(t, eye)
}
fn world_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
{
use ghast_protocol::v1_8::play::clientbound::id;
self.session.note(raw, id::LOGIN, id::RESPAWN);
}
if let Some(t) = &mut self.entities
&& t.wants(raw.id)
{
t.apply(raw)?;
}
use ghast_protocol::v1_8::play::clientbound as cb;
if self.entities.is_some()
&& (raw.id == cb::id::SPAWN_ENTITY_LIVING
|| (!self.watched.is_empty()
&& matches!(
raw.id,
cb::id::ENTITY_TELEPORT
| cb::id::REL_ENTITY_MOVE
| cb::id::ENTITY_MOVE_LOOK
| cb::id::ENTITY_LOOK
| cb::id::ENTITY
| cb::id::ENTITY_HEAD_ROTATION
| cb::id::ENTITY_METADATA
| cb::id::ENTITY_DESTROY
)))
{
self.watched_packet(raw)?;
}
if self.entities.is_some()
&& (raw.id == cb::id::ATTACH_ENTITY
|| (self.ride.is_some()
&& matches!(
raw.id,
cb::id::ENTITY_TELEPORT
| cb::id::REL_ENTITY_MOVE
| cb::id::ENTITY_MOVE_LOOK
| cb::id::ENTITY_LOOK
| cb::id::ENTITY
| cb::id::ENTITY_VELOCITY
| cb::id::ENTITY_HEAD_ROTATION
| cb::id::ENTITY_DESTROY
)))
{
return self.vehicle_packet(raw);
}
let w = &mut self.world;
match raw.id {
cb::id::LOGIN => {
self.ride = None;
self.watched.clear();
self.pistons.clear();
let p: cb::Login = raw.decode_as()?;
self.own_id = Some(p.entity_id);
w.apply_login(&p);
// A new client world: the tracker has seen every entity of it.
self.tracker_late = false;
self.boarded.clear();
self.world_replaced();
}
cb::id::ENTITY_METADATA => return self.own_metadata(raw),
cb::id::RESPAWN => {
self.ride = None;
self.watched.clear();
self.pistons.clear();
if w.apply_respawn(&raw.decode_as()?) == ghast_world::Applied::Changed {
// Another dimension: a new client world.
self.tracker_late = false;
self.boarded.clear();
}
self.world_replaced();
}
cb::id::MAP_CHUNK => {
let p: cb::MapChunk = raw.decode_as()?;
// A full chunk (or an unload) replaces the column and its block entities.
if p.ground_up && !self.pistons.is_empty() {
self.pistons.chunk_replaced(p.x, p.z);
}
let r = w.apply_map_chunk(&p);
self.columns_loaded(std::iter::once((p.x, p.z)));
r?;
}
cb::id::MAP_CHUNK_BULK => {
let p: cb::MapChunkBulk = raw.decode_as()?;
if !self.pistons.is_empty() {
for m in &p.meta {
self.pistons.chunk_replaced(m.x, m.z);
}
}
let r = w.apply_map_chunk_bulk(&p);
self.columns_loaded(p.meta.iter().map(|m| (m.x, m.z)));
r?;
}
cb::id::BLOCK_CHANGE => {
let p: cb::BlockChange = raw.decode_as()?;
let new_head = p.r#type >> 4 == 34;
if new_head || self.heads_center.is_some() {
let l = p.location;
let old = w.block_state(l.x, l.y, l.z);
self.head_change(l.x, l.y, l.z, old, new_head);
}
let w = &mut self.world;
self.updates.push(p.location, p.r#type as u32);
w.apply_block_change(&p);
self.prune_pistons();
}
cb::id::BLOCK_ACTION => return self.block_action(raw),
cb::id::MULTI_BLOCK_CHANGE => {
let p: cb::MultiBlockChange = raw.decode_as()?;
for r in &p.records {
let x = p.chunk_x * 16 + i32::from(r.horizontal_pos >> 4);
let z = p.chunk_z * 16 + i32::from(r.horizontal_pos & 15);
let new_head = r.block_id >> 4 == 34;
if new_head || self.heads_center.is_some() {
let old = self.world.block_state(x, i32::from(r.y), z);
self.head_change(x, i32::from(r.y), z, old, new_head);
}
self.updates
.push(BlockPos::new(x, i32::from(r.y), z), r.block_id as u32);
}
let w = &mut self.world;
w.apply_multi_block_change(&p);
self.prune_pistons();
}
cb::id::EXPLOSION => {
w.apply_explosion(&raw.decode_as()?);
self.prune_pistons();
}
cb::id::WORLD_BORDER => {
w.apply_world_border(&raw.decode_as()?);
}
cb::id::UPDATE_SIGN if self.block_entities => {
w.apply_update_sign(&raw.decode_as()?);
}
cb::id::TILE_ENTITY_DATA if self.block_entities => {
w.apply_tile_entity_data(&raw.decode_as()?);
}
_ => {}
}
Ok(())
}
fn reset_player(&mut self) {
// A fresh ClientPlayerEntity: at the origin, lastReported* zero; abilities and food are
// re-sent by the server.
let abilities = self.player.abilities;
let food = self.player.food_level;
self.player = ghast_physics::v1_8::PlayerState::new([0.0; 3], 0.0, 0.0);
self.piston_uncertain_at = None;
self.pistons.forget_shared_bounds();
self.player.abilities = abilities;
self.player.food_level = food;
self.ride = None;
self.server_flags = None;
self.absorption_dirty |= self.absorption != 0.0;
self.absorption = 0.0;
}
fn mount_rules(&self, entity_id: i32) -> Option<ghast_inventory::MountRules> {
// HorseScreenHandler: the saddle slot always takes a saddle; the armor slot horse armor
// when the horse type (entity data 19) is 0.
use ghast_inventory::{MountArmor, MountRules};
let t = self.entities.as_ref()?;
let e = t.get(entity_id)?;
if ghast_entity::v1_8::info(e.entity_type())?.name != "EntityHorse" || !t.config().metadata
{
return None;
}
let horse = e.metadata().byte(19).unwrap_or(0) == 0;
let armor = if horse {
MountArmor::HorseArmor
} else {
MountArmor::None
};
Some(MountRules::new(true, armor))
}
fn vehicle(&self) -> Option<crate::common::Vehicle> {
let r = self.ride.as_deref()?;
let b = match &r.seat {
Seat18::Boat(b) => b,
Seat18::Mount(m) => {
return Some(crate::common::Vehicle {
entity_id: r.id,
pos: Vec3::new(m.pos[0], m.pos[1], m.pos[2]),
yaw: m.yaw,
pitch: m.pitch,
on_ground: m.on_ground,
controlled: false,
});
}
Seat18::Cart(c) => {
return Some(crate::common::Vehicle {
entity_id: r.id,
pos: Vec3::new(c.pos[0], c.pos[1], c.pos[2]),
yaw: c.yaw,
pitch: c.pitch,
on_ground: false,
controlled: false,
});
}
};
Some(crate::common::Vehicle {
entity_id: r.id,
pos: Vec3::new(b.pos[0], b.pos[1], b.pos[2]),
yaw: b.yaw,
pitch: b.pitch,
on_ground: b.on_ground,
controlled: true,
})
}
fn teleport(&mut self, pose: &mut Pose, t: &Teleport) {
use crate::common::teleport_flags as fl;
let rel = [
t.flags & fl::X != 0,
t.flags & fl::Y != 0,
t.flags & fl::Z != 0,
t.flags & fl::YAW != 0,
t.flags & fl::PITCH != 0,
];
// The engine keeps the look (its rotation may have moved it since the last tick).
self.player.yaw = pose.yaw;
self.player.pitch = pose.pitch;
let _reply = self
.player
.apply_teleport([t.x, t.y, t.z], t.yaw, t.pitch, rel);
if let Some(r) = &mut self.rec {
let p = &self.player;
r.teleport(
[t.x, t.y, t.z],
t.yaw,
t.pitch,
t.flags,
t.teleport_id,
[p.pos[0], p.bb.min_y, p.pos[2]],
p.yaw,
p.pitch,
);
}
sync_pose(pose, &self.player);
}
fn abilities(&mut self, a: Abilities) {
let a = ghast_physics::Abilities {
invulnerable: a.flags & 1 != 0,
flying: a.flags & 2 != 0,
allow_flying: a.flags & 4 != 0,
creative: a.flags & 8 != 0,
fly_speed: a.flying_speed,
walk_speed: a.walking_speed,
};
if let Some(r) = &mut self.rec {
r.abilities(&a);
}
self.player.apply_abilities(a);
}
fn food(&mut self, food: i32) {
self.player.food_level = food;
}
fn velocity(&mut self, v: Vec3, add: bool) {
if let Some(r) = &mut self.rec {
if add {
r.note("explosion push not representable");
} else {
r.velocity([
(v.x * 8000.0).round() as i32,
(v.y * 8000.0).round() as i32,
(v.z * 8000.0).round() as i32,
]);
}
}
let p = &mut self.player;
if add {
p.vel[0] += v.x;
p.vel[1] += v.y;
p.vel[2] += v.z;
} else {
p.vel = [v.x, v.y, v.z];
}
}
fn movement_speed(&mut self, base: f64, modifiers: &[(u128, f64, u8)]) {
if let Some(r) = &mut self.rec {
r.speed_attribute(base, modifiers);
}
self.player.apply_speed_attribute(base, modifiers);
}
fn status_effects(&mut self, effects: &std::collections::BTreeMap<i8, i8>) {
if let Some(r) = &mut self.rec {
r.effects(effects);
}
let e = &mut self.player.effects;
e.jump_boost = effects.get(&8).map(|a| i32::from(*a));
e.blindness = effects.contains_key(&15);
}
fn boots(&mut self, depth_strider: u8, _soul_speed: u8) {
// Soul speed does not exist in 1.8.
self.player.depth_strider = depth_strider;
}
fn spectator(&mut self, on: bool) {
self.player.spectator = on;
}
fn set_flying(&mut self, flying: bool, out: &mut Vec<Outbound>) {
let a = &mut self.player.abilities;
if a.flying == flying || (flying && !a.allow_flying) {
return;
}
a.flying = flying;
let a = *a;
if let Some(r) = &mut self.rec {
r.abilities(&a);
}
out.push(Outbound::Abilities {
flags: abilities_flags(&a),
flying_speed: a.fly_speed,
walking_speed: a.walk_speed,
});
}
fn collect_block_updates(&mut self, on: bool) {
self.updates.on = on;
if !on {
self.updates.list.clear();
}
}
fn drain_block_updates(&mut self, out: &mut Vec<(BlockPos, u32)>) -> usize {
out.append(&mut self.updates.list);
std::mem::take(&mut self.updates.dropped)
}
fn world_packet_ids(&self) -> Vec<i32> {
let mut ids: Vec<i32> = self.world.packet_ids().collect();
// Our own entity data (the flags byte), decoded only when it is ours.
ids.push(ghast_protocol::v1_8::play::clientbound::id::ENTITY_METADATA);
// Pistons: the client moves the blocks itself.
ids.push(ghast_protocol::v1_8::play::clientbound::id::BLOCK_ACTION);
ids
}
#[cfg(all(test, ghast_modern, feature = "v1_8", feature = "v1_16_5"))]
fn test_set_own_id(&mut self, id: i32) {
self.own_id = Some(id);
}
fn attack_hurts(&self, e: &ghast_entity::Entity) -> bool {
use ghast_entity::EntityType as T;
// 1.8.9 `damage` on the client: `OtherClientPlayerEntity` always, boats and minecarts
// (`world.isClient` → true), the end crystal, the ghast fireball (an attacker given).
// LivingEntity is false on the client; paintings / item frames are skipped by
// `handleAttack`; small fireballs and wither skulls are never damaged.
match e.entity_type() {
T::Player => true,
T::LegacyObject(t) => matches!(t, 1 | 10 | 51 | 63),
_ => false,
}
}
fn attack_slow(&mut self, target: i32, yaw: f32, knockback: i32, sprint_bonus: bool) {
let p = &mut self.player;
if super::attack_knockback_applies(knockback, p.sprinting, sprint_bonus) {
// The target's addVelocity (the client view moves a boat by it).
if let Some(t) = &mut self.entities {
let k = (knockback + i32::from(p.sprinting && sprint_bonus)) as f32;
let r = yaw * std::f32::consts::PI / 180.0;
t.add_velocity(
target,
[
f64::from(-ghast_physics::math::sin(r) * k * 0.5),
0.1,
f64::from(ghast_physics::math::cos(r) * k * 0.5),
],
);
}
p.vel[0] *= 0.6;
p.vel[2] *= 0.6;
p.set_sprinting(false);
if let Some(r) = &mut self.rec {
r.note("attack slow-down not representable");
}
}
}
fn server_flags(&self) -> Option<u8> {
self.server_flags
}
#[inline]
fn take_absorption(&mut self) -> Option<f32> {
std::mem::take(&mut self.absorption_dirty).then_some(self.absorption)
}
fn velocity_now(&self) -> Vec3 {
let v = self.player.vel;
Vec3::new(v[0], v[1], v[2])
}
fn entity_config(&self) -> Option<ghast_entity::Config> {
self.entities.as_ref().map(|t| t.config())
}
fn set_entities(&mut self, config: Option<ghast_entity::Config>) {
if self.entity_config() == config {
return;
}
// A tracker started after the join does not know the entities spawned before.
self.tracker_late = config.is_some() && self.session.login.is_some();
self.entities = config.map(|c| {
let mut t = ghast_entity::v1_8::Tracker::new(c);
self.session.replay(|r| {
if let Err(e) = t.apply(r) {
log::debug!("entity tracker: session packet 0x{:02x}: {e}", r.id);
}
});
t
});
}
/// `World.tickEntities`: the other entities' interpolation steps (what the next tick's
/// pick sees).
fn tick_entities(&mut self, pose: &mut Pose) {
if let Some(t) = &mut self.entities {
t.tick_client();
if !self.watched.is_empty() {
let ridden = self.ride.as_ref().map(|r| r.id);
tick_watched_mounts(&mut self.watched, t, ridden);
}
if self.piston_phase {
self.tick_piston_phase(pose);
}
}
}
fn entities_mut(&mut self) -> Option<&mut ghast_entity::Entities> {
self.entities.as_mut().map(|t| t.store_mut())
}
fn entity_packet_ids(&self) -> Vec<i32> {
self.entities
.as_ref()
.map(|t| t.packet_ids().collect())
.unwrap_or_default()
}
fn predict_air(&mut self, x: i32, y: i32, z: i32) {
self.world
.set_block_state(x, y, z, ghast_data::v1_8::BlockState::AIR);
}
fn place_sent(&mut self, p: &crate::sim::predict::PlaceSent<'_>) -> bool {
// 1.8.9: the oracle-proven rules (`ghast_data::v1_8::place`); what they do not decide
// is the server's block update
let player = self.player.bb;
let used = crate::sim::place18::sent(&mut self.world, &player, p);
log::debug!("place at {:?}: item used {used}", p.pos);
used
}
fn place_rules(
&self,
q: &crate::sim::predict::PlaceQuery<'_>,
) -> crate::sim::predict::PlaceRules {
crate::sim::place18::rules(&self.world, &self.player.bb, q)
}
fn air_use(&self, q: &crate::sim::predict::AirQuery<'_>) -> crate::sim::predict::AirAnswer {
// Some uses trace a ray of their own, which sets shared bounds moving boxes read.
self.pistons.note_use_ray();
#[cfg(test)]
let vaporizes = self.vaporizes || self.world.dimension() == -1;
#[cfg(not(test))]
let vaporizes = self.world.dimension() == -1;
let riding = self.ride.is_some()
|| self
.entities
.as_deref()
.zip(self.own_id)
.is_some_and(|(t, id)| t.iter().any(|e| e.id() == id && e.vehicle().is_some()));
crate::sim::use18::air_use(
&crate::sim::use18::Ctx {
world: &self.world,
bb: self.player.bb,
vaporizes,
entities: self.entities.as_deref(),
own_id: self.own_id,
riding,
},
q,
)
}
fn air_use_sent(&mut self, blocks: &[(BlockPos, u32)]) {
for &(p, raw) in blocks {
let s = ghast_data::v1_8::BlockState::from_raw_vanilla(raw as u16);
log::debug!("item use set {} at {p:?}", s.block().name());
if s.block().id() == 34 {
let old = self.world.block_state(p.x, p.y, p.z);
self.head_change(p.x, p.y, p.z, old, true);
}
self.world.set_block_state(p.x, p.y, p.z, s);
}
}
#[cfg(test)]
fn test_air_case(&mut self, case: &serde_json::Value) {
self.vaporizes = case["ultrawarm"].as_bool().unwrap_or(false);
}
#[cfg(test)]
fn test_tracker_from_join(&mut self) {
self.tracker_late = false;
}
fn place_suppressed(&self, pos: BlockPos, face: crate::common::Face, held: u16) -> bool {
use ghast_data::v1_8::{Block, BlockState};
// Anvils and slab items (stone, wooden, red sandstone): not decided.
const UNDECIDED: &[u16] = &[44, 126, 145, 182];
let w = &self.world;
let unit = ghast_data::Aabb {
min_x: 0.0,
min_y: 0.0,
min_z: 0.0,
max_x: 1.0,
max_y: 1.0,
max_z: 1.0,
};
crate::sim::predict::legacy_place_suppressed(
pos,
face,
held,
UNDECIDED,
|q| w.block_state(q.x, q.y, q.z).map(BlockState::raw),
|id| {
u8::try_from(id)
.ok()
.and_then(Block::from_id)
.is_some_and(|b| b.material().replaceable)
},
|id| {
let Some(b) = u8::try_from(id).ok().and_then(Block::from_id) else {
return false;
};
b.shape_dependency() == ghast_data::ShapeDependency::None
&& (0..16u8).all(|m| {
let s = BlockState::new(b, m);
!s.is_registered() || s.shape() == [unit]
})
},
&self.player.bb,
// 1.8 keeps no client positions of other entities (interpolation): not decided.
|_| false,
)
}
#[cfg(test)]
fn set_player_pos(&mut self, p: Vec3) {
self.player.set_position(p.x, p.y, p.z);
}
fn held_item(&self, id: u16, count: u8, efficiency: u8) -> HeldItem {
held_item_facts(DataSet::V1_8, id, count, efficiency)
}
fn step(
&mut self,
pose: &mut Pose,
controls: Controls,
using_item: bool,
entity_id: i32,
out: &mut Vec<Outbound>,
) {
let input = ghast_physics::TickInput {
keys: keys(controls),
yaw: pose.yaw,
pitch: pose.pitch,
using_item,
};
self.packets.clear();
if let Some(r) = &mut self.rec
&& !r.started()
{
r.start_1_8(&self.player);
}
if let Some(r) = &mut self.rec {
let w = &self.world;
r.observe(self.player.pos, |x, y, z| {
w.is_column_loaded(x >> 4, z >> 4)
.then(|| w.block_state(x, y, z).map_or(0, |s| u32::from(s.raw())))
});
}
let riding = self.ride.is_some();
if !riding {
self.jump_bar.idle();
}
if riding {
if let Some(r) = &mut self.rec {
r.note_once("riding not representable");
}
self.step_ride(&input);
} else if self.pistons.is_empty()
&& (!self.pistons.head_bounds_set() || self.heads_out_of_reach())
{
ghast_physics::v1_8::tick(&mut self.player, &input, &self.world, &mut self.packets);
} else {
self.step_pistons(&input);
}
if riding && !self.pistons.is_empty() {
if self.entities.is_some() {
self.piston_phase = true;
} else {
self.tick_piston_blocks();
}
}
if self.force_step_position != ForceStepPosition::Off && !riding {
let p = &mut self.player;
let cur = [p.pos[0], p.bb.min_y, p.pos[2]];
force_position(
&mut self.packets,
cur,
&mut p.sent.pos,
&mut p.sent.ticks_since_pos,
self.force_step_position,
);
}
if let Some(r) = &mut self.rec {
r.tick(
&input,
&crate::record::state_1_8(&self.player),
&self.packets,
);
}
push_packets(&self.packets, entity_id, out);
sync_pose(pose, &self.player);
// A moving world border advances with the client's clock.
self.world.advance_time(50);
}
}
/// Lists the piston heads within `r` blocks (a cube) of `at`.
#[cold]
#[inline(never)]
fn scan_heads(w: &ghast_world::v1_8::World, at: [i32; 3], r: i32, out: &mut Vec<[i32; 3]>) {
for x in at[0] - r..=at[0] + r {
for z in at[2] - r..=at[2] + r {
if !w.is_column_loaded(x >> 4, z >> 4) {
continue;
}
for y in (at[1] - r).max(0)..=(at[1] + r).min(255) {
if w.block_state(x, y, z).is_some_and(|s| s.block().id() == 34) {
out.push([x, y, z]);
}
}
}
}
}
/// `1 << facing` of a piston head state, else 0.
#[inline]
fn head_facing(s: Option<ghast_data::v1_8::BlockState>) -> u8 {
match s {
Some(s) if s.block().id() == 34 && s.meta() & 7 <= 5 => 1 << (s.meta() & 7),
_ => 0,
}
}
fn sync_pose(pose: &mut Pose, p: &ghast_physics::v1_8::PlayerState) {
pose.pos = Vec3::new(p.pos[0], p.bb.min_y, p.pos[2]);
pose.motion = Vec3::new(p.vel[0], p.vel[1], p.vel[2]);
pose.yaw = p.yaw;
pose.pitch = p.pitch;
pose.on_ground = p.on_ground;
pose.flying = p.abilities.flying;
pose.sneaking = p.sneaking();
pose.sprinting = p.sprinting;
}