voxel-framework 0.13.2

A reusable voxel engine framework built on Bevy
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
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
# voxel-framework

> A reusable voxel engine framework built on [Bevy](https://bevyengine.org/).

## Features

- 16×16×16 voxel chunks with efficient flat-array storage
- Greedy meshing with LOD support and neighbor-aware face culling
- Seam-free borders via neighbor-aware meshing (default in the live system)
- Pluggable `ChunkGenerator` trait — bring your own world generation
- Built-in `AsteroidGenerator` with FBM noise and mineral distribution
- World streaming — automatic chunk load/unload based on viewer position
- Save-on-unload — edited chunks written to disk when streaming out
- PBR rendering via Bevy's `StandardMaterial` with vertex colors
- Binary chunk persistence
- Dynamic LOD (2 levels based on viewer distance)
- Auto-save chunk persistence (optional, disk-backed)
- TOML world configuration via `world.toml`
- Coordinate utilities for world/chunk/voxel space conversions
- Occlusion culling — chunks surrounded by solid neighbors are auto-hidden
- Capsule-voxel collision for player movement
- Mining API — break-time tracking and `VoxelBroken` events
- Block placement API — cooldown tracking and `VoxelPlaced` events
- Loading progress — `LoadingProgress` messages and a `WorldReady` event for loading screens

## Release Status & Stability

`voxel-framework` 0.13 is the current package line for this Bevy-first voxel game
framework. It is intended to be usable by real consumer crates, examples, and
experiments, but it is not a 1.0 stability promise yet. Package metadata and
guidance may be prepared before the corresponding crate and tag are published.

Version **0.9.0** introduces focused player input and explicit click-to-capture.
Players start with a free cursor; losing focus releases control. See the player
section and CHANGELOG migration notes for changes to public system signatures.

Compatibility target:

| Area | Current status |
|---|---|
| Crate version | `0.13.x` |
| Bevy version | `0.18` |
| Rust version | MSRV `1.89` |
| Stability | Public API can still change across `0.x` minor releases |
| Distribution | crates.io for released versions; git tags for pinned source installs |

Bevy 0.18.1 and `bevy_ecs` require Rust 1.89.0. The MSRV CI lane uses
Rust 1.89.0 for `cargo check --locked --lib` with default, no-default, and
all features, plus focused inventory, crafting, and persistence tests on Linux.
Since this library does not track `Cargo.lock`,
CI resolves a fresh lockfile on that toolchain before the locked checks;
consumer dependency resolutions and other targets may require newer Rust.

The candidate gate covers formatting, feature combinations, doctests, integration
tests, exact Rust 1.89.0 checks, documentation, package contents, and targeted
Windows inventory-persistence tests. The CI workflow in `.github/workflows/rust.yml`
supports these gates without using `cargo build`. Candidate preparation does not
publish, push, tag, or integrate the candidate; publication is a separate human
decision after validation.

## Inventory-backed hotbar

With `items`, add `HotbarContentPlugin<I>` alongside `HotbarUiPlugin` to display
the unique primary container's icons, quantities, and selected item name.
Register explicit associations with `ItemIconPalette<I>::register_voxel` to
reuse material colors without images or matching item/voxel IDs.
The existing slot-only UI remains available. See [the hotbar guide](docs/hotbar.md)
and `cargo run --example hotbar_icons -- 800 600 --verify`.
These APIs are available starting with version 0.10.4.

Slot borders are styled with the `HotbarSlotStyle` resource: border width and
color for normal and selected slots, plus `empty_slot_alpha` to fade empty
slots when `HotbarContentPlugin<I>` is present. Its defaults reproduce the
previous hardcoded look. Insert `HotbarPickupPulse { scale, duration }` to make
the slot that received a picked-up item pulse briefly; it is disabled by
default and every value comes from the game.

```rust
app.insert_resource(HotbarSlotStyle {
    border_width: 1.0,
    selected_border_width: 3.0,
    empty_slot_alpha: 0.2,
    ..Default::default()
})
.insert_resource(HotbarPickupPulse { scale: 1.15, duration: 0.2 });
```

## Visible collectible drops

With the `items` feature, explicitly compose `DropsPlugin<I>` for gameplay and
`DropVisualPlugin<I>` for optional default presentation. The latter draws small,
unlit cubes using item colors and shared assets; it requires no external art or
lights. Full inventories retain drops, partial pickups retain their remainder,
and lifetime expiration works without a collector. Insert a `DropVisualConfig`
to make waiting drops spin and bob; the motion is applied to a child entity, so
a drop's own position is never changed. The game owns the camera,
mining input, mappings, and collector/container entities.

See [the drop integration guide](docs/drops.md) and run
`cargo run --example drops --no-default-features --features items` for a visible
collection/expiration demo. These plugins are not added by convenience bundles.

## Known Limitations

- This is a framework/library, not a complete editor or standalone game. Your
  game crate still owns window setup, input choices, game state, and custom UX.
- `basic_world` and `minetest` are graphical Bevy apps and require a working
  display. `content_definitions`, `stats_definitions`, and
  `effect_definitions` use `MinimalPlugins` and run headlessly in a terminal.
  Headless examples and tests do not replace manual playtesting of the
  graphical runtime.
- `ViewerPosition` must be kept in sync with your camera/player every frame; it
  drives chunk streaming. If it never changes, no new chunks stream in.
- `ChunkGenerator::generate` runs on background threads. Generators must be
  deterministic, owned, and `Send + Sync`; they must not access the Bevy
  `World`, `Commands`, `Res`, or `Query`.
- Mining and placement expose reusable state machines and helper functions. You
  still decide when to call them from your own input systems unless you opt into
  the provided input-adapter plugins.
- Persistence is disk-backed chunk persistence for local worlds. The binary
  format is suitable for `0.x` projects but should not be treated as a permanent
  1.0 save-file compatibility guarantee yet.
- Multiplayer, networking, world editing tools, and advanced asset pipelines are
  outside the current release scope.


## Plugin Architecture

`voxel-framework` is a flat catalog of composable Bevy plugins grouped by
responsibility. Games choose the plugins they need from these official
categories:

| Category | Meaning | Examples |
|---|---|---|
| Engine | Foundation for streamable/renderable voxel worlds | `WorldPlugin`, `RenderPlugin<V>`, `MeshPlugin<V>`, `OcclusionPlugin<V>`, `LoadingPlugin` |
| World Data | Chunk sources, generation, persistence, lifecycle data | `GeneratorPlugin<V>`, `MultiGeneratorPlugin<V>`, `PersistencePlugin<V>` |
| Gameplay | Reusable rules and interactions | `VoxelContentPlugin<V>`, `VoxelStatsPlugin`, `VoxelEffectsPlugin`, `MiningPlugin`, `PlacementPlugin`, `PlayerPlugin<V>`, `HotbarPlugin`, `DropsPlugin<I>` |
| Default Implementation | Replaceable UI/audio/visual defaults | `UiPlugin`, `VoxelHudPlugin`, `SkyboxPlugin`, `FragmentPlugin`, `DropVisualPlugin<I>`, `DefaultAudioPlugin` |
| Convenience | Bundles, input adapters, compatibility, recipes/prototyping helpers | `VoxelCorePlugin<V>`, `VoxelPlugin<V>`, `MiningInputPlugin<V, I>`, `PlacementInputPlugin<V>` |

The categories are also exposed as marker traits:
`EnginePlugin`, `WorldDataPlugin`, `GameplayPlugin`,
`DefaultImplementationPlugin`, and `ConveniencePlugin`.

`VoxelCorePlugin<V>` and `VoxelPlugin<V>` are convenience bundles kept for
compatibility and quick starts. They are useful, but they are not the primary
architecture:

| Bundle | What it composes |
|---|---|
| `VoxelCorePlugin<V>` | Engine foundation plus the lightweight gameplay primitives `MiningPlugin` and `PlacementPlugin` |
| `VoxelPlugin<V>` | `VoxelCorePlugin<V>` plus selected defaults: fragments, skybox, SFX events, UI, and hotbar when the `items` feature is enabled |

`GeneratorPlugin<V>` and `PersistencePlugin<V>` are explicit World Data choices
regardless of which convenience bundle you use.

`VoxelContentPlugin<V>`, `VoxelStatsPlugin`, and `VoxelEffectsPlugin` are
independent, horizontal Gameplay choices. They initialize empty registries and
runtime state for definitions owned by the game author; they do not install a
vertical genre preset or a JSON-driven configuration layer. Register only the
content, stats, and effects your game needs through the Rust API. Deterministic
snapshots are available for tooling and may be serialized by the caller, but
they are not a second configuration model.

```rust
// Compatibility bundle: historical core runtime
App::new()
    .add_plugins(DefaultPlugins)
    .add_plugins(VoxelCorePlugin::<DefaultVoxel>::new())
    .add_plugins(GeneratorPlugin::<DefaultVoxel>::new());

// Quick-start bundle for examples/prototypes
App::new()
    .add_plugins(DefaultPlugins)
    .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
    .add_plugins(GeneratorPlugin::<DefaultVoxel>::new());
```

## Quick Start

Add the dependency to your `Cargo.toml`. Use crates.io for released versions;
for unreleased candidate development, use a local checkout or an explicitly
chosen repository revision. Do not assume candidate metadata implies a tag.

```toml
[dependencies]
# Option A — released 0.13 line (recommended for consumers):
voxel-framework = "0.13"

# Option B — local clone side-by-side (development):
voxel-framework = { path = "../voxel-framework" }

# Option C — from the matching release tag:
voxel-framework = { git = "https://github.com/cristhofert/voxel-framework", tag = "v0.13.2" }

# Option D — follow the dev branch (bleeding-edge):
voxel-framework = { git = "https://github.com/cristhofert/voxel-framework", branch = "dev" }

bevy = "0.18"
```

> To run the bundled examples, clone the repository — the demo `assets/` live in the repo and are not pulled in automatically when depending via git.

### Choosing the right starting point

| I want to... | Start with | Notes |
|---|---|---|
| See a working voxel world fast | `cargo run --example basic_world` | Best first smoke test after cloning the repo |
| Build a prototype with defaults | `VoxelPlugin<V>` + `GeneratorPlugin<V>` | Includes core runtime, UI/visual helpers, and SFX request generation; audio playback remains opt-in |
| Build my own game UI/audio | `VoxelCorePlugin<V>` + `GeneratorPlugin<V>` | Keeps rendering, streaming, meshing, mining and placement primitives |
| Add procedural generation | `GeneratorPlugin<V>` + `GeneratorResource<V>` | Your generator implements `ChunkGenerator<V>` |
| Save modified chunks | `PersistencePlugin<V>::with_world("world")` | Writes under `./worlds/{world}/chunks` |
| Drive loading screens | `LoadingPlugin` / `WorldReady` / `LoadingProgress` | Bundled by the convenience plugins |
| Mine or place blocks manually | `MiningPlugin` / `PlacementPlugin` | Call `tick_mining`, `stop_mining`, `try_place_voxel`, and `tick_placement` from your systems |
| Publish an author-defined retained HUD | `VoxelHudPlugin` | Explicit, non-generic, domain-neutral, and not included in `UiPlugin` or convenience bundles |
| Use included item/hotbar UX | default features or `--features items` | Enables inventory, hotbar, drops, and related UI |

Minimal `main.rs` that spawns an asteroid world with config and persistence:

```rust
use std::sync::Arc;
use bevy::prelude::*;
use voxel_framework::prelude::*;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        // Registers WorldPlugin, RenderPlugin, MeshPlugin, and WorldConfigPlugin.
        .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
        // Registers the async generation system.
        .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
        // Enables auto-save on chunk modification under ./worlds/{world_name}/chunks.
        .add_plugins(PersistencePlugin::<DefaultVoxel>::with_world("world"))
        // Supply the generator implementation.
        .insert_resource(GeneratorResource::<DefaultVoxel> {
            generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
        })
        .add_systems(Startup, setup)
        .run();
}

fn setup(mut commands: Commands, mut viewer: ResMut<ViewerPosition>) {
    // Drive chunk streaming by keeping ViewerPosition in sync with the camera.
    viewer.position = Vec3::new(0.0, 50.0, 100.0);

    commands.spawn((
        Camera3d::default(),
        Transform::from_xyz(0.0, 50.0, 100.0).looking_at(Vec3::ZERO, Vec3::Y),
    ));

    commands.spawn((
        DirectionalLight { illuminance: 10_000.0, shadows_enabled: true, ..default() },
        Transform::from_xyz(100.0, 200.0, 100.0).looking_at(Vec3::ZERO, Vec3::Y),
    ));
}
```

Update `ViewerPosition` every frame so the streaming system knows where to load chunks:

```rust
fn sync_viewer(
    mut viewer: ResMut<ViewerPosition>,
    camera: Query<&Transform, With<Camera3d>>,
) {
    if let Ok(t) = camera.single() {
        viewer.position = t.translation;
    }
}
```

Run the bundled example:

```sh
cargo run --example basic_world
```

### Bundled examples

| Example | Runtime | Purpose |
|---|---|---|
| `content_definitions` | Headless (`MinimalPlugins`); requires `items` (enabled by default) | Author-defined blocks, items, drops, validation, and snapshots |
| `stats_definitions` | Headless (`MinimalPlugins`) | Author-defined global/entity stats, mutation helpers, and messages |
| `effect_definitions` | Headless (`MinimalPlugins`) | Author-defined global/entity effects, ticking, and lifecycle messages |
| `hud` | Headless (`MinimalPlugins`); feature-independent | Neutral text, bar, icon, and segment definitions with same-frame publication and retained updates |
| `terrain_materials` | Graphical; display required; feature-independent | A custom palette where one voxel type is drawn with a game-registered material |
| `basic_world` | Graphical; display required; requires `items` (enabled by default) | Small playable asteroid world; see [`examples/basic_world.md`](examples/basic_world.md) |
| `minetest` | Graphical; display required; requires `items`, `crafting`, and `mobs` (enabled by default) | Larger integration example, including day/night mob spawn rules |

The headless examples are the fastest way to inspect author-defined APIs without
opening a window. The HUD, stats, and effects examples do not require optional
framework features.

## Module Overview

| Module | Description |
|---|---|
| `voxel` | `VoxelType` trait, `DefaultVoxel` enum, and `VoxelPalette` resource |
| `content` | Author-defined `BlockDefinition`, `BlockRegistry`, and `VoxelContentPlugin` |
| `stats` | Author-defined `StatDefinition`, `StatRegistry`, `StatSet`, and `VoxelStatsPlugin` |
| `effects` | Author-defined `EffectDefinition`, `EffectRegistry`, `ActiveEffectSet`, and `VoxelEffectsPlugin` |
| `ui::hud` | Author-defined `HudRegistry`, `HudValueSet`, retained presentations, and explicit `VoxelHudPlugin` |
| `chunk` | `Chunk<V>` flat-array storage, `ChunkCoord`, constants, coordinate utilities, and binary persistence |
| `noise` | Seed-based value noise, FBM, and `hash3` — no external noise crates |
| `particles` | `AmbientParticlesPlugin`: sparse unlit particles kept around the viewer |
| `generator` | `ChunkGenerator<V>` trait, `GeneratorPlugin`, and `GeneratorResource` |
| `generator::asteroid` | `AsteroidGenerator` with FBM surface deformation and mineral veins |
| `mesh` | Greedy meshing (`generate_chunk_mesh`, `generate_chunk_mesh_with_neighbors`), `MeshPlugin`, LOD computation |
| `world` | `ChunkManager`, `ViewerPosition`, lifecycle events, streaming system, `WorldPlugin`, `WorldConfig`, `PersistencePlugin` |
| `world/occlusion` | `OcclusionPlugin`, `is_chunk_occluded` — hides chunks fully enclosed by solid neighbors |
| `world/collision` | Sphere and capsule collision detection and resolution against solid voxels |
| `world/mining` | `MiningPlugin`, `MiningConfig`, `MiningState`, `tick_mining`, `stop_mining`, `VoxelBroken`, `MiningProgress` |
| `world/mining_overlay` | Optional `MiningOverlayPlugin`, `MiningOverlayConfig`, `MiningOverlayStage`, `mining_overlay_stage` |
| `world/placement` | `PlacementPlugin`, `PlacementConfig`, `PlacementState`, `try_place_voxel`, `tick_placement`, `VoxelPlaced` |
| `world/loading` | `LoadingPlugin`, `LoadingProgress`, `WorldReady`, `WorldLoadingState` |
| `render` | Shared `StandardMaterial` for vertex-colored chunks, `RenderPlugin` |
| `player` | 6DOF jetpack player (`PlayerPlugin`, `PlayerConfig`, capsule collision) |
| `lighting` | Optional `SceneLightingPlugin` (fixed sun, fill light, ambient), `HeadlampPlugin` and `PlacedLightsPlugin` |
| `ui/pause_menu` | Optional `PauseMenuPlugin` with `PauseMenuState`, `PauseMenuConfig` and `PauseMenuTheme` |
| `settings` | `PersistedSettings` and the optional `SettingsPlugin`, which loads and saves the pause menu settings of a world |
| `audio` | `SfxPlugin` request layer (`SfxRequest`, `PitchedSfxRequest`, `SfxConfig`), `DefaultAudioPlugin` playback, `SfxFilter` |
| `prelude` | Convenience re-export of all public types |

## Author-defined Content

`VoxelContentPlugin<V>` initializes a `BlockRegistry<V>` resource.
With the `items` feature enabled, `ItemContentPlugin<I>` and
`BlockDropContentPlugin<I>` also provide `ItemRegistry<I>` and
`BlockDropRegistry<I>`. These registries do **not** create a game, ship
space/survival presets, or impose a closed list of gameplay categories. They are
horizontal tools: the game author registers content definitions and decides what
their gameplay attributes mean.

For setup code that should fail loudly, registries also expose `require(...)`
helpers and block-drop validation:

- `BlockRegistry::require("id")` / `ItemRegistry::require("id")` return explicit
  missing-id errors instead of `Option`.
- `BlockDropRegistry::validate_blocks(&blocks)` catches drops attached to block
  ids that were never registered.
- `BlockDropRegistry::validate_items(&items)` catches drops that produce item
  values that were never registered.
- `BlockDropRegistry::apply_to_drop_table(&blocks, &mut drop_table)` bridges
  author-defined block ids into the runtime voxel-byte `DropTable` consumed by
  `DropsPlugin`.
- `snapshot()` on block, item, and drop registries returns deterministic
  serializable data for docs, tooling, manifests, or AI inspection.

The framework only separates two concerns:

1. **Engine contracts** — technical facts the voxel runtime may need, such as
   whether a block emits mesh geometry, collides, has opacity, color, or texture
   layers.
2. **Author-defined gameplay data** — arbitrary attributes and tags such as
   hardness, rarity, mana conductivity, drops, faction, temperature, item mass,
   or tool rules.

```rust
use bevy::prelude::*;
use voxel_framework::prelude::*;

fn register_blocks(mut blocks: ResMut<BlockRegistry<DefaultTerrainVoxel>>) {
    blocks
        .register(
            BlockDefinition::new("moon_regolith", DefaultTerrainVoxel::Sand)
                .named("Moon Regolith")
                .tag("terrain")
                .attribute("hardness", 0.8)
                .attribute("dusty", true)
                .attribute("drops", ContentValue::strings(["moon_regolith"])),
        )
        .expect("block id and voxel value should be unique");
}

App::new()
    .add_plugins(MinimalPlugins)
    .add_plugins(VoxelContentPlugin::<DefaultTerrainVoxel>::new())
    .add_systems(Startup, register_blocks);
```

With the `items` feature, item and drop content uses the same author-defined
style:

```rust
use bevy::prelude::*;
use voxel_framework::prelude::*;

fn register_items_and_drops(
    mut items: ResMut<ItemRegistry<DefaultItem>>,
    mut drops: ResMut<BlockDropRegistry<DefaultItem>>,
) {
    items
        .register(
            ItemDefinition::new("moon_regolith", DefaultItem::Sand)
                .named("Moon Regolith")
                .tag("building_material")
                .attribute("mass", 0.4),
        )
        .expect("item id and item value should be unique");

    drops.register_drop(
        "moon_regolith",
        BlockDropDefinition::new(DefaultItem::Sand, DropCount::range(1, 3)),
    );

    drops.validate_items(&items).expect("drops should use registered items");
}

fn bridge_content_drops_to_runtime(
    blocks: Res<BlockRegistry<DefaultTerrainVoxel>>,
    drops: Res<BlockDropRegistry<DefaultItem>>,
    mut drop_table: ResMut<DropTable<DefaultItem>>,
) {
    drops
        .apply_to_drop_table(&blocks, &mut drop_table)
        .expect("drops should reference registered blocks");
}

App::new()
    .add_plugins(MinimalPlugins)
    .add_plugins(ItemContentPlugin::<DefaultItem>::new())
    .add_plugins(BlockDropContentPlugin::<DefaultItem>::new())
    .add_plugins(DropsPlugin::<DefaultItem>::new())
    .add_systems(Startup, (register_items_and_drops, bridge_content_drops_to_runtime).chain());
```

Run the headless content example:

```sh
cargo run --example content_definitions
```

The example also prints a JSON block-content snapshot so you can see the exact
author-defined content surface exposed to external tools.

## Author-defined Stats

`VoxelStatsPlugin` initializes two empty resources:

- `StatRegistry` — the catalog of stats the game author chooses to define.
- `StatSet` — runtime values keyed by those author-defined stat ids.

The plugin intentionally registers **no** default health, stamina, oxygen, mana,
hunger, thirst, or body schema. Those are game decisions. A survival game can
define `oxygen`; an RPG can define `mana`; an arcade sandbox can define no stats
at all. The framework only provides ids, bounds, clamping, mutation helpers,
metadata, tags, and deterministic snapshots.

For inspection, `StatSet::normalized(id, &registry)` returns a `0.0..=1.0`
ratio across the stat bounds, while `is_at_or_below`,
`is_at_or_above`, `is_at_or_below_percent`, and
`is_at_or_above_percent` give authors small threshold helpers. These helpers are
for the author's own UI, rules, effects, alarms, or progression systems; the
framework still does **not** implement any of those layers or assign gameplay
meaning to a stat id.

`StatSet` works in two scopes:

- **Global stats**: use the `StatSet` resource initialized by
  `VoxelStatsPlugin` for world/session values.
- **Entity stats**: attach `StatSet::from_registry(&registry)` as a component
  to any entity that needs its own values: player, mob, vehicle, machine,
  settlement, or any other author-defined subject.

```rust
use bevy::prelude::*;
use bevy::ecs::message::{MessageReader, MessageWriter};
use voxel_framework::prelude::*;

fn register_stats(mut registry: ResMut<StatRegistry>, mut values: ResMut<StatSet>) {
    registry
        .register(
            StatDefinition::new("oxygen", 100.0)
                .named("Suit Oxygen")
                .bounds(0.0, 100.0)
                .tag("space_suit")
                .attribute("ui_hint", "bar")
                .attribute("critical_threshold", 15.0),
        )
        .expect("stat id should be unique");

    values.ensure_registered(&registry);
}

fn spawn_subject(mut commands: Commands, registry: Res<StatRegistry>) {
    commands.spawn(StatSet::from_registry(&registry));
}

fn space_tick(
    registry: Res<StatRegistry>,
    mut values: ResMut<StatSet>,
    mut changed: MessageWriter<StatChanged>,
) {
    drain_stat("oxygen", 1.5, &registry, &mut values, &mut changed)
        .expect("oxygen should be registered");
}

fn react_to_stats(mut changed: MessageReader<StatChanged>) {
    for event in changed.read() {
        if event.id.as_str() == "oxygen" && event.current <= 15.0 {
            println!("Low oxygen!");
        }
    }
}

App::new()
    .add_plugins(MinimalPlugins)
    .add_plugins(VoxelStatsPlugin)
    .add_systems(Startup, (register_stats, spawn_subject).chain())
    .add_systems(Update, (space_tick, react_to_stats).chain());
```

Run the headless stats example:

```sh
cargo run --example stats_definitions
```

Like content snapshots, `StatRegistry::snapshot()` and `StatSet::snapshot()`
return deterministic serializable data for docs, tooling, manifests, or AI
inspection.

Use read helpers when you want to inspect state without changing it:

```rust
let oxygen_ratio = values.normalized("oxygen", &registry)?;

if values.is_at_or_below_percent("oxygen", 0.15, &registry)? {
    // Author-defined reaction: update UI, trigger rules, emit effects, etc.
}
```

Use `set_stat`, `add_stat`, `drain_stat`, and `fill_stat` when a Bevy system
wants to emit a `StatChanged` message. They emit only when the clamped value
actually changes. If you only need a plain data mutation, `StatSet::set`,
`StatSet::add`, `StatSet::drain`, and `StatSet::fill` remain available and do
not depend on Bevy message writers. If a reader must react in the same update as
the writer, order it after the writer with `.chain()` or explicit Bevy system
ordering.

## Author-defined Effects

`VoxelEffectsPlugin` initializes two empty resources:

- `EffectRegistry` — the catalog of effects the game author chooses to define.
- `ActiveEffectSet` — runtime active effects, usable globally or as an entity
  component.

This is not the older `player::effects::StatusEffectsPlugin`, and it is not a
potion system. The plugin intentionally registers **no** poison, speed,
regeneration, low-oxygen, buff/debuff taxonomy, or player-specific behavior.
Those are game decisions. The framework only provides ids, durations, stacks,
metadata, tags, deterministic snapshots, and optional Bevy lifecycle messages.

```rust
use bevy::prelude::*;
use bevy::ecs::message::{MessageReader, MessageWriter};
use voxel_framework::prelude::*;

fn register_effects(mut registry: ResMut<EffectRegistry>) {
    registry
        .register(
            EffectDefinition::new("low_oxygen")
                .named("Low Oxygen")
                .duration_secs(10.0)
                .max_stacks(3)
                .tag("space_suit")
                .attribute("ui_hint", "warning"),
        )
        .expect("effect id should be unique");
}

fn apply_effects(
    registry: Res<EffectRegistry>,
    mut active: ResMut<ActiveEffectSet>,
    mut applied: MessageWriter<EffectApplied>,
) {
    apply_effect("low_oxygen", &registry, &mut active, &mut applied)
        .expect("effect should be registered");
}

fn tick_active_effects(
    mut active: ResMut<ActiveEffectSet>,
    mut expired: MessageWriter<EffectExpired>,
) {
    tick_effects(1.0, &mut active, &mut expired);
}

fn react_to_effects(
    mut applied: MessageReader<EffectApplied>,
    mut expired: MessageReader<EffectExpired>,
) {
    for event in applied.read() {
        println!("Applied {}", event.id);
    }
    for event in expired.read() {
        println!("Expired {}", event.id);
    }
}

App::new()
    .add_plugins(MinimalPlugins)
    .add_plugins(VoxelEffectsPlugin)
    .add_systems(Startup, register_effects)
    .add_systems(
        Update,
        (apply_effects, tick_active_effects, react_to_effects).chain(),
    );
```

Attach `ActiveEffectSet::new()` to entities when the effect scope belongs to a
specific subject:

```rust
commands.spawn((MyMob, ActiveEffectSet::new()));
```

Read-side helpers keep gameplay and UI code registry-free once an effect is
active:

```rust
if active.is_active("low_oxygen") {
    let stacks = active.stacks("low_oxygen");
    let remaining = active.remaining_secs("low_oxygen");
    let ratio = active.remaining_ratio("low_oxygen");
}
```

Run the headless effects example:

```sh
cargo run --example effect_definitions
```

Like content and stats snapshots, `EffectRegistry::snapshot()` and
`ActiveEffectSet::snapshot()` return deterministic serializable data for docs,
tooling, manifests, or AI inspection. Active effect snapshots include both the
initial duration and current remaining duration for timed instances.

## Author-defined Retained HUD

`VoxelHudPlugin` is an explicit, non-generic presentation plugin. It is not
included in `UiPlugin`, `VoxelCorePlugin<V>`, or `VoxelPlugin<V>`, and it does
not require gameplay plugins or optional Cargo features:

```rust
App::new()
    .add_plugins(DefaultPlugins)
    .add_plugins(VoxelHudPlugin)
    .add_systems(Startup, register_hud)
    .add_systems(
        Update,
        publish_hud_values.in_set(HudSystemSet::Publish),
    );
```

Authors register neutral text, bar, icon, and bounded-segment definitions in
`HudRegistry`, then publish screen-ready `HudValue`s through `HudValueSet`.
`HudSystemSet::Publish` is the same-frame boundary before retained
reconciliation and rendering. Missing or mismatched values hide safely or use a
compatible author fallback, with transition-deduplicated `HudDiagnostic`
messages instead of panics.

`HudRegistry::snapshot()` and `HudValueSet::snapshot()` provide deterministic,
id-ordered inspection. They are not a persistence format or JSON/config DSL.
The plugin coexists with `UiPlugin` and custom Bevy UI, so custom overlays can
migrate element by element: keep game-owned queries, explicitly publish neutral
view values, verify each retained replacement, then remove the old entity.

There are no reserved ids, vertical presets, automatic stats/effects/content
bridges, player discovery, thresholds, rules, or interactions. See the complete
[HUD guide](docs/hud.md) and run the feature-independent headless example:

```sh
cargo run --example hud
cargo run --no-default-features --example hud
```

## World Configuration

The framework reads `world.toml` from the working directory at startup via `WorldConfigPlugin` (included in `VoxelPlugin`). If the file is absent or malformed, all values fall back to their defaults.

The bundled examples also support loading persisted world metadata from `worlds/<name>/world.json` when re-opening an existing saved world.

### world.toml format

```toml
seed = 42
spawn_position = [0.0, 0.0, 0.0]
load_distance = 150.0
unload_distance = 200.0

[asteroids]
seed = 42
count = 20
min_radius = 15.0
max_radius = 40.0

[lighting]
sun_illuminance = 15000.0
ambient_brightness = 0.1
```

`WorldConfig` is inserted as a Bevy resource after loading and can be read in any system:

```rust
fn my_system(config: Res<WorldConfig>) {
    println!("world seed: {}", config.seed);
}
```

### Building a generator from config

`WorldConfig::build_asteroid_generator()` constructs an `AsteroidGenerator` directly from the TOML asteroid settings:

```rust
fn setup(config: Res<WorldConfig>, mut commands: Commands) {
    use std::sync::Arc;
    use voxel_framework::prelude::*;

    let generator = config.build_asteroid_generator();
    commands.insert_resource(GeneratorResource::<DefaultVoxel> {
        generator: Arc::new(generator),
    });
}
```

The `WorldConfigPlugin` is registered automatically by `VoxelPlugin`. To add it standalone:

```rust
use voxel_framework::world::WorldConfigPlugin;

App::new()
    .add_plugins(WorldConfigPlugin)
    .run();
```

### Partial drop collection

With `DropsPlugin<I>`, collection inserts only what the primary inventory can
accept. A drop of three units arriving with room for one adds one unit and emits
one `ItemPickedUp<I>` message with `count = 1`; the same drop entity keeps two
units. When space becomes available, those two can be collected and the entity
is removed. Subsequent frames do not repeat the collection.

If the inventory accepts nothing, no pickup message is emitted and the entire
drop remains available until collection or its normal expiry. These rules use
the existing inventory capacity and quantity contracts; they introduce no stack
limit or inventory API change.

## Inventory and Crafting

With `items`, `Inventory<I>` and `ContainerComponent<I>` implement
`Container<I>` using the ordinary Rust API. With `crafting`, recipe input and
output quantities are aggregated by `ItemType` equality in first-occurrence
order, not by serialized bytes. Zero quantities are ignored, empty recipes are
allowed, and positive default/`is_empty()` items or totals above `u32::MAX` make
a recipe invalid. `can_craft` checks ingredients only, not output capacity.

Built-in containers stage consumption and production privately, then commit
only a complete exchange. Capacity is evaluated **after consumption**, so an
ingredient can free a slot for a different output. Failed exchanges leave the
inventory unchanged. Live stacks must be positive and non-empty, `capacity`
must equal `slots.len()`, and each item's aggregate quantity must fit `u32`.
`add` returns all unaccepted quantities, including representational overflow;
`count_of` defensively saturates for malformed public fields. There is no new
author-configured stack limit.

Custom containers can opt into the defaulted method
`Container::try_exchange_atomic(&mut self, remove: &[(I, u32)], add: &[(I, u32)])`
returning `Option<Result<(), ContainerExchangeError>>`. `None` and `Some(Err(_))`
must not mutate; `Some(Ok(()))` means the entire exchange completed. The neutral,
public `#[non_exhaustive]` error is available through `items` and the prelude:
`InvalidRequest`, `InvalidContainer`, `InsufficientItems`, and `CapacityExceeded`.
No new trait bounds or mandatory methods are required.

`try_craft` keeps its three errors: invalid requests/recipes become
`InvalidRecipe`, missing ingredients become `InsufficientIngredients`, and
invalid containers or output-capacity failures become `InventoryFull`.
Legacy containers returning `None` use a conservative **non-atomic fallback**:
it checks current space without crediting slots that consumption might free,
deduplicates requests, and checks actual removal/addition returns. It stops on
the first failure, never reports false success, and does not invent rollback.
Such a failure **may leave partial consumption or production**; implement the
atomic hook when all-or-nothing crafting is required.

### Inventory JSON persistence

`save_inventory` and `load_inventory` keep their existing signatures and JSON
schema. Saving a malformed source returns an `InvalidInput` I/O error. Loading
rejects a capacity/slot-length mismatch or per-item aggregate overflow with
`InvalidData`; malformed JSON is also an error. Zero-count entries and item
bytes decoded as unknown/default/`is_empty()` become `None` at the same indexes.
Valid holes, duplicate stacks, and slot order are preserved, including
zero-capacity inventories. No save migration or arbitrary capacity ceiling is
introduced.

Saving serializes first, writes a private sibling temporary file with
`write_all`, applies existing `Permissions`, syncs the file, and replaces the
destination atomically. Any failure before replacement preserves the previous
bytes and cleans up the temporary file; there is no delete-old-first or direct
write fallback. New files retain private temporary-file permissions. Existing
symlinks are followed while preserving the link; dangling symlinks, non-regular
or read-only targets, and multiply hard-linked files on Unix are rejected.

These guarantees concern whole-file visibility and pre-replacement failure,
**not universal power-cut durability**. Existing `Permissions` are preserved,
but ownership, ACLs, extended attributes, and protection against hostile parent
namespace races are not guaranteed. Concurrent successful writers leave one
whole last-writer snapshot, not transaction isolation. These inventory-JSON
guarantees do not change chunk/world persistence or add automatic game-state
saving.

## Persistence

`PersistencePlugin` wires chunk auto-save into the Bevy game loop. Only chunks whose voxels or state bytes changed are written: after an edit, the next `ChunkModified` event saves the chunk in binary format, and a chunk that still has unsaved changes is saved when it streams out of range (save-on-unload). Generated terrain that nobody edited is never written; it is generated again the next time it loads.

```rust
use voxel_framework::prelude::*;

App::new()
    .add_plugins(PersistencePlugin::<DefaultVoxel>::new());
```

Use a custom voxel type the same way:

```rust
App::new()
    .add_plugins(PersistencePlugin::<MyVoxel>::new());
```

### Overriding PersistenceConfig

`PersistenceConfig` controls the save directory and whether auto-save is active. `PersistencePlugin` installs its defaults when it is added, so insert your override after the plugin:

```rust
use voxel_framework::world::PersistenceConfig;

App::new()
    .add_plugins(PersistencePlugin::<DefaultVoxel>::new())
    .insert_resource(PersistenceConfig {
        save_dir: "./saves/chunks".to_string(),
        auto_save: true,
    });
```

| Field | Default | Description |
|---|---|---|
| `save_dir` | `"./worlds/world/chunks"` | Directory for chunk binary files (created automatically) |
| `auto_save` | `true` | Save chunks with unsaved changes, on `ChunkModified` and on unload |

On load, the generator pipeline's background task calls `try_load_chunk` first. If a saved file exists for a given coordinate it is restored and generation is skipped; no chunk file is read on the main thread. A restored chunk is not written back until it is edited again.

`Chunk::is_dirty()` reports whether a chunk has unsaved changes. `Chunk::set` and `Chunk::set_state` track them for you; if you write the public `Chunk::states` array directly, call `Chunk::mark_dirty()` so the change is saved.

## Meshing budget

Chunk meshes are built on the main thread. When a whole region finishes loading at once (the initial load, or flying fast into unloaded terrain), thousands of chunks ask for a mesh in the same frame. `ChunkMeshBudget` bounds how many are built per frame; the rest wait in `PendingChunkMeshes` and are built on the following frames, nearest to the viewer first.

```rust
use voxel_framework::prelude::*;

App::new()
    .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
    // Default is 64 meshes per frame.
    .insert_resource(ChunkMeshBudget::new(32));
```

| Value | Effect |
|---|---|
| `ChunkMeshBudget::default()` | 64 meshes per frame |
| `ChunkMeshBudget::new(n)` | `n` meshes per frame: lower means shorter frames and slower fill-in |
| `ChunkMeshBudget::UNLIMITED` | Everything in the frame it was requested (the behavior before this budget existed) |

Only chunks that reach the mesher count against the budget. All-air chunks and chunks that were unloaded meanwhile are skipped at a small fraction of the cost (up to 16 of them per unit of budget each frame). `PendingChunkMeshes::len()` tells how many chunks are still waiting, and `MeshSystems` is the system set to order after if you want to read it for the current frame.

A voxel edit on a chunk border asks for two chunks to be remeshed. With a very small budget, or in the middle of a backlog, the two can be rebuilt on different frames.

## LOD System

Chunks have two discrete detail levels driven by distance from the viewer. The `ChunkLod` component on each chunk entity tracks the current level and is updated every frame by `lod_update_system`.

| LOD level | Distance from viewer | Greedy-mesh step | Detail |
|---|---|---|---|
| `0` | < 200 units | 1 | Full |
| `1` | >= 200 units | 2 | Half |

When the level changes, a `ChunkModified` event is emitted so the mesh system regenerates the geometry at the new step size.

**Hysteresis** prevents oscillation at boundaries: a chunk must move clearly past a threshold before the LOD level changes, avoiding rapid mesh rebuilds when the viewer hovers near a distance boundary.

`compute_lod` and `lod_to_step` are available from the prelude if you need to query LOD directly:

```rust
use voxel_framework::prelude::*;

// chunk_pos is the world-space position of the chunk (e.g. from chunk_center())
let lod: u8 = voxel_framework::mesh::lod::compute_lod(chunk_pos, viewer_pos);
let step: usize = voxel_framework::mesh::lod::lod_to_step(lod);
```

## Occlusion Culling

`OcclusionPlugin` hides any chunk whose six face-adjacent neighbors are all fully solid. Because none of that chunk's border faces are visible, its mesh is set to `Visibility::Hidden` automatically and restored when a neighbor changes.

```rust
use voxel_framework::prelude::*;

App::new()
    .add_plugins(DefaultPlugins)
    .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
    .add_plugins(OcclusionPlugin::<DefaultVoxel>::new())
    .run();
```

You can also query occlusion directly without the plugin:

```rust
use voxel_framework::prelude::*;

let occluded = is_chunk_occluded::<DefaultVoxel>(coord, &manager, &chunks);
```

## Mining & Placement

Both systems are pure-function APIs — no hidden Bevy systems are injected. Register the plugins to initialize resources and messages, then call the free functions from your own systems.

```rust
App::new()
    .add_plugins(MiningPlugin)
    .add_plugins(PlacementPlugin);
```

### Mining

`tick_mining` is called every frame while the mine button is held. It accumulates elapsed time against `MiningConfig::break_time`, emits `MiningProgress` each frame, and emits `VoxelBroken` (plus `ChunkModified` to trigger remeshing) when the voxel breaks.

```rust
fn my_mining_system(
    time: Res<Time>,
    mut state: ResMut<MiningState>,
    config: Res<MiningConfig>,
    manager: Res<ChunkManager>,
    mut chunks: Query<&mut Chunk<DefaultVoxel>>,
    mut broken: MessageWriter<VoxelBroken>,
    mut progress: MessageWriter<MiningProgress>,
    mut modified: MessageWriter<ChunkModified>,
) {
    // Call when mine button held:
    tick_mining(target_chunk, target_local, time.delta_secs(),
        &mut state, &config, &manager, &mut chunks,
        &mut broken, &mut progress, &mut modified);
}
```

The input adapter mines a 2×2 patch on the struck face after the primary
voxel breaks. Every neighboring voxel independently requires the active tool
to meet its `mining_level()`. Protected neighbors remain intact and emit no
`VoxelBroken` message, so they cannot produce drops through the drop plugin.
The raycast reach remains six world units.

Call `stop_mining` when the button is released to reset progress:

```rust
stop_mining(&mut state);
```

Override break time via `MiningConfig`:

```rust
app.insert_resource(MiningConfig { break_time: 2.0 });
```

### Mining progress overlay

`MiningOverlayPlugin` is an optional Default Implementation plugin that shows
how far along the targeted voxel is. It is not part of `VoxelCorePlugin` or
`VoxelPlugin`. It reads `MiningState` in `PostUpdate` and keeps one overlay
entity (`MiningOverlay`) on the voxel while it is mined; the entity is moved
when the target changes and despawned when mining stops or the voxel breaks.
The chunk mesh and the chunk material are not involved.

The framework ships no artwork: the game supplies one `StandardMaterial` per
damage stage. With no stages (the default) nothing is drawn.

```rust
fn setup_overlay(
    mut config: ResMut<MiningOverlayConfig>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    config.stages = [0.15, 0.3, 0.45]
        .into_iter()
        .map(|alpha| {
            MiningOverlayStage::new(materials.add(StandardMaterial {
                base_color: Color::srgba(0.0, 0.0, 0.0, alpha),
                alpha_mode: AlphaMode::Blend,
                unlit: true,
                ..default()
            }))
        })
        .collect();
}

app.add_plugins(MiningOverlayPlugin)
    .add_systems(Startup, setup_overlay);
```

| `MiningOverlayConfig` field | Default | Meaning |
|---|---|---|
| `visible` | `true` | `false` removes the overlay |
| `stages` | empty | Stages from least to most damaged; progress is split evenly across them |
| `mesh` | `None` | Mesh shared by the stages; `None` is a cube one voxel wide |
| `scale` | `1.002` | Uniform scale that keeps the overlay just outside the voxel faces |

A stage can carry its own mesh (`MiningOverlayStage::with_mesh`).
`mining_overlay_stage(progress, stage_count)` is the pure mapping the plugin
uses, in case a game wants the same stages for sound or UI. To add components
to the overlay entity (a render layer, a shadow setting), query
`Added<MiningOverlay>`.

### Placement

`try_place_voxel` is called once when the place button is pressed. It returns `false` if the cooldown has not expired or the target voxel is already solid. `tick_placement` advances the cooldown timer and must be called every frame.

```rust
fn my_placement_system(
    time: Res<Time>,
    mut state: ResMut<PlacementState>,
    config: Res<PlacementConfig>,
    manager: Res<ChunkManager>,
    mut chunks: Query<&mut Chunk<DefaultVoxel>>,
    mut placed: MessageWriter<VoxelPlaced>,
    mut modified: MessageWriter<ChunkModified>,
) {
    // Advance cooldown every frame:
    tick_placement(time.delta_secs(), &mut state, &config);

    // Call once on button press:
    try_place_voxel(target_chunk, target_local, DefaultVoxel::Rock, face_normal,
        &mut state, &config, &manager, &mut chunks,
        &mut placed, &mut modified);
}
```

Override cooldown via `PlacementConfig`:

```rust
app.insert_resource(PlacementConfig { cooldown: 0.5 });
```

## Loading Screen

`LoadingPlugin` tracks the initial chunk load and emits two message types:

- `LoadingProgress` — fired every frame while loading, carries `loaded`, `total`, and `progress` (0.0–1.0).
- `WorldReady` — fired exactly once when all chunks within `load_distance` are loaded for the first time and none of them is still waiting for its mesh (see [Meshing budget](#meshing-budget)). `LoadingProgress::progress` can therefore sit at `1.0` for a few frames before `WorldReady` arrives.

```rust
App::new()
    .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
    .add_plugins(LoadingPlugin);
```

Detect `WorldReady` to transition out of a loading screen:

```rust
fn loading_system(mut ready: MessageReader<WorldReady>) {
    for _ in ready.read() {
        // Transition out of loading screen
    }
}
```

Drive a progress bar with `LoadingProgress`:

```rust
fn progress_system(mut progress_events: MessageReader<LoadingProgress>) {
    for ev in progress_events.read() {
        println!("Loading: {}/{} ({:.0}%)", ev.loaded, ev.total, ev.progress * 100.0);
    }
}
```

### Built-in overlay

`LoadingScreenPlugin` (part of `UiPlugin`) draws a full-screen overlay with a title and a progress bar until the world is ready. Insert its resources before `Startup` to restyle it: `LoadingScreenConfig` for the background, text color, title and whether the bar is shown, and `LoadingScreenTheme` for the colors of the bar. The font of the title is `UiFonts::display` (see [UI Fonts](#ui-fonts)):

```rust
use voxel_framework::prelude::{LoadingScreenConfig, LoadingScreenTheme};

app.insert_resource(LoadingScreenConfig {
    background_color: [0.95, 0.95, 0.92, 1.0],
    text_color: [0.1, 0.1, 0.1, 1.0],
    ..Default::default()
})
.insert_resource(LoadingScreenTheme {
    bar_color: Color::srgb(0.2, 0.2, 0.2),
    bar_background: Color::srgb(0.8, 0.8, 0.78),
});
```

| `LoadingScreenTheme` field | Default | Applies to |
|---|---|---|
| `bar_color` | `Color::srgba(0.2, 0.7, 0.3, 1.0)` | Filled part of the progress bar |
| `bar_background` | `Color::srgba(0.2, 0.2, 0.2, 1.0)` | Track behind it |

`WorldLoadingState` is also available as a resource if you prefer polling over event handling:

```rust
fn check_ready(state: Res<WorldLoadingState>) {
    if state.ready {
        // world is loaded
    }
}
```

## Player

`PlayerPlugin<V>` adds a first-person player with capsule collision, mouse look, WASD movement, and selectable movement/look modes. The default is zero-g 6DOF flight; anchored free flight and grounded gravity movement are also available through `PlayerConfig::mode`.

```rust
use voxel_framework::player::PlayerPlugin;

App::new()
    .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
    .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
    .insert_resource(PlayerConfig {
        spawn_position: Vec3::new(0.0, 50.0, 150.0),
        speed: 16.0,
        ..default()
    });
```

`PlayerMovementConfig` tunes how quickly the player reaches and loses speed, and when a collision is reported:

```rust
app.insert_resource(PlayerMovementConfig {
    acceleration: 4.0,           // default 12.0; lower = slower to reach speed
    deceleration: 2.0,           // default 7.0; lower = longer coast
    impact_speed_threshold: 3.0, // default 1.0 units/s
});
```

When the player runs into terrain faster than `impact_speed_threshold`, `player_resolve_collision` writes one `PlayerImpact { position, normal, speed }` message. Use it for feedback scaled by `speed`, such as a sound. Staying pressed against the surface does not repeat the message; set the threshold to `f32::INFINITY` to turn it off.

### Camera response to movement

`CameraResponseConfig` makes the player camera react to movement: the field of view widens with speed and the camera leans toward sideways movement. The default is neutral (both amounts are zero), so nothing changes until a game sets them:

```rust
app.insert_resource(CameraResponseConfig {
    fov_boost_degrees: 6.0,  // added to the base FOV at full speed; default 0.0
    lean_degrees: 2.0,       // roll toward strafing at full sideways speed; default 0.0
    smoothing_seconds: 0.15, // time constant; default 0.0 follows instantly
    ..default()              // enabled: true, reference_speed: None (= Player::speed)
});
```

Set `enabled` to `false` at runtime (for example from an accessibility setting) to put the camera back to its base field of view and orientation on the next frame while keeping the tuned amounts.

- The boost is added to whatever field of view the camera's `Projection` holds. A value written by something else, such as the settings menu, becomes the new base. `CameraResponse::base_fov_radians()` on the player entity returns the base without the boost.
- The lean is a roll around the view direction. It is removed before `player_look` and applied again after collision, so movement axes, the collision capsule and snap roll use the player's own orientation, and the view direction never changes. Systems that read the player's `Transform` outside the player systems see `up` and `right` tilted by the lean.
- While the pause menu is open the camera is back at its base values.
- With manually registered systems, add `camera_response_restore` before `player_look` and `camera_response_apply` after `player_resolve_collision`.

| Input | Action |
|---|---|
| Mouse | Depends on `PlayerConfig::mode`: `FreeFlightSixDof` gives yaw + pitch with no clamp; `FreeFlightAnchored` gives FPS-style yaw around a world-axis anchor with pitch clamped to ±89° and a level horizon |
| Q / E | In `FreeFlightSixDof`, roll left/right (continuous or snap, configured in the mode); in `FreeFlightAnchored`, switch the anchor to the next signed world axis (±X/±Y/±Z) with a snap animation; disabled in `Grounded` |
| W / S | Forward / backward |
| A / D | Strafe left / right |
| Space | Move along local up |
| Shift | Move along local down |
| Left click in focused window | Lock cursor and enable player input |
| Escape | Without `PauseMenuPlugin`: release cursor (if already free: close focused window). With it: open the pause menu |

The player starts with a free, visible cursor. Click the focused game window to
control it. Losing focus releases control; returning requires another click.
Look and movement ignore input while unfocused or released. Pointer capture does
not grant OS keyboard focus or disable desktop shortcuts. Headless simulations
without a primary window retain synthetic-input support. Other input systems can
use `player_input_active` as a run condition; keep `player_look` scheduled so it
can discard inactive mouse motion.

For a native diagnostic, run `cargo run --example player_focus`. Click the window,
move with WASD, press Escape, and Alt-Tab away and back. The example logs native
focus events and received keys. Verify that startup and focus return leave the
cursor free, inactive input does not move/rotate the camera, and a fresh focused
click restores control. Check ordinary keys separately from desktop shortcuts.

`PlayerPlugin` works together with `PauseMenuPlugin`: the player pauses with the menu, Escape opens the menu instead of releasing the cursor or closing the window, and click-to-capture and focus-loss release keep working while unpaused.

If your game uses its own `AppState`, gate or order the whole plugin through the `PlayerSystems` set:

```rust
App::new()
    .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
    .configure_sets(Update, PlayerSystems.run_if(in_state(MyState::Playing)));
```

Or skip `PlayerPlugin` and add the systems manually (this drops the plugin's spawn-position persistence):

```rust
use voxel_framework::prelude::{
    player_cursor_system, player_look, player_move, player_resolve_collision,
};

App::new()
    .add_systems(Startup, spawn_player)
    .add_systems(Update, player_cursor_system)
    .add_systems(Update,
        (player_look, player_move, player_resolve_collision::<DefaultVoxel>)
            .chain()
            .run_if(in_state(MyState::Playing)),
    );
```

## Mobs

Requires the `mobs` feature (on by default). `MobPlugin<V>` runs the basic mob:
a colored box with patrol/chase/attack AI, gravity and voxel collision.
`spawn_mob` places one by hand.

Mob types are named configurations of that basic mob. Register them in
`MobRegistry` and let `MobSpawnerPlugin<V>` spawn them around every `Player`
according to rules:

```rust
use voxel_framework::prelude::*;

let mut registry = MobRegistry::default();
registry.register("slime", MobConfig::default());
registry
    .register_variant("night_slime", "slime", |config| {
        config.chase_speed = 5.0;
        config.color = Color::srgb(0.3, 0.1, 0.6);
    })
    .unwrap();

let rules = MobSpawnRules::default()
    .with_rule(SpawnRule::new("slime").time(TimeWindow::Day).cap(3))
    .with_rule(
        SpawnRule::new("night_slime")
            .time(TimeWindow::Night)
            .ring(12.0, 32.0)          // min/max distance from the player
            .cap(6)                    // live mobs of this kind per player
            .zone(|ctx| ctx.position.y < 80.0)
            .despawn_outside_window(true),
    );

app.add_plugins(MobPlugin::<MyVoxel>::new())
    .add_plugins(MobSpawnerPlugin::<MyVoxel>::new())
    .add_plugins(DayCyclePlugin)
    .insert_resource(registry)
    .insert_resource(rules);
```

| Rule field | Default | Meaning |
|---|---|---|
| `weight` | `1.0` | Relative chance among the rules that apply |
| `ring` | `[12, 32]` | Distance band around the player; capped below the kind's `despawn_distance`. Ground rules need at least 1.5 units of width |
| `time` | `Any` | `Any`, `Day` (`[0.25, 0.75)`), `Night`, or `Range { start, end }` (wraps midnight) |
| `placement` | `Ground` | `Ground`: on a solid voxel with two free voxels above, never farther than `ring.max` in 3D. `Air`: free space, for zero-gravity mobs |
| `cap` | `4` | Most live mobs of the kind within `ring.max` of one player |
| `zone` | none | Extra predicate on the candidate position (hook for biomes or regions) |
| `despawn_outside_window` | `false` | Despawn the mob when `time` stops applying |

The spawner evaluates every `MobSpawnRules::interval_secs` (default 2 s) and
spawns at most one mob per player per evaluation, only in loaded chunks.
Without `DayCyclePlugin` only `TimeWindow::Any` rules apply. Mobs despawn by
distance to the nearest `Player`; mob AI still assumes a single `Player`.

## Crosshair

`CrosshairPlugin` (part of `UiPlugin`) draws a center-screen crosshair. By
default it is the four-arm cross described by `CrosshairConfig`. Two more
resources, both initialized by the plugin unless the game inserted them first,
select another shape and switch it with what the player points at:

| Resource | Controls | Default |
|---|---|---|
| `CrosshairConfig` | The classic cross (`color`, `size`, `gap`, `thickness`) and `visible` | white cross, visible |
| `CrosshairStyles` | An optional `CrosshairStyle` for the `idle` state and one for `targeting` | both `None`: the classic cross in every state |
| `CrosshairTarget` | The state: `Idle` or `Targeting` | `Idle` |

A `CrosshairStyle` has a `shape` (`CrosshairShape::Cross`, `Dot`, `Diamond`
outline or `Image(handle)`), a `color`, and `size`, `gap` and `thickness` in
logical pixels. `size` is the arm length of a cross, the diameter of a dot,
the corner-to-corner width of a diamond and the side of an image.

```rust
App::new()
    .insert_resource(CrosshairStyles {
        idle: Some(CrosshairStyle::dot(4.0)),
        targeting: Some(CrosshairStyle {
            color: [1.0, 0.9, 0.3, 1.0],
            ..CrosshairStyle::diamond(18.0)
        }),
    })
    .add_plugins(CrosshairPlugin)
    // Optional: publish the state from a camera raycast.
    .insert_resource(CrosshairReach { max_distance: 6.0 })
    .add_plugins(CrosshairTargetPlugin::<DefaultVoxel>::new());
```

The framework does not decide what "in reach" means; `CrosshairTarget` is
published. `CrosshairTargetPlugin<V>` is an opt-in adapter, not part of
`UiPlugin` or of any bundle: each frame it raycasts along the forward
direction of the single `Camera3d` and sets `Targeting` when the first solid
voxel within `CrosshairReach::max_distance` can be mined with the current
`ToolStats::tool_level` (level `0` without that resource). For any other rule,
leave it out and write the resource from a game system:

```rust
fn publish_target(mut target: ResMut<CrosshairTarget>) {
    let can_act = /* the game's own check */ true;
    target.set_if_neq(if can_act {
        CrosshairTarget::Targeting
    } else {
        CrosshairTarget::Idle
    });
}

app.add_systems(Update, publish_target.in_set(CrosshairSystems::Publish));
```

Systems in `CrosshairSystems::Publish` run before the crosshair is redrawn, so
the new state shows in the same frame. Any system can also read
`CrosshairTarget`, for example to show a hint next to the crosshair. A missing
style falls back: `idle: None` keeps the classic cross and `targeting: None`
shows the idle look. Styled shapes are centered on the screen; a state without
a style keeps the classic cross exactly as `CrosshairConfig` draws it.

## Static Sky

`SkyboxMode::Static` describes a sky with no day cycle: a background color and
any number of layers of unlit figures. The framework decides nothing about the
look; every color, shape, size, count and timing is a value in
`StaticSkyConfig`. The default mode is still the starfield.

## Ambient Particles

`AmbientParticlesPlugin` (Default Implementation, not part of any bundle)
keeps a pool of small unlit particles in a sphere around `ViewerPosition`.
They have no gravity and no lifetime: each one rests at a fixed place in the
world, so the field streams past when the viewer moves. A particle that leaves
the volume is recycled on the opposite side, and particles shrink to nothing
near the surface of the sphere so recycling does not pop.

```rust
use bevy::prelude::*;
use voxel_framework::prelude::*;

fn sky() -> SkyboxConfig {
    SkyboxConfig {
        mode: SkyboxMode::Static(StaticSkyConfig {
            background: Color::srgb(0.02, 0.02, 0.05),
            seed: 7,
            layers: vec![
                SkyLayer {
                    shape: SkyShape::Quad,
                    count: 600,
                    size: SkyRange::new(1.0, 3.0),
                    colors: vec![(Color::WHITE, 3.0), (Color::srgb(1.0, 0.8, 0.6), 1.0)],
                    placement: SkyPlacement::Scattered,
                    animation: Some(SkyTwinkle {
                        amplitude: 0.4,
                        period: SkyRange::new(4.0, 9.0),
                        groups: 8,
                    }),
                    ..default()
                },
                SkyLayer {
                    shape: SkyShape::Diamond,
                    count: 12,
                    size: SkyRange::fixed(20.0),
                    region: SkyRegion::band(0.2, 0.6),
                    ..default()
                },
            ],
            ..default()
        }),
    }
}
```

Insert the resource before adding `SkyboxPlugin` (or `VoxelPlugin`, which
includes it).

| `SkyLayer` field | Default | Meaning |
|---|---|---|
| `shape` | `SkyShape::Cube` | `Cube`, `Quad`, `Diamond` (octahedron) or `Mesh(handle)`; meshes are unit-sized and scaled by the figure size |
| `count` | `0` | Number of figures |
| `size` | `1.0` | A value or a `SkyRange`, picked per figure |
| `colors` | empty (white) | `(Color, weight)` pairs, picked per figure |
| `placement` | `SkyPlacement::Even` | `Even` golden-angle spiral or seeded `Scattered` |
| `region` | full sphere | `SkyRegion::full()`, `band(min, max)` or `cap(center, half_angle)`, in radians |
| `orientation` | `SkyOrientation::FaceCenter` | `FaceCenter` turns local `+Z` to the sky center; `WorldAligned` keeps the world axes |
| `animation` | `None` | `SkyTwinkle`: brightness varies between `1 - amplitude` and `1` |

`StaticSkyConfig` also has `radius` (default `900.0`, keep it below the camera
far plane), `seed`, and `follow_viewer` (default `true`), which keeps the sky
centered on `ViewerPosition` so figures stay at a fixed distance.
`StaticSkyConfig::from_starfield(&StarfieldConfig::default())` gives the
starfield as a one-layer static sky to extend.

The layout comes from pure functions, `generate_sky_layer` and
`generate_sky_layout`, so the same configuration always gives the same sky and
a game can inspect or test it without a window. Animated layers use one
material per color and group, not per figure. The sky is built once at
startup, `world.toml` cannot describe it, and `DayCyclePlugin` overrides the
background color when both are active.

App::new()
    .add_plugins(DefaultPlugins)
    .insert_resource(AmbientParticlesConfig {
        count: 200,
        volume_radius: 30.0,
        size_range: (0.02, 0.06),
        color: Color::srgb(0.8, 0.85, 1.0),
        shape: AmbientParticleShape::Sphere,
        ..Default::default()
    })
    .add_plugins(AmbientParticlesPlugin)
    .run();
```

| Field | Meaning | Default |
|---|---|---|
| `enabled` | Show particles; `false` empties the pool | `true` |
| `count` | Pooled entities, spread over the cube that bounds the volume (a little over half are inside the sphere at once) | `96` |
| `volume_radius` | Radius of the visible sphere around the viewer | `24.0` |
| `size_range` | Smallest and largest particle size | `(0.03, 0.08)` |
| `color` | Base color of the shared unlit material; alpha below 1 blends | white |
| `shape` | `Cube`, `Sphere` or `Custom(Handle<Mesh>)` (unit-size mesh) | `Cube` |
| `edge_fade` | Fraction of the radius over which particles shrink at the edge | `0.25` |
| `drift_speed` | Speed of each particle along its own fixed direction | `0.0` |
| `seed` | Seed of the particle field | `0` |

All particles share one mesh and one material (`AmbientParticleAssets`); sizes
are applied through each entity's `Transform`. The config can be changed at
runtime. The systems run in `PostUpdate` in the `AmbientParticleSystems` set,
so a `ViewerPosition` written in `Update` is used in the same frame. The game
must keep `ViewerPosition` updated; the framework never discovers a camera.

Placement is a pure function, `ambient_particle_state(index, viewer,
elapsed_secs, &config)`, which a game can call to test or preview a
configuration without a window.

## Pickup Notifications

With `items`, `PickupNotificationPlugin<I>` (part of `UiPlugin` for
`DefaultItem`) shows a timed `+N ItemName` line for each `ItemPickedUp<I>`
message. Four resources configure it; the plugin initializes each one unless
the game inserted it first, and the defaults give a plain white line per
pickup in the top-right corner.

| Resource | Controls | Default |
|---|---|---|
| `PickupNotificationConfig` | Visibility, duration, text color, how many at once | visible, 3 s, white, 5 |
| `PickupNotificationFilter` | Which pickups notify: `Every`, `FirstPerItemType`, `OnRequest` | `Every` |
| `PickupNotificationLayout` | `anchor` (a `HudAnchor`), `offset`, optional `background`, `padding`, `accent_bar` and `label` line | top-right, `[16, 16]`, no decoration |
| `PickupNotificationSeen<I>` | Item types already announced under `FirstPerItemType` | empty |

```rust
App::new()
    .insert_resource(PickupNotificationFilter::FirstPerItemType)
    .insert_resource(PickupNotificationLayout {
        anchor: HudAnchor::BottomLeft,
        offset: [24.0, 96.0],
        background: Some([0.0, 0.0, 0.0, 0.6]),
        padding: [10.0, 6.0],
        accent_bar: Some(PickupNotificationAccentBar {
            color: [1.0, 0.8, 0.2, 1.0],
            width: 4.0,
        }),
        label: Some(PickupNotificationLabel {
            text: "New item".to_string(),
            color: [1.0, 0.8, 0.2, 1.0],
        }),
    })
    .add_plugins(PickupNotificationPlugin::<DefaultItem>::new());
```

`PickupNotificationSeen<I>` lives in memory only. To keep "first time" across
sessions, save the items yourself and call `insert` for each on load; `clear`
starts over.

For a rule of your own, set `PickupNotificationFilter::OnRequest`, read
`ItemPickedUp<I>` in a game system and write `ShowPickupNotification<I>` for
the pickups to announce. That message is shown under every filter and does not
touch the seen record.

Placement follows `PickupNotificationLayout` whenever it changes; decoration
applies to notifications spawned afterwards. Both text lines use the same
font (`UiFonts::text`, see [UI Fonts](#ui-fonts)) and size.

## UI Fonts

The `UiFonts` resource holds the fonts of the text drawn by the built-in UI
plugins. Its default is two default handles, which select the engine default
font, so nothing changes until a game inserts its own:

```rust
use voxel_framework::prelude::UiFonts;

fn load_fonts(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.insert_resource(UiFonts::new(
        asset_server.load("fonts/Display.ttf"),
        asset_server.load("fonts/Text.ttf"),
    ));
}

app.add_systems(Startup, load_fonts);
```

| `UiFonts` field | Used by |
|---|---|
| `display` | Loading screen title (`LoadingScreenPlugin`) |
| `text` | Retained HUD text (`VoxelHudPlugin`), hotbar item name, symbols and counts (`HotbarContentPlugin<I>`), pickup notification lines (`PickupNotificationPlugin<I>`) |

`UiFonts::uniform(font)` uses one font for both. The struct is
`#[non_exhaustive]`, so build it with `new` or `uniform`, or change the fields
of `UiFonts::default()`.

A change to the resource at runtime is applied to the text that is already on
screen, not only to text spawned later. The system that inserts it therefore
needs no ordering against the plugins, and fonts can be swapped while the game
runs.

One retained HUD element can use another font, which takes precedence over
`UiFonts::text`:

```rust
registry.register(
    HudElementDefinition::new("title", HudPresentation::Text(HudText::new("title_value")))
        .font(asset_server.load("fonts/Display.ttf")),
)?;
```

The framework only stores the handles: the game loads the fonts. The pause menu
keeps its own fonts in `PauseMenuConfig` (see [Pause Menu](#pause-menu)), and
the debug overlay always uses the engine default font.

## Test Automation

With the `automation` cargo feature, `AutomationPlugin` lets a script or a remote client drive a running game: press keys and UI buttons, move the camera, list the UI on screen, save screenshots, and exit with a status code. It exists so a change to something drawn can be checked without a person watching the window.

It is off by default twice over: nothing is compiled without the feature, and with the feature the plugin still does nothing unless the game adds `AutomationPlugin::enabled(config)`, typically behind a command-line flag of its own. The framework never enables it by itself, and the remote endpoint only ever listens on `127.0.0.1`.

```sh
cargo run --example basic_world --features automation -- \
    --automation examples/automation/pause_menu.json
```

That run opens the pause menu and its settings submenu, saves three screenshots and a UI listing under `./automation/`, and exits. The script format, the remote methods and the limits are in [`docs/automation.md`](docs/automation.md).

## Pause Menu

`PauseMenuPlugin` is an optional plugin that provides a full pause menu with a settings submenu. It manages its own `PauseMenuState`. `PlayerPlugin` reads it automatically; gate your own gameplay systems on it:

```rust
use voxel_framework::prelude::{PauseMenuPlugin, PauseMenuState};

App::new()
    .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
    .add_plugins(PauseMenuPlugin)
    .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
    .add_systems(Update, my_gameplay_system.run_if(in_state(PauseMenuState::Playing)));
```

Cursor ownership with both plugins:

| Event | Result |
|---|---|
| Left click in the focused window while playing | Cursor captured |
| Window loses focus | Cursor released; the game does not pause |
| Escape while playing | Menu opens, cursor released (the window never closes) |
| Resume or Escape in the menu | Cursor captured again if the window is focused |
| Click on a menu button other than Resume | Does not capture the cursor |

If you register the player systems by hand instead of using `PlayerPlugin`, add `player_cursor_system` too: the pause menu on its own does not capture on the first click or release on focus loss.

| State | Description |
|---|---|
| `PauseMenuState::Playing` | Normal gameplay — menus hidden |
| `PauseMenuState::Paused` | Pause overlay visible (Resume / Settings / Quit) |
| `PauseMenuState::Settings` | Settings submenu (FOV, SFX volume) |

The Settings submenu edits four values: field of view (the camera's `Projection` and `PlayerConfig::fov_degrees`), SFX volume (`SfxConfig::volume`), render distance (`WorldConfig` and `ChunkManager`) and mouse sensitivity (`PlayerConfig::sensitivity` and every live `Player`). Leaving it writes `SaveSettingsRequest`.

### Saving the settings

`SettingsPlugin` keeps those four values for one world. It is opt-in and no bundle adds it:

```rust
App::new()
    .add_plugins(PauseMenuPlugin)
    .add_plugins(SettingsPlugin::with_world("my_world"));
```

- **At startup** it reads `worlds/my_world/settings.json` and writes the values to `PlayerConfig`, `WorldConfig`, `ChunkManager` and `SfxConfig`, each only if the resource exists. It runs in `SettingsSystems::Load`, after `world.toml` is loaded and before `spawn_player`, so the player spawns with the saved field of view and sensitivity.
- **On `SaveSettingsRequest`** it writes the current values to the file. Any system may write that message.
- A missing or unreadable file changes nothing. Values outside the menu ranges are limited to them (50–120°, 0–1, 4–32 chunks, 10–100 %).
- A saved render distance equal to the configured load distance leaves your unload distance as it is. A different one sets the unload distance to the load distance plus `RENDER_DISTANCE_UNLOAD_MARGIN` (32 world units), which is what the menu does.
- Replace the `SettingsFile` resource to keep the file somewhere else.

For different rules, skip the plugin and use `PersistedSettings::load`, `apply`, `capture` and `save` from your own systems.

### Customizing the font

Override `PauseMenuConfig` before adding the plugin:

```rust
use voxel_framework::prelude::PauseMenuConfig;

fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.insert_resource(PauseMenuConfig {
        font: asset_server.load("fonts/MyFont.ttf"),
    });
}
```

### Customizing colors and the panel

The menu is a full-screen overlay that dims the scene and a centered panel that holds the title and the controls. Insert a `PauseMenuTheme` resource to restyle both the pause menu and its settings submenu; anything you leave out keeps the built-in look:

```rust
use voxel_framework::prelude::{ButtonColors, PauseMenuTheme};

app.insert_resource(PauseMenuTheme {
    overlay: Color::srgba(0.0, 0.0, 0.0, 0.5),
    panel: Color::srgb(0.95, 0.95, 0.92),
    header: Color::srgb(0.1, 0.1, 0.1),
    button: ButtonColors {
        normal: Color::srgb(0.2, 0.2, 0.2),
        hovered: Color::srgb(0.3, 0.3, 0.3),
        pressed: Color::srgb(0.1, 0.1, 0.1),
        text: Color::WHITE,
    },
    corner_radius: 8.0,
    panel_width: Val::Px(520.0),
    panel_padding: UiRect::all(Val::Px(32.0)),
    ..Default::default()
});
```

| Field | Default | Applies to |
|---|---|---|
| `overlay` | `Color::srgba(0.0, 0.0, 0.0, 0.78)` | Full-screen dim behind the panel |
| `panel` | `Color::NONE` | Background of the centered panel |
| `header` | `Color::WHITE` | Menu title (`PAUSED`, `SETTINGS`) |
| `text` | `Color::WHITE` | Current value in each settings row |
| `label` | `Color::srgb(0.8, 0.8, 0.8)` | Name of each settings row |
| `button` | dark blue-grey, white text | `Resume` and `Back` |
| `secondary_button` | same as `button` | `Settings`, `Quit` and the settings arrows |
| `corner_radius` | `0.0` | Panel and buttons, in logical pixels |
| `panel_width` | `Val::Auto` | Panel width; `Auto` fits the content |
| `panel_padding` | `UiRect::ZERO` | Space between the panel's edges and its content |

`ButtonColors` holds the `normal`, `hovered` and `pressed` backgrounds and the label's `text` color. The theme is read when a menu opens and when a button changes interaction state, so a change made while a menu is open is fully visible the next time it opens. Button sizes, font sizes and the order of the controls are fixed.

## Sound Effects

Sound effects are split into a request layer and a playback layer. `SfxPlugin` (included in `VoxelPlugin`) turns framework events into `SfxRequest` messages; `DefaultAudioPlugin` (opt-in) plays them with Bevy audio, or you read the messages in your own playback system. `SfxConfig` maps each `SfxEvent` to asset paths and holds the SFX volume; it is an ordinary resource, so paths can be re-registered at runtime to swap a sound set.

```rust
use voxel_framework::prelude::*;

fn setup_audio(mut sfx: ResMut<SfxConfig>) {
    sfx.register(SfxEvent::ItemPickup, vec!["sounds/pickup.ogg"]);
    sfx.register(SfxEvent::Custom("alarm".into()), vec!["sounds/alarm.ogg"]);

## Lighting

Three optional Default Implementation plugins in `lighting`. No bundle adds them, and each one does nothing until the game configures it. Every color, intensity, angle and budget comes from the game.

```rust
use bevy::prelude::*;
use voxel_framework::prelude::*;

fn setup(mut commands: Commands, mut lights: ResMut<PlacedLights>) {
    // The game decides which entity carries the headlamp.
    commands.spawn((Camera3d::default(), Headlamp { enabled: false, range: 30.0, ..default() }));
    // A light recorded at a voxel position.
    lights.insert(placed_light_voxel(Vec3::new(4.2, 10.9, -2.5)), PlacedLight::default());
}

fn toggle_headlamp(keys: Res<ButtonInput<KeyCode>>, mut lamps: Query<&mut Headlamp>) {
    if keys.just_pressed(KeyCode::KeyF) {
        for mut lamp in &mut lamps {
            lamp.toggle();
        }
    }
}

App::new()
    .add_plugins(DefaultPlugins)
    .add_plugins(VoxelPlugin::<DefaultVoxel>::new()) // includes SfxPlugin
    .add_plugins(DefaultAudioPlugin)
    .add_systems(Startup, setup_audio);
```

### Pitch per request

`PitchedSfxRequest` is a second message with the same event and optional position as `SfxRequest`, plus a playback-speed multiplier. `SfxRequest` itself is unchanged.

```rust
fn rising_sound(mut streak: Local<u32>, mut sfx: MessageWriter<PitchedSfxRequest>) {
    let pitch = 1.0 + 0.05 * (*streak).min(12) as f32;
    *streak += 1;
    sfx.write(PitchedSfxRequest::new(SfxEvent::ItemPickup, pitch));
    // With a position: PitchedSfxRequest::new(event, pitch).at(world_pos)
}
```

Pitch is playback speed: `2.0` is one octave up and half as long. NaN, infinite, zero and negative values play at normal speed; other values are clamped to `0.1..=8.0`. A custom playback system that wants pitched sounds reads `PitchedSfxRequest` and uses `effective_pitch()`.

### Muffling sound effects

`SfxFilter` is a resource, initialized by `DefaultAudioPlugin` with the filter off. Set a cutoff to low-pass filter the sound effects that plugin plays, and clear it to return to normal:

```rust
fn enter_muffled_state(mut filter: ResMut<SfxFilter>) {
    filter.low_pass_hz = Some(700.0);
}

fn leave_muffled_state(mut filter: ResMut<SfxFilter>) {
    *filter = SfxFilter::NONE;
}
```

Limits:

- Only sounds played by `DefaultAudioPlugin` are filtered. Audio you spawn yourself, and custom playback systems, are not.
- The filter is chosen when a sound starts. A sound started while the filter is on follows later cutoff changes; a sound started while it is off stays unfiltered until it ends.
- It is a 12 dB/octave low-pass per channel. There are no other effects.
- NaN, infinite, zero and negative cutoffs mean "no filter"; other values are clamped to `20..=20000` Hz.
- It needs Bevy's `AudioPlugin` and `AssetPlugin` (both in `DefaultPlugins`).

    .insert_resource(SceneLightingConfig {
        sun: Some(SunConfig { direction: Vec3::new(-1.0, -2.0, -1.0), shadows_enabled: true, ..default() }),
        fill: Some(FillLightConfig { color: Color::srgb(0.5, 0.6, 1.0), illuminance: 300.0, direction: None }),
        ambient: None,
    })
    .insert_resource(PlacedLightBudget { max_active: 8, max_distance: 96.0 })
    .add_plugins((SceneLightingPlugin, HeadlampPlugin, PlacedLightsPlugin))
    .add_systems(Startup, setup)
    .add_systems(Update, toggle_headlamp.before(LightingSystems::Headlamp))
    .run();
```

### Fixed sun, fill light and ambient

`SceneLightingPlugin` keeps the scene equal to the `SceneLightingConfig` resource and applies changes made at runtime. The default config is all `None`, which creates nothing.

| Field | Type | Effect |
|---|---|---|
| `sun` | `Option<SunConfig>` | A directional light tagged `SceneSunLight`: `color`, `illuminance`, `direction` (the way the light travels), `shadows_enabled` |
| `fill` | `Option<FillLightConfig>` | A shadowless directional light tagged `SceneFillLight`: `color`, `illuminance`, optional `direction`. Without a direction it opposes the sun |
| `ambient` | `Option<AmbientConfig>` | `color` and `brightness` written to Bevy's `GlobalAmbientLight`. `None` leaves it untouched |

`DayCyclePlugin` animates its own sun (`SunLight`) and the ambient brightness. The two plugins use different markers and do not edit each other's lights; pick one for the sun. To add a fill light to a day cycle, set only `fill`, with an explicit `direction`.

### Headlamp

`HeadlampPlugin` gives every entity that has a `Headlamp` component a child spot light (tagged `HeadlampLight`) that shines along the carrier's local `-Z`, which is where a camera looks. The framework does not look for a player or a camera: the game adds the component to the entity it wants, which needs a `Transform` and a `Visibility`. The fields are `enabled`, `color`, `intensity`, `range`, `radius`, `inner_angle`, `outer_angle`, `shadows_enabled` and `offset`; the default equals Bevy's `SpotLight::default()`, switched on. Changing a field updates the light, `Headlamp::toggle()` flips `enabled`, and removing the component despawns the light. The plugin reads no input.

### Placed lights

`PlacedLights` is a resource that records lights by voxel position (`insert`, `remove`, `get`, `get_mut`, `contains`, `iter`, `len`, `clear`). `PlacedLightsPlugin` shows a record as a point light (tagged `PlacedLightSource`) only while it is active, which means: its chunk is loaded, it is within `PlacedLightBudget::max_distance` of the `ViewerPosition`, and it is among the `max_active` nearest such lights (default `16`, no distance limit).

When a chunk unloads, the lights in it are despawned and their records stay, so they come back when the chunk loads again. The framework does not tie a record to the voxel at its position and does not save the records: remove the record when the game breaks the voxel that holds the light, and store the records with the game's own save data.

## Coordinate Utilities

Four free functions convert between world space, chunk grid, and local voxel space. All are available via `use voxel_framework::prelude::*`.

```rust
use bevy::math::Vec3;
use voxel_framework::prelude::*;

let world_pos = Vec3::new(18.5, 0.0, 0.0);

// Which chunk contains this world position?
let coord = world_to_chunk_coord(world_pos);
// → IVec3(1, 0, 0)  (chunk boundary at x=16.0)

// Which voxel within that chunk?
let (lx, ly, lz) = world_to_local_coord(world_pos);
// → (2, 0, 0)

// World-space minimum corner of a chunk.
let origin = chunk_origin(coord);
// → Vec3(16.0, 0.0, 0.0)

// World-space center of a chunk.
let center = chunk_center(coord);
// → Vec3(24.0, 8.0, 8.0)
```

All functions use Euclidean division so negative coordinates map to the correct chunk (e.g. `world_pos.x = -1.0` maps to chunk `-1`, not `0`).

## Asteroid Materials and Classes

`AsteroidGenerator` is generic over the voxel palette. `AsteroidGenerator::new(config)` builds the built-in `DefaultVoxel` field (rock with rare mineral, silicon crystal and iron ore veins) and its output for a given configuration does not change. `AsteroidGenerator::with_materials(config, materials)` takes your own material set for any `V: VoxelType`:

```rust
use std::sync::Arc;
use voxel_framework::prelude::*;

let materials = AsteroidMaterials::new(vec![
    // Common kind: stone with a metal core.
    AsteroidClass::new(MyVoxel::Stone)
        .with_weight(3.0)
        .with_mineral(
            AsteroidMineral::new(MyVoxel::Metal, 0.10, 100)
                .with_placement(MineralPlacement::RadialBand { min: 0.0, max: 0.5 }),
        ),
    // Rarer kind: small asteroids made of ice with scattered crystals.
    AsteroidClass::new(MyVoxel::Ice)
        .with_mineral(AsteroidMineral::new(MyVoxel::Crystal, 0.35, 200))
        .with_radius_range(10.0, 20.0),
])
.with_origin_class(0);

let generator = AsteroidGenerator::with_materials(AsteroidConfig::default(), materials);

app.add_plugins(GeneratorPlugin::<MyVoxel>::new())
   .insert_resource(GeneratorResource::<MyVoxel> {
       generator: Arc::new(generator),
   });
```

- **`AsteroidClass<V>`** is a kind of asteroid: `weight` (relative likelihood), `base` (the voxel used where no mineral matches), `minerals` and an optional `radius_range`. Each asteroid gets one class, chosen from the seed, so the same configuration and materials always give the same field.
- **`AsteroidMineral<V>`** is one rule: `voxel`, `threshold`, `seed_offset`, `noise_frequency` and `placement`. Each rule samples its own noise field in `[-1, 1]` and claims the voxel where the sample exceeds `threshold`, so a higher threshold is a rarer mineral. Rules are tried in order and the first match wins. Give each rule of a class a different `seed_offset`.
- **`MineralPlacement`** limits a rule by depth: `Anywhere`, or `RadialBand { min, max }` in fractions of the asteroid radius (`0.0` center, `1.0` nominal surface).
- **`AsteroidMaterials::origin_class`** forces the class of the asteroid at the world origin, for a spawn asteroid of a known kind. `AsteroidGenerator::asteroid_class(index)` reports the class assigned to each asteroid.

Asteroid positions depend only on `AsteroidConfig`; a class's `radius_range` changes sizes, not positions. `WorldConfig::asteroid_config()` gives the `AsteroidConfig` built from `world.toml` for use with `with_materials`. The material set is owned data inside the generator, so it follows the generator rule: nothing is read from the Bevy `World` on the worker threads.

Chunks that were never modified are generated again on load, so changing the materials of an existing world changes those chunks. Keep a world's materials stable, or start a new world.

## Terrain Materials

"Material" here means the rendering material, how a surface responds to
light, not the kind of voxel. By default every chunk is one mesh drawn with
the shared chunk material. A game can give a voxel type a material of its own:

```rust
use bevy::prelude::*;
use voxel_framework::prelude::*;

const ICE: TerrainMaterialId = TerrainMaterialId(1);

// 1. The voxel type names its material (default: TerrainMaterialId::DEFAULT).
//    impl VoxelType for MyVoxel {
//        fn material(&self) -> TerrainMaterialId {
//            match self { MyVoxel::Ice => ICE, _ => TerrainMaterialId::DEFAULT }
//        }
//    }

// 2. The game registers what is drawn for that id.
fn register_terrain_materials(
    mut terrain: ResMut<TerrainMaterials>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    terrain.register(
        ICE,
        materials.add(StandardMaterial {
            perceptual_roughness: 0.1,
            ..default()
        }),
    );
}
```

- **Any Bevy `Material`.** `register` takes a `Handle<M>` for any
  `M: Material`: a `StandardMaterial` or a type the game defines. The game adds
  the `MaterialPlugin` of its own types. The framework does not read the
  material; it only routes faces to it, so a new surface property needs no
  framework change.
- **Ids are the game's.** `TerrainMaterialId(u16)` has no meaning to the
  framework. An id with nothing registered is drawn with the shared chunk
  material, so a game that registers nothing renders as before. Registering
  `TerrainMaterialId::DEFAULT` replaces the shared material for every voxel
  type that names no other.
- **How it is drawn.** For each registered material present in a chunk, the
  mesh system keeps a child entity of the chunk marked with
  `ChunkMaterialSection { material }`, with its own mesh. Sections are
  despawned and hidden with their chunk, follow its LOD, and greedy merging
  stays within a material.
- **Cost.** One more mesh and one more draw call per registered material
  present in a chunk.
- **Vertex data.** Every terrain mesh has position, normal, UV (0 to 1 across
  each merged quad), vertex color (the voxel color in linear RGB, darkened by
  baked ambient occlusion) and `ATTRIBUTE_TEXTURE_LAYER`. `StandardMaterial`
  multiplies its base color by the vertex color.
- **Changing the registry at runtime** rebuilds the meshes of the loaded
  chunks.
- `generate_chunk_material_meshes(chunk, neighbors, step)` is the pure
  function behind it: one `(TerrainMaterialId, Mesh)` per material with
  visible faces.

See [`examples/terrain_materials.rs`](examples/terrain_materials.rs).

## Edge Chamfer

The mesher can cut the outward edges of the terrain with a flat facet, for a
faceted look on cubic voxels. It is off by default.

```rust
use bevy::prelude::*;
use voxel_framework::prelude::*;

fn main() {
    let mut app = App::new();
    app.insert_resource(MeshConfig {
        // Part of each face that is cut, as a fraction of the voxel (max 0.5).
        edge_chamfer: Some(0.15),
    });
}
```

- **Visual only.** It changes the chunk mesh and nothing else: collision,
  raycasts, mining, placement and saved chunks are the same.
- **Which edges.** Only convex edges of solid, opaque voxels, where nothing is
  drawn in front of either face. Voxels surrounded by others are untouched and
  flat seams between neighbors still merge into large quads.
- **Shading.** A chamfer facet has its own normal, halfway between the two
  faces. Its vertices take the color, baked ambient occlusion and texture
  layer of the face they border.
- **LOD.** Only LOD 0 is chamfered. LOD 1 meshes stay sharp.
- **Cost.** Each chamfered side of a quad adds 4 vertices, each convex corner
  4 and each chamfer that ends against another voxel 3. A lone voxel goes from
  24 to 216 vertices; a large flat surface gains only its outline. Rough,
  noisy terrain pays the most.
- **Chunk borders.** Chamfers continue across loaded neighbor chunks. Where
  the mesher cannot know the voxels (chunks that only share an edge or a
  corner) it closes the chamfer with a small cap that may be hidden inside
  the terrain.
- **Runtime changes** to `MeshConfig` rebuild the meshes of the loaded chunks.
- It works together with terrain materials: each material's mesh is chamfered.

Try it with `cargo run --example terrain_materials -- --chamfer 0.2`.

## Faces Exposed by Mining

The framework records which voxel faces were uncovered by edits since the
chunk was generated, so a terrain material can give mined surfaces a fresh
look and leave the original surface weathered. The framework only reports it;
how the two look is the game's material.

- **The record.** `Chunk::exposed_faces(x, y, z)` returns one bit per face
  (bit `i` = face index `i`: `0` +Y, `1` -Y, `2` +X, `3` -X, `4` +Z, `5` -Z).
  A generated chunk has none.
- **What fills it.** `set_voxel_at`, `tick_mining`, the mining input adapter
  and `try_place_voxel` call `record_voxel_edit`. Removing a voxel marks the
  faces of its drawn neighbors that looked at it, also across chunk borders.
  Filling a cell covers those faces again and they leave the record. The
  faces of a placed voxel are not exposed faces. `Chunk::set` alone does not
  touch the record (that is what keeps generation out of it); a game that
  edits chunks directly calls `record_voxel_edit` itself.
- **What the material sees.** Every terrain mesh has the vertex attribute
  `ATTRIBUTE_FACE_EXPOSED` (`Float32`): `1.0` on the vertices of an exposed
  face, `0.0` elsewhere. A fresh face and an original face never merge into
  one quad. `StandardMaterial` and the built-in `ChunkMaterial` ignore the
  attribute; a game material registered in `TerrainMaterials` declares it in
  its `specialize` and reads it in its shader.
- **Saved with the chunk.** A chunk file with exposed faces has one more
  section after the voxel and state bytes: the marker `XFAC` and one byte per
  voxel (4 100 bytes). Chunks without exposed faces are written exactly as
  before, older saves load unchanged, and an older framework version ignores
  the section.
- **Limits.** A neighbor in a chunk that is not loaded when the edit happens
  is not marked. The record does not expire; `Chunk::clear_exposed_faces`
  and `set_exposed_faces` let the game manage it.

## Implementing a Custom Voxel Type

```rust
use voxel_framework::voxel::VoxelType;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum MyVoxel {
    #[default]
    Air,
    Dirt,
    Stone,
}

impl VoxelType for MyVoxel {
    fn name(&self) -> &'static str {
        match self {
            MyVoxel::Air => "Air",
            MyVoxel::Dirt => "Dirt",
            MyVoxel::Stone => "Stone",
        }
    }

    fn is_solid(&self) -> bool {
        !matches!(self, MyVoxel::Air)
    }

    fn color(&self) -> [f32; 4] {
        match self {
            MyVoxel::Air   => [0.0, 0.0, 0.0, 0.0],
            MyVoxel::Dirt  => [0.45, 0.30, 0.15, 1.0],
            MyVoxel::Stone => [0.50, 0.50, 0.50, 1.0],
        }
    }

    fn to_byte(&self) -> u8 {
        match self {
            MyVoxel::Air   => 0,
            MyVoxel::Dirt  => 1,
            MyVoxel::Stone => 2,
        }
    }

    fn from_byte(byte: u8) -> Self {
        match byte {
            1 => MyVoxel::Dirt,
            2 => MyVoxel::Stone,
            _ => MyVoxel::Air,
        }
    }
}
```

## Implementing a Custom Generator

```rust
use bevy::math::IVec3;
use voxel_framework::chunk::Chunk;
use voxel_framework::generator::ChunkGenerator;

pub struct MyGenerator;

impl ChunkGenerator<MyVoxel> for MyGenerator {
    /// Called on a background thread — must not access the Bevy World.
    fn generate(&self, coord: IVec3, chunk: &mut Chunk<MyVoxel>) {
        use voxel_framework::chunk::CHUNK_SIZE;

        for x in 0..CHUNK_SIZE {
            for y in 0..CHUNK_SIZE {
                for z in 0..CHUNK_SIZE {
                    let world_y = coord.y * CHUNK_SIZE as i32 + y as i32;
                    let voxel = if world_y < 0 {
                        MyVoxel::Stone
                    } else if world_y < 4 {
                        MyVoxel::Dirt
                    } else {
                        MyVoxel::Air
                    };
                    chunk.set(x, y, z, voxel);
                }
            }
        }
    }
}
```

Register it the same way as `AsteroidGenerator`:

```rust
use std::sync::Arc;
use voxel_framework::generator::{GeneratorPlugin, GeneratorResource};

app.add_plugins(GeneratorPlugin::<MyVoxel>::new())
   .insert_resource(GeneratorResource::<MyVoxel> {
       generator: Arc::new(MyGenerator),
   });
```

## Voxel Palette (DefaultVoxel)

| Variant | Byte | RGBA color |
|---|---|---|
| `Air` | 0 | `(0.00, 0.00, 0.00, 0.0)` — transparent |
| `Rock` | 1 | `(0.35, 0.30, 0.28, 1.0)` — warm grey-brown |
| `IronOre` | 2 | `(0.55, 0.35, 0.20, 1.0)` — rusty orange |
| `SiliconCrystal` | 3 | `(0.40, 0.50, 0.80, 1.0)` — blue-violet |
| `RareMineral` | 4 | `(0.20, 0.85, 0.60, 1.0)` — vivid teal-green |

### Chunk opacity

All four solid default voxels are opaque. Air emits no geometry at either LOD.
Without a texture array, chunks use an opaque shared `StandardMaterial` so
foreground terrain writes depth and occludes surfaces behind it.

Custom palettes that need the previous blended fallback must opt in before
startup:

```rust,no_run
use bevy::prelude::*;
use voxel_framework::render::ChunkMaterialConfig;

let mut app = App::new();
app.insert_resource(ChunkMaterialConfig {
    alpha_mode: AlphaMode::Blend,
    ..default()
});
```

This policy applies to every fallback chunk, not individual voxel types.
Blending retains the existing sorting limitations; it does not provide separate
opaque/translucent meshes or per-triangle sorting. The texture-array path is
unchanged and ignores this configuration. Existing fully specified
`ChunkMaterialConfig` literals must add `alpha_mode` or use
`..Default::default()`.

## Profiling

Compile with `--features tracing` to enable internal spans for hot paths
(mesh generation, chunk load/unload, async generation dispatch, occlusion,
collision, raycast). With the feature off the spans expand to nothing —
zero runtime overhead in default builds.

Add `--features tracy` to route spans to a [Tracy](https://github.com/wolfpld/tracy)
profiler client. Call `voxel_framework::profile::init_tracy()` from your `main()`
**before** constructing the Bevy `App` so the subscriber is installed first
(only one global tracing subscriber may be active at a time):

```rust,no_run
fn main() {
    #[cfg(feature = "tracy")]
    voxel_framework::profile::init_tracy();

    bevy::prelude::App::new()/* ... */.run();
}
```

## For AI Assistants and Code Agents

This repository includes compact orientation files for tools like ChatGPT,
Codex, Claude, and other code agents:

- [`llms.txt`](llms.txt) is the shortest high-signal summary: what the crate is,
  which files to read first, and the runtime contracts that matter.
- [`AGENTS.md`](AGENTS.md) explains how to build a game *with*
  `voxel-framework`: core abstractions, plugin choices, feature flags, commands,
  and common gotchas.
- [`docs/architecture.md`](docs/architecture.md) is the deeper architecture
  reference for plugin categories, runtime flow, persistence, interaction flow,
  and extension seams.
- Rustdoc remains the source of truth for public API signatures and examples.

If you pass this project to an AI assistant, start with `llms.txt`, then
`README.md`, then `AGENTS.md`, and only then dive into `src/lib.rs` / rustdoc.
That order gives the model the product intent before the implementation detail.


## License

LGPL-3.0-or-later. See [`LICENSE`](LICENSE).

The embedded Noto Sans fonts in `src/ui/` are licensed under the SIL Open Font
License 1.1 (see [`src/ui/OFL-NotoSans.txt`](src/ui/OFL-NotoSans.txt)). Example
asset credits are in [`assets/CREDITS.md`](assets/CREDITS.md).