yog-abi 0.30.7

Yog stable C ABI — the shared contract between mods and the runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
//! Yog stable C ABI — the ONLY types that cross the mod/runtime boundary.
//!
//! Rules this file must never break:
//!  - Every type is `#[repr(C)]`.
//!  - No Rust trait objects, no generics, no std types in public structs.
//!  - Adding is a minor change: new fields go at the END of structs, new
//!    callback types and functions are new names; increment `ABI_MINOR`.
//!  - Anything else is a major change: removing (clean out what's obsolete
//!    then, here, in the runtime, the hosts' JNI, yog-api), reordering,
//!    changing a type or a meaning; increment `ABI_MAJOR`, `ABI_MINOR` = 0.
//!
//! Mods and the runtime are compiled independently; the runtime loads a mod
//! of its major version and a minor no newer than its own ([`compatible`]):
//! such a mod sees a prefix of every table, all of it there.

use std::os::raw::c_void;

// ── Version ──────────────────────────────────────────────────────────────────

pub const ABI_MAJOR: u32 = 3;
pub const ABI_MINOR: u32 = 7;
/// `ABI_MAJOR * 10_000 + ABI_MINOR`.  Checked at mod load time.
pub const ABI_VERSION: u32 = ABI_MAJOR * 10_000 + ABI_MINOR;

/// Whether a mod built for ABI `version` runs on this one: the same major,
/// a minor no newer (what it knows is all here; later additions it doesn't use).
pub const fn compatible(version: u32) -> bool {
    version / 10_000 == ABI_MAJOR && version % 10_000 <= ABI_MINOR
}

// ── Primitive types ───────────────────────────────────────────────────────────

/// Borrowed UTF-8 byte slice passed to a function. NOT null-terminated.
/// Valid only for the duration of the call that provides it — never store.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YogStr {
    pub ptr: *const u8,
    pub len: u32,
}

impl YogStr {
    pub const EMPTY: Self = Self {
        ptr: std::ptr::null(),
        len: 0,
    };

    /// Borrow `s` — not `FromStr`, which can't return a borrowing value.
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn from_str(s: &str) -> Self {
        Self {
            ptr: s.as_ptr(),
            len: s.len() as u32,
        }
    }

    #[inline]
    pub fn is_empty(self) -> bool {
        self.len == 0 || self.ptr.is_null()
    }

    /// # Safety
    ///
    /// `ptr` must be valid UTF-8 of `len` bytes for at least the duration of
    /// the call that provided this `YogStr`.
    #[inline]
    pub unsafe fn as_str<'a>(self) -> &'a str {
        unsafe {
            if self.ptr.is_null() || self.len == 0 {
                return "";
            }
            std::str::from_utf8_unchecked(std::slice::from_raw_parts(self.ptr, self.len as usize))
        }
    }
}

/// Heap-allocated UTF-8 string owned by the RUNTIME.
/// `ptr == null` encodes `None` / "not found".
/// When `ptr` is non-null the caller MUST free it via `YogServer::free_str`.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YogOwnedStr {
    pub ptr: *mut u8,
    pub len: u32,
}

impl YogOwnedStr {
    pub const NONE: Self = Self {
        ptr: std::ptr::null_mut(),
        len: 0,
    };

    /// Allocate a new `YogOwnedStr` from a Rust `String`.
    pub fn from_string(s: String) -> Self {
        let len = s.len() as u32;
        let ptr = Box::into_raw(s.into_bytes().into_boxed_slice()) as *mut u8;
        Self { ptr, len }
    }

    #[inline]
    pub fn is_none(self) -> bool {
        self.ptr.is_null()
    }
}

/// Integer 3-D block position.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YogBlockPos {
    pub x: i32,
    pub y: i32,
    pub z: i32,
}

/// Float 3-D vector (position, velocity, …).
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YogVec3 {
    pub x: f64,
    pub y: f64,
    pub z: f64,
}

// ── Event structs (Java → Rust) ───────────────────────────────────────────────

#[repr(C)]
pub struct YogBlockBreakEvent {
    pub player: YogStr,
    pub block: YogStr,
    pub pos: YogBlockPos,
    /// Dimension the block was broken in, e.g. `minecraft:overworld`.
    pub dimension: YogStr,
}

#[repr(C)]
pub struct YogChatEvent {
    pub player: YogStr,
    pub message: YogStr,
    pub dimension: YogStr,
}

/// Shared by player_join and player_leave.
#[repr(C)]
pub struct YogPlayerEvent {
    pub player: YogStr,
    pub uuid: YogStr,
    pub dimension: YogStr,
}

#[repr(C)]
pub struct YogUseItemEvent {
    pub player: YogStr,
    pub item: YogStr,
    /// ABI minor 25: whether the player was sneaking (shift) during use.
    pub sneaking: bool,
    pub dimension: YogStr,
}

#[repr(C)]
pub struct YogUseBlockEvent {
    pub player: YogStr,
    pub block: YogStr,
    pub pos: YogBlockPos,
    pub dimension: YogStr,
    /// Whether the player was sneaking (shift).
    pub sneaking: bool,
}

#[repr(C)]
pub struct YogAttackEntityEvent {
    pub player: YogStr,
    pub target_type: YogStr,
    pub target_uuid: YogStr,
    pub dimension: YogStr,
}

#[repr(C)]
pub struct YogEntityDamageEvent {
    pub entity_type: YogStr,
    pub uuid: YogStr,
    pub amount: f32,
    pub source: YogStr,
    pub dimension: YogStr,
}

#[repr(C)]
pub struct YogEntityDeathEvent {
    pub entity_type: YogStr,
    pub uuid: YogStr,
    pub source: YogStr,
    pub dimension: YogStr,
}

#[repr(C)]
pub struct YogEntitySpawnEvent {
    pub entity_type: YogStr,
    pub uuid: YogStr,
    pub dimension: YogStr,
}

/// Fired when a player dies (Pre: before death is processed; Post: after death).
/// Pre phase — return false to prevent death (keep entity alive at 0.5 HP).
#[repr(C)]
pub struct YogPlayerDeathEvent {
    pub player: YogStr,
    pub uuid: YogStr,
    /// Damage source identifier, e.g. `"player"`, `"fall"`.
    pub source: YogStr,
    pub dimension: YogStr,
}

/// Fired when a player respawns after death.
#[repr(C)]
pub struct YogPlayerRespawnEvent {
    pub player: YogStr,
    pub uuid: YogStr,
    /// True if respawning at a bed or anchor, false at world spawn.
    pub at_anchor: bool,
    /// Dimension respawned into (may differ from where the player died).
    pub dimension: YogStr,
}

/// Fired when a player earns an advancement (Post only).
#[repr(C)]
pub struct YogAdvancementEvent {
    pub player: YogStr,
    pub uuid: YogStr,
    /// Namespaced id, e.g. `"minecraft:story/mine_stone"`.
    pub advancement: YogStr,
    pub dimension: YogStr,
}

/// Fired when a player right-clicks (interacts with) an entity (Pre: before; Post: after).
/// Pre phase — return false to cancel the interaction.
#[repr(C)]
pub struct YogEntityInteractEvent {
    pub player: YogStr,
    pub player_uuid: YogStr,
    pub entity_type: YogStr,
    pub entity_uuid: YogStr,
    /// `"main_hand"` or `"off_hand"`.
    pub hand: YogStr,
    pub dimension: YogStr,
}

/// Fired when a player takes a crafted item from a crafting output slot (Post only).
#[repr(C)]
pub struct YogCraftEvent {
    pub player: YogStr,
    pub player_uuid: YogStr,
    pub result_item: YogStr,
    pub result_count: u32,
    pub dimension: YogStr,
}

/// A machine (an inventory's `.yui` `<RecipeArea>`) and the recipe its
/// slots make. Pre: whether it may — the result shows only if every
/// handler allows it (a workbench short of a resource says no); `player`
/// empty. Post: a player took the result — the mod takes its share (the
/// host takes the ingredients).
#[repr(C)]
pub struct YogMachineCraftEvent {
    /// The machine's inventory, e.g. `mymod:press`.
    pub machine: YogStr,
    /// The recipe's kind and id.
    pub kind: YogStr,
    pub recipe: YogStr,
    pub result_item: YogStr,
    pub result_count: u32,
    /// The recipe's values (`{ "energy": 4 }`), as JSON.
    pub values: YogStr,
    pub pos: YogBlockPos,
    pub dimension: YogStr,
    pub player: YogStr,
}

/// Fired when an explosion occurs in a world (Pre: before block destruction; Post: after).
/// Pre phase — return false to cancel the explosion (block and entity damage suppressed).
#[repr(C)]
pub struct YogExplosionEvent {
    pub dimension: YogStr,
    pub x: f64,
    pub y: f64,
    pub z: f64,
    pub power: f32,
    /// UUID of the entity that caused the explosion, or empty if world/tnt.
    pub cause_uuid: YogStr,
}

// ── ABI minor 9–10 event structs ──────────────────────────────────────────────

/// A hopper or dropper puts an item into a block that accepts items
/// (Pre: would it take it; Post: it takes it).
#[repr(C)]
pub struct YogItemInsertEvent {
    pub block: YogStr,
    pub pos: YogBlockPos,
    pub dimension: YogStr,
    pub item_id: YogStr,
    pub count: u32,
    /// The item's data as SNBT (`{}` for none).
    pub nbt: YogStr,
}

/// Fired when a player picks up an item entity (Pre: cancellable; Post: informational).
#[repr(C)]
pub struct YogItemPickupEvent {
    pub player: YogStr,
    pub player_uuid: YogStr,
    /// Registry id of the item, e.g. `"minecraft:diamond"`.
    pub item_id: YogStr,
    pub item_count: u32,
    /// UUID of the item entity that was picked up.
    pub entity_uuid: YogStr,
    pub dimension: YogStr,
}

/// Fired when a player sends a movement packet (Post only; very high frequency).
#[repr(C)]
pub struct YogPlayerMoveEvent {
    pub player: YogStr,
    pub player_uuid: YogStr,
    pub x: f64,
    pub y: f64,
    pub z: f64,
    pub yaw: f32,
    pub pitch: f32,
    pub dimension: YogStr,
}

/// Fired when a player opens a container screen (Pre: cancellable; Post: informational).
/// `container_type` is the screen handler registry id, e.g. `"minecraft:chest"`.
/// Empty string if the type is not in the registry (e.g. the player inventory).
#[repr(C)]
pub struct YogContainerOpenEvent {
    pub player: YogStr,
    pub player_uuid: YogStr,
    pub container_type: YogStr,
    pub dimension: YogStr,
}

/// Fired when a player closes a container screen (Post only).
#[repr(C)]
pub struct YogContainerCloseEvent {
    pub player: YogStr,
    pub player_uuid: YogStr,
    pub dimension: YogStr,
}

/// Fired when a persistent projectile (arrow, trident) hits a target (Pre: cancellable).
/// Pre phase — return false to cancel the hit (projectile passes through).
#[repr(C)]
pub struct YogProjectileHitEvent {
    /// Registry id of the projectile, e.g. `"minecraft:arrow"`.
    pub projectile_type: YogStr,
    pub projectile_uuid: YogStr,
    /// UUID of the entity that shot/threw this projectile, or empty.
    pub shooter_uuid: YogStr,
    /// `"block"` or `"entity"`.
    pub hit_type: YogStr,
    /// UUID of the entity that was hit (empty for block hits).
    pub hit_entity_uuid: YogStr,
    pub x: f64,
    pub y: f64,
    pub z: f64,
    pub dimension: YogStr,
}

/// Fired when a player places a block (Pre: before placement; Post: after).
#[repr(C)]
pub struct YogPlaceBlockEvent {
    pub player: YogStr,
    pub block: YogStr,
    pub pos: YogBlockPos,
    pub dimension: YogStr,
    /// Whether the player was sneaking (shift).
    pub sneaking: bool,
}

#[repr(C)]
pub struct YogPacketEvent {
    pub channel: YogStr,
    pub player: YogStr, // empty string on client-received packets
    pub payload: *const u8,
    pub payload_len: u32,
}

#[repr(C)]
pub struct YogCommandEvent {
    pub name: YogStr,
    pub args: YogStr,
    pub source: YogStr,
    pub uuid: YogStr,
    /// Empty for console-run commands (no world).
    pub dimension: YogStr,
}

// ── ABI minor 10 client event structs ─────────────────────────────────────────

/// Key press / release / repeat from the keyboard (client-side only).
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YogKeyPressEvent {
    /// GLFW key code (e.g. `GLFW_KEY_E = 69`).
    pub key_code: i32,
    pub scan_code: i32,
    /// 0 = release, 1 = press, 2 = repeat.
    pub action: i32,
    /// Modifier bitmask: 1=shift, 2=ctrl, 4=alt, 8=super.
    pub modifiers: i32,
}

// ── Handler function-pointer types ────────────────────────────────────────────
//
// All event handlers receive a `phase: u8` argument:
//   0 = Pre  — fires before the action; return value matters (false = cancel).
//   1 = Post — fires after the action; return value is ignored.
//
// This unified signature lets one registered closure handle both phases.
//
// Client-side handlers (minor 10) do NOT receive a `YogServer*` — they run on
// the render thread and have no server context.

pub type YogBlockBreakFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogBlockBreakEvent, u8) -> bool;
pub type YogChatFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogChatEvent, u8) -> bool;
pub type YogPlayerFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogPlayerEvent, u8) -> bool;
pub type YogUseItemFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogUseItemEvent, u8) -> bool;
pub type YogUseBlockFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogUseBlockEvent, u8) -> bool;
pub type YogAttackEntityFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogAttackEntityEvent, u8) -> bool;
pub type YogEntityDamageFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogEntityDamageEvent, u8) -> bool;
pub type YogEntityDeathFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogEntityDeathEvent, u8) -> bool;
pub type YogEntitySpawnFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogEntitySpawnEvent, u8) -> bool;
pub type YogPlaceBlockFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogPlaceBlockEvent, u8) -> bool;
pub type YogPlayerDeathFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogPlayerDeathEvent, u8) -> bool;
pub type YogPlayerRespawnFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogPlayerRespawnEvent, u8) -> bool;
pub type YogAdvancementFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogAdvancementEvent, u8) -> bool;
pub type YogEntityInteractFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogEntityInteractEvent, u8) -> bool;
pub type YogCraftFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogCraftEvent, u8) -> bool;
pub type YogMachineCraftFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogMachineCraftEvent, u8) -> bool;
pub type YogExplosionFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogExplosionEvent, u8) -> bool;
pub type YogItemInsertFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogItemInsertEvent, u8) -> bool;
pub type YogItemPickupFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogItemPickupEvent, u8) -> bool;
pub type YogPlayerMoveFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogPlayerMoveEvent, u8) -> bool;
pub type YogContainerOpenFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogContainerOpenEvent, u8) -> bool;
pub type YogContainerCloseFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogContainerCloseEvent, u8) -> bool;
pub type YogProjectileHitFn =
    unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogProjectileHitEvent, u8) -> bool;

/// Packet events — always Post, no phase.
pub type YogPacketFn = unsafe extern "C" fn(*mut c_void, *const YogServer, *const YogPacketEvent);
/// Server lifecycle / tick — no event struct, always fires.
pub type YogServerFn = unsafe extern "C" fn(*mut c_void, *const YogServer);
/// A loot table rolled (`yog_registry::Loot`, Yog Data's binary form):
/// the handler writes the items it should give instead
/// (`Vec<yog_registry::LootStack>`, the same form) to `sink`, or nothing
/// to leave them.
pub type YogLootFn =
    unsafe extern "C" fn(ud: *mut c_void, server: *const YogServer, loot: *const u8, len: usize, sink: *mut c_void, write: YogBytesSink);
/// A tick of one entity of a mod's type: `(ud, server, uuid)`.
pub type YogEntityTickFn = unsafe extern "C" fn(*mut c_void, *const YogServer, YogStr);
/// Command handler.
pub type YogCommandFn = unsafe extern "C" fn(
    ud: *mut c_void,
    srv: *const YogServer,
    ev: *const YogCommandEvent,
    reply_buf: *mut u8,
    reply_cap: u32,
    reply_len: *mut u32,
);
/// Scheduler handler (once or repeating).
pub type YogScheduledFn = unsafe extern "C" fn(*mut c_void, *const YogServer);

// ── ABI minor 10 — client-side function pointer types ────────────────────────

/// Client tick — no event, no server context.
pub type YogClientFn = unsafe extern "C" fn(ud: *mut c_void);
/// UI event for a `register_ui` screen. `event_id` is one of
/// `click:X:Y`, `drag:X:Y`, `release:X:Y`, `scroll:DY` and (ABI minor 33)
/// `key:KEY:MODS` — a GLFW key code pressed or repeating, with GLFW modifier
/// bits — and `char:CODEPOINT` — a typed character (Unicode scalar value).
/// Call `YogApi::ui_consume_event` while handling `key:`/`char:` to stop the
/// host's default handling of that key (Esc closing the screen, ...).
pub type YogUIEventFn = unsafe extern "C" fn(ud: *mut c_void, ui_id: YogStr, event_id: YogStr);
/// HUD render — `gfx` is the graphics context for this frame; only valid for
/// the call duration.  `draw2d_*` functions in `gfx` work here.
pub type YogHudRenderFn = unsafe extern "C" fn(ud: *mut c_void, gfx: *const YogGfxApi);
/// A book page's picture: `data`/`len` is the page's `data` (Yog Data,
/// binary), `x, y, w, h` its box in screen pixels; `gfx` is valid for the
/// call.
pub type YogPageDrawFn = unsafe extern "C" fn(
    ud: *mut c_void,
    gfx: *const YogGfxApi,
    data: *const u8,
    len: usize,
    x: f32,
    y: f32,
    w: f32,
    h: f32,
);
/// Whether a stack of `item` with custom data `snbt` gets a tooltip
/// picture; if so its size in GUI pixels goes to `w`, `h`.
pub type YogTooltipSizeFn =
    unsafe extern "C" fn(ud: *mut c_void, item: YogStr, snbt: YogStr, w: *mut f32, h: *mut f32) -> bool;
/// Draw the tooltip picture of a stack of `item` (custom data `snbt`) in
/// the box `x, y, w, h` (screen pixels); `gfx` is valid for the call.
pub type YogTooltipDrawFn = unsafe extern "C" fn(
    ud: *mut c_void,
    gfx: *const YogGfxApi,
    item: YogStr,
    snbt: YogStr,
    x: f32,
    y: f32,
    w: f32,
    h: f32,
);
/// Where a callback writes text it gives back: `write(sink, text)`, the
/// text copied by the caller during the call.
pub type YogTextSink = unsafe extern "C" fn(sink: *mut c_void, text: YogStr);
/// The name and tooltip lines of a stack of `item` with custom data
/// `snbt`: `false` for the item's own; else one `write` of the name (empty:
/// the item's own) and the lines that stand instead of its description,
/// separated by `\n`.
/// Takes bytes a handler writes (copies them; valid for the call).
pub type YogBytesSink = unsafe extern "C" fn(sink: *mut c_void, data: *const u8, len: usize);
/// A body frame (`yog_body::Frame`, its wire form): the handler writes its
/// ops (`yog_body::Ops`) to `sink`.
pub type YogBodyFn = unsafe extern "C" fn(ud: *mut c_void, frame: *const u8, len: usize, sink: *mut c_void, write: YogBytesSink);
/// The camera this frame; the handler changes `out` (each handler sees the
/// last one's result).
pub type YogCameraFn = unsafe extern "C" fn(ud: *mut c_void, frame: *const YogCameraFrame, out: *mut YogCameraOut);
/// The local player's travel step: `true` and `velocity` set replaces it.
pub type YogTravelFn = unsafe extern "C" fn(ud: *mut c_void, frame: *const YogTravelFrame, velocity: *mut [f32; 3]) -> bool;

/// See `yog_body::CameraFrame`.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YogCameraFrame {
    pub uuid: YogStr,
    pub partial: f32,
    pub pos: [f64; 3],
    pub yaw: f32,
    pub pitch: f32,
    pub detached: bool,
    pub flags: u32,
}

/// See `yog_body::CameraOut`.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YogCameraOut {
    pub local_offset: [f32; 3],
    pub world_offset: [f32; 3],
    pub yaw: f32,
    pub pitch: f32,
    pub roll: f32,
    pub fov: f32,
}

/// See `yog_body::TravelFrame`.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YogTravelFrame {
    pub uuid: YogStr,
    pub velocity: [f32; 3],
    pub look: [f32; 3],
    pub yaw: f32,
    pub pitch: f32,
    pub forward: f32,
    pub strafe: f32,
    pub jumping: bool,
    pub sneaking: bool,
    pub gravity: f32,
    pub flags: u32,
}

pub type YogItemTextFn =
    unsafe extern "C" fn(ud: *mut c_void, item: YogStr, snbt: YogStr, sink: *mut c_void, write: YogTextSink) -> bool;
/// World render — `gfx` contains `view_proj` and `camera_pos` for 3D rendering.
/// Valid only for the call duration.
pub type YogWorldRenderFn = unsafe extern "C" fn(ud: *mut c_void, gfx: *const YogGfxApi);
/// Key press — return `false` to cancel (prevent Minecraft from processing the key).
pub type YogKeyPressFn = unsafe extern "C" fn(ud: *mut c_void, ev: *const YogKeyPressEvent) -> bool;
/// Screen event — `screen_class` is the simple class name (e.g. `"InventoryScreen"`).
/// For `on_screen_open` return `false` to prevent the screen from opening.
pub type YogScreenFn = unsafe extern "C" fn(ud: *mut c_void, screen_class: YogStr) -> bool;

// ── ABI minor 14 — low-level GPU pipeline ────────────────────────────────────

/// Low-level GPU context passed to render handlers.
///
/// Provides direct access to the OpenGL pipeline: buffer objects, vertex arrays,
/// shader programs, textures, draw calls, and render state.
///
/// The per-frame fields (`screen_w/h`, `delta_tick`, `view_proj`, `camera_pos`)
/// are filled by the runtime before calling the handler; the function pointers
/// point to statically-allocated implementations.
///
/// Valid only for the duration of the render callback — never store the pointer.
/// GPU resource **handles** (`u32`) may be stored between frames.
///
/// Colors are `0xAARRGGBB` (Minecraft convention).
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YogGfxApi {
    // ── Per-frame context ─────────────────────────────────────────────────────
    /// GUI-pixel screen width.
    pub screen_w: i32,
    /// GUI-pixel screen height.
    pub screen_h: i32,
    /// Partial-tick interpolation factor (0.0–1.0).
    pub delta_tick: f32,
    /// GUI scale factor: physical pixels per GUI pixel (e.g. 2.0 for 2× GUI scale).
    /// Useful for converting GUI-pixel coordinates to physical pixels for OpenGL calls.
    pub scale_factor: f32,
    /// View-projection matrix in camera-relative space (column-major, 16 × f32).
    /// All zeros during `on_hud_render`; filled during `on_world_render`.
    pub view_proj: [f32; 16],
    /// Camera world-space position.  All zeros during `on_hud_render`.
    pub camera_pos: [f32; 3],
    /// Local player world-space position (eye height).  All zeros during `on_hud_render`.
    /// Differs from `camera_pos` in third-person view.
    pub player_pos: [f32; 3],
    pub _pad1: f32,

    // ── GPU buffers ───────────────────────────────────────────────────────────
    /// Allocate a new GPU buffer (VBO / EBO). Returns 0 on failure.
    pub buf_create: unsafe extern "C" fn() -> u32,
    /// Delete a buffer created by `buf_create`.
    pub buf_delete: unsafe extern "C" fn(handle: u32),
    /// Upload `len` bytes from `bytes` into `handle`.
    /// `dynamic`: hints frequent updates (`GL_DYNAMIC_DRAW` vs `GL_STATIC_DRAW`).
    pub buf_data: unsafe extern "C" fn(handle: u32, bytes: *const u8, len: u32, dynamic: bool),
    /// Overwrite `len` bytes at `offset` in `handle`.
    pub buf_subdata: unsafe extern "C" fn(handle: u32, offset: u32, bytes: *const u8, len: u32),

    // ── Vertex arrays ─────────────────────────────────────────────────────────
    /// Create a vertex array object. Returns 0 on failure.
    pub vao_create: unsafe extern "C" fn() -> u32,
    /// Delete a VAO created by `vao_create`.
    pub vao_delete: unsafe extern "C" fn(handle: u32),
    /// Declare one vertex attribute in `vao`, sourced from `vbo`.
    /// `dtype`: 0=f32, 1=u8, 2=i32, 3=u32.
    pub vao_attrib: unsafe extern "C" fn(
        vao: u32,
        vbo: u32,
        index: u32,
        components: u8,
        dtype: u8,
        normalized: bool,
        stride: u32,
        offset: u32,
    ),
    /// Bind an index buffer (EBO) to `vao`.
    pub vao_set_ebo: unsafe extern "C" fn(vao: u32, ebo: u32),

    // ── Shader programs ───────────────────────────────────────────────────────
    /// Compile + link `vert_src` / `frag_src` (GLSL 150 core).
    /// Writes the program handle to `*out`. Returns false and logs on error.
    pub prog_create: unsafe extern "C" fn(vert: YogStr, frag: YogStr, out: *mut u32) -> bool,
    /// Delete a shader program.
    pub prog_delete: unsafe extern "C" fn(handle: u32),
    pub prog_uniform_1i: unsafe extern "C" fn(prog: u32, name: YogStr, v: i32),
    pub prog_uniform_1f: unsafe extern "C" fn(prog: u32, name: YogStr, v: f32),
    pub prog_uniform_2f: unsafe extern "C" fn(prog: u32, name: YogStr, x: f32, y: f32),
    pub prog_uniform_3f: unsafe extern "C" fn(prog: u32, name: YogStr, x: f32, y: f32, z: f32),
    pub prog_uniform_4f:
        unsafe extern "C" fn(prog: u32, name: YogStr, x: f32, y: f32, z: f32, w: f32),
    /// Set a mat4 uniform from 16 column-major floats.
    pub prog_uniform_mat4: unsafe extern "C" fn(prog: u32, name: YogStr, col_major: *const f32),

    // ── Textures ──────────────────────────────────────────────────────────────
    /// Upload RGBA8 pixel data as a new texture.
    /// `linear`: `GL_LINEAR` if true, `GL_NEAREST` if false.
    pub tex_create: unsafe extern "C" fn(w: u32, h: u32, rgba: *const u8, linear: bool) -> u32,
    /// Delete a texture created by `tex_create`.
    pub tex_delete: unsafe extern "C" fn(handle: u32),
    /// Bind `handle` to texture unit `unit` (0–7).
    pub tex_bind: unsafe extern "C" fn(unit: u32, handle: u32),
    /// Return the GL texture handle Minecraft uses for a namespaced resource
    /// (e.g. `"minecraft:textures/gui/icons.png"`). Returns 0 if not found.
    /// Do **not** delete handles obtained this way — Minecraft owns them.
    pub tex_from_mc: unsafe extern "C" fn(id: YogStr) -> u32,

    // ── Draw calls ────────────────────────────────────────────────────────────
    /// Draw `count` primitives from `vao`, using shader `prog`.
    /// `mode`: 0=Triangles, 1=Lines, 2=LineStrip, 3=TriangleStrip, 4=TriangleFan.
    pub draw_arrays: unsafe extern "C" fn(vao: u32, prog: u32, mode: u8, first: u32, count: u32),
    /// Draw indexed primitives.  `ebo` must be bound to `vao` via `vao_set_ebo`.
    /// `u32_idx`: `true` for `u32` indices, `false` for `u16` indices.
    pub draw_elements:
        unsafe extern "C" fn(vao: u32, ebo: u32, prog: u32, mode: u8, count: u32, u32_idx: bool),

    // ── Render state ──────────────────────────────────────────────────────────
    /// Enable/disable blending. `src`/`dst` are raw GL blend factor enum values.
    pub set_blend: unsafe extern "C" fn(enabled: bool, src: u32, dst: u32),
    /// Enable/disable depth testing and depth writes.
    pub set_depth: unsafe extern "C" fn(test: bool, write: bool),
    /// Enable the GL scissor: `x, y, w, h` in framebuffer pixels, from the
    /// bottom-left corner — for the GPU drawing here, not `draw2d_*` (the
    /// game batches 2D drawing; clip it by hand, as yog-ui does).
    pub set_scissor: unsafe extern "C" fn(x: i32, y: i32, w: i32, h: i32),
    /// Disable scissor clipping.
    pub clear_scissor: unsafe extern "C" fn(),
    /// Set the GL viewport (physical pixel coordinates).
    pub set_viewport: unsafe extern "C" fn(x: i32, y: i32, w: i32, h: i32),

    // ── 2D convenience (HUD-render only — uses MC's DrawContext) ─────────────
    /// Filled rectangle. Only valid during `on_hud_render`.
    pub draw2d_rect: unsafe extern "C" fn(x1: f32, y1: f32, x2: f32, y2: f32, color: u32),
    /// Vertical-gradient rectangle. Only valid during `on_hud_render`.
    pub draw2d_gradient:
        unsafe extern "C" fn(x1: f32, y1: f32, x2: f32, y2: f32, top: u32, bottom: u32),
    /// MC text renderer string. Only valid during `on_hud_render`.
    pub draw2d_text: unsafe extern "C" fn(text: YogStr, x: f32, y: f32, color: u32, shadow: bool),

    // ── appended in ABI minor 21 ──────────────────────────────────────────────
    /// Render an item stack (3D block models included) via MC's item renderer,
    /// like Patchouli's `renderItemStack`. `id` is a registry item id
    /// ("minecraft:crafting_table"); `size` is the on-screen size in GUI px
    /// (16 = inventory size). Only valid during `on_hud_render`.
    pub draw2d_item: unsafe extern "C" fn(id: YogStr, x: f32, y: f32, size: f32),

    // ── appended in ABI minor 33 ──────────────────────────────────────────────
    /// `draw2d_text` in the font `font` — a font id such as
    /// `"minecraft:default"`, `"minecraft:uniform"`, `"minecraft:alt"` or a
    /// resource-pack font (`"mymod:fancy"`); empty = the default font. Only
    /// valid during a render callback.
    pub draw2d_text_font:
        unsafe extern "C" fn(text: YogStr, font: YogStr, x: f32, y: f32, color: u32, shadow: bool),
    /// Width in GUI pixels of `text` drawn in `font` (empty = default), as the
    /// host's text renderer measures it. Callable from the render thread at
    /// any time (render callbacks and UI event handlers); the pointer stays
    /// valid for the life of the process.
    pub text_width: unsafe extern "C" fn(text: YogStr, font: YogStr) -> f32,

    // ── appended in ABI minor 34 ──────────────────────────────────────────────
    /// Draw the image `source` — a Yog image source (`item:apple`,
    /// `block:stone`, `sprite:button`, `mymod:gui/logo`, ...; see
    /// `yog_gfx::image`), resolved by the host for its Minecraft version —
    /// scaled into `(x, y, w, h)` (GUI pixels, nearest-neighbour). `(u, v,
    /// uw, vh)` is the part of the image to draw, in the image's own pixels;
    /// `uw <= 0` or `vh <= 0` = the whole image (items and sprites are
    /// always whole). `tint` multiplies the colors (`0xAARRGGBB`;
    /// `0xFFFFFFFF` = none; items ignore it). Only valid during a render
    /// callback.
    pub draw2d_image: unsafe extern "C" fn(
        source: YogStr,
        x: f32,
        y: f32,
        w: f32,
        h: f32,
        u: f32,
        v: f32,
        uw: f32,
        vh: f32,
        tint: u32,
    ),
    /// Natural size in GUI pixels of the image `source` (16×16 for items, a
    /// texture's pixel size, ...) into `*w`/`*h`. `false` (outputs untouched)
    /// when the source can't be resolved. Callable from the render thread at
    /// any time; the pointer stays valid for the life of the process.
    pub image_size: unsafe extern "C" fn(source: YogStr, w: *mut f32, h: *mut f32) -> bool,

    // ── ABI 1.4 ──────────────────────────────────────────────────────────────
    /// Draws the SVG document `data` scaled into `(x, y, w, h)` GUI pixels
    /// (rasterized by the host at the screen's resolution, cached).
    pub draw2d_svg: unsafe extern "C" fn(data: YogStr, x: f32, y: f32, w: f32, h: f32),
    /// Draws a living entity of type `entity` (`minecraft:zombie`) standing
    /// in `(x, y, w, h)` GUI pixels, as big as fits, turned `yaw` degrees
    /// (0 = facing the viewer) and tilted `pitch` degrees.
    pub draw2d_entity:
        unsafe extern "C" fn(entity: YogStr, x: f32, y: f32, w: f32, h: f32, yaw: f32, pitch: f32),

    // ── ABI 1.5 ──────────────────────────────────────────────────────────────
    /// Draws `text` in `font` (empty = default) at `(x, y)`, `scale` times
    /// its size.
    pub draw2d_text_scaled: unsafe extern "C" fn(
        text: YogStr,
        font: YogStr,
        x: f32,
        y: f32,
        scale: f32,
        color: u32,
        shadow: bool,
    ),
    /// Draws blocks in 3D, as big as fits in `(x, y, w, h)`: `blocks` is one
    /// `x y z state` line per block (`0 0 0 minecraft:furnace[facing=north]`),
    /// turned `yaw` degrees about the vertical and tilted `pitch` degrees.
    pub draw2d_blocks:
        unsafe extern "C" fn(blocks: YogStr, x: f32, y: f32, w: f32, h: f32, yaw: f32, pitch: f32),
}

unsafe impl Send for YogGfxApi {}
unsafe impl Sync for YogGfxApi {}

// ── Server action table (runtime → mod direction is wrong; it's mod → runtime) ─

/// All Minecraft-mutating calls available inside a handler.
///
/// `ctx` is an opaque pointer to the runtime's JNI state.  Every function takes
/// it as its first argument.  The pointer is valid for the lifetime of the process.
///
/// Strings **returned** by functions in this table are heap-allocated by the
/// runtime and must be freed with `free_str` after the caller has read them.
#[repr(C)]
pub struct YogServer {
    pub ctx: *mut c_void,
    pub abi_version: u32,
    /// `sizeof(YogServer)` at build time — allows mods compiled against an older
    /// table to detect and skip fields they don't know about.
    pub size: u32,

    /// Free a string returned by any function in this table.
    pub free_str: unsafe extern "C" fn(ptr: *mut u8, len: u32),

    // ── chat ─────────────────────────────────────────────────────────────────
    pub broadcast: unsafe extern "C" fn(ctx: *mut c_void, msg: YogStr),

    // ── world ────────────────────────────────────────────────────────────────
    pub get_block:
        unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> YogOwnedStr,
    pub set_block: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        pos: YogBlockPos,
        block: YogStr,
    ) -> bool,
    pub world_time: unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, out: *mut i64) -> bool,
    pub set_time: unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, time: i64) -> bool,
    pub is_raining: unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr) -> bool,
    pub set_weather:
        unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, raining: bool, dur: i32) -> bool,

    // ── player ───────────────────────────────────────────────────────────────
    pub give_item:
        unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, item: YogStr, count: u32) -> bool,
    pub player_teleport:
        unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, pos: YogVec3) -> bool,
    pub send_to_player: unsafe extern "C" fn(
        ctx: *mut c_void,
        player: YogStr,
        channel: YogStr,
        data: *const u8,
        len: u32,
    ) -> bool,
    pub send_to_server:
        unsafe extern "C" fn(ctx: *mut c_void, channel: YogStr, data: *const u8, len: u32) -> bool,
    pub kick_player: unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, reason: YogStr) -> bool,
    pub set_gamemode: unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, mode: YogStr) -> bool,
    pub send_title: unsafe extern "C" fn(
        ctx: *mut c_void,
        player: YogStr,
        title: YogStr,
        sub: YogStr,
        fi: i32,
        stay: i32,
        fo: i32,
    ) -> bool,
    pub send_actionbar: unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, msg: YogStr) -> bool,
    pub play_sound: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        pos: YogVec3,
        sound: YogStr,
        vol: f32,
        pitch: f32,
    ) -> bool,
    pub play_sound_player: unsafe extern "C" fn(
        ctx: *mut c_void,
        player: YogStr,
        sound: YogStr,
        vol: f32,
        pitch: f32,
    ) -> bool,

    // ── entity ───────────────────────────────────────────────────────────────
    pub entity_teleport: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, pos: YogVec3) -> bool,
    pub entity_position:
        unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, out: *mut YogVec3) -> bool,
    pub entity_health: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, out: *mut f32) -> bool,
    pub entity_set_health: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, hp: f32) -> bool,
    pub entity_kill: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr) -> bool,
    pub spawn_entity: unsafe extern "C" fn(
        ctx: *mut c_void,
        type_id: YogStr,
        dim: YogStr,
        pos: YogVec3,
    ) -> YogOwnedStr,
    pub entity_add_effect: unsafe extern "C" fn(
        ctx: *mut c_void,
        uuid: YogStr,
        fx: YogStr,
        dur: i32,
        amp: u8,
        particles: bool,
    ) -> bool,
    pub entity_remove_effect:
        unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, fx: YogStr) -> bool,
    pub entity_clear_effects: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr) -> bool,
    pub entity_velocity:
        unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, out: *mut YogVec3) -> bool,
    pub entity_set_velocity:
        unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, vel: YogVec3) -> bool,
    pub entity_add_velocity:
        unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, vel: YogVec3) -> bool,

    // ── tags & loot ──────────────────────────────────────────────────────────
    pub has_item_tag: unsafe extern "C" fn(ctx: *mut c_void, item: YogStr, tag: YogStr) -> bool,
    pub has_block_tag: unsafe extern "C" fn(ctx: *mut c_void, block: YogStr, tag: YogStr) -> bool,
    pub drop_loot:
        unsafe extern "C" fn(ctx: *mut c_void, table: YogStr, dim: YogStr, pos: YogVec3) -> bool,

    // ── scoreboard ───────────────────────────────────────────────────────────
    pub scoreboard_get:
        unsafe extern "C" fn(ctx: *mut c_void, obj: YogStr, player: YogStr, out: *mut i32) -> bool,
    pub scoreboard_set:
        unsafe extern "C" fn(ctx: *mut c_void, obj: YogStr, player: YogStr, score: i32) -> bool,
    pub scoreboard_add: unsafe extern "C" fn(
        ctx: *mut c_void,
        obj: YogStr,
        player: YogStr,
        delta: i32,
        out: *mut i32,
    ) -> bool,

    // ── boss bar ─────────────────────────────────────────────────────────────
    pub bossbar_create: unsafe extern "C" fn(
        ctx: *mut c_void,
        id: YogStr,
        title: YogStr,
        color: YogStr,
        style: YogStr,
    ) -> bool,
    pub bossbar_remove: unsafe extern "C" fn(ctx: *mut c_void, id: YogStr) -> bool,
    pub bossbar_set_title:
        unsafe extern "C" fn(ctx: *mut c_void, id: YogStr, title: YogStr) -> bool,
    pub bossbar_set_progress:
        unsafe extern "C" fn(ctx: *mut c_void, id: YogStr, progress: f32) -> bool,
    pub bossbar_set_color:
        unsafe extern "C" fn(ctx: *mut c_void, id: YogStr, color: YogStr) -> bool,
    pub bossbar_add_player:
        unsafe extern "C" fn(ctx: *mut c_void, id: YogStr, player: YogStr) -> bool,
    pub bossbar_remove_player:
        unsafe extern "C" fn(ctx: *mut c_void, id: YogStr, player: YogStr) -> bool,
    pub bossbar_set_visible:
        unsafe extern "C" fn(ctx: *mut c_void, id: YogStr, visible: bool) -> bool,

    // ── misc ─────────────────────────────────────────────────────────────────
    pub game_dir: unsafe extern "C" fn(ctx: *mut c_void) -> YogOwnedStr,

    // ── player query (ABI minor 4) ────────────────────────────────────────────
    /// Newline-separated list of online player names, or NONE if server not up.
    pub online_players: unsafe extern "C" fn(ctx: *mut c_void) -> YogOwnedStr,

    // ── block entity (NBT, ABI minor 3) ──────────────────────────────────────
    /// SNBT string of the block entity at `pos`, or NONE if there is none.
    pub get_block_nbt:
        unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> YogOwnedStr,
    /// Write SNBT into the block entity at `pos`. Returns false if no block entity exists.
    pub set_block_nbt:
        unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, pos: YogBlockPos, snbt: YogStr) -> bool,

    // ── inventory (ABI minor 3) ───────────────────────────────────────────────
    /// Tab/newline-encoded inventory: one line per occupied slot, `slot\titem_id\tcount`.
    pub player_inventory: unsafe extern "C" fn(ctx: *mut c_void, player: YogStr) -> YogOwnedStr,
    /// Set (or clear when count==0) a specific inventory slot.
    pub player_set_slot: unsafe extern "C" fn(
        ctx: *mut c_void,
        player: YogStr,
        slot: u32,
        item_id: YogStr,
        count: u32,
    ) -> bool,

    // ── inventory-backed block slots (ABI minor 25, yog-inventory) ──────────
    /// `"item_id\tcount\tsnbt"` for the given slot of the block container
    /// at `pos`, or NONE if the slot is empty / there's no container there.
    pub get_inventory_slot: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        pos: YogBlockPos,
        slot: u32,
    ) -> YogOwnedStr,
    /// Set (or clear when count==0) a slot of the block container at `pos`;
    /// `item_id` may carry the item's SNBT after a tab. Returns false if
    /// there's no container there.
    pub set_inventory_slot: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        pos: YogBlockPos,
        slot: u32,
        item_id: YogStr,
        count: u32,
    ) -> bool,

    // ── cross-dimension teleport (ABI minor 3) ────────────────────────────────
    pub player_teleport_dim:
        unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, dim: YogStr, pos: YogVec3) -> bool,
    pub entity_teleport_dim:
        unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, dim: YogStr, pos: YogVec3) -> bool,

    // ── entity counting ───────────────────────────────────────────────────────
    /// Count loaded instances of `entity_type` in `dimension`. Returns -1 on error.
    pub world_entity_count:
        unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, entity_type: YogStr) -> i32,

    // ── entity NBT (ABI minor 6) ──────────────────────────────────────────────
    /// SNBT of the entity's persistent data, or NONE if entity not found.
    pub entity_get_nbt: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr,
    /// Merge SNBT data into the entity. Returns false if entity not found.
    pub entity_set_nbt: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, snbt: YogStr) -> bool,

    // ── particles (ABI minor 6) ───────────────────────────────────────────────
    /// Spawn `count` particles at `pos` in `dim`.
    /// `dx/dy/dz` control spread, `speed` controls particle speed.
    /// Returns false if the dimension or particle type is unknown.
    pub spawn_particles: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        pos: YogVec3,
        particle_type: YogStr,
        count: i32,
        dx: f64,
        dy: f64,
        dz: f64,
        speed: f64,
    ) -> bool,

    // ── attributes (ABI minor 7) ──────────────────────────────────────────────
    /// Get the base value of an attribute on a living entity.
    /// `attribute_id` is a registry id, e.g. `"minecraft:generic.max_health"`.
    /// Returns `f64::NAN` if entity or attribute is not found.
    pub entity_attribute_get:
        unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, attribute_id: YogStr) -> f64,
    /// Set the base value of an attribute. Returns false if entity or attribute is not found.
    pub entity_attribute_set: unsafe extern "C" fn(
        ctx: *mut c_void,
        uuid: YogStr,
        attribute_id: YogStr,
        value: f64,
    ) -> bool,

    // ── held item NBT (ABI minor 11) ─────────────────────────────────────────
    /// SNBT of the item currently held in the player's main hand.
    /// Returns NONE if the player is offline or holding air.
    pub get_held_item_nbt: unsafe extern "C" fn(ctx: *mut c_void, player: YogStr) -> YogOwnedStr,
    /// Merge `snbt` data into the NBT of the player's held main-hand item in-place.
    /// Returns false if the player is offline or holding air.
    pub set_held_item_nbt:
        unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, snbt: YogStr) -> bool,

    // ── item stack query (ABI minor 12) ──────────────────────────────────────
    /// SNBT of the item in the player's off hand, or NONE if offline / holding air.
    pub get_offhand_item_nbt: unsafe extern "C" fn(ctx: *mut c_void, player: YogStr) -> YogOwnedStr,
    /// Merge `snbt` into the NBT of the player's off-hand item.
    /// Returns false if offline or holding air.
    pub set_offhand_item_nbt:
        unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, snbt: YogStr) -> bool,
    /// Full item stack at inventory `slot`: tab-separated `item_id\tcount\tsnbt`.
    /// `snbt` is `{}` when the item has no NBT. Returns NONE if offline or slot empty.
    pub get_slot_item:
        unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, slot: u32) -> YogOwnedStr,
    /// Replace inventory `slot` with an item stack. `snbt` may be empty to clear NBT.
    /// Pass `count == 0` to clear the slot (ignores `item_id` and `snbt`).
    pub set_slot_item: unsafe extern "C" fn(
        ctx: *mut c_void,
        player: YogStr,
        slot: u32,
        item_id: YogStr,
        count: u32,
        snbt: YogStr,
    ) -> bool,

    // ── entity rotation (ABI minor 25) ───────────────────────────────────────
    /// Yaw and pitch (degrees) of an entity by UUID. Returns false if the
    /// entity does not exist. `out` receives x=yaw, y=pitch, z=0.
    pub entity_rotation:
        unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, out: *mut YogVec3) -> bool,

    // ── world queries & effects (ABI minor 1) ────────────────────────────────
    // Records come back as one tab-separated line; `yog_core`'s `EntityInfo`,
    // `BlockHit`, `BlockInfo` and `PlayerInfo` document and decode them.
    /// `EntityInfo` line of a loaded entity, or NONE.
    pub entity_info: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr,
    /// Newline-separated uuids of the entities touching the box.
    pub entities_in_box: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        min: YogVec3,
        max: YogVec3,
    ) -> YogOwnedStr,
    /// `BlockHit` line of the first block on the segment, or NONE.
    pub raycast_block: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        from: YogVec3,
        to: YogVec3,
    ) -> YogOwnedStr,
    /// Uuid of the nearest entity on the segment (not `exclude`), or NONE.
    pub raycast_entity: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        from: YogVec3,
        to: YogVec3,
        exclude: YogStr,
    ) -> YogOwnedStr,
    /// `BlockInfo` line of the block at `pos`, or NONE.
    pub block_info:
        unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> YogOwnedStr,
    pub break_block: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        pos: YogBlockPos,
        drop: bool,
        breaker: YogStr,
    ) -> bool,
    pub place_block_from_slot: unsafe extern "C" fn(
        ctx: *mut c_void,
        player: YogStr,
        slot: u32,
        dim: YogStr,
        pos: YogBlockPos,
    ) -> bool,
    pub bonemeal: unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> bool,
    pub explode: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        pos: YogVec3,
        power: f32,
        fire: bool,
        source: YogStr,
    ) -> bool,
    /// `json` is a JSON text component (the `/tellraw` format).
    pub tellraw: unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, json: YogStr) -> bool,
    pub entity_damage: unsafe extern "C" fn(
        ctx: *mut c_void,
        uuid: YogStr,
        amount: f32,
        damage_type: YogStr,
        attacker: YogStr,
    ) -> bool,
    pub entity_set_fire_ticks:
        unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, ticks: i32) -> bool,
    pub player_add_xp: unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, amount: i32) -> bool,
    pub player_set_may_fly:
        unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, may_fly: bool) -> bool,
    /// `PlayerInfo` line of an online player, or NONE.
    pub player_info: unsafe extern "C" fn(ctx: *mut c_void, player: YogStr) -> YogOwnedStr,
    /// Uuid of the dropped item entity, or NONE.
    pub spawn_item: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        pos: YogVec3,
        vel: YogVec3,
        item_id: YogStr,
        count: u32,
        snbt: YogStr,
    ) -> YogOwnedStr,
    /// `item_id\tcount\tsnbt` of a dropped item entity, or NONE.
    pub item_entity_stack: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr,
    pub item_entity_set_stack: unsafe extern "C" fn(
        ctx: *mut c_void,
        uuid: YogStr,
        item_id: YogStr,
        count: u32,
        snbt: YogStr,
    ) -> bool,
    // ── ABI minor 2 ──
    /// `json` is a JSON text component.
    pub actionbar_json:
        unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, json: YogStr) -> bool,
    /// `face` is a `Direction` ordinal (down, up, north, south, west, east).
    pub use_item_on_block: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        pos: YogBlockPos,
        face: u8,
        item_id: YogStr,
        player: YogStr,
    ) -> bool,
    pub pour_fluid: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        pos: YogBlockPos,
        bucket_item_id: YogStr,
    ) -> bool,
    pub has_entity_tag:
        unsafe extern "C" fn(ctx: *mut c_void, entity_type: YogStr, tag_id: YogStr) -> bool,
    /// The block id a block item places, or NONE.
    pub item_block: unsafe extern "C" fn(ctx: *mut c_void, item_id: YogStr) -> YogOwnedStr,
    pub place_feature: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        pos: YogBlockPos,
        feature_id: YogStr,
    ) -> bool,

    // ── ABI minor 3 ──────────────────────────────────────────────────────────
    pub set_item_cooldown:
        unsafe extern "C" fn(ctx: *mut c_void, player: YogStr, item_id: YogStr, ticks: i32) -> bool,
    /// The UUID of what an entity rides, or NONE.
    pub entity_vehicle: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr,
    /// The UUIDs of what rides an entity directly, one a line (empty: none).
    pub entity_passengers: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr,
    /// Seats `rider` on `vehicle`; `force`: even one that wouldn't take it.
    pub entity_mount:
        unsafe extern "C" fn(ctx: *mut c_void, rider: YogStr, vehicle: YogStr, force: bool) -> bool,
    /// Gets an entity off what it rides.
    pub entity_dismount: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr) -> bool,
    /// Received redstone power 0–15, or -1 (no such dimension).
    pub redstone_power: unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> i32,
    /// Sets how far an entity has fallen (fall damage counts it on landing).
    pub entity_set_fall_distance: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, distance: f32) -> bool,
    /// The strongest signal the block gives off 0–15, or -1 (not a source).
    pub redstone_signal: unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> i32,
    pub set_redstone_output:
        unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, pos: YogBlockPos, level: i32) -> bool,
    /// `"ns:id[prop=value,...]"`, or NONE.
    pub get_block_state: unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> YogOwnedStr,
    pub set_block_state:
        unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, pos: YogBlockPos, state: YogStr) -> bool,
    pub world_is_thundering: unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr) -> bool,
    pub world_set_thunder:
        unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, thundering: bool, duration_ticks: i32) -> bool,
    /// Sets every block of the box `from..=to` to `state`; how many changed, or -1.
    pub fill_region: unsafe extern "C" fn(
        ctx: *mut c_void,
        dim: YogStr,
        from: YogBlockPos,
        to: YogBlockPos,
        state: YogStr,
    ) -> i32,
    /// The non-air blocks of the box `from..=to`: `"x y z state"` lines, or NONE.
    pub scan_region:
        unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, from: YogBlockPos, to: YogBlockPos) -> YogOwnedStr,

    // ── ABI 3.1 — entity dimensions ─────────────────────────────────────────
    /// An entity's own hitbox and eye height (blocks), or vanilla's again
    /// (`width` < 0); `false` if there's no such entity.
    pub entity_set_dimensions:
        unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, width: f32, height: f32, eye: f32) -> bool,

    // ── ABI 3.2 — entity data ───────────────────────────────────────────────
    /// Sets (`flags` & 1) or removes a value an entity keeps under `key`;
    /// `flags` & 2 saves it with the entity. The players who see the entity
    /// get it. `false` for an empty uuid or key.
    pub entity_data_set:
        unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, key: YogStr, data: *const u8, len: u32, flags: u32) -> bool,
    /// The value under `key`, written to `sink`; `false` if there's none.
    pub entity_data_get:
        unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, key: YogStr, sink: *mut c_void, write: YogBytesSink) -> bool,

    // ── ABI 3.5 — the world's save ──────────────────────────────────────────
    /// The directory of the world being played (its save: `saves/<world>`
    /// on a client, the level directory on a server) — where a mod keeps
    /// what belongs to this world. Free with `free_str`.
    pub world_dir: unsafe extern "C" fn(ctx: *mut c_void) -> YogOwnedStr,

    // ── ABI 3.6 — attribute values ──────────────────────────────────────────
    /// An attribute's value on a living entity — its base changed by every
    /// modifier (effects, equipment); `f64::NAN` if there's no such entity
    /// or attribute.
    pub entity_attribute_value: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, attribute_id: YogStr) -> f64,

    // ── ABI 3.7 — advancements ──────────────────────────────────────────────
    /// Awards advancement `id` to the player `uuid` (every criterion it has
    /// left); `false` if there's no such player or advancement.
    pub advancement_grant: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, id: YogStr) -> bool,
    /// Whether the player `uuid` has advancement `id`.
    pub advancement_done: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, id: YogStr) -> bool,
}

// ctx = *mut JavaVM which is global/stable. All fn ptrs are pure C-ABI.
unsafe impl Send for YogServer {}
unsafe impl Sync for YogServer {}

// ── Chunk generator callback (ABI minor 29) ───────────────────────────────────

/// Per-callback context handed to a registered chunk generator (see
/// `YogApi::register_chunk_generator`) — mirrors `YogGfxApi`'s pattern of
/// bundling per-call context with the function pointer(s) needed to act on
/// it. Valid only for the duration of the generator callback.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YogChunkWriterApi {
    /// Chunk X coordinate (in chunks, not blocks).
    pub chunk_x: i32,
    /// Chunk Z coordinate (in chunks, not blocks).
    pub chunk_z: i32,
    /// Minimum build height (world Y) for this dimension.
    pub min_y: i32,
    /// Total world height for this dimension.
    pub height: i32,
    /// Opaque host-side handle for the chunk currently being generated.
    pub ctx: *mut c_void,
    /// Set a block within this chunk column. `x`/`z` are local (0..16)
    /// chunk-relative coordinates; `y` is world-absolute.
    pub set_block:
        unsafe extern "C" fn(ctx: *mut c_void, x: i32, y: i32, z: i32, block_id: YogStr) -> bool,
}

unsafe impl Send for YogChunkWriterApi {}
unsafe impl Sync for YogChunkWriterApi {}

/// Called by the host once per chunk column that needs generating in the
/// registered dimension. `writer` is valid only for the duration of the call.
pub type YogChunkGeneratorFn =
    unsafe extern "C" fn(ud: *mut c_void, writer: *const YogChunkWriterApi);

// ── Registration table (passed to yog_mod_register) ──────────────────────────

/// Passed to `yog_mod_register`. Call the function pointers here to register
/// handlers, commands, content, and schedulers.
///
/// When mods compiled against ABI `N` load on a runtime with ABI `M > N`:
/// fields beyond `size` are not present in the mod's view — check `size` before
/// accessing fields added in later minor versions.
#[repr(C)]
pub struct YogApi {
    pub abi_version: u32,
    /// `sizeof(YogApi)` at the runtime's build time.
    pub size: u32,
    /// Opaque pointer to runtime handler storage.
    pub ctx: *mut c_void,
    /// Stable server action table — pass to handlers.
    pub server: *const YogServer,

    // ── events — all handlers receive (ud, srv, event, phase: u8) → bool ────────
    // phase 0 = Pre (return false to cancel), phase 1 = Post (return ignored).
    pub on_block_break: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogBlockBreakFn),
    pub on_chat: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogChatFn),
    pub on_player_join: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogPlayerFn),
    pub on_player_leave: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogPlayerFn),
    pub on_use_item: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogUseItemFn),
    pub on_use_block: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogUseBlockFn),
    pub on_attack_entity:
        unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogAttackEntityFn),
    pub on_entity_damage:
        unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogEntityDamageFn),
    pub on_entity_death:
        unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogEntityDeathFn),
    pub on_entity_spawn:
        unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogEntitySpawnFn),
    pub on_player_place_block:
        unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogPlaceBlockFn),
    pub on_player_death:
        unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogPlayerDeathFn),
    pub on_player_respawn:
        unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogPlayerRespawnFn),
    pub on_advancement:
        unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogAdvancementFn),
    // ── ABI minor 8 ──────────────────────────────────────────────────────────
    pub on_entity_interact:
        unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogEntityInteractFn),
    pub on_item_craft: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogCraftFn),
    pub on_explosion: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogExplosionFn),
    // ── ABI minor 9 ──────────────────────────────────────────────────────────
    pub on_item_pickup: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogItemPickupFn),
    pub on_item_insert: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogItemInsertFn),
    pub on_player_move: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogPlayerMoveFn),
    pub on_container_open:
        unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogContainerOpenFn),
    pub on_container_close:
        unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogContainerCloseFn),
    pub on_projectile_hit:
        unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogProjectileHitFn),
    pub on_server_tick: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogServerFn),
    pub on_server_started: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogServerFn),
    pub on_server_stopping: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogServerFn),

    // ── networking ───────────────────────────────────────────────────────────
    pub on_packet:
        unsafe extern "C" fn(ctx: *mut c_void, channel: YogStr, ud: *mut c_void, h: YogPacketFn),
    pub on_client_packet:
        unsafe extern "C" fn(ctx: *mut c_void, channel: YogStr, ud: *mut c_void, h: YogPacketFn),

    // ── commands ─────────────────────────────────────────────────────────────
    pub register_command:
        unsafe extern "C" fn(ctx: *mut c_void, name: YogStr, ud: *mut c_void, h: YogCommandFn),
    pub register_typed_command: unsafe extern "C" fn(
        ctx: *mut c_void,
        name: YogStr,
        schema: YogStr,
        ud: *mut c_void,
        h: YogCommandFn,
    ),

    // ── content ──────────────────────────────────────────────────────────────
    /// Register content of `kind` (`item`, `block`, `inventory`, `recipe`,
    /// `book`, `dimension`, `startup_grant`) named `id`: its definition as
    /// a Yog Data blob (`yog_data::binary`, `len` bytes at `data`), the
    /// shape of `yog_registry`'s / `yog_inventory`'s definitions, a recipe
    /// in Yog's format, a book, a dimension. One call for every kind of
    /// content — new kinds need no new ABI.
    pub register_content: unsafe extern "C" fn(ctx: *mut c_void, kind: YogStr, id: YogStr, data: *const u8, len: usize),

    // ── scheduler ────────────────────────────────────────────────────────────
    pub schedule_once: unsafe extern "C" fn(
        ctx: *mut c_void,
        delay_ticks: u64,
        ud: *mut c_void,
        h: YogScheduledFn,
    ),
    pub schedule_repeating: unsafe extern "C" fn(
        ctx: *mut c_void,
        period_ticks: u64,
        ud: *mut c_void,
        h: YogScheduledFn,
    ),

    // ── ABI minor 10 — client-side events ────────────────────────────────────
    pub on_client_tick: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogClientFn),
    pub on_hud_render: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogHudRenderFn),
    pub on_key_press: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogKeyPressFn),
    pub on_screen_open: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogScreenFn),
    pub on_screen_close: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogScreenFn),

    // ── ABI minor 14 — world render ──────────────────────────────────────────
    /// Register a handler that fires after world geometry is rendered.
    /// `gfx.view_proj` and `gfx.camera_pos` are filled; use them to project
    /// custom 3D geometry into clip space.
    pub on_world_render:
        unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, h: YogWorldRenderFn),

    // ── ABI minor 19 — UI system ──────────────────────────────────────────────
    /// Register a UI tree. `ui_id` is the unique identifier (e.g. "mymod:menu").
    /// `layout_json` is the serialized layout tree.
    /// `handler` is called when an interactive element is clicked/keyed.
    pub register_ui: unsafe extern "C" fn(
        ctx: *mut c_void,
        ui_id: YogStr,
        layout_json: YogStr,
        ud: *mut c_void,
        h: YogUIEventFn,
    ),

    // ── ABI minor 20 — per-UI screen renderer ────────────────────────────────
    /// Register a render callback that fires during `YogUIScreen.render()` for a
    /// specific UI id — i.e. AFTER the screen darkening, unlike `on_hud_render`.
    /// Reuses `YogHudRenderFn` (`fn(ud, gfx)`); `gfx.screen_w/h` are set.
    /// Clicks are forwarded as `"click:X:Y"` events to the `register_ui` handler
    /// so mods can do their own hit-testing with their stored layout.
    pub on_ui_render:
        unsafe extern "C" fn(ctx: *mut c_void, ui_id: YogStr, ud: *mut c_void, h: YogHudRenderFn),

    // ── ABI minor 22 — menu entry registration ──────────────────────────────
    /// Register a button/link that the host renders on vanilla screens
    /// (TitleScreen on Fabric, ModListScreen on Forge/NeoForge).
    /// `label` is the human-readable button text (e.g. "Yog Mods").
    /// `ui_id` is the Yog UI to open when clicked (e.g. "example:menu").
    pub register_menu_entry: unsafe extern "C" fn(ctx: *mut c_void, label: YogStr, ui_id: YogStr),

    // ── ABI minor 23 — installed mods listing ───────────────────────────────
    /// All installed mods as TSV, one per line:
    /// `source \t id \t name \t version \t authors \t description`
    /// where `source` is `yog` (a .yog mod) or `platform` (a loader mod, e.g.
    /// a Fabric/Forge jar). Tabs and newlines inside fields become spaces.
    /// Callable at any time after registration (also client-side).
    pub mods_list: unsafe extern "C" fn(ctx: *mut c_void) -> YogOwnedStr,
    /// Free a `YogOwnedStr` returned by an api-table call (same allocator as
    /// `YogServer::free_str`).
    pub free_str: unsafe extern "C" fn(ptr: *mut u8, len: u32),

    // ── ABI minor 24 — open a Yog UI screen ─────────────────────────────────
    /// Open the Yog UI registered as `ui_id` on the client (schedules onto the
    /// render thread). Client-side only; a no-op on dedicated servers.
    /// `modal` blocks game input; `pause` pauses a singleplayer game.
    pub ui_open: unsafe extern "C" fn(ctx: *mut c_void, ui_id: YogStr, modal: bool, pause: bool),

    // ── ABI minor 26 — inter-mod communication ─────────────────────────────
    /// Export a function pointer under `symbol` for the calling mod (`mod_id`).
    /// Other mods can import it via `interop_import`.
    pub interop_export:
        unsafe extern "C" fn(ctx: *mut c_void, mod_id: YogStr, symbol: YogStr, ptr: *const c_void),
    /// Import a function pointer exported by `mod_id` under `symbol`.
    /// Returns null if the symbol is not (yet) registered.
    pub interop_import:
        unsafe extern "C" fn(ctx: *mut c_void, mod_id: YogStr, symbol: YogStr) -> *const c_void,

    // ── ABI minor 29 — custom dimensions ────────────────────────────────────
    /// Register a chunk generator for a previously-declared dimension `id`.
    /// `handler` is called once per chunk column that needs generating —
    /// see `YogChunkWriterApi`/`YogChunkGeneratorFn`.
    pub register_chunk_generator:
        unsafe extern "C" fn(ctx: *mut c_void, id: YogStr, ud: *mut c_void, h: YogChunkGeneratorFn),

    // ── ABI minor 33 — closing Yog UI screens, consuming UI key events ──────
    /// Close the Yog UI screen showing `ui_id` (empty = whichever Yog UI
    /// screen is open). Scheduled onto the render thread, so it's safe to
    /// call from that screen's own event handler. Client-side only.
    pub ui_close: unsafe extern "C" fn(ctx: *mut c_void, ui_id: YogStr),
    /// Called from inside a `register_ui` handler while it handles a `key:`
    /// or `char:` event: the mod used the key, so the host skips its default
    /// handling (Esc closing the screen, Tab focus navigation, ...).
    pub ui_consume_event: unsafe extern "C" fn(ctx: *mut c_void),

    // ── ABI minor 33 — translations ─────────────────────────────────────────
    /// The text of translation key `key` (e.g. `mymod.screen.title`) in the
    /// game's current language, from the loaded lang files — resource packs
    /// and `.yog` mods' `assets/<ns>/lang/*.json` (compiled from `.yres`).
    /// `YogOwnedStr::NONE` when no language defines the key. Format
    /// specifiers (`%s`, `%1$s`) come back as-is. Free with `free_str`.
    /// Client-side; a dedicated server only knows `en_us`.
    pub translate: unsafe extern "C" fn(ctx: *mut c_void, key: YogStr) -> YogOwnedStr,

    // ── ABI minor 1 — client: screen flags, sounds, held items, keys ────────
    /// Like `ui_open`, with [`ui_flags`] bits: `MODAL`, `PAUSE`,
    /// `NO_BACKGROUND` (no dimmed/blurred world behind the screen).
    /// Client-side only.
    pub ui_open_flags: unsafe extern "C" fn(ctx: *mut c_void, ui_id: YogStr, flags: u32),
    /// Play sound event `sound_id` for the local player only: at the
    /// player's position, or (`looping`) as a loop that follows the player
    /// until `client_stop_sound`. Returns a handle (0 = failed).
    pub client_play_sound: unsafe extern "C" fn(
        ctx: *mut c_void,
        sound_id: YogStr,
        volume: f32,
        pitch: f32,
        looping: bool,
    ) -> u32,
    /// Stop a sound started by `client_play_sound` (0 or unknown: no-op).
    pub client_stop_sound: unsafe extern "C" fn(ctx: *mut c_void, handle: u32),
    /// Item id in the local player's main hand (`off_hand` false) or off
    /// hand, `YogOwnedStr::NONE` for air or no player. Free with `free_str`.
    pub client_held_item: unsafe extern "C" fn(ctx: *mut c_void, off_hand: bool) -> YogOwnedStr,
    /// Tints the block at `pos` in `dim` on this client (its faces with a
    /// tint index), `color` 0xRRGGBB; -1 clears it.
    pub client_set_block_tint: unsafe extern "C" fn(ctx: *mut c_void, dim: YogStr, pos: YogBlockPos, color: i64),
    /// Whether GLFW key `key` is held down right now (client window).
    pub client_key_down: unsafe extern "C" fn(ctx: *mut c_void, key: i32) -> bool,

    // ── ABI 2.1 — book pages drawn by mods ──────────────────────────────────
    /// Draw the pictures of book pages of type `drawn` whose `drawer` is
    /// `drawer` (`hexcasting:pattern`) — see [`YogPageDrawFn`].
    pub on_book_page:
        unsafe extern "C" fn(ctx: *mut c_void, drawer: YogStr, ud: *mut c_void, f: YogPageDrawFn),

    // ── ABI 2.2 — pictures in item tooltips ─────────────────────────────────
    /// A picture under the tooltip of item `item` (Hex Casting's scrolls
    /// show their pattern): `size` says whether a stack gets one and how
    /// big, `draw` draws it — see [`YogTooltipSizeFn`], [`YogTooltipDrawFn`].
    pub on_item_tooltip: unsafe extern "C" fn(
        ctx: *mut c_void,
        item: YogStr,
        ud: *mut c_void,
        size: YogTooltipSizeFn,
        draw: YogTooltipDrawFn,
    ),

    // ── ABI 2.3 — other mods ────────────────────────────────────────────────
    /// Whether mod `id` is loaded — a Yog mod or a Java one (Fabric's,
    /// Forge's or NeoForge's mod list).
    pub is_mod_loaded: unsafe extern "C" fn(ctx: *mut c_void, id: YogStr) -> bool,
    /// Calls into a Java mod's API by reflection: `expr` is a chain from a
    /// class — `virtuoel.pehkui.api.ScaleTypes.BASE.getScaleData($0).getScale()`
    /// — `$n` the `n`-th of `args`, a list in Yog Data text (an entity is
    /// `@entity:<uuid>`). The result in Yog Data text, or
    /// [`YogOwnedStr::NONE`] when the call failed (said in the log).
    /// Free with `free_str`.
    pub java_call: unsafe extern "C" fn(ctx: *mut c_void, expr: YogStr, args: YogStr) -> YogOwnedStr,

    // ── ABI 2.4 — a stack's own name and tooltip ────────────────────────────
    /// The name and tooltip lines of stacks of `item` from its custom data
    /// (a written blueprint shows its design) — see [`YogItemTextFn`].
    pub on_item_text: unsafe extern "C" fn(ctx: *mut c_void, item: YogStr, ud: *mut c_void, f: YogItemTextFn),

    // ── ABI 2.5 — machines ──────────────────────────────────────────────────
    /// A machine making a recipe — see [`YogMachineCraftEvent`].
    pub on_machine_craft: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, f: YogMachineCraftFn),

    // ── ABI 3.0 — bodies, camera, movement (yog-body) ───────────────────────
    /// Asks the mods about entity `uuid`'s body each frame (`on`) or not.
    pub client_body_track: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, on: bool),
    /// The same for every entity of type `entity_type`.
    pub client_body_track_type: unsafe extern "C" fn(ctx: *mut c_void, entity_type: YogStr, on: bool),
    /// The body of a tracked entity, each frame — see [`YogBodyFn`].
    pub on_body: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, f: YogBodyFn),
    /// The camera, each frame — see [`YogCameraFn`].
    pub on_camera: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, f: YogCameraFn),
    /// The local player's travel step, each tick — see [`YogTravelFn`].
    pub on_travel: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, f: YogTravelFn),

    // ── ABI 3.1 — entity dimensions (client) ────────────────────────────────
    /// This client's side of `entity_set_dimensions` (the local player
    /// collides with it); `width` < 0 gives vanilla's back.
    pub client_set_dimensions: unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, width: f32, height: f32, eye: f32),

    // ── ABI 3.2 — entity data (client) ──────────────────────────────────────
    /// What this client was told the entity keeps under `key`, written to
    /// `sink`; `false` if nothing.
    pub client_entity_data:
        unsafe extern "C" fn(ctx: *mut c_void, uuid: YogStr, key: YogStr, sink: *mut c_void, write: YogBytesSink) -> bool,

    // ── ABI 3.3 — mod entities ──────────────────────────────────────────────
    /// Each tick of every entity of `entity_type` (a mod's, with `ticks`).
    pub on_entity_tick: unsafe extern "C" fn(ctx: *mut c_void, entity_type: YogStr, ud: *mut c_void, f: YogEntityTickFn),

    // ── ABI 3.4 — loot ──────────────────────────────────────────────────────
    /// Every loot table rolled — a chest's, a block's drops, a mob's — before
    /// its items are given: see [`YogLootFn`]. Each handler sees the last
    /// one's items.
    pub on_loot: unsafe extern "C" fn(ctx: *mut c_void, ud: *mut c_void, f: YogLootFn),

    // ── ABI 3.6 — attribute values (client) ─────────────────────────────────
    /// An attribute's value on this client's player (a casting grid's size
    /// from an effect, say); `f64::NAN` without a player or attribute.
    pub client_attribute_value: unsafe extern "C" fn(ctx: *mut c_void, attribute_id: YogStr) -> f64,

    // ── ABI 3.7 — advancements (client) ─────────────────────────────────────
    /// Whether this client's player has advancement `id` (what a book's
    /// locked entries wait for).
    pub client_advancement_done: unsafe extern "C" fn(ctx: *mut c_void, id: YogStr) -> bool,
}

/// Flag bits for [`YogApi::ui_open_flags`].
pub mod ui_flags {
    /// Blocks game input (what `ui_open`'s `modal` does).
    pub const MODAL: u32 = 1;
    /// Pauses a singleplayer game.
    pub const PAUSE: u32 = 1 << 1;
    /// Draws no background behind the screen: the world stays visible.
    pub const NO_BACKGROUND: u32 = 1 << 2;
}

unsafe impl Send for YogApi {}
unsafe impl Sync for YogApi {}

#[cfg(test)]
mod tests {
    use super::*;
    use std::mem::{align_of, size_of};

    /// Sizes and alignments of every type crossing the ABI, folded together.
    fn layout_fingerprint() -> u64 {
        macro_rules! layouts {
            ($($t:ty),* $(,)?) => { [$((stringify!($t), size_of::<$t>(), align_of::<$t>())),*] };
        }
        let all = layouts!(
            YogStr, YogOwnedStr, YogBlockPos, YogVec3, YogBlockBreakEvent, YogChatEvent, YogPlayerEvent,
            YogUseItemEvent, YogUseBlockEvent, YogAttackEntityEvent, YogEntityDamageEvent, YogEntityDeathEvent,
            YogEntitySpawnEvent, YogPlayerDeathEvent, YogPlayerRespawnEvent, YogAdvancementEvent,
            YogEntityInteractEvent, YogCraftEvent, YogExplosionEvent, YogItemPickupEvent, YogItemInsertEvent, YogPlayerMoveEvent,
            YogContainerOpenEvent, YogContainerCloseEvent, YogProjectileHitEvent, YogPlaceBlockEvent,
            YogPacketEvent, YogCommandEvent,
            YogKeyPressEvent, YogGfxApi, YogServer, YogChunkWriterApi, YogApi,
        );
        // FNV-1a over (name, size, align).
        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
        for (name, size, align) in all {
            for b in name.bytes().chain((size as u64).to_le_bytes()).chain((align as u64).to_le_bytes()) {
                h = (h ^ b as u64).wrapping_mul(0x0100_0000_01b3);
            }
        }
        h
    }

    /// A type crossing the ABI changed without `ABI_VERSION` changing: bump
    /// `ABI_MINOR` (fields appended at the end) or `ABI_MAJOR` (anything
    /// else), then record the new fingerprint here.
    #[test]
    #[cfg(target_pointer_width = "64")]
    fn the_layout_matches_its_version() {
        assert_eq!((ABI_VERSION, layout_fingerprint()), (30007, 0x932a_1f5e_aa4f_7b94), "layout fingerprint: {:#x}", layout_fingerprint());
    }

    #[test]
    fn older_minors_of_the_major_are_compatible() {
        assert!(compatible(ABI_VERSION));
        assert!(compatible(ABI_MAJOR * 10_000));
        assert!(!compatible(ABI_VERSION + 1), "a newer minor may use what isn't here");
        assert!(!compatible((ABI_MAJOR - 1) * 10_000 + ABI_MINOR), "another major");
        assert!(!compatible((ABI_MAJOR + 1) * 10_000));
    }

    #[test]
    fn strings_cross_and_come_back() {
        let s = YogStr::from_str("Ünïcode ✓");
        assert_eq!(unsafe { s.as_str() }, "Ünïcode ✓");
        assert!(YogStr::EMPTY.is_empty());
        assert_eq!(unsafe { YogStr::EMPTY.as_str() }, "");
        let owned = YogOwnedStr::from_string("runtime".to_string());
        assert!(!owned.is_none() && owned.len == 7);
        assert!(YogOwnedStr::NONE.is_none());
        // What `free_str` does with it.
        drop(unsafe { Box::from_raw(std::ptr::slice_from_raw_parts_mut(owned.ptr, owned.len as usize)) });
    }
}