nightshade-api 0.46.0

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

use crate::scene::{Body, Object, Shape};
use nightshade::prelude::{Entity, KeyCode, MouseButton, TextAlignment, Vec3, World, vec3};
use serde::{Deserialize, Serialize};

/// How a command names an entity: an existing [`Entity`](crate::prelude::Entity) a reply handed back, or
/// the entity produced by an earlier command in the same [`submit_commands`]
/// batch. `Entity` is itself serializable and stable, so a binding stores it and
/// hands it back verbatim, no separate handle type needed.
#[derive(Serialize, Deserialize, Clone, Copy, Debug, enum2schema::Schema)]
pub enum Ref {
    Entity(#[schema(with = entity_schema)] Entity),
    Result(u32),
    /// A live entity named by its id alone, resolved against the world at
    /// dispatch. Lets a caller reference an existing entity without tracking
    /// its generation, which is what a picked editor selection or a script's
    /// entity handle has.
    Existing(u32),
}

/// What a [`Command`] returns. Setters reply [`CommandReply::None`], spawns reply
/// the [`Entity`](crate::prelude::Entity) they made, queries reply their value, and a failed reference
/// resolution replies [`CommandReply::Error`].
#[derive(Serialize, Deserialize, Clone, Debug, enum2schema::Schema)]
pub enum CommandReply {
    None,
    Entity(#[schema(with = entity_schema)] Entity),
    Bool(bool),
    Float(f32),
    Int(i64),
    Text(String),
    Vector([f32; 3]),
    Entities(#[schema(with = entities_schema)] Vec<Entity>),
    Strings(Vec<String>),
    Bytes(Vec<u8>),
    /// A structured value (a struct, array, or object) serialized as json, for
    /// the queries whose result does not fit a scalar reply: an entity
    /// description, the scene tree, a material, bounds, and so on. A binding
    /// deserializes it into its own shape.
    Json(#[schema(with = any_schema)] enum2schema::serde_json::Value),
    Error(String),
}

/// One field of a [`Command`] as data: its name, its Rust type as written, and
/// the dispatch role that says how the value is bound. Emitted by the same
/// registry that defines the commands, so a binding generator reads the surface
/// from a compiled artifact instead of parsing source.
#[derive(Serialize, Clone, Debug)]
pub struct FieldSpec {
    pub name: &'static str,
    pub type_name: &'static str,
    pub role: &'static str,
}

/// One [`Command`] as data: its variant name, fields, reply kind, and a one-line
/// description of what it does. A binding generator emits the description as a
/// doc comment so every language surface is documented from one source.
#[derive(Serialize, Clone, Debug)]
pub struct CommandSpec {
    pub name: &'static str,
    pub fields: Vec<FieldSpec>,
    pub reply: &'static str,
    pub description: &'static str,
}

/// [`command_manifest`] as a json string, the input a binding code generator
/// reads alongside [`command_schema`].
pub fn command_manifest_json() -> String {
    enum2schema::serde_json::to_string(&command_manifest()).unwrap_or_default()
}

fn entity_schema() -> enum2schema::serde_json::Value {
    enum2schema::serde_json::json!({
        "type": "object",
        "properties": {
            "id": { "type": "integer" },
            "generation": { "type": "integer" }
        },
        "required": ["id", "generation"]
    })
}

fn entities_schema() -> enum2schema::serde_json::Value {
    enum2schema::serde_json::json!({ "type": "array", "items": entity_schema() })
}

fn any_schema() -> enum2schema::serde_json::Value {
    enum2schema::serde_json::json!({})
}

/// The json schema for [`Command`], the wire form a binding builds. Derived from
/// the command enum by the same registry that defines it, so it always matches
/// the surface. Pair with [`command_reply_schema`] for the output shape.
pub fn command_schema() -> enum2schema::serde_json::Value {
    <Command as enum2schema::Schema>::schema()
}

/// The json schema for [`CommandReply`], what a binding reads back.
pub fn command_reply_schema() -> enum2schema::serde_json::Value {
    <CommandReply as enum2schema::Schema>::schema()
}

/// Runs one command and returns its reply.
pub fn submit_command(world: &mut World, command: &Command) -> CommandReply {
    dispatch(world, command, &[])
}

/// Runs a batch in order and returns one reply per command. A command may name
/// an entity an earlier command in the same batch produced with [`Ref::Result`],
/// so a batch can spawn entities and then configure and parent them in one call.
pub fn submit_commands(world: &mut World, commands: &[Command]) -> Vec<CommandReply> {
    let mut produced: Vec<Option<Entity>> = Vec::with_capacity(commands.len());
    let mut replies = Vec::with_capacity(commands.len());
    for command in commands {
        let reply = dispatch(world, command, &produced);
        produced.push(match &reply {
            CommandReply::Entity(entity) => Some(*entity),
            _ => None,
        });
        replies.push(reply);
    }
    replies
}

fn resolve(world: &World, reference: Ref, produced: &[Option<Entity>]) -> Option<Entity> {
    match reference {
        Ref::Entity(entity) => Some(entity),
        Ref::Result(index) => produced.get(index as usize).copied().flatten(),
        Ref::Existing(id) => world
            .core
            .entity_locations
            .get(id)
            .filter(|location| location.allocated)
            .map(|location| Entity {
                id,
                generation: location.generation,
            }),
    }
}

fn array_to_vec3(values: [f32; 3]) -> Vec3 {
    vec3(values[0], values[1], values[2])
}

fn array_to_vec2(values: [f32; 2]) -> nightshade::prelude::Vec2 {
    nightshade::prelude::vec2(values[0], values[1])
}

/// Adapts the flat command fields to [`spawn_object`](crate::scene::spawn_object),
/// which takes an [`Object`] struct. The dispatch macro calls functions with
/// positional arguments, so the one command that builds a struct goes through
/// this rather than special casing the macro.
fn spawn_object_command(
    world: &mut World,
    shape: Shape,
    position: Vec3,
    scale: Vec3,
    color: [f32; 4],
    body: Body,
) -> Entity {
    crate::scene::spawn_object(
        world,
        Object {
            shape,
            position,
            scale,
            color,
            body,
        },
    )
}

/// Wire form of an [`InstanceTransform`](nightshade::prelude::InstanceTransform)
/// for the instancing commands: a position, a rotation quaternion as
/// `[x, y, z, w]`, and a scale.
#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, enum2schema::Schema)]
pub struct InstanceWire {
    pub position: [f32; 3],
    pub rotation: [f32; 4],
    pub scale: [f32; 3],
}

fn instance_from_wire(wire: &InstanceWire) -> nightshade::prelude::InstanceTransform {
    use nightshade::prelude::nalgebra_glm::Quat;
    nightshade::prelude::InstanceTransform::new(
        array_to_vec3(wire.position),
        Quat::new(
            wire.rotation[3],
            wire.rotation[0],
            wire.rotation[1],
            wire.rotation[2],
        ),
        array_to_vec3(wire.scale),
    )
}

fn register_material_command(
    world: &mut World,
    name: &str,
    base_color: [f32; 4],
    metallic: f32,
    roughness: f32,
    emissive: [f32; 3],
) -> String {
    crate::materials::register_material(
        world,
        name,
        nightshade::ecs::material::components::Material {
            base_color,
            metallic,
            roughness,
            emissive_factor: emissive,
            ..Default::default()
        },
    )
}

fn spawn_objects_command(
    world: &mut World,
    shape: Shape,
    scale: Vec3,
    color: [f32; 4],
    body: Body,
    positions: &[Vec3],
) -> Vec<Entity> {
    crate::scene::spawn_objects(
        world,
        Object {
            shape,
            position: vec3(0.0, 0.0, 0.0),
            scale,
            color,
            body,
        },
        positions,
    )
}

#[cfg(feature = "navmesh")]
#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, enum2schema::Schema)]
pub struct RecastConfigWire {
    pub agent_radius: f32,
    pub agent_height: f32,
    pub cell_size_fraction: f32,
    pub cell_height_fraction: f32,
    pub walkable_climb: f32,
    pub walkable_slope_angle: f32,
    pub min_region_size: u32,
    pub merge_region_size: u32,
    pub max_simplification_error: f32,
    pub edge_max_len_factor: u32,
    pub max_vertices_per_polygon: u32,
    pub detail_sample_dist: f32,
    pub detail_sample_max_error: f32,
}

#[cfg(feature = "navmesh")]
fn bake_navmesh_with_command(world: &mut World, config: RecastConfigWire) {
    crate::navigation::bake_navmesh_with(
        world,
        &nightshade::prelude::RecastNavMeshConfig {
            agent_radius: config.agent_radius,
            agent_height: config.agent_height,
            cell_size_fraction: config.cell_size_fraction,
            cell_height_fraction: config.cell_height_fraction,
            walkable_climb: config.walkable_climb,
            walkable_slope_angle: config.walkable_slope_angle,
            min_region_size: config.min_region_size as u16,
            merge_region_size: config.merge_region_size as u16,
            max_simplification_error: config.max_simplification_error,
            edge_max_len_factor: config.edge_max_len_factor as u16,
            max_vertices_per_polygon: config.max_vertices_per_polygon as u16,
            detail_sample_dist: config.detail_sample_dist,
            detail_sample_max_error: config.detail_sample_max_error,
        },
    );
}

/// Wire form of a curated [`ParticleEmitter`](nightshade::prelude::ParticleEmitter):
/// the common knobs, with a single base color expanded into an explosion
/// gradient. The Rust `spawn_particle_emitter` takes the full struct for finer
/// control.
#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, enum2schema::Schema)]
pub struct EmitterWire {
    pub position: [f32; 3],
    pub color: [f32; 3],
    pub spawn_rate: f32,
    pub burst_count: u32,
    pub lifetime: [f32; 2],
    pub size: [f32; 2],
    pub gravity: [f32; 3],
    pub drag: f32,
    pub one_shot: bool,
}

fn emitter_from_wire(wire: &EmitterWire) -> nightshade::prelude::ParticleEmitter {
    let mut emitter = nightshade::prelude::ParticleEmitter::firework_explosion(
        array_to_vec3(wire.position),
        array_to_vec3(wire.color),
        wire.burst_count,
    );
    emitter.spawn_rate = wire.spawn_rate;
    emitter.particle_lifetime_min = wire.lifetime[0];
    emitter.particle_lifetime_max = wire.lifetime[1];
    emitter.size_start = wire.size[0];
    emitter.size_end = wire.size[1];
    emitter.gravity = array_to_vec3(wire.gravity);
    emitter.drag = wire.drag;
    emitter.one_shot = wire.one_shot;
    emitter.enabled = true;
    emitter
}

fn spawn_particle_emitter_command(world: &mut World, emitter: EmitterWire) -> Entity {
    crate::effects::spawn_particle_emitter(world, emitter_from_wire(&emitter))
}

fn set_emitter_command(world: &mut World, emitter_entity: Entity, emitter: EmitterWire) {
    crate::effects::set_emitter(world, emitter_entity, emitter_from_wire(&emitter));
}

fn update_material_command(
    world: &mut World,
    name: &str,
    base_color: [f32; 4],
    metallic: f32,
    roughness: f32,
    emissive: [f32; 3],
) {
    crate::materials::update_material(
        world,
        name,
        nightshade::ecs::material::components::Material {
            base_color,
            metallic,
            roughness,
            emissive_factor: emissive,
            ..Default::default()
        },
    );
}

fn set_material_variant_command(world: &mut World, variant: &str) -> usize {
    let variant = if variant.is_empty() {
        None
    } else {
        Some(variant)
    };
    crate::materials::set_material_variant(world, variant)
}

fn set_fog_command(world: &mut World, enabled: bool, color: [f32; 3], start: f32, end: f32) {
    let fog = if enabled {
        Some(nightshade::ecs::graphics::resources::Fog { color, start, end })
    } else {
        None
    };
    crate::environment::set_fog(world, fog);
}

fn set_depth_of_field_command(
    world: &mut World,
    enabled: bool,
    focus_distance: f32,
    focus_range: f32,
    max_blur_radius: f32,
    bokeh_threshold: f32,
) {
    crate::environment::set_depth_of_field(
        world,
        nightshade::ecs::graphics::resources::DepthOfField {
            enabled,
            focus_distance,
            focus_range,
            max_blur_radius,
            bokeh_threshold,
            ..Default::default()
        },
    );
}

fn panel_data_grid_command(
    world: &mut World,
    panel: Entity,
    headers: &[&str],
    widths: &[f32],
    pool_size: usize,
) -> Entity {
    let columns: Vec<(&str, f32)> = headers
        .iter()
        .zip(widths.iter())
        .map(|(header, width)| (*header, *width))
        .collect();
    crate::ui::panel_data_grid(world, panel, &columns, pool_size)
}

fn panel_selectable_command(
    world: &mut World,
    panel: Entity,
    text: &str,
    group: u32,
    grouped: bool,
) -> Entity {
    crate::ui::panel_selectable(world, panel, text, grouped.then_some(group))
}

fn panel_splitter_command(
    world: &mut World,
    panel: Entity,
    horizontal: bool,
    ratio: f32,
) -> Entity {
    let direction = if horizontal {
        nightshade::prelude::SplitDirection::Horizontal
    } else {
        nightshade::prelude::SplitDirection::Vertical
    };
    crate::ui::panel_splitter(world, panel, direction, ratio)
}

fn screenshot_command(world: &mut World, path: &str) {
    crate::environment::screenshot(world, std::path::PathBuf::from(path));
}

fn easing_from_name(name: &str) -> nightshade::prelude::EasingFunction {
    use nightshade::prelude::EasingFunction::*;
    match name.to_ascii_lowercase().as_str() {
        "quadin" => QuadIn,
        "quadout" => QuadOut,
        "quadinout" => QuadInOut,
        "cubicin" => CubicIn,
        "cubicout" => CubicOut,
        "cubicinout" => CubicInOut,
        "quartin" => QuartIn,
        "quartout" => QuartOut,
        "quartinout" => QuartInOut,
        "quintin" => QuintIn,
        "quintout" => QuintOut,
        "quintinout" => QuintInOut,
        "sinein" => SineIn,
        "sineout" => SineOut,
        "sineinout" => SineInOut,
        "expoin" => ExpoIn,
        "expoout" => ExpoOut,
        "expoinout" => ExpoInOut,
        _ => Linear,
    }
}

fn animate_position_command(
    world: &mut World,
    entity: Entity,
    to: Vec3,
    seconds: f32,
    easing: &str,
) {
    crate::animate::animate_position(world, entity, to, seconds, easing_from_name(easing));
}

fn animate_scale_command(world: &mut World, entity: Entity, to: Vec3, seconds: f32, easing: &str) {
    crate::animate::animate_scale(world, entity, to, seconds, easing_from_name(easing));
}

fn animate_color_command(
    world: &mut World,
    entity: Entity,
    to: [f32; 4],
    seconds: f32,
    easing: &str,
) {
    crate::animate::animate_color(world, entity, to, seconds, easing_from_name(easing));
}

fn set_shading_mode_command(world: &mut World, mode: &str) {
    use nightshade::prelude::ShadingMode;
    let mode = match mode.to_ascii_lowercase().as_str() {
        "wireframe" => ShadingMode::Wireframe,
        "flat" => ShadingMode::Flat,
        "rendered" => ShadingMode::Rendered,
        _ => ShadingMode::Solid,
    };
    crate::camera::set_shading_mode(world, mode);
}

#[cfg(feature = "physics")]
#[derive(Serialize)]
struct RaycastResultWire {
    entity_id: u32,
    distance: f32,
    point: [f32; 3],
    normal: [f32; 3],
}

#[cfg(feature = "physics")]
fn raycast_command(
    world: &mut World,
    origin: Vec3,
    direction: Vec3,
    max_distance: f32,
) -> Option<RaycastResultWire> {
    crate::physics::raycast(world, origin, direction, max_distance).map(|hit| RaycastResultWire {
        entity_id: hit.entity.id,
        distance: hit.distance,
        point: [hit.point.x, hit.point.y, hit.point.z],
        normal: [hit.normal.x, hit.normal.y, hit.normal.z],
    })
}

#[cfg(feature = "physics")]
fn attach_fixed_command(world: &mut World, parent: Entity, child: Entity) -> bool {
    crate::physics::attach_fixed(world, parent, child).is_some()
}

#[cfg(feature = "physics")]
fn attach_hinge_command(world: &mut World, parent: Entity, child: Entity, axis: &str) -> bool {
    use nightshade::ecs::physics::joints::JointAxisDirection;
    let axis = match axis.to_ascii_lowercase().as_str() {
        "y" => JointAxisDirection::Y,
        "z" => JointAxisDirection::Z,
        _ => JointAxisDirection::X,
    };
    crate::physics::attach_hinge(world, parent, child, axis).is_some()
}

#[cfg(feature = "physics")]
fn attach_spring_command(
    world: &mut World,
    parent: Entity,
    child: Entity,
    rest_length: f32,
    stiffness: f32,
    damping: f32,
) -> bool {
    crate::physics::attach_spring(world, parent, child, rest_length, stiffness, damping).is_some()
}

#[cfg(feature = "physics")]
fn attach_rope_command(
    world: &mut World,
    parent: Entity,
    child: Entity,
    max_distance: f32,
) -> bool {
    crate::physics::attach_rope(world, parent, child, max_distance).is_some()
}

#[cfg(feature = "picking")]
#[derive(Serialize)]
struct SurfacePickWire {
    world_position: [f32; 3],
    world_normal: [f32; 3],
    depth: f32,
    entity_id: Option<u32>,
}

#[cfg(feature = "picking")]
fn take_surface_pick_command(world: &mut World) -> Option<SurfacePickWire> {
    crate::picking::take_surface_pick(world).map(|result| SurfacePickWire {
        world_position: [
            result.world_position.x,
            result.world_position.y,
            result.world_position.z,
        ],
        world_normal: [
            result.world_normal.x,
            result.world_normal.y,
            result.world_normal.z,
        ],
        depth: result.depth,
        entity_id: result.entity_id,
    })
}

fn save_scene_command(world: &mut World, name: &str) -> Vec<u8> {
    crate::serialize::save_scene(world, name).unwrap_or_default()
}

fn load_scene_command(world: &mut World, bytes: &[u8]) -> Vec<Entity> {
    crate::serialize::load_scene(world, bytes).unwrap_or_default()
}

/// Maps a plain key name to a [`KeyCode`](crate::prelude::KeyCode) for the input-query commands, so the
/// wire form names keys as strings like `"a"`, `"space"`, or `"left"` rather
/// than carrying the engine's key enum.
fn key_from_name(name: &str) -> Option<KeyCode> {
    let lower = name.to_ascii_lowercase();
    Some(match lower.as_str() {
        "a" => KeyCode::KeyA,
        "b" => KeyCode::KeyB,
        "c" => KeyCode::KeyC,
        "d" => KeyCode::KeyD,
        "e" => KeyCode::KeyE,
        "f" => KeyCode::KeyF,
        "g" => KeyCode::KeyG,
        "h" => KeyCode::KeyH,
        "i" => KeyCode::KeyI,
        "j" => KeyCode::KeyJ,
        "k" => KeyCode::KeyK,
        "l" => KeyCode::KeyL,
        "m" => KeyCode::KeyM,
        "n" => KeyCode::KeyN,
        "o" => KeyCode::KeyO,
        "p" => KeyCode::KeyP,
        "q" => KeyCode::KeyQ,
        "r" => KeyCode::KeyR,
        "s" => KeyCode::KeyS,
        "t" => KeyCode::KeyT,
        "u" => KeyCode::KeyU,
        "v" => KeyCode::KeyV,
        "w" => KeyCode::KeyW,
        "x" => KeyCode::KeyX,
        "y" => KeyCode::KeyY,
        "z" => KeyCode::KeyZ,
        "0" => KeyCode::Digit0,
        "1" => KeyCode::Digit1,
        "2" => KeyCode::Digit2,
        "3" => KeyCode::Digit3,
        "4" => KeyCode::Digit4,
        "5" => KeyCode::Digit5,
        "6" => KeyCode::Digit6,
        "7" => KeyCode::Digit7,
        "8" => KeyCode::Digit8,
        "9" => KeyCode::Digit9,
        "space" => KeyCode::Space,
        "enter" | "return" => KeyCode::Enter,
        "escape" | "esc" => KeyCode::Escape,
        "tab" => KeyCode::Tab,
        "backspace" => KeyCode::Backspace,
        "delete" => KeyCode::Delete,
        "left" => KeyCode::ArrowLeft,
        "right" => KeyCode::ArrowRight,
        "up" => KeyCode::ArrowUp,
        "down" => KeyCode::ArrowDown,
        "shift" | "lshift" => KeyCode::ShiftLeft,
        "rshift" => KeyCode::ShiftRight,
        "ctrl" | "control" | "lctrl" => KeyCode::ControlLeft,
        "rctrl" => KeyCode::ControlRight,
        "alt" | "lalt" => KeyCode::AltLeft,
        "ralt" => KeyCode::AltRight,
        _ => return None,
    })
}

/// Maps a button index to a [`MouseButton`](crate::prelude::MouseButton): 0 left, 1 middle, 2 right.
fn mouse_button_from_index(index: u8) -> MouseButton {
    match index {
        1 => MouseButton::Middle,
        2 => MouseButton::Right,
        _ => MouseButton::Left,
    }
}

fn key_down_command(world: &World, key: &str) -> bool {
    key_from_name(key)
        .map(|key| crate::input::key_down(world, key))
        .unwrap_or(false)
}

fn key_pressed_command(world: &World, key: &str) -> bool {
    key_from_name(key)
        .map(|key| crate::input::key_pressed(world, key))
        .unwrap_or(false)
}

fn mouse_down_command(world: &World, button: u8) -> bool {
    crate::input::mouse_down(world, mouse_button_from_index(button))
}

fn mouse_clicked_command(world: &World, button: u8) -> bool {
    crate::input::mouse_clicked(world, mouse_button_from_index(button))
}

macro_rules! bind_argument {
    ($field:ident, entity, $produced:ident, $world:ident) => {
        let $field = match resolve($world, *$field, $produced) {
            Some(entity) => entity,
            None => {
                return CommandReply::Error(
                    concat!(stringify!($field), ": unresolved entity reference").to_string(),
                );
            }
        };
    };
    ($field:ident, opt_entity, $produced:ident, $world:ident) => {
        let $field = match $field {
            Some(reference) => match resolve($world, *reference, $produced) {
                Some(entity) => Some(entity),
                None => {
                    return CommandReply::Error(
                        concat!(stringify!($field), ": unresolved entity reference").to_string(),
                    );
                }
            },
            None => None,
        };
    };
    ($field:ident, vec3, $produced:ident, $world:ident) => {
        let $field = array_to_vec3(*$field);
    };
    ($field:ident, vec2, $produced:ident, $world:ident) => {
        let $field = array_to_vec2(*$field);
    };
    ($field:ident, copy, $produced:ident, $world:ident) => {
        let $field = *$field;
    };
    ($field:ident, owned, $produced:ident, $world:ident) => {
        let $field = $field.clone();
    };
    ($field:ident, text, $produced:ident, $world:ident) => {
        let $field = $field.as_str();
    };
    ($field:ident, bytes, $produced:ident, $world:ident) => {
        let $field = $field.as_slice();
    };
    ($field:ident, strs, $produced:ident, $world:ident) => {
        let $field: Vec<&str> = $field.iter().map(|value| value.as_str()).collect();
        let $field = $field.as_slice();
    };
    ($field:ident, vec3_list, $produced:ident, $world:ident) => {
        let $field: Vec<Vec3> = $field.iter().map(|value| array_to_vec3(*value)).collect();
        let $field = $field.as_slice();
    };
    ($field:ident, floats, $produced:ident, $world:ident) => {
        let $field = $field.as_slice();
    };
    ($field:ident, indices, $produced:ident, $world:ident) => {
        let $field: Vec<usize> = $field.iter().map(|value| *value as usize).collect();
        let $field = $field.as_slice();
    };
    ($field:ident, opt_vec3, $produced:ident, $world:ident) => {
        let $field = (*$field).map(array_to_vec3);
    };
    ($field:ident, transforms, $produced:ident, $world:ident) => {
        let $field: Vec<nightshade::prelude::InstanceTransform> =
            $field.iter().map(instance_from_wire).collect();
    };
    ($field:ident, refs, $produced:ident, $world:ident) => {
        let mut resolved = Vec::with_capacity($field.len());
        for reference in $field.iter() {
            match resolve($world, *reference, $produced) {
                Some(entity) => resolved.push(entity),
                None => {
                    return CommandReply::Error(
                        concat!(stringify!($field), ": unresolved entity reference").to_string(),
                    );
                }
            }
        }
        let $field = resolved.as_slice();
    };
}

macro_rules! wrap_reply {
    (none, $call:expr) => {{
        $call;
        CommandReply::None
    }};
    (entity, $call:expr) => {
        CommandReply::Entity($call)
    };
    (opt_entity, $call:expr) => {
        match $call {
            Some(entity) => CommandReply::Entity(entity),
            None => CommandReply::None,
        }
    };
    (bool, $call:expr) => {
        CommandReply::Bool($call)
    };
    (float, $call:expr) => {
        CommandReply::Float($call)
    };
    (vector, $call:expr) => {{
        let value = $call;
        CommandReply::Vector([value.x, value.y, value.z])
    }};
    (opt_vector, $call:expr) => {
        match $call {
            Some(value) => CommandReply::Vector([value.x, value.y, value.z]),
            None => CommandReply::None,
        }
    };
    (entities, $call:expr) => {
        CommandReply::Entities($call)
    };
    (strings, $call:expr) => {
        CommandReply::Strings($call)
    };
    (int, $call:expr) => {
        CommandReply::Int($call as i64)
    };
    (text, $call:expr) => {
        CommandReply::Text($call)
    };
    (bytes, $call:expr) => {
        CommandReply::Bytes($call)
    };
    (json, $call:expr) => {
        CommandReply::Json(
            enum2schema::serde_json::to_value($call)
                .unwrap_or(enum2schema::serde_json::Value::Null),
        )
    };
}

/// The rhai method name a command variant is called by: its name in snake_case,
/// with acronym runs kept together and a digit split off after a letter, so
/// `SpawnCube` becomes `spawn_cube`, `SetIblIntensity` becomes
/// `set_ibl_intensity`, and `DrawText3d` becomes `draw_text_3d`. A tool that
/// highlights or documents the script surface uses this to map a
/// [`CommandSpec`] name to the identifier a script actually writes.
#[cfg(feature = "scripting")]
pub fn command_method_name(variant: &str) -> String {
    let characters: Vec<char> = variant.chars().collect();
    let mut name = String::new();
    for index in 0..characters.len() {
        let character = characters[index];
        if character.is_uppercase() {
            let previous_lower = index > 0
                && (characters[index - 1].is_lowercase() || characters[index - 1].is_ascii_digit());
            let previous_upper = index > 0 && characters[index - 1].is_uppercase();
            let next_lower = index + 1 < characters.len() && characters[index + 1].is_lowercase();
            if index != 0 && (previous_lower || (previous_upper && next_lower)) {
                name.push('_');
            }
            name.extend(character.to_lowercase());
        } else if character.is_ascii_digit() {
            if index > 0 && characters[index - 1].is_alphabetic() {
                name.push('_');
            }
            name.push(character);
        } else {
            name.push(character);
        }
    }
    name
}

/// Wraps a command's named fields in the `{ Variant: { fields } }` shape the
/// script command collector deserializes into a typed [`Command`], identical to
/// what the map-literal form produces.
#[cfg(feature = "scripting")]
fn command_method_map(name: &str, pairs: Vec<(&'static str, rhai::Dynamic)>) -> rhai::Dynamic {
    let mut fields = rhai::Map::new();
    for (key, value) in pairs {
        fields.insert(key.into(), value);
    }
    let mut outer = rhai::Map::new();
    outer.insert(name.into(), rhai::Dynamic::from_map(fields));
    rhai::Dynamic::from_map(outer)
}

/// A one-line description of what each command does, keyed by variant name.
/// Generated from the command registry, surfaced through [`command_manifest`] so
/// every binding documents its surface from one source. A command with no entry
/// reads as empty, which the `every_command_has_a_description` test forbids.
fn command_description(variant: &str) -> &'static str {
    match variant {
        "SpawnCube" => "Spawn a cube at the given position",
        "SpawnSphere" => "Spawn a sphere at the given position",
        "SpawnCylinder" => "Spawn a cylinder at the given position",
        "SpawnCone" => "Spawn a cone at the given position",
        "SpawnPlane" => "Spawn a plane at the given position",
        "SpawnTorus" => "Spawn a torus at the given position",
        "SpawnFloor" => "Spawn a flat ground plane reaching the half extent in each direction",
        "SpawnGroup" => "Spawn an invisible group at a position for building hierarchies",
        "SpawnModel" => "Spawn a glb model with its textures, materials, skins, and animations",
        "SpawnObject" => "Spawn an object with mesh, color, and optional physics body in one call",
        "SetColor" => "Set the entity's base color as linear RGBA",
        "SetMetallicRoughness" => "Set the entity's metallic and roughness factors",
        "SetEmissive" => "Make the entity glow with the given color and strength",
        "SetUnlit" => "Disable lighting on the entity so its color renders as is",
        "SetTexture" => "Set the entity's base color texture by name",
        "SetTextureTiling" => {
            "Tile the entity's base color texture the given number of times per axis"
        }
        "SetNormalTexture" => "Set the entity's normal map by texture name",
        "SetMetallicRoughnessTexture" => {
            "Set the entity's metallic and roughness map by texture name"
        }
        "SetEmissiveTexture" => "Set the entity's emissive map by texture name",
        "SetOcclusionTexture" => "Set the entity's ambient occlusion map by texture name",
        "SetPosition" => "Set the entity's position in its parent's space",
        "SetScale" => "Set the entity's scale",
        "SetRotation" => "Replace the entity's rotation with the given angle around an axis",
        "Rotate" => "Rotate the entity around an axis on top of its current rotation",
        "Position" => "Get the entity's position in world space",
        "SetParent" => "Parent a child to a parent or unparent it, keeping its world position",
        "SetVisible" => "Show or hide the entity without despawning it",
        "Despawn" => "Despawn the entity and its descendants",
        "Tag" => "Tag the entity with a label",
        "Untag" => "Remove a label from the entity",
        "HasTag" => "Check whether the entity carries the label",
        "QueryTagged" => "Get every entity carrying the label",
        "PointLight" => "Add a point light at the given position",
        "SpotLight" => "Add a shadow casting spot light aimed at a target",
        "SetSun" => "Adjust the default sun's color and intensity",
        "SetBackground" => "Set the scene background",
        "ShowGrid" => "Show or hide the reference grid",
        "SetAmbient" => "Set the ambient light color as linear RGBA",
        "SetBloom" => "Toggle bloom",
        "SetBloomIntensity" => "Set the bloom strength",
        "SetSsao" => "Toggle screen-space ambient occlusion",
        "SetSsr" => "Toggle screen-space reflections on glossy surfaces",
        "SetSsgi" => "Toggle screen-space global illumination",
        "SetFxaa" => "Toggle FXAA full-screen antialiasing",
        "SetExposure" => "Set the manual exposure multiplier",
        "SetColorGrading" => "Set saturation, contrast, and brightness color grading",
        "SetTimeOfDay" => "Set the hour of the day from 0 to 24",
        "SetTitle" => "Set the window title",
        "EmitFire" => "Emit a continuous fire at the given position",
        "EmitSmoke" => "Emit a continuous smoke column at the given position",
        "EmitBurst" => "Emit a one-shot burst of colored particles at the given position",
        "DrawCube" => "Draw a cube with the given size and color for one frame",
        "DrawSphere" => "Draw a sphere with the given radius and color for one frame",
        "DrawCylinder" => "Draw an upright cylinder with the given size and color for one frame",
        "DrawCone" => "Draw an upright cone with the given size and color for one frame",
        "DrawTorus" => "Draw a flat torus with the given size and color for one frame",
        "DrawLine" => "Draw a line from start to end for one frame",
        "DrawText3d" => "Draw billboard text at a 3d position for one frame",
        "SpawnLabel" => "Spawn 3d text at a position that always faces the camera",
        "SpawnText" => "Spawn screen text at the given anchor",
        "SetText" => "Replace the content of a text entity",
        "SetTextColor" => "Set a text entity's color as linear RGBA",
        "SetTextSize" => "Set a text entity's font size",
        "SpawnPanel" => {
            "Spawn an empty panel anchored to a window corner or center, sized in pixels"
        }
        "PanelLabel" => "Add a line of text to a panel",
        "PanelButton" => "Add a themed button to a panel",
        "ButtonClicked" => "Check whether the button was clicked this frame",
        "ButtonHovered" => "Check whether the pointer is over the button",
        "DespawnPanel" => "Remove a panel and everything in it",
        "PanelRow" => "Add a horizontal row to a panel",
        "PanelGrid" => "Add a fixed-column grid to a panel",
        "PanelScroll" => "Add a scrollable region to a panel and return its content container",
        "SetScrollOffset" => "Scroll a panel-scroll region to a pixel offset from the top",
        "SetFocusOrder" => "Set a widget's keyboard focus order",
        "FocusWidget" => "Give keyboard focus to a widget immediately",
        "SpawnPanelAt" => {
            "Spawn a panel at any of the nine screen positions with a pixel offset and size"
        }
        "PanelText" => "Add a text label to a parent in a pixel rectangle with alignment",
        "PanelBox" => "Add a solid colored rectangle to a parent at a pixel offset and size",
        "PanelButtonAt" => "Add an interactive button to a parent at a pixel offset and size",
        "SetPanelRect" => "Reposition and resize a UI node within its parent, in pixels",
        "SetPanelColor" => "Set a UI node's background color as linear RGBA",
        "SetPanelText" => "Replace a panel text label's content",
        "SetPanelTextColor" => "Recolor a panel text label",
        "SetPanelSelected" => "Toggle a button's selected highlight with an accent tint",
        "SetPanelVisible" => "Show or hide a UI node and its children",
        "PlayAnimation" => "Start playing the model's animation clip at the given index",
        "PlayAnimationNamed" => "Play the animation clip with the given name",
        "SetAnimationLooping" => "Set whether the entity's current animation repeats",
        "SetAnimationSpeed" => "Set the playback speed of the entity's animation",
        "BlendToAnimation" => "Cross-fade from the current clip to another over the given seconds",
        "PauseAnimation" => "Pause the entity's animation at the current frame",
        "ResumeAnimation" => "Resume a paused animation from where it left off",
        "StopAnimation" => "Stop the entity's animation and reset it to the first frame",
        "AnimationClips" => "Get the names of the entity's animation clips in index order",
        "AddAnimationEvent" => "Add a named marker at a time on the clip at the given index",
        "AddAnimationEventNamed" => "Add a named marker at a time on the clip with the given name",
        "SetAnimationLayerWeight" => "Set the blend weight of an animation layer",
        "ClearAnimationLayers" => "Remove every animation layer, leaving only the base animation",
        "AimAt" => "Point a bone's forward axis at a world target, recomputed each frame",
        "OrbitCamera" => "Add an orbit camera focused on a point at the given radius",
        "FlyCamera" => "Add a free-flying camera at the given position",
        "FixedCamera" => "Add a stationary camera at an eye looking at a target",
        "LookAt" => "Repoint the active camera to look at a target from an eye",
        "SetOrbitFocus" => "Move the orbit camera's focus point",
        "SetOrbitView" => "Set the orbit camera's focus, distance, yaw, and pitch at once",
        "SetOrbitZoom" => "Enable or disable scroll-wheel zoom on the orbit camera",
        "SetOrbitModifier" => {
            "Set the modifier key the orbit camera requires before drag orbits, or clear it"
        }
        "SetFieldOfView" => "Set the active perspective camera's vertical field of view in degrees",
        "SetOrthographic" => "Switch the active camera to an orthographic projection",
        "SetPerspective" => "Switch the active camera to a perspective projection",
        "CameraPosition" => "Get the active camera's world position",
        "CameraForward" => "Get the active camera's forward direction as a unit vector",
        "FirstPerson" => {
            "Add a walking first-person player with mouse look, WASD, sprint, and jump"
        }
        "DeltaTime" => "Get the seconds the previous frame took",
        "ElapsedSeconds" => "Get the seconds since the app started",
        "KeyDown" => "Check whether a key is held down",
        "KeyPressed" => "Check whether a key went down this frame",
        "MouseDown" => "Check whether a mouse button is held down",
        "MouseClicked" => "Check whether a mouse button went down this frame",
        "Wasd" => "Get the WASD movement direction on the ground plane",
        "PointerOverUi" => "Check whether the pointer is over a UI element this frame",
        "MouseScroll" => "Get the scroll wheel delta this frame",
        "Push" => "Apply an instant impulse to a dynamic entity",
        "SetVelocity" => "Set a dynamic body's linear velocity directly",
        "ApplyForce" => "Apply a continuous force to a dynamic entity for this step",
        "ApplyTorque" => "Apply a continuous torque to a dynamic entity for this step",
        "SetAngularVelocity" => "Set a dynamic body's angular velocity directly",
        "Velocity" => "Get the entity's current linear velocity if it has a body",
        "AngularVelocity" => "Get the entity's current angular velocity if it has a body",
        "MakeSensor" => "Turn the entity's collider into an overlap-reporting sensor",
        "OverlapSphere" => "Get every entity whose collider overlaps a sphere",
        "SetCollisionGroups" => "Set the entity collider's membership and filter collision masks",
        "SetFriction" => "Set an entity collider's friction",
        "SetRestitution" => "Set an entity collider's restitution or bounciness",
        "SetLinearDamping" => "Set a dynamic body's linear damping",
        "SetAngularDamping" => "Set a dynamic body's angular damping",
        "SetMass" => "Set a dynamic body's mass in kilograms",
        "SetGravityScale" => "Set a body's per-body gravity multiplier",
        "BakeNavmesh" => "Bake a navmesh over the current static geometry",
        "SpawnWalker" => "Spawn a navmesh agent that walks to ordered destinations",
        "WalkTo" => "Order an agent to walk to a destination along the navmesh",
        "SetWalkSpeed" => "Set an agent's walk speed in units per second",
        "StopWalking" => "Stop an agent where it stands and clear its path",
        "ClickedEntity" => "Get the entity clicked this frame, if any",
        "EntityUnderCursor" => "Get the entity currently under the cursor, if any",
        "CursorOnGround" => "Get where the cursor ray meets the ground plane, if it does",
        "SpawnWorldPanel" => "Spawn a flat panel in the 3d world facing the camera",
        "WorldPanelButton" => "Add a button to a world panel at local coordinates",
        "WorldPanelLabel" => "Add a text label to a world panel at local coordinates",
        "WorldButtonClicked" => "Check whether a world-panel button was clicked this frame",
        "PauseSound" => "Pause a playing sound, keeping its position",
        "ResumeSound" => "Resume a paused sound from where it stopped",
        "FadeVolume" => "Fade a playing sound to a target volume over the given seconds",
        "Crossfade" => "Crossfade between two sounds over the given seconds",
        "SetBusVolume" => "Set an audio bus's volume in decibels, fading over seconds",
        "DuckVoice" => "Duck the music and ambient buses under the voice bus",
        "DirectionalLight" => {
            "Add a directional light shining along a direction, like a second sun"
        }
        "AreaLight" => "Add a rectangular area light, a glowing panel facing a target",
        "SetLightShadows" => "Turn shadow casting on or off for a light entity",
        "EmitSparks" => "Emit a continuous fountain of bright sparks at the given position",
        "EmitFirework" => "Launch a firework shell that arcs and bursts on its own",
        "EmitParticles" => "Spawn a configurable continuous emitter at the given position",
        "SetAlphaBlend" => "Turn alpha blending on or off for the entity",
        "SetAlphaCutoff" => "Switch the entity to alpha cutout, discarding texels below the cutoff",
        "SetDoubleSided" => "Render both faces of the entity's triangles",
        "SetIor" => "Set the index of refraction for the entity's surface",
        "SetTransmission" => "Set how much light passes through the entity",
        "SetClearcoat" => "Add a clearcoat layer over the entity with its own factor and roughness",
        "SetAnisotropy" => "Set anisotropic reflection stretching highlights along a rotation",
        "SetUvTransform" => "Transform the entity's base color texture coordinates",
        "SetSheen" => "Add a soft retroreflective sheen tint to the entity",
        "SetIridescence" => "Add a thin-film iridescence to the entity",
        "SetSpecular" => "Set the entity's specular reflectance factor and tint",
        "SetNormalScale" => "Scale the strength of the entity's normal map",
        "SetOcclusionStrength" => {
            "Scale how strongly the entity's ambient occlusion map darkens it"
        }
        "SetEmissiveStrength" => "Set the entity's emissive strength on its own",
        "SetThickness" => "Set the volume thickness of a transmissive entity",
        "SetTextOutline" => "Set a 3d text or label entity's outline width and color",
        "SetMorphWeight" => "Set one morph target's weight on an entity by index",
        "SetWindowTitle" => "Set the OS window title",
        "LockCursor" => "Lock the cursor to the window for mouse-look, or release it",
        "RequestExit" => "Ask the app to exit at the end of the frame",
        "SetRenderLayer" => "Put an entity on a render layer cameras can selectively show",
        "SetCameraLayers" => "Set which render layers a camera sees as a bitmask",
        "ThirdPersonCamera" => "Add a third-person camera trailing a target at a distance",
        "SpawnCloth" => "Spawn a cloth grid hanging from a position, pinned along its top edge",
        "ResetCloth" => "Reset a cloth back to its spawned shape, clearing all motion",
        "SetWind" => "Set a global wind force on all cloth",
        "PauseCutscene" => "Pause the running cutscene timeline",
        "ResumeCutscene" => "Resume a paused cutscene",
        "StopCutscene" => "Stop the cutscene and clear it",
        "SeekCutscene" => "Jump the cutscene to the given time along its timeline",
        "SetCutsceneCamera" => "Set the camera the cutscene drives",
        "BindCutsceneActor" => "Bind a named cutscene track to an entity it animates",
        "SpawnCylinderBody" => "Spawn a dynamic cylinder physics body at the given position",
        "SpawnCapsuleBody" => "Spawn a dynamic capsule physics body at the given position",
        "SetControllerSpeed" => "Set a character controller's move speed in units per second",
        "SetControllerJump" => "Set a character controller's jump impulse",
        "IsGrounded" => "Check whether a character controller is grounded this frame",
        "EnableTerrain" => "Turn on procedural terrain seeded by the given value",
        "DisableTerrain" => "Turn off procedural terrain",
        "SetTerrainHeightRange" => "Set the terrain's minimum and maximum height in world units",
        "SetTerrainSnowHeight" => "Set the elevation above which terrain turns to snow",
        "EnableGrass" => "Turn on procedural grass over the terrain",
        "DisableGrass" => "Turn off procedural grass",
        "LoadTexture" => "Register a texture from encoded png or jpeg bytes",
        "LoadTextureLinear" => {
            "Register a linear-space texture for normal, metallic-roughness, or occlusion data"
        }
        "RegisterTexture" => "Register a texture from raw RGBA8 pixels",
        "ListMaterials" => "Get every registered material name",
        "GetMaterial" => "Get a registered material's properties by name",
        "RegisterMaterial" => "Register a named material in the shared registry",
        "UpdateMaterial" => "Replace the material registered under a name and reupload it",
        "SetMaterialVariant" => "Activate a material variant by name across the scene",
        "SpawnObjects" => "Spawn one object at each position, all sharing one material",
        "SpawnInstanced" => {
            "Spawn one entity rendering many copies of a shape in a single draw call"
        }
        "SpawnInstancedWithMaterial" => {
            "Spawn an instanced mesh drawing every transform with a named material"
        }
        "SetInstances" => {
            "Replace an instanced batch's transforms and reupload its instance buffer"
        }
        "SpawnClothSheet" => "Spawn a simulated cloth sheet hanging from a position, pinned on top",
        "BlendToAnimationNamed" => "Cross-fade to a named clip over the given seconds",
        "AddAnimationLayer" => "Play an extra clip on top of the base animation at a weight",
        "NameEntity" => "Register an entity under a name so it can be looked up",
        "Name" => "Get the entity's name, or a stable fallback when it has none",
        "SetEntityName" => "Rename the entity",
        "Children" => "Get the entity's direct children in id order",
        "Descendants" => "Get the entity's whole subtree below it",
        "Roots" => "Get every parentless transform entity in id order",
        "SceneTree" => "Get the whole transform hierarchy flattened depth-first",
        "MaterialOf" => "Get the entity's resolved material as json",
        "GetColor" => "Get the entity's base color as linear RGBA",
        "GetMetallicRoughness" => "Get the entity's metallic and roughness factors",
        "GetEmissive" => "Get the entity's emissive color and strength",
        "GetUnlit" => "Check whether the entity renders unlit",
        "GetTexture" => "Get the entity's base color texture name, if any",
        "DescribeEntity" => "Get a summary of the entity as json",
        "SetTextAlignment" => "Set the horizontal alignment of a 3d text or label entity",
        "SetMorphWeights" => "Set every morph weight at once in target order",
        "MorphWeight" => "Get one morph target's weight by index",
        "MorphTargetCount" => "Get the number of morph targets the entity has",
        "SetFog" => "Enable distance fog between a start and end, or disable it",
        "SetDepthOfField" => "Set depth of field focus and blur parameters",
        "Screenshot" => "Save a screenshot of the next rendered frame to a path as png",
        "SetShadingMode" => "Set the active camera's shading mode",
        "AnimatePosition" => "Glide the entity to a target position over the given seconds",
        "AnimateScale" => "Grow or shrink the entity to a target scale over the given seconds",
        "AnimateColor" => "Fade the entity's base color to a target over the given seconds",
        "ShakeCamera" => "Shake the camera for a duration at the given strength",
        "ReachTo" => "Bend a three-joint chain so the tip reaches a world target",
        "Bounds" => "Get an entity's world-space bounding box as json",
        "BoundsOf" => "Get the combined world-space bounding box of several entities",
        "FrameEntities" => "Frame the given entities in view, moving the camera to fit them",
        "SpawnParticleEmitter" => "Spawn a fully configured particle emitter",
        "SetEmitter" => "Replace a spawned emitter's configuration",
        "SpawnDecal" => "Project a texture onto the surface at a position facing a normal",
        "SaveScene" => "Capture the world to a self-contained compressed binary scene",
        "LoadScene" => "Spawn a saved scene into the world and return its root entities",
        "WindowSize" => "Get the window's inner size in physical pixels",
        "CursorLocked" => "Check whether the cursor is currently locked",
        "FramesPerSecond" => "Get the current frames per second",
        "FrameCount" => "Get the number of frames rendered since startup",
        "UptimeMilliseconds" => "Get the milliseconds since the app started",
        "BakeNavmeshWith" => "Bake the navmesh with an explicit Recast configuration",
        "Raycast" => "Cast a ray against all physics colliders and return the closest hit",
        "AttachFixed" => "Weld two bodies together rigidly",
        "AttachHinge" => "Hinge two bodies around an axis",
        "AttachSpring" => "Connect two bodies with a spring",
        "AttachRope" => "Tether two bodies with a maximum separation",
        "ControllerVelocity" => "Get a character controller's current velocity",
        "MoveCharacter" => "Move a character controller this frame with input and a jump flag",
        "RequestSurfacePick" => "Request a precise GPU surface pick at a screen position",
        "TakeSurfacePick" => "Take the result of a requested surface pick, if ready",
        "WorldButtonHovered" => "Check whether the pointer is over a world-panel button this frame",
        "LoadSound" => "Register a sound from encoded audio file bytes",
        "PlaySound" => "Play a loaded sound once and return its voice entity",
        "PlaySoundLooping" => "Play a loaded sound on a loop and return its voice entity",
        "PlaySoundAt" => "Play a loaded sound once at a world position, attenuating with distance",
        "SetVolume" => "Set a playing sound's volume",
        "StopSound" => "Stop a sound and free its voice",
        "SetPitch" => "Set a sound's pitch and speed multiplier",
        "SetSpatialDistance" => "Set the distance range over which a spatial sound fades",
        "PanelCheckbox" => "Add a labeled checkbox to a panel",
        "CheckboxValue" => "Get the checkbox's current on or off value",
        "PanelSlider" => "Add a slider from min to max starting at an initial value to a panel",
        "SliderValue" => "Get the slider's current value",
        "SetSliderValue" => "Set the slider's value",
        "PanelTextInput" => "Add a single-line text input with placeholder text to a panel",
        "TextInputChanged" => "Get the input's new contents if it changed this frame",
        "PanelDropdown" => "Add a dropdown of options with an initial selection to a panel",
        "DropdownSelected" => "Get the newly chosen index if the dropdown changed this frame",
        "PanelProgressBar" => "Add a progress bar filled to an initial value to a panel",
        "SetProgress" => "Set a progress bar's fill from 0 to 1",
        "PanelToggle" => "Add an on or off toggle to a panel",
        "ToggleValue" => "Get the toggle's current on or off value",
        "PanelRadio" => "Add a radio button to a panel as one option of a group",
        "RadioSelected" => "Get the selected option index of a radio group, if any",
        "PanelRangeSlider" => "Add a dual-handle range slider to a panel",
        "SetRange" => "Set both handles of a range slider",
        "PanelTabs" => "Add a tab bar of labels to a panel with an initial selection",
        "SetTab" => "Select a tab bar's active tab by index",
        "PanelCollapsing" => "Add a collapsing section to a panel and return its content container",
        "PanelColorPicker" => "Add a color picker to a panel starting at a linear RGBA color",
        "ColorValue" => "Get the color picker's current color as linear RGBA",
        "PanelTextArea" => "Add a multi-line text area with placeholder text to a panel",
        "PanelTextAreaWithValue" => {
            "Add a multi-line text area pre-filled with an initial value to a panel"
        }
        "SetTextArea" => "Replace a text area's contents",
        "PanelMultiSelect" => "Add a multi-select chip list of options to a panel",
        "SetMultiSelect" => "Set a multi-select's chosen option indices",
        "PanelDatePicker" => "Add a date picker starting at a given date to a panel",
        "SetDate" => "Set a date picker's value",
        "PanelMenu" => "Add a dropdown menu listing items to a panel",
        "PanelColorPickerHsv" => {
            "Add an HSV color picker starting at a linear RGBA color to a panel"
        }
        "PanelSplitter" => "Add a draggable splitter dividing a panel into two resizable panes",
        "PanelBreadcrumb" => "Add a breadcrumb trail of segments to a panel",
        "PanelVirtualList" => "Add a virtual list that recycles a pool of rows to a panel",
        "PanelTable" => "Add a simple table with column headers and widths to a panel",
        "PanelDataGrid" => "Add a sortable, selectable data grid to a panel",
        "SetDataGridRows" => "Set a data grid's total row count",
        "SetDataGridCell" => "Set the text of a single data grid cell",
        "DataGridSelectionChanged" => {
            "Check whether the data grid's row selection changed this frame"
        }
        "PanelCommandPalette" => "Add a searchable command palette overlay to a panel",
        "PanelPropertyGrid" => "Add a two-column label and value property grid to a panel",
        "PanelPropertyRow" => "Add a labeled row to a property grid and return its value cell",
        "PanelTreeView" => "Add a tree view to a panel",
        "TreeContent" => "Get the root container of a tree view for adding top-level nodes",
        "TreeNode" => "Add a node at a depth under a container in a tree view",
        "TreeNodeChildren" => "Get the container a node's children go into for nesting",
        "SetTreeNodeExpanded" => "Expand or collapse a tree node",
        "TreeViewSelected" => "Get the entities of the currently selected tree nodes",
        "PanelDragValue" => "Add a numeric drag value field that scrubs as you drag to a panel",
        "DragValue" => "Get the drag value's current value",
        "PanelSelectable" => "Add a selectable label to a panel",
        "PanelModal" => "Add a centered modal dialog to a panel and return its content container",
        "PanelSpinner" => "Add an animated loading spinner to a panel",
        "PanelSeparator" => "Add a thin horizontal divider line to a panel",
        "PanelHeading" => "Add a larger heading-styled line of text to a panel",
        "SaveSceneToFile" => "Serialize the scene and write it to a file path (native only)",
        "LoadSceneFromFile" => {
            "Read a scene file from a path and spawn it, replying its root entities (native only)"
        }
        _ => "",
    }
}

macro_rules! commands {
    (
        $(
            $(#[$meta:meta])*
            $variant:ident { $( $field:ident : $field_type:ty [$role:ident] ),* $(,)? }
                => $func:path , $reply:ident ;
        )*
    ) => {
        /// One API call as data. Field names and types match the free function
        /// it mirrors. Positions, axes, and colors are plain arrays so the wire
        /// form is clean json rather than a math library's internal layout.
        #[derive(Serialize, Deserialize, Clone, Debug, enum2schema::Schema)]
        pub enum Command {
            $(
                $(#[$meta])*
                $variant { $( $field : $field_type ),* },
            )*
        }

        impl Command {
            /// This command's variant name, the key the manifest and a binding use,
            /// read straight off the value with no serialization.
            pub fn name(&self) -> &'static str {
                match self {
                    $(
                        $(#[$meta])*
                        Command::$variant { .. } => stringify!($variant),
                    )*
                }
            }
        }

        fn dispatch(
            world: &mut World,
            command: &Command,
            produced: &[Option<Entity>],
        ) -> CommandReply {
            match command {
                $(
                    $(#[$meta])*
                    Command::$variant { $( $field ),* } => {
                        $( bind_argument!($field, $role, produced, world); )*
                        wrap_reply!($reply, $func(world $(, $field)*))
                    }
                )*
            }
        }

        /// The command surface as data, generated from the same registry as
        /// [`Command`] and its dispatch. cfg-gated commands appear only when
        /// their feature is compiled, so the manifest matches the surface a
        /// binding can actually reach.
        pub fn command_manifest() -> Vec<CommandSpec> {
            let mut specs = Vec::new();
            $(
                $(#[$meta])*
                specs.extend([CommandSpec {
                    name: stringify!($variant),
                    fields: vec![
                        $( FieldSpec {
                            name: stringify!($field),
                            type_name: stringify!($field_type),
                            role: stringify!($role),
                        } ),*
                    ],
                    reply: stringify!($reply),
                    description: command_description(stringify!($variant)),
                }]);
            )*
            specs
        }

        /// Registers every command as a method on a rhai array, so a script
        /// writes `commands.spawn_cube([x, y, z])` instead of pushing the
        /// command's map shape by hand. The arguments are the command's fields in
        /// order, each taken as a dynamic value and serialized exactly like the
        /// map form, so the two are equivalent. Generated from the same registry
        /// as the command enum, so the script surface never drifts from it.
        #[cfg(feature = "scripting")]
        pub fn register_command_methods(engine: &mut rhai::Engine) {
            $(
                $(#[$meta])*
                engine.register_fn(
                    command_method_name(stringify!($variant)),
                    |commands: &mut rhai::Array $(, $field: rhai::Dynamic )*| {
                        commands.push(command_method_map(
                            stringify!($variant),
                            vec![ $( (stringify!($field), $field) ),* ],
                        ));
                    },
                );
            )*
        }
    };
}

commands! {
    SpawnCube { position: [f32; 3] [vec3] } => crate::scene::spawn_cube, entity;
    SpawnSphere { position: [f32; 3] [vec3] } => crate::scene::spawn_sphere, entity;
    SpawnCylinder { position: [f32; 3] [vec3] } => crate::scene::spawn_cylinder, entity;
    SpawnCone { position: [f32; 3] [vec3] } => crate::scene::spawn_cone, entity;
    SpawnPlane { position: [f32; 3] [vec3] } => crate::scene::spawn_plane, entity;
    SpawnTorus { position: [f32; 3] [vec3] } => crate::scene::spawn_torus, entity;
    SpawnFloor { half_extent: f32 [copy] } => crate::scene::spawn_floor, entity;
    SpawnGroup { position: [f32; 3] [vec3] } => crate::scene::spawn_group, entity;
    SpawnModel { glb: Vec<u8> [bytes], position: [f32; 3] [vec3] } => crate::scene::spawn_model, entity;
    SpawnObject { shape: Shape [copy], position: [f32; 3] [vec3], scale: [f32; 3] [vec3], color: [f32; 4] [copy], body: Body [copy] } => spawn_object_command, entity;

    SetColor { entity: Ref [entity], color: [f32; 4] [copy] } => crate::appearance::set_color, none;
    SetMetallicRoughness { entity: Ref [entity], metallic: f32 [copy], roughness: f32 [copy] } => crate::appearance::set_metallic_roughness, none;
    SetEmissive { entity: Ref [entity], color: [f32; 3] [copy], strength: f32 [copy] } => crate::appearance::set_emissive, none;
    SetUnlit { entity: Ref [entity], unlit: bool [copy] } => crate::appearance::set_unlit, none;
    SetTexture { entity: Ref [entity], texture: String [text] } => crate::appearance::set_texture, none;
    SetTextureTiling { entity: Ref [entity], repeats: f32 [copy] } => crate::appearance::set_texture_tiling, none;
    SetNormalTexture { entity: Ref [entity], texture: String [text] } => crate::appearance::set_normal_texture, none;
    SetMetallicRoughnessTexture { entity: Ref [entity], texture: String [text] } => crate::appearance::set_metallic_roughness_texture, none;
    SetEmissiveTexture { entity: Ref [entity], texture: String [text] } => crate::appearance::set_emissive_texture, none;
    SetOcclusionTexture { entity: Ref [entity], texture: String [text] } => crate::appearance::set_occlusion_texture, none;

    SetPosition { entity: Ref [entity], position: [f32; 3] [vec3] } => crate::placement::set_position, none;
    SetScale { entity: Ref [entity], scale: [f32; 3] [vec3] } => crate::placement::set_scale, none;
    SetRotation { entity: Ref [entity], axis: [f32; 3] [vec3], radians: f32 [copy] } => crate::placement::set_rotation, none;
    Rotate { entity: Ref [entity], axis: [f32; 3] [vec3], radians: f32 [copy] } => crate::placement::rotate, none;
    Position { entity: Ref [entity] } => crate::placement::position, vector;

    SetParent { child: Ref [entity], parent: Option<Ref> [opt_entity] } => crate::scene::set_parent, none;
    SetVisible { entity: Ref [entity], visible: bool [copy] } => crate::scene::set_visible, none;
    Despawn { entity: Ref [entity] } => crate::scene::despawn, none;

    Tag { entity: Ref [entity], label: String [text] } => crate::groups::tag, none;
    Untag { entity: Ref [entity], label: String [text] } => crate::groups::untag, none;
    HasTag { entity: Ref [entity], label: String [text] } => crate::groups::has_tag, bool;
    QueryTagged { label: String [text] } => crate::groups::tagged, entities;

    PointLight { position: [f32; 3] [vec3], color: [f32; 3] [copy], intensity: f32 [copy] } => crate::lighting::point_light, entity;
    SpotLight { position: [f32; 3] [vec3], target: [f32; 3] [vec3], color: [f32; 3] [copy], intensity: f32 [copy] } => crate::lighting::spot_light, entity;
    SetSun { color: [f32; 3] [copy], intensity: f32 [copy] } => crate::lighting::set_sun, none;

    SetBackground { background: crate::environment::Background [owned] } => crate::environment::set_background, none;
    ShowGrid { enabled: bool [copy] } => crate::environment::show_grid, none;
    SetAmbient { color: [f32; 4] [copy] } => crate::environment::set_ambient, none;
    SetBloom { enabled: bool [copy] } => crate::environment::set_bloom, none;
    SetBloomIntensity { intensity: f32 [copy] } => crate::environment::set_bloom_intensity, none;
    SetSsao { enabled: bool [copy] } => crate::environment::set_ssao, none;
    SetSsr { enabled: bool [copy] } => crate::environment::set_ssr, none;
    SetSsgi { enabled: bool [copy] } => crate::environment::set_ssgi, none;
    SetFxaa { enabled: bool [copy] } => crate::environment::set_fxaa, none;
    SetExposure { exposure: f32 [copy] } => crate::environment::set_exposure, none;
    SetColorGrading { saturation: f32 [copy], contrast: f32 [copy], brightness: f32 [copy] } => crate::environment::set_color_grading, none;
    SetTimeOfDay { hour: f32 [copy] } => crate::environment::set_time_of_day, none;
    SetTitle { title: String [text] } => crate::environment::set_title, none;

    EmitFire { position: [f32; 3] [vec3] } => crate::effects::emit_fire, entity;
    EmitSmoke { position: [f32; 3] [vec3] } => crate::effects::emit_smoke, entity;
    EmitBurst { position: [f32; 3] [vec3], color: [f32; 4] [copy], count: u32 [copy] } => crate::effects::emit_burst, entity;

    DrawCube { position: [f32; 3] [vec3], scale: [f32; 3] [vec3], color: [f32; 4] [copy] } => crate::draw::draw_cube, none;
    DrawSphere { position: [f32; 3] [vec3], radius: f32 [copy], color: [f32; 4] [copy] } => crate::draw::draw_sphere, none;
    DrawCylinder { position: [f32; 3] [vec3], scale: [f32; 3] [vec3], color: [f32; 4] [copy] } => crate::draw::draw_cylinder, none;
    DrawCone { position: [f32; 3] [vec3], scale: [f32; 3] [vec3], color: [f32; 4] [copy] } => crate::draw::draw_cone, none;
    DrawTorus { position: [f32; 3] [vec3], scale: [f32; 3] [vec3], color: [f32; 4] [copy] } => crate::draw::draw_torus, none;
    DrawLine { start: [f32; 3] [vec3], end: [f32; 3] [vec3], color: [f32; 4] [copy] } => crate::draw::draw_line, none;
    DrawText3d { text: String [text], position: [f32; 3] [vec3] } => crate::draw::draw_text_3d, none;

    SpawnLabel { text: String [text], position: [f32; 3] [vec3] } => crate::text::spawn_label, entity;
    SpawnText { text: String [text], anchor: crate::text::ScreenAnchor [copy] } => crate::text::spawn_text, entity;
    SetText { entity: Ref [entity], text: String [text] } => crate::text::set_text, none;
    SetTextColor { entity: Ref [entity], color: [f32; 4] [copy] } => crate::text::set_text_color, none;
    SetTextSize { entity: Ref [entity], size: f32 [copy] } => crate::text::set_text_size, none;

    SpawnPanel { anchor: crate::text::ScreenAnchor [copy], width: f32 [copy], height: f32 [copy] } => crate::ui::spawn_panel, entity;
    PanelLabel { panel: Ref [entity], text: String [text] } => crate::ui::panel_label, entity;
    PanelButton { panel: Ref [entity], text: String [text] } => crate::ui::panel_button, entity;
    ButtonClicked { button: Ref [entity] } => crate::ui::button_clicked, bool;
    ButtonHovered { button: Ref [entity] } => crate::ui::button_hovered, bool;
    DespawnPanel { panel: Ref [entity] } => crate::ui::despawn_panel, none;
    PanelRow { panel: Ref [entity], height: f32 [copy] } => crate::ui::panel_row, entity;
    PanelGrid { panel: Ref [entity], columns: usize [copy], row_height: f32 [copy], height: f32 [copy] } => crate::ui::panel_grid, entity;
    PanelScroll { panel: Ref [entity], height: f32 [copy] } => crate::ui::panel_scroll, entity;
    SetScrollOffset { scroll_area: Ref [entity], offset: f32 [copy] } => crate::ui::set_scroll_offset, none;
    SetFocusOrder { entity: Ref [entity], order: i32 [copy] } => crate::ui::set_focus_order, none;
    FocusWidget { entity: Ref [entity] } => crate::ui::focus_widget, none;
    SpawnPanelAt { anchor: crate::text::ScreenAnchor [copy], offset: [f32; 2] [vec2], size: [f32; 2] [vec2], color: [f32; 4] [copy] } => crate::ui::spawn_panel_at, entity;
    PanelText { parent: Ref [entity], text: String [text], rect: [f32; 4] [copy], font_size: f32 [copy], color: [f32; 4] [copy], align: TextAlignment [copy] } => crate::ui::panel_text, entity;
    PanelBox { parent: Ref [entity], offset: [f32; 2] [vec2], size: [f32; 2] [vec2], color: [f32; 4] [copy] } => crate::ui::panel_box, entity;
    PanelButtonAt { parent: Ref [entity], label: String [text], offset: [f32; 2] [vec2], size: [f32; 2] [vec2] } => crate::ui::panel_button_at, entity;
    SetPanelRect { node: Ref [entity], offset: [f32; 2] [vec2], size: [f32; 2] [vec2] } => crate::ui::set_panel_rect, none;
    SetPanelColor { node: Ref [entity], color: [f32; 4] [copy] } => crate::ui::set_panel_color, none;
    SetPanelText { label: Ref [entity], text: String [text] } => crate::ui::set_panel_text, none;
    SetPanelTextColor { label: Ref [entity], color: [f32; 4] [copy] } => crate::ui::set_panel_text_color, none;
    SetPanelSelected { button: Ref [entity], selected: bool [copy], accent: [f32; 4] [copy] } => crate::ui::set_panel_selected, none;
    SetPanelVisible { node: Ref [entity], visible: bool [copy] } => crate::ui::set_panel_visible, none;

    PlayAnimation { entity: Ref [entity], clip: usize [copy] } => crate::scene::play_animation, none;
    PlayAnimationNamed { entity: Ref [entity], name: String [text] } => crate::scene::play_animation_named, bool;
    SetAnimationLooping { entity: Ref [entity], looping: bool [copy] } => crate::scene::set_animation_looping, none;
    SetAnimationSpeed { entity: Ref [entity], speed: f32 [copy] } => crate::scene::set_animation_speed, none;
    BlendToAnimation { entity: Ref [entity], clip: usize [copy], seconds: f32 [copy] } => crate::scene::blend_to_animation, none;
    PauseAnimation { entity: Ref [entity] } => crate::scene::pause_animation, none;
    ResumeAnimation { entity: Ref [entity] } => crate::scene::resume_animation, none;
    StopAnimation { entity: Ref [entity] } => crate::scene::stop_animation, none;
    AnimationClips { entity: Ref [entity] } => crate::scene::animation_clips, strings;
    AddAnimationEvent { entity: Ref [entity], clip_index: usize [copy], time: f32 [copy], name: String [text] } => crate::scene::add_animation_event, bool;
    AddAnimationEventNamed { entity: Ref [entity], clip_name: String [text], time: f32 [copy], name: String [text] } => crate::scene::add_animation_event_named, bool;
    SetAnimationLayerWeight { entity: Ref [entity], layer_index: usize [copy], weight: f32 [copy] } => crate::scene::set_animation_layer_weight, none;
    ClearAnimationLayers { entity: Ref [entity] } => crate::scene::clear_animation_layers, none;
    AimAt { bone: Ref [entity], target: [f32; 3] [vec3], forward: [f32; 3] [vec3] } => crate::animate::aim_at, none;

    OrbitCamera { focus: [f32; 3] [vec3], radius: f32 [copy] } => crate::camera::orbit_camera, entity;
    FlyCamera { position: [f32; 3] [vec3] } => crate::camera::fly_camera, entity;
    FixedCamera { eye: [f32; 3] [vec3], target: [f32; 3] [vec3] } => crate::camera::fixed_camera, entity;
    LookAt { eye: [f32; 3] [vec3], target: [f32; 3] [vec3] } => crate::camera::look_at, none;
    SetOrbitFocus { focus: [f32; 3] [vec3] } => crate::camera::set_orbit_focus, none;
    SetOrbitView { focus: [f32; 3] [vec3], radius: f32 [copy], yaw: f32 [copy], pitch: f32 [copy] } => crate::camera::set_orbit_view, none;
    SetOrbitZoom { enabled: bool [copy] } => crate::camera::set_orbit_zoom, none;
    SetOrbitModifier { modifier: String [text] } => crate::camera::set_orbit_modifier, none;
    SetFieldOfView { degrees: f32 [copy] } => crate::camera::set_field_of_view, none;
    SetOrthographic { half_height: f32 [copy] } => crate::camera::set_orthographic, none;
    SetPerspective { degrees: f32 [copy] } => crate::camera::set_perspective, none;
    CameraPosition {} => crate::camera::camera_position, vector;
    CameraForward {} => crate::camera::camera_forward, vector;
    #[cfg(feature = "physics")]
    FirstPerson { position: [f32; 3] [vec3] } => crate::camera::first_person, entity;

    DeltaTime {} => crate::input::delta_time, float;
    ElapsedSeconds {} => crate::input::elapsed_seconds, float;
    KeyDown { key: String [text] } => key_down_command, bool;
    KeyPressed { key: String [text] } => key_pressed_command, bool;
    MouseDown { button: u8 [copy] } => mouse_down_command, bool;
    MouseClicked { button: u8 [copy] } => mouse_clicked_command, bool;
    Wasd {} => crate::input::wasd, vector;
    PointerOverUi {} => crate::input::pointer_over_ui, bool;
    MouseScroll {} => crate::input::mouse_scroll, float;

    #[cfg(feature = "physics")]
    Push { entity: Ref [entity], impulse: [f32; 3] [vec3] } => crate::physics::push, none;
    #[cfg(feature = "physics")]
    SetVelocity { entity: Ref [entity], velocity: [f32; 3] [vec3] } => crate::physics::set_velocity, none;
    #[cfg(feature = "physics")]
    ApplyForce { entity: Ref [entity], force: [f32; 3] [vec3] } => crate::physics::apply_force, none;
    #[cfg(feature = "physics")]
    ApplyTorque { entity: Ref [entity], torque: [f32; 3] [vec3] } => crate::physics::apply_torque, none;
    #[cfg(feature = "physics")]
    SetAngularVelocity { entity: Ref [entity], velocity: [f32; 3] [vec3] } => crate::physics::set_angular_velocity, none;
    #[cfg(feature = "physics")]
    Velocity { entity: Ref [entity] } => crate::physics::velocity, opt_vector;
    #[cfg(feature = "physics")]
    AngularVelocity { entity: Ref [entity] } => crate::physics::angular_velocity, opt_vector;
    #[cfg(feature = "physics")]
    MakeSensor { entity: Ref [entity] } => crate::physics::make_sensor, none;
    #[cfg(feature = "physics")]
    OverlapSphere { center: [f32; 3] [vec3], radius: f32 [copy] } => crate::physics::overlap_sphere, entities;
    #[cfg(feature = "physics")]
    SetCollisionGroups { entity: Ref [entity], membership: u32 [copy], filter: u32 [copy] } => crate::physics::set_collision_groups, none;
    #[cfg(feature = "physics")]
    SetFriction { entity: Ref [entity], friction: f32 [copy] } => crate::physics::set_friction, none;
    #[cfg(feature = "physics")]
    SetRestitution { entity: Ref [entity], restitution: f32 [copy] } => crate::physics::set_restitution, none;
    #[cfg(feature = "physics")]
    SetLinearDamping { entity: Ref [entity], damping: f32 [copy] } => crate::physics::set_linear_damping, none;
    #[cfg(feature = "physics")]
    SetAngularDamping { entity: Ref [entity], damping: f32 [copy] } => crate::physics::set_angular_damping, none;
    #[cfg(feature = "physics")]
    SetMass { entity: Ref [entity], mass: f32 [copy] } => crate::physics::set_mass, none;
    #[cfg(feature = "physics")]
    SetGravityScale { entity: Ref [entity], scale: f32 [copy] } => crate::physics::set_gravity_scale, none;

    #[cfg(feature = "navmesh")]
    BakeNavmesh {} => crate::navigation::bake_navmesh, none;
    #[cfg(feature = "navmesh")]
    SpawnWalker { position: [f32; 3] [vec3] } => crate::navigation::spawn_walker, entity;
    #[cfg(feature = "navmesh")]
    WalkTo { agent: Ref [entity], destination: [f32; 3] [vec3] } => crate::navigation::walk_to, none;
    #[cfg(feature = "navmesh")]
    SetWalkSpeed { agent: Ref [entity], speed: f32 [copy] } => crate::navigation::set_walk_speed, none;
    #[cfg(feature = "navmesh")]
    StopWalking { agent: Ref [entity] } => crate::navigation::stop_walking, none;

    #[cfg(feature = "picking")]
    ClickedEntity {} => crate::picking::clicked_entity, opt_entity;
    #[cfg(feature = "picking")]
    EntityUnderCursor {} => crate::picking::entity_under_cursor, opt_entity;
    #[cfg(feature = "picking")]
    CursorOnGround {} => crate::picking::cursor_on_ground, opt_vector;
    #[cfg(feature = "picking")]
    SpawnWorldPanel { position: [f32; 3] [vec3], width: f32 [copy], height: f32 [copy], color: [f32; 4] [copy] } => crate::world_ui::spawn_world_panel, entity;
    #[cfg(feature = "picking")]
    WorldPanelButton { panel: Ref [entity], x: f32 [copy], y: f32 [copy], width: f32 [copy], height: f32 [copy], color: [f32; 4] [copy] } => crate::world_ui::world_panel_button, entity;
    #[cfg(feature = "picking")]
    WorldPanelLabel { panel: Ref [entity], text: String [text], x: f32 [copy], y: f32 [copy] } => crate::world_ui::world_panel_label, entity;
    #[cfg(feature = "picking")]
    WorldButtonClicked { button: Ref [entity] } => crate::world_ui::world_button_clicked, bool;

    #[cfg(feature = "audio")]
    PauseSound { entity: Ref [entity] } => crate::audio::pause_sound, none;
    #[cfg(feature = "audio")]
    ResumeSound { entity: Ref [entity] } => crate::audio::resume_sound, none;
    #[cfg(feature = "audio")]
    FadeVolume { entity: Ref [entity], volume: f32 [copy], seconds: f32 [copy] } => crate::audio::fade_volume, none;
    #[cfg(feature = "audio")]
    Crossfade { fade_out: Ref [entity], fade_in: Ref [entity], volume: f32 [copy], seconds: f32 [copy] } => crate::audio::crossfade, none;
    #[cfg(feature = "audio")]
    SetBusVolume { bus: nightshade::prelude::AudioBus [copy], decibels: f32 [copy], fade_seconds: f32 [copy] } => crate::audio::set_bus_volume, none;
    #[cfg(feature = "audio")]
    DuckVoice { amount: f32 [copy], fade_seconds: f32 [copy] } => crate::audio::duck_voice, none;

    DirectionalLight { direction: [f32; 3] [vec3], color: [f32; 3] [copy], intensity: f32 [copy] } => crate::lighting::directional_light, entity;
    AreaLight { position: [f32; 3] [vec3], target: [f32; 3] [vec3], width: f32 [copy], height: f32 [copy], color: [f32; 3] [copy], intensity: f32 [copy] } => crate::lighting::area_light, entity;
    SetLightShadows { light: Ref [entity], enabled: bool [copy] } => crate::lighting::set_light_shadows, none;

    EmitSparks { position: [f32; 3] [vec3] } => crate::effects::emit_sparks, entity;
    EmitFirework { position: [f32; 3] [vec3], velocity: [f32; 3] [vec3] } => crate::effects::emit_firework, entity;
    EmitParticles { position: [f32; 3] [vec3], rate: f32 [copy], lifetime: f32 [copy], size: f32 [copy], gravity: [f32; 3] [vec3] } => crate::effects::emit_particles, entity;

    SetAlphaBlend { entity: Ref [entity], enabled: bool [copy] } => crate::appearance::set_alpha_blend, none;
    SetAlphaCutoff { entity: Ref [entity], cutoff: f32 [copy] } => crate::appearance::set_alpha_cutoff, none;
    SetDoubleSided { entity: Ref [entity], double_sided: bool [copy] } => crate::appearance::set_double_sided, none;
    SetIor { entity: Ref [entity], ior: f32 [copy] } => crate::appearance::set_ior, none;
    SetTransmission { entity: Ref [entity], factor: f32 [copy] } => crate::appearance::set_transmission, none;
    SetClearcoat { entity: Ref [entity], factor: f32 [copy], roughness: f32 [copy] } => crate::appearance::set_clearcoat, none;
    SetAnisotropy { entity: Ref [entity], strength: f32 [copy], rotation: f32 [copy] } => crate::appearance::set_anisotropy, none;
    SetUvTransform { entity: Ref [entity], offset: [f32; 2] [copy], scale: [f32; 2] [copy], rotation: f32 [copy] } => crate::appearance::set_uv_transform, none;
    SetSheen { entity: Ref [entity], color: [f32; 3] [copy], roughness: f32 [copy] } => crate::appearance::set_sheen, none;
    SetIridescence { entity: Ref [entity], factor: f32 [copy], ior: f32 [copy] } => crate::appearance::set_iridescence, none;
    SetSpecular { entity: Ref [entity], factor: f32 [copy], color: [f32; 3] [copy] } => crate::appearance::set_specular, none;
    SetNormalScale { entity: Ref [entity], scale: f32 [copy] } => crate::appearance::set_normal_scale, none;
    SetOcclusionStrength { entity: Ref [entity], strength: f32 [copy] } => crate::appearance::set_occlusion_strength, none;
    SetEmissiveStrength { entity: Ref [entity], strength: f32 [copy] } => crate::appearance::set_emissive_strength, none;
    SetThickness { entity: Ref [entity], thickness: f32 [copy] } => crate::appearance::set_thickness, none;

    SetTextOutline { entity: Ref [entity], width: f32 [copy], color: [f32; 4] [copy] } => crate::text::set_text_outline, none;

    SetMorphWeight { entity: Ref [entity], index: u32 [copy], weight: f32 [copy] } => crate::morph::set_morph_weight, none;

    SetWindowTitle { title: String [text] } => crate::window::set_window_title, none;
    LockCursor { locked: bool [copy] } => crate::window::lock_cursor, none;
    RequestExit {} => crate::window::request_exit, none;

    SetRenderLayer { entity: Ref [entity], layer: u32 [copy] } => crate::render::set_render_layer, none;
    SetCameraLayers { camera: Ref [entity], mask: u32 [copy] } => crate::render::set_camera_layers, none;

    ThirdPersonCamera { target: Ref [entity], distance: f32 [copy] } => crate::camera::third_person_camera, entity;

    SpawnCloth { position: [f32; 3] [vec3], width: f32 [copy], height: f32 [copy], columns: u32 [copy], rows: u32 [copy] } => crate::cloth::spawn_cloth, entity;
    ResetCloth { entity: Ref [entity] } => crate::cloth::reset_cloth, none;
    SetWind { direction: [f32; 3] [vec3], strength: f32 [copy] } => crate::cloth::set_wind, none;

    PauseCutscene {} => crate::cutscene::pause_cutscene, none;
    ResumeCutscene {} => crate::cutscene::resume_cutscene, none;
    StopCutscene {} => crate::cutscene::stop_cutscene, none;
    SeekCutscene { seconds: f32 [copy] } => crate::cutscene::seek_cutscene, none;
    SetCutsceneCamera { camera: Ref [entity] } => crate::cutscene::set_cutscene_camera, none;
    BindCutsceneActor { name: String [text], entity: Ref [entity] } => crate::cutscene::bind_cutscene_actor, none;

    #[cfg(feature = "physics")]
    SpawnCylinderBody { position: [f32; 3] [vec3], half_height: f32 [copy], radius: f32 [copy], mass: f32 [copy], color: [f32; 4] [copy] } => crate::physics::spawn_cylinder_body, entity;
    #[cfg(feature = "physics")]
    SpawnCapsuleBody { position: [f32; 3] [vec3], half_height: f32 [copy], radius: f32 [copy], mass: f32 [copy], color: [f32; 4] [copy] } => crate::scene::spawn_capsule_body, entity;
    #[cfg(feature = "physics")]
    SetControllerSpeed { entity: Ref [entity], speed: f32 [copy] } => crate::character::set_controller_speed, none;
    #[cfg(feature = "physics")]
    SetControllerJump { entity: Ref [entity], impulse: f32 [copy] } => crate::character::set_controller_jump, none;
    #[cfg(feature = "physics")]
    IsGrounded { entity: Ref [entity] } => crate::character::is_grounded, bool;

    #[cfg(feature = "terrain")]
    EnableTerrain { seed: u32 [copy] } => crate::terrain::enable_terrain, none;
    #[cfg(feature = "terrain")]
    DisableTerrain {} => crate::terrain::disable_terrain, none;
    #[cfg(feature = "terrain")]
    SetTerrainHeightRange { min: f32 [copy], max: f32 [copy] } => crate::terrain::set_terrain_height_range, none;
    #[cfg(feature = "terrain")]
    SetTerrainSnowHeight { height: f32 [copy] } => crate::terrain::set_terrain_snow_height, none;
    #[cfg(feature = "grass")]
    EnableGrass {} => crate::terrain::enable_grass, none;
    #[cfg(feature = "grass")]
    DisableGrass {} => crate::terrain::disable_grass, none;

    LoadTexture { name: String [text], image_bytes: Vec<u8> [bytes] } => crate::appearance::load_texture, none;
    LoadTextureLinear { name: String [text], image_bytes: Vec<u8> [bytes] } => crate::appearance::load_texture_linear, none;
    RegisterTexture { name: String [text], width: u32 [copy], height: u32 [copy], rgba: Vec<u8> [bytes] } => crate::appearance::register_texture, none;

    ListMaterials {} => crate::materials::list_materials, json;
    GetMaterial { name: String [text] } => crate::materials::get_material, json;
    RegisterMaterial { name: String [text], base_color: [f32; 4] [copy], metallic: f32 [copy], roughness: f32 [copy], emissive: [f32; 3] [copy] } => register_material_command, text;
    UpdateMaterial { name: String [text], base_color: [f32; 4] [copy], metallic: f32 [copy], roughness: f32 [copy], emissive: [f32; 3] [copy] } => update_material_command, none;
    SetMaterialVariant { variant: String [text] } => set_material_variant_command, int;

    SpawnObjects { shape: Shape [copy], scale: [f32; 3] [vec3], color: [f32; 4] [copy], body: Body [copy], positions: Vec<[f32; 3]> [vec3_list] } => spawn_objects_command, entities;
    SpawnInstanced { shape: Shape [copy], transforms: Vec<InstanceWire> [transforms], color: [f32; 4] [copy] } => crate::scene::spawn_instanced, entity;
    SpawnInstancedWithMaterial { shape: Shape [copy], transforms: Vec<InstanceWire> [transforms], material: String [text] } => crate::scene::spawn_instanced_with_material, entity;
    SetInstances { batch: Ref [entity], transforms: Vec<InstanceWire> [transforms] } => crate::scene::set_instances, none;
    SpawnClothSheet { position: [f32; 3] [vec3], width: f32 [copy], height: f32 [copy] } => crate::scene::spawn_cloth_sheet, entity;
    BlendToAnimationNamed { entity: Ref [entity], name: String [text], seconds: f32 [copy] } => crate::scene::blend_to_animation_named, bool;
    AddAnimationLayer { entity: Ref [entity], clip_index: usize [copy], weight: f32 [copy] } => crate::scene::add_animation_layer, none;
    NameEntity { name: String [text], entity: Ref [entity] } => crate::scene::name_entity, none;

    Name { entity: Ref [entity] } => crate::hierarchy::name, text;
    SetEntityName { entity: Ref [entity], name: String [text] } => crate::hierarchy::set_name, none;
    Children { entity: Ref [entity] } => crate::hierarchy::children, entities;
    Descendants { entity: Ref [entity] } => crate::hierarchy::descendants, entities;
    Roots {} => crate::hierarchy::roots, entities;
    SceneTree {} => crate::hierarchy::scene_tree, json;

    MaterialOf { entity: Ref [entity] } => crate::inspect::material_of, json;
    GetColor { entity: Ref [entity] } => crate::inspect::get_color, json;
    GetMetallicRoughness { entity: Ref [entity] } => crate::inspect::get_metallic_roughness, json;
    GetEmissive { entity: Ref [entity] } => crate::inspect::get_emissive, json;
    GetUnlit { entity: Ref [entity] } => crate::inspect::get_unlit, json;
    GetTexture { entity: Ref [entity] } => crate::inspect::get_texture, json;
    DescribeEntity { entity: Ref [entity] } => crate::inspect::describe_entity, json;

    SetTextAlignment { entity: Ref [entity], alignment: TextAlignment [copy] } => crate::text::set_text_alignment, none;

    SetMorphWeights { entity: Ref [entity], weights: Vec<f32> [floats] } => crate::morph::set_morph_weights, none;
    MorphWeight { entity: Ref [entity], index: u32 [copy] } => crate::morph::morph_weight, float;
    MorphTargetCount { entity: Ref [entity] } => crate::morph::morph_target_count, int;

    SetFog { enabled: bool [copy], color: [f32; 3] [copy], start: f32 [copy], end: f32 [copy] } => set_fog_command, none;
    SetDepthOfField { enabled: bool [copy], focus_distance: f32 [copy], focus_range: f32 [copy], max_blur_radius: f32 [copy], bokeh_threshold: f32 [copy] } => set_depth_of_field_command, none;
    Screenshot { path: String [text] } => screenshot_command, none;

    SetShadingMode { mode: String [text] } => set_shading_mode_command, none;

    AnimatePosition { entity: Ref [entity], to: [f32; 3] [vec3], seconds: f32 [copy], easing: String [text] } => animate_position_command, none;
    AnimateScale { entity: Ref [entity], to: [f32; 3] [vec3], seconds: f32 [copy], easing: String [text] } => animate_scale_command, none;
    AnimateColor { entity: Ref [entity], to: [f32; 4] [copy], seconds: f32 [copy], easing: String [text] } => animate_color_command, none;
    ShakeCamera { strength: f32 [copy], seconds: f32 [copy] } => crate::animate::shake_camera, none;
    ReachTo { root: Ref [entity], mid: Ref [entity], tip: Ref [entity], target: [f32; 3] [vec3], pole: Option<[f32; 3]> [opt_vec3] } => crate::animate::reach_to, none;

    Bounds { entity: Ref [entity] } => crate::bounds::bounds, json;
    BoundsOf { entities: Vec<Ref> [refs] } => crate::bounds::bounds_of, json;
    FrameEntities { entities: Vec<Ref> [refs] } => crate::bounds::frame_entities, none;

    SpawnParticleEmitter { emitter: EmitterWire [owned] } => spawn_particle_emitter_command, entity;
    SetEmitter { emitter_entity: Ref [entity], emitter: EmitterWire [owned] } => set_emitter_command, none;

    SpawnDecal { texture: String [text], position: [f32; 3] [vec3], normal: [f32; 3] [vec3], size: f32 [copy] } => crate::decals::spawn_decal, entity;

    SaveScene { name: String [text] } => save_scene_command, bytes;
    LoadScene { bytes: Vec<u8> [bytes] } => load_scene_command, entities;

    WindowSize {} => crate::window::window_size, json;
    CursorLocked {} => crate::window::cursor_locked, bool;
    FramesPerSecond {} => crate::window::frames_per_second, float;
    FrameCount {} => crate::window::frame_count, int;
    UptimeMilliseconds {} => crate::window::uptime_milliseconds, int;

    #[cfg(feature = "navmesh")]
    BakeNavmeshWith { config: RecastConfigWire [owned] } => bake_navmesh_with_command, none;

    #[cfg(feature = "physics")]
    Raycast { origin: [f32; 3] [vec3], direction: [f32; 3] [vec3], max_distance: f32 [copy] } => raycast_command, json;
    #[cfg(feature = "physics")]
    AttachFixed { parent: Ref [entity], child: Ref [entity] } => attach_fixed_command, bool;
    #[cfg(feature = "physics")]
    AttachHinge { parent: Ref [entity], child: Ref [entity], axis: String [text] } => attach_hinge_command, bool;
    #[cfg(feature = "physics")]
    AttachSpring { parent: Ref [entity], child: Ref [entity], rest_length: f32 [copy], stiffness: f32 [copy], damping: f32 [copy] } => attach_spring_command, bool;
    #[cfg(feature = "physics")]
    AttachRope { parent: Ref [entity], child: Ref [entity], max_distance: f32 [copy] } => attach_rope_command, bool;
    #[cfg(feature = "physics")]
    ControllerVelocity { entity: Ref [entity] } => crate::character::controller_velocity, vector;
    #[cfg(feature = "physics")]
    MoveCharacter { entity: Ref [entity], movement: [f32; 2] [vec2], jump: bool [copy] } => crate::character::move_character, none;

    #[cfg(feature = "picking")]
    RequestSurfacePick { screen_pos: [f32; 2] [vec2] } => crate::picking::request_surface_pick, none;
    #[cfg(feature = "picking")]
    TakeSurfacePick {} => take_surface_pick_command, json;
    #[cfg(feature = "picking")]
    WorldButtonHovered { button: Ref [entity] } => crate::world_ui::world_button_hovered, bool;

    #[cfg(feature = "audio")]
    LoadSound { name: String [text], bytes: Vec<u8> [bytes] } => crate::audio::load_sound, none;
    #[cfg(feature = "audio")]
    PlaySound { name: String [text] } => crate::audio::play_sound, entity;
    #[cfg(feature = "audio")]
    PlaySoundLooping { name: String [text] } => crate::audio::play_sound_looping, entity;
    #[cfg(feature = "audio")]
    PlaySoundAt { name: String [text], position: [f32; 3] [vec3] } => crate::audio::play_sound_at, entity;
    #[cfg(feature = "audio")]
    SetVolume { entity: Ref [entity], volume: f32 [copy] } => crate::audio::set_volume, none;
    #[cfg(feature = "audio")]
    StopSound { entity: Ref [entity] } => crate::audio::stop_sound, none;
    #[cfg(feature = "audio")]
    SetPitch { entity: Ref [entity], rate: f32 [copy] } => crate::audio::set_pitch, none;
    #[cfg(feature = "audio")]
    SetSpatialDistance { entity: Ref [entity], min: f32 [copy], max: f32 [copy] } => crate::audio::set_spatial_distance, none;

    PanelCheckbox { panel: Ref [entity], label: String [text], initial: bool [copy] } => crate::ui::panel_checkbox, entity;
    CheckboxValue { checkbox: Ref [entity] } => crate::ui::checkbox_value, bool;
    PanelSlider { panel: Ref [entity], min: f32 [copy], max: f32 [copy], initial: f32 [copy] } => crate::ui::panel_slider, entity;
    SliderValue { slider: Ref [entity] } => crate::ui::slider_value, float;
    SetSliderValue { slider: Ref [entity], value: f32 [copy] } => crate::ui::set_slider_value, none;
    PanelTextInput { panel: Ref [entity], placeholder: String [text] } => crate::ui::panel_text_input, entity;
    TextInputChanged { input: Ref [entity] } => crate::ui::text_input_changed, json;
    PanelDropdown { panel: Ref [entity], options: Vec<String> [strs], initial: usize [copy] } => crate::ui::panel_dropdown, entity;
    DropdownSelected { dropdown: Ref [entity] } => crate::ui::dropdown_selected, json;
    PanelProgressBar { panel: Ref [entity], initial: f32 [copy] } => crate::ui::panel_progress_bar, entity;
    SetProgress { bar: Ref [entity], value: f32 [copy] } => crate::ui::set_progress, none;
    PanelToggle { panel: Ref [entity], initial: bool [copy] } => crate::ui::panel_toggle, entity;
    ToggleValue { toggle: Ref [entity] } => crate::ui::toggle_value, bool;
    PanelRadio { panel: Ref [entity], label: String [text], group_id: u32 [copy], option_index: usize [copy] } => crate::ui::panel_radio, entity;
    RadioSelected { group_id: u32 [copy] } => crate::ui::radio_selected, json;
    PanelRangeSlider { panel: Ref [entity], min: f32 [copy], max: f32 [copy], low: f32 [copy], high: f32 [copy] } => crate::ui::panel_range_slider, entity;
    SetRange { slider: Ref [entity], low: f32 [copy], high: f32 [copy] } => crate::ui::set_range, none;
    PanelTabs { panel: Ref [entity], labels: Vec<String> [strs], initial: usize [copy] } => crate::ui::panel_tabs, entity;
    SetTab { tabs: Ref [entity], index: usize [copy] } => crate::ui::set_tab, none;
    PanelCollapsing { panel: Ref [entity], label: String [text], open: bool [copy] } => crate::ui::panel_collapsing, entity;
    PanelColorPicker { panel: Ref [entity], initial: [f32; 4] [copy] } => crate::ui::panel_color_picker, entity;
    ColorValue { picker: Ref [entity] } => crate::ui::color_value, json;
    PanelTextArea { panel: Ref [entity], placeholder: String [text], rows: usize [copy] } => crate::ui::panel_text_area, entity;
    PanelTextAreaWithValue { panel: Ref [entity], placeholder: String [text], rows: usize [copy], initial: String [text] } => crate::ui::panel_text_area_with_value, entity;
    SetTextArea { area: Ref [entity], text: String [text] } => crate::ui::set_text_area, none;
    PanelMultiSelect { panel: Ref [entity], options: Vec<String> [strs] } => crate::ui::panel_multi_select, entity;
    SetMultiSelect { widget: Ref [entity], indices: Vec<u32> [indices] } => crate::ui::set_multi_select, none;
    PanelDatePicker { panel: Ref [entity], year: i32 [copy], month: u32 [copy], day: u32 [copy] } => crate::ui::panel_date_picker, entity;
    SetDate { picker: Ref [entity], year: i32 [copy], month: u32 [copy], day: u32 [copy] } => crate::ui::set_date, none;
    PanelMenu { panel: Ref [entity], label: String [text], items: Vec<String> [strs] } => crate::ui::panel_menu, entity;
    PanelColorPickerHsv { panel: Ref [entity], initial: [f32; 4] [copy] } => crate::ui::panel_color_picker_hsv, entity;
    PanelSplitter { panel: Ref [entity], horizontal: bool [copy], ratio: f32 [copy] } => panel_splitter_command, entity;
    PanelBreadcrumb { panel: Ref [entity], segments: Vec<String> [strs] } => crate::ui::panel_breadcrumb, entity;
    PanelVirtualList { panel: Ref [entity], item_height: f32 [copy], pool_size: usize [copy] } => crate::ui::panel_virtual_list, entity;
    PanelTable { panel: Ref [entity], headers: Vec<String> [strs], widths: Vec<f32> [floats] } => crate::ui::panel_table, entity;
    PanelDataGrid { panel: Ref [entity], headers: Vec<String> [strs], widths: Vec<f32> [floats], pool_size: usize [copy] } => panel_data_grid_command, entity;
    SetDataGridRows { grid: Ref [entity], count: usize [copy] } => crate::ui::set_data_grid_rows, none;
    SetDataGridCell { grid: Ref [entity], row: usize [copy], column: usize [copy], text: String [text] } => crate::ui::set_data_grid_cell, none;
    DataGridSelectionChanged { grid: Ref [entity] } => crate::ui::data_grid_selection_changed, bool;
    PanelCommandPalette { panel: Ref [entity], pool_size: usize [copy] } => crate::ui::panel_command_palette, entity;
    PanelPropertyGrid { panel: Ref [entity], label_width: f32 [copy] } => crate::ui::panel_property_grid, entity;
    PanelPropertyRow { grid: Ref [entity], label: String [text] } => crate::ui::panel_property_row, entity;
    PanelTreeView { panel: Ref [entity], multi_select: bool [copy] } => crate::ui::panel_tree_view, entity;
    TreeContent { tree_view: Ref [entity] } => crate::ui::tree_content, entity;
    TreeNode { tree_view: Ref [entity], parent_container: Ref [entity], label: String [text], depth: usize [copy], user_data: u64 [copy] } => crate::ui::tree_node, entity;
    TreeNodeChildren { node: Ref [entity] } => crate::ui::tree_node_children, entity;
    SetTreeNodeExpanded { node: Ref [entity], expanded: bool [copy] } => crate::ui::set_tree_node_expanded, none;
    TreeViewSelected { tree_view: Ref [entity] } => crate::ui::tree_view_selected, entities;
    PanelDragValue { panel: Ref [entity], min: f32 [copy], max: f32 [copy], initial: f32 [copy] } => crate::ui::panel_drag_value, entity;
    DragValue { widget: Ref [entity] } => crate::ui::drag_value, float;
    PanelSelectable { panel: Ref [entity], text: String [text], group: u32 [copy], grouped: bool [copy] } => panel_selectable_command, entity;
    PanelModal { panel: Ref [entity], title: String [text], width: f32 [copy], height: f32 [copy] } => crate::ui::panel_modal, entity;
    PanelSpinner { panel: Ref [entity] } => crate::ui::panel_spinner, entity;
    PanelSeparator { panel: Ref [entity] } => crate::ui::panel_separator, entity;
    PanelHeading { panel: Ref [entity], text: String [text] } => crate::ui::panel_heading, entity;

    SaveSceneToFile { path: String [text] } => crate::filesystem::save_scene_to_path, bool;
    LoadSceneFromFile { path: String [text] } => crate::filesystem::load_scene_from_path, entities;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn command_schema_covers_the_surface() {
        let schema = command_schema();
        assert!(schema.get("oneOf").is_some());
        let text = enum2schema::serde_json::to_string(&schema).unwrap();
        for variant in [
            "SpawnCube",
            "SpawnObject",
            "SetColor",
            "Rotate",
            "QueryTagged",
        ] {
            assert!(text.contains(variant), "schema missing {variant}");
        }
    }

    #[test]
    fn reply_schema_is_generated() {
        assert!(command_reply_schema().get("oneOf").is_some());
    }

    #[test]
    fn manifest_covers_the_surface() {
        let manifest = command_manifest();
        assert!(!manifest.is_empty());
        let names: Vec<&str> = manifest.iter().map(|spec| spec.name).collect();
        for variant in [
            "SpawnCube",
            "SpawnObject",
            "SetColor",
            "Rotate",
            "QueryTagged",
        ] {
            assert!(names.contains(&variant), "manifest missing {variant}");
        }
        let replies = [
            "none",
            "entity",
            "opt_entity",
            "bool",
            "float",
            "int",
            "text",
            "vector",
            "opt_vector",
            "entities",
            "strings",
            "bytes",
            "json",
        ];
        for spec in &manifest {
            assert!(
                replies.contains(&spec.reply),
                "unknown reply {}",
                spec.reply
            );
        }
    }

    #[test]
    fn every_command_has_a_description() {
        for spec in command_manifest() {
            assert!(
                !spec.description.is_empty(),
                "command {} has no description; add one to command_description",
                spec.name
            );
        }
    }

    #[test]
    fn entity_reference_serializes_as_its_schema_claims() {
        let entity = Entity {
            id: 3,
            generation: 1,
        };
        let value = enum2schema::serde_json::to_value(Ref::Entity(entity)).unwrap();
        let inner = value
            .get("Entity")
            .and_then(|tagged| tagged.as_object())
            .expect("Ref::Entity serializes as an externally tagged object");
        assert!(inner.contains_key("id"));
        assert!(inner.contains_key("generation"));
        assert_eq!(inner.len(), 2);
    }
}