voxel-framework 0.13.0

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
//! Procedural asteroid generator, generic over the voxel palette.
//!
//! [`AsteroidGenerator::new`] builds the classic [`DefaultVoxel`] field.
//! [`AsteroidGenerator::with_materials`] takes an [`AsteroidMaterials`] set
//! for any [`VoxelType`]: one or more [`AsteroidClass`]es, each with its own
//! base voxel, ordered [`AsteroidMineral`] rules and optional radius range.
//!
//! # Algorithm
//!
//! [`AsteroidGenerator`] populates chunks using a density-field approach:
//!
//! 1. **Asteroid placement** — at construction time, [`AsteroidConfig::asteroid_count`]
//!    asteroid centers and radii are derived deterministically from the seed
//!    using [`hash3`] with decorrelated per-component inputs.  No `rand` crate
//!    is involved, which avoids version-drift and guarantees identical output
//!    across platforms.  The first asteroid is always pinned at the world
//!    origin so there is always a guaranteed spawn point.
//!
//! 2. **Surface deformation** — for each voxel candidate the distance to the
//!    nearest asteroid center is computed.  A surface displacement is sampled
//!    from an FBM noise field (using [`fbm`] with configurable octaves,
//!    frequency, and amplitude) evaluated at world-space coordinates normalized
//!    by `2 × radius`.  The density is `radius − dist + surface_displacement`;
//!    voxels with positive density are solid.
//!
//! 3. **Mineral distribution** — every asteroid belongs to one
//!    [`AsteroidClass`], chosen from the seed by class weight.  For a solid
//!    voxel the class's [`AsteroidMineral`] rules are tried in order: each
//!    samples its own FBM field (asteroid seed plus the rule's `seed_offset`)
//!    and claims the voxel when the sample exceeds the rule's `threshold` and
//!    the rule's [`MineralPlacement`] allows that depth.  When no rule claims
//!    the voxel it becomes the class's `base`.  The default class reproduces
//!    the original fixed distribution: seed offsets `+100`, `+200` and `+300`
//!    for rare minerals, silicon crystals and iron ore (see
//!    [`MineralFrequencies`] for the default thresholds), with rock as base.
//!
//! 4. **First-asteroid-wins** — when multiple asteroids overlap, the first one
//!    in the precomputed list claims the voxel.  This keeps the logic O(n) per
//!    voxel and produces seamless asteroid interiors.

use bevy::math::{IVec3, Vec3};

use crate::chunk::CHUNK_SIZE;
use crate::chunk::Chunk;
use crate::noise::{fbm, hash3};
use crate::voxel::{DefaultVoxel, VoxelType};

use super::ChunkGenerator;

/// Approximate volumetric distribution frequencies for each mineral type within
/// a solid asteroid.
///
/// The values are not used as direct probability weights; rather they document
/// the intended proportions that the FBM noise thresholds in
/// the default [`AsteroidClass`] were tuned to produce.  Changing
/// these fields alone has no effect — they are for documentation and future
/// tooling that may auto-tune thresholds to match target frequencies.
///
/// Values represent the fraction of solid voxels expected to contain each
/// mineral.  The sum should be approximately `1.0`.
#[derive(Clone, Debug)]
pub struct MineralFrequencies {
    /// Expected fraction of solid voxels that are rare mineral nodes.
    ///
    /// Default: `0.05` (~5 %).  Achieved by requiring `rare_noise > 0.55`.
    pub rare_mineral: f32,
    /// Expected fraction of solid voxels that are silicon crystal veins.
    ///
    /// Default: `0.15` (~15 %).  Achieved by requiring `crystal_noise > 0.30`.
    pub silicon_crystal: f32,
    /// Expected fraction of solid voxels that are iron ore deposits.
    ///
    /// Default: `0.25` (~25 %).  Achieved by requiring `iron_noise > 0.20`.
    pub iron_ore: f32,
    /// Expected fraction of solid voxels that are common rock (the fallback).
    ///
    /// Default: `0.55` (~55 %).
    pub rock: f32,
}

impl Default for MineralFrequencies {
    fn default() -> Self {
        Self {
            rare_mineral: 0.05,
            silicon_crystal: 0.15,
            iron_ore: 0.25,
            rock: 0.55,
        }
    }
}

/// Configuration for the [`AsteroidGenerator`].
///
/// Controls asteroid count, size distribution, surface noise parameters, and
/// mineral frequencies.  All generation is fully deterministic: the same
/// `AsteroidConfig` always produces the same world.
///
/// Construct via [`AsteroidConfig::default`] and override individual fields:
///
/// ```rust,no_run
/// use voxel_framework::generator::asteroid::AsteroidConfig;
///
/// let config = AsteroidConfig {
///     seed: 42,
///     asteroid_count: 12,
///     min_radius: 15.0,
///     max_radius: 80.0,
///     ..AsteroidConfig::default()
/// };
/// ```
#[derive(Clone, Debug)]
pub struct AsteroidConfig {
    /// Seed for the hash-based pseudo-random number generator.
    ///
    /// Changing the seed produces a completely different asteroid field.
    pub seed: u32,

    /// Number of asteroids to pre-compute and place in the world.
    ///
    /// The first asteroid is always at the origin.  Valid range: `1..`.
    pub asteroid_count: usize,

    /// Minimum asteroid radius in world units.
    ///
    /// Must satisfy `min_radius ≤ max_radius`.  Valid range: `> 0.0`.
    pub min_radius: f32,

    /// Maximum asteroid radius in world units.
    ///
    /// Must satisfy `max_radius ≥ min_radius`.
    pub max_radius: f32,

    /// Number of FBM octaves used for surface deformation.
    ///
    /// More octaves add finer surface detail at the cost of more noise
    /// evaluations per voxel.  Typical range: `2..=6`.  Default: `4`.
    pub noise_octaves: u32,

    /// Base sampling frequency for the surface FBM field.
    ///
    /// Higher values produce a rougher, more pitted surface.  The field is
    /// sampled at world coordinates divided by `2 × radius`, so the actual
    /// spatial frequency scales with asteroid size.  Default: `2.5`.
    pub noise_frequency: f32,

    /// Surface displacement amplitude as a fraction of the asteroid radius.
    ///
    /// A value of `0.34` means the surface can deviate by up to ±34 % of the
    /// radius.  Valid range: `0.0..=1.0`.  Default: `0.34`.
    pub noise_amplitude: f32,

    /// Intended mineral distribution frequencies (documentation only).
    ///
    /// See [`MineralFrequencies`] for details.  The distribution that is
    /// actually generated comes from the [`AsteroidMaterials`] given to
    /// [`AsteroidGenerator::with_materials`].
    pub mineral_frequencies: MineralFrequencies,
}

impl Default for AsteroidConfig {
    fn default() -> Self {
        Self {
            seed: 12345,
            asteroid_count: 8,
            min_radius: 20.0,
            max_radius: 60.0,
            noise_octaves: 4,
            noise_frequency: 2.5,
            noise_amplitude: 0.34,
            mineral_frequencies: MineralFrequencies::default(),
        }
    }
}

/// Number of FBM octaves used by every mineral noise field.
const MINERAL_OCTAVES: u32 = 3;
/// FBM lacunarity used by every mineral noise field.
const MINERAL_LACUNARITY: f32 = 2.0;
/// FBM gain used by every mineral noise field.
const MINERAL_GAIN: f32 = 0.5;

/// Sampling frequency of a mineral noise field when an [`AsteroidMineral`]
/// does not override it.
///
/// This is the frequency the built-in [`DefaultVoxel`] distribution uses.
pub const DEFAULT_MINERAL_NOISE_FREQUENCY: f32 = 5.0;

/// Where inside an asteroid an [`AsteroidMineral`] may appear.
///
/// Positions are expressed as a **radial fraction**: the distance from the
/// asteroid center divided by the asteroid radius.  `0.0` is the center and
/// `1.0` is the nominal surface; surface noise can push solid voxels out to
/// `1.0 + AsteroidConfig::noise_amplitude`.
///
/// ```rust
/// use voxel_framework::generator::asteroid::MineralPlacement;
///
/// let core = MineralPlacement::RadialBand { min: 0.0, max: 0.4 };
/// assert!(core.allows(0.2));
/// assert!(!core.allows(0.9));
/// assert!(MineralPlacement::Anywhere.allows(0.9));
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum MineralPlacement {
    /// The mineral may appear at any depth.  This is the default.
    #[default]
    Anywhere,
    /// The mineral may appear only where the radial fraction lies in
    /// `min..=max` (both ends inclusive).
    ///
    /// Use `min: 0.0` for a core deposit, or a `max` of `f32::INFINITY` for a
    /// crust that reaches the displaced surface.  A band with `min > max`, or
    /// with a `NaN` bound, never matches.
    RadialBand {
        /// Smallest allowed radial fraction.
        min: f32,
        /// Largest allowed radial fraction.
        max: f32,
    },
}

impl MineralPlacement {
    /// Returns `true` when a voxel at `radial_fraction` (distance from the
    /// asteroid center divided by the asteroid radius) may hold the mineral.
    ///
    /// A `NaN` fraction is only allowed by [`MineralPlacement::Anywhere`].
    #[inline]
    pub fn allows(&self, radial_fraction: f32) -> bool {
        match *self {
            MineralPlacement::Anywhere => true,
            MineralPlacement::RadialBand { min, max } => {
                radial_fraction >= min && radial_fraction <= max
            }
        }
    }
}

/// One mineral rule of an [`AsteroidClass`]: a voxel, how often it appears and
/// where.
///
/// Each rule owns an independent FBM noise field in world space, seeded with
/// the asteroid seed plus [`seed_offset`](Self::seed_offset).  A solid voxel
/// becomes [`voxel`](Self::voxel) when the field's sample there is greater
/// than [`threshold`](Self::threshold) and [`placement`](Self::placement)
/// allows its depth.  Rules are tried in the order they are listed in
/// [`AsteroidClass::minerals`]; the first match wins.
///
/// # Choosing a threshold
///
/// The field's samples lie in `[-1.0, 1.0]`, so the threshold acts as an
/// inverse frequency: a higher threshold gives a rarer mineral, and a
/// threshold of `1.0` or more disables the rule.  The built-in distribution
/// uses `0.55` for roughly 5 % of solid voxels, `0.30` for roughly 15 % and
/// `0.20` for roughly 25 % (each measured after the earlier rules took their
/// share).
///
/// ```rust
/// use voxel_framework::generator::asteroid::{AsteroidMineral, MineralPlacement};
/// use voxel_framework::voxel::DefaultVoxel;
///
/// // A rare deposit that only forms near the center.
/// let core_ore = AsteroidMineral::new(DefaultVoxel::RareMineral, 0.45, 100)
///     .with_placement(MineralPlacement::RadialBand { min: 0.0, max: 0.5 });
/// assert_eq!(core_ore.voxel, DefaultVoxel::RareMineral);
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AsteroidMineral<V: VoxelType> {
    /// Voxel placed where this rule matches.
    pub voxel: V,
    /// Noise value in `[-1.0, 1.0]` the field must exceed.  Higher is rarer.
    pub threshold: f32,
    /// Added (wrapping) to the asteroid seed to seed this rule's noise field.
    ///
    /// Give every rule of a class a different offset; two rules with the same
    /// offset and frequency sample the same field, so their veins coincide.
    pub seed_offset: u32,
    /// Sampling frequency of the noise field in world space.  Higher values
    /// give smaller, more scattered veins.
    ///
    /// Default: [`DEFAULT_MINERAL_NOISE_FREQUENCY`].
    pub noise_frequency: f32,
    /// Depth restriction.  Default: [`MineralPlacement::Anywhere`].
    pub placement: MineralPlacement,
}

impl<V: VoxelType> AsteroidMineral<V> {
    /// Creates a rule that may match at any depth and samples its field at
    /// [`DEFAULT_MINERAL_NOISE_FREQUENCY`].
    pub fn new(voxel: V, threshold: f32, seed_offset: u32) -> Self {
        Self {
            voxel,
            threshold,
            seed_offset,
            noise_frequency: DEFAULT_MINERAL_NOISE_FREQUENCY,
            placement: MineralPlacement::Anywhere,
        }
    }

    /// Returns the rule restricted to `placement`.
    pub fn with_placement(mut self, placement: MineralPlacement) -> Self {
        self.placement = placement;
        self
    }

    /// Returns the rule with a different noise sampling frequency.
    pub fn with_noise_frequency(mut self, noise_frequency: f32) -> Self {
        self.noise_frequency = noise_frequency;
        self
    }
}

/// A kind of asteroid: its dominant voxel, its mineral rules and its size.
///
/// An [`AsteroidMaterials`] set holds one or more classes.  Each asteroid of
/// the field is assigned exactly one class, chosen deterministically from the
/// seed with probability proportional to [`weight`](Self::weight).
///
/// `AsteroidClass::<DefaultVoxel>::default()` is the built-in class: rock
/// with rare mineral, silicon crystal and iron ore veins.
///
/// ```rust
/// use voxel_framework::generator::asteroid::{AsteroidClass, AsteroidMineral};
/// use voxel_framework::voxel::DefaultVoxel;
///
/// // Small, iron-dominated asteroids, three times as common as weight 1.0.
/// let metallic = AsteroidClass::new(DefaultVoxel::IronOre)
///     .with_weight(3.0)
///     .with_mineral(AsteroidMineral::new(DefaultVoxel::RareMineral, 0.40, 100))
///     .with_radius_range(12.0, 25.0);
/// assert_eq!(metallic.minerals.len(), 1);
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct AsteroidClass<V: VoxelType> {
    /// Relative likelihood of an asteroid being of this class.
    ///
    /// Only the ratio between classes matters.  A weight that is zero,
    /// negative or not finite means the class is never chosen from the seed
    /// (it can still be used through [`AsteroidMaterials::origin_class`]).
    /// When no class has a usable weight, every asteroid uses the first class.
    pub weight: f32,
    /// Voxel placed where no mineral rule matches: the dominant material.
    pub base: V,
    /// Mineral rules, tried in order; the first match wins.
    pub minerals: Vec<AsteroidMineral<V>>,
    /// Radius range `(min, max)` in world units for asteroids of this class.
    ///
    /// `None` uses [`AsteroidConfig::min_radius`] and
    /// [`AsteroidConfig::max_radius`].  The two values may be given in either
    /// order; a range with a bound that is not finite and positive is ignored
    /// in favor of the configuration's.  Asteroid *positions* always derive
    /// from [`AsteroidConfig::max_radius`], whatever the class.
    pub radius_range: Option<(f32, f32)>,
}

impl<V: VoxelType> AsteroidClass<V> {
    /// Creates a class made only of `base`, with weight `1.0`, no mineral
    /// rules and the configuration's radius range.
    pub fn new(base: V) -> Self {
        Self {
            weight: 1.0,
            base,
            minerals: Vec::new(),
            radius_range: None,
        }
    }

    /// Returns the class with a different selection weight.
    pub fn with_weight(mut self, weight: f32) -> Self {
        self.weight = weight;
        self
    }

    /// Returns the class with `mineral` appended to its rules.
    pub fn with_mineral(mut self, mineral: AsteroidMineral<V>) -> Self {
        self.minerals.push(mineral);
        self
    }

    /// Returns the class with its own radius range, in world units.
    pub fn with_radius_range(mut self, min: f32, max: f32) -> Self {
        self.radius_range = Some((min, max));
        self
    }
}

impl Default for AsteroidClass<DefaultVoxel> {
    /// The built-in class.  A generator using only this class produces chunks
    /// identical to those of [`AsteroidGenerator::new`].
    fn default() -> Self {
        Self {
            weight: 1.0,
            base: DefaultVoxel::Rock,
            minerals: vec![
                AsteroidMineral::new(DefaultVoxel::RareMineral, 0.55, 100),
                AsteroidMineral::new(DefaultVoxel::SiliconCrystal, 0.30, 200),
                AsteroidMineral::new(DefaultVoxel::IronOre, 0.20, 300),
            ],
            radius_range: None,
        }
    }
}

/// The material set of an asteroid field: every [`AsteroidClass`] an asteroid
/// can belong to.
///
/// Pass it to [`AsteroidGenerator::with_materials`].  The set is plain owned
/// data, so the generator stays `Send + Sync` and never needs the Bevy
/// `World`.
///
/// `AsteroidMaterials::<DefaultVoxel>::default()` holds the single built-in
/// class.
///
/// ```rust
/// use voxel_framework::generator::asteroid::{
///     AsteroidClass, AsteroidMaterials, AsteroidMineral,
/// };
/// use voxel_framework::voxel::DefaultVoxel;
///
/// let materials = AsteroidMaterials::new(vec![
///     AsteroidClass::<DefaultVoxel>::default().with_weight(4.0),
///     AsteroidClass::new(DefaultVoxel::IronOre)
///         .with_mineral(AsteroidMineral::new(DefaultVoxel::RareMineral, 0.35, 100)),
/// ])
/// .with_origin_class(0);
/// assert_eq!(materials.classes.len(), 2);
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct AsteroidMaterials<V: VoxelType> {
    /// The classes asteroids are drawn from.
    ///
    /// With an empty list the generator places no asteroids at all.
    pub classes: Vec<AsteroidClass<V>>,
    /// Class index forced on the asteroid at the world origin (asteroid `0`).
    ///
    /// `None`, or an index outside [`classes`](Self::classes), lets the seed
    /// choose like for every other asteroid.  Set it when the spawn asteroid
    /// must be of a known kind.
    pub origin_class: Option<usize>,
}

impl<V: VoxelType> AsteroidMaterials<V> {
    /// Creates a set from `classes`, with the origin asteroid's class chosen
    /// from the seed.
    pub fn new(classes: Vec<AsteroidClass<V>>) -> Self {
        Self {
            classes,
            origin_class: None,
        }
    }

    /// Creates a set with one class, used by every asteroid.
    pub fn single(class: AsteroidClass<V>) -> Self {
        Self::new(vec![class])
    }

    /// Returns the set with the origin asteroid forced to class `index`.
    pub fn with_origin_class(mut self, index: usize) -> Self {
        self.origin_class = Some(index);
        self
    }
}

impl Default for AsteroidMaterials<DefaultVoxel> {
    /// The built-in material set: one default [`AsteroidClass`].
    fn default() -> Self {
        Self::single(AsteroidClass::default())
    }
}

/// Selection weight actually used for a class: non-finite and non-positive
/// weights count as zero.
#[inline]
fn usable_weight(weight: f32) -> f32 {
    if weight.is_finite() && weight > 0.0 {
        weight
    } else {
        0.0
    }
}

/// Picks a class index for `roll` in `[0.0, 1.0]`, proportionally to the
/// usable class weights.
///
/// Returns `0` when `classes` is empty or no class has a usable weight.
fn pick_class<V: VoxelType>(classes: &[AsteroidClass<V>], roll: f32) -> usize {
    let total: f32 = classes
        .iter()
        .map(|class| usable_weight(class.weight))
        .sum();
    if !total.is_finite() || total <= 0.0 {
        return 0;
    }

    let target = roll * total;
    let mut accumulated = 0.0_f32;
    let mut last_usable = 0;
    for (index, class) in classes.iter().enumerate() {
        let weight = usable_weight(class.weight);
        if weight <= 0.0 {
            continue;
        }
        accumulated += weight;
        last_usable = index;
        if target < accumulated {
            return index;
        }
    }
    // `roll == 1.0` or float rounding: the last selectable class.
    last_usable
}

/// Radius range used for asteroids of a class.
///
/// `None` (and any unusable override) returns the configuration's values
/// untouched, so the default material set keeps the historical radii.
fn class_radius_range(config: &AsteroidConfig, range: Option<(f32, f32)>) -> (f32, f32) {
    match range {
        Some((a, b)) if a.is_finite() && b.is_finite() && a > 0.0 && b > 0.0 => {
            (a.min(b), a.max(b))
        }
        _ => (config.min_radius, config.max_radius),
    }
}

/// Pre-computed asteroid with center position and radius.
#[derive(Clone, Debug)]
struct Asteroid {
    center: Vec3,
    radius: f32,
    /// Per-asteroid seed derived from global seed + index.
    seed: u32,
    /// Y-axis flattening factor in [0.5, 1.0]. 0.5 = flat disk, 1.0 = sphere.
    flatten_y: f32,
    /// Index into `AsteroidMaterials::classes`.
    class: usize,
}

/// Procedural generator that fills the world with asteroid-shaped voxel
/// formations, implementing [`ChunkGenerator<V>`] for any [`VoxelType`].
///
/// See the [module-level documentation](self) for a full description of the
/// generation algorithm.  Asteroid positions, radii and classes are computed
/// once at construction time; subsequent calls to [`ChunkGenerator::generate`]
/// are read-only and safe to call concurrently from multiple worker threads.
///
/// The type parameter defaults to [`DefaultVoxel`], and
/// [`AsteroidGenerator::new`] exists only for that palette, so existing code
/// that writes `AsteroidGenerator` or `AsteroidGenerator::new(config)` keeps
/// compiling and keeps producing the same chunks.
///
/// # Examples
///
/// The built-in field:
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use voxel_framework::generator::GeneratorResource;
/// use voxel_framework::generator::asteroid::{AsteroidConfig, AsteroidGenerator};
/// use voxel_framework::voxel::DefaultVoxel;
///
/// let config = AsteroidConfig { seed: 99, asteroid_count: 5, ..AsteroidConfig::default() };
/// let generator = Arc::new(AsteroidGenerator::new(config));
///
/// // Insert into Bevy as a resource:
/// // app.insert_resource(GeneratorResource::<DefaultVoxel> { generator });
/// ```
///
/// A custom palette with two kinds of asteroid:
///
/// ```rust
/// use bevy::math::IVec3;
/// use voxel_framework::chunk::Chunk;
/// use voxel_framework::generator::ChunkGenerator;
/// use voxel_framework::generator::asteroid::{
///     AsteroidClass, AsteroidConfig, AsteroidGenerator, AsteroidMaterials, AsteroidMineral,
///     MineralPlacement,
/// };
/// use voxel_framework::voxel::VoxelType;
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
/// enum Ore { #[default] Air, Stone, Ice, Metal }
///
/// impl VoxelType for Ore {
///     fn name(&self) -> &'static str { "ore" }
///     fn is_solid(&self) -> bool { !matches!(self, Ore::Air) }
///     fn color(&self) -> [f32; 4] { [0.5, 0.5, 0.5, 1.0] }
///     fn to_byte(&self) -> u8 { *self as u8 }
///     fn from_byte(byte: u8) -> Self {
///         match byte { 1 => Ore::Stone, 2 => Ore::Ice, 3 => Ore::Metal, _ => Ore::Air }
///     }
/// }
///
/// let materials = AsteroidMaterials::new(vec![
///     // Stony asteroids with a metal core, the common kind.
///     AsteroidClass::new(Ore::Stone)
///         .with_weight(3.0)
///         .with_mineral(
///             AsteroidMineral::new(Ore::Metal, 0.10, 100)
///                 .with_placement(MineralPlacement::RadialBand { min: 0.0, max: 0.5 }),
///         ),
///     // Small icy asteroids.
///     AsteroidClass::new(Ore::Ice).with_radius_range(10.0, 20.0),
/// ])
/// .with_origin_class(0);
///
/// let generator = AsteroidGenerator::with_materials(AsteroidConfig::default(), materials);
/// assert_eq!(generator.asteroid_class(0), Some(0));
///
/// let mut chunk = Chunk::<Ore>::new();
/// generator.generate(IVec3::ZERO, &mut chunk);
/// assert!(!chunk.is_empty());
/// ```
pub struct AsteroidGenerator<V: VoxelType = DefaultVoxel> {
    config: AsteroidConfig,
    materials: AsteroidMaterials<V>,
    asteroids: Vec<Asteroid>,
}

impl AsteroidGenerator<DefaultVoxel> {
    /// Creates an [`AsteroidGenerator`] for [`DefaultVoxel`] from the given
    /// [`AsteroidConfig`], using the built-in material set
    /// (`AsteroidMaterials::<DefaultVoxel>::default()`).
    ///
    /// All `config.asteroid_count` asteroid centers and radii are computed
    /// immediately using [`hash3`]-based pseudo-random generation.  Construction
    /// is O(n) in `asteroid_count` and allocates a single `Vec`; it is fast
    /// enough to run on the main thread at app startup.
    ///
    /// For a given configuration the generated chunks are stable across
    /// releases, because saved worlds only store the chunks a player modified.
    pub fn new(config: AsteroidConfig) -> Self {
        Self::with_materials(config, AsteroidMaterials::default())
    }
}

impl<V: VoxelType> AsteroidGenerator<V> {
    /// Creates an [`AsteroidGenerator`] that builds its asteroids from
    /// `materials`, for any voxel palette.
    ///
    /// Each asteroid is assigned one [`AsteroidClass`] of the set, chosen
    /// from `config.seed` and the asteroid index with probability
    /// proportional to the class weights; the same configuration and
    /// materials always give the same field.  With an empty
    /// [`AsteroidMaterials::classes`] no asteroid is placed and every chunk
    /// stays empty.
    ///
    /// Asteroid positions depend only on `config`, never on the materials.
    /// Changing the materials of an existing saved world changes the voxels
    /// of chunks that were never modified (those are regenerated, not loaded
    /// from disk).
    pub fn with_materials(config: AsteroidConfig, materials: AsteroidMaterials<V>) -> Self {
        let asteroids = Self::build_asteroids(&config, &materials);
        Self {
            config,
            materials,
            asteroids,
        }
    }

    /// Returns a reference to the generator's configuration.
    pub fn config(&self) -> &AsteroidConfig {
        &self.config
    }

    /// Returns the material set the generator was built with.
    pub fn materials(&self) -> &AsteroidMaterials<V> {
        &self.materials
    }

    /// Returns the number of pre-computed asteroids.
    ///
    /// This is `config.asteroid_count`, or `0` when the material set has no
    /// classes.
    pub fn asteroid_count(&self) -> usize {
        self.asteroids.len()
    }

    /// Returns the index into [`AsteroidMaterials::classes`] of the class
    /// assigned to asteroid `asteroid`, or `None` when there is no such
    /// asteroid.  Asteroid `0` is the one at the world origin.
    pub fn asteroid_class(&self, asteroid: usize) -> Option<usize> {
        self.asteroids.get(asteroid).map(|entry| entry.class)
    }

    /// Deterministically generates asteroid positions, radii and classes from
    /// the seed.
    fn build_asteroids(config: &AsteroidConfig, materials: &AsteroidMaterials<V>) -> Vec<Asteroid> {
        if materials.classes.is_empty() {
            return Vec::new();
        }

        let mut asteroids = Vec::with_capacity(config.asteroid_count);

        for i in 0..config.asteroid_count {
            let per_seed = config.seed.wrapping_add(i as u32 * 97 + 1);

            // Class choice uses its own hash input (y = 4), so it does not
            // disturb the position and radius hashes below.
            let forced = if i == 0 {
                materials
                    .origin_class
                    .filter(|&index| index < materials.classes.len())
            } else {
                None
            };
            let class = match forced {
                Some(index) => index,
                None => pick_class(&materials.classes, hash3(i as i32, 4, 0, per_seed)),
            };
            let (min_radius, max_radius) =
                class_radius_range(config, materials.classes[class].radius_range);

            let (center, radius, flatten_y) = if i == 0 {
                // First asteroid always at origin (guaranteed spawn reference point).
                let r = (min_radius + max_radius) * 0.5;
                (Vec3::ZERO, r, 1.0)
            } else {
                // Hash the seed + index for each component.
                // Use different z-values to decorrelate x, y, z, radius, flatten.
                let hx = hash3(i as i32, 0, 0, per_seed);
                let hy = hash3(i as i32, 1, 0, per_seed);
                let hz = hash3(i as i32, 2, 0, per_seed);
                let hr = hash3(i as i32, 3, 0, per_seed);

                // Spread always derives from the configuration, so a class's
                // radius range never moves asteroids.
                let spread_xz = config.max_radius * 10.0;
                let spread_y = config.max_radius * 5.0;

                let x = (hx * 2.0 - 1.0) * spread_xz;
                let y = (hy * 2.0 - 1.0) * spread_y;
                let z = (hz * 2.0 - 1.0) * spread_xz;

                let r = min_radius + hr * (max_radius - min_radius);

                (Vec3::new(x, y, z), r, 1.0_f32)
            };

            asteroids.push(Asteroid {
                center,
                radius,
                seed: per_seed,
                flatten_y,
                class,
            });
        }

        asteroids
    }

    /// Determines the voxel for a solid position of an asteroid of `class`.
    ///
    /// Tries the class's mineral rules in order. Each rule samples its own
    /// FBM field (3 octaves, lacunarity 2.0, gain 0.5) seeded with
    /// `asteroid_seed + seed_offset`; the first rule whose placement allows
    /// `radial_fraction` and whose sample exceeds its threshold wins.
    /// Fields are independent, so sampling them lazily gives the same result
    /// as sampling all of them up front.
    #[inline]
    fn determine_voxel(
        class: &AsteroidClass<V>,
        world_pos: Vec3,
        asteroid_seed: u32,
        radial_fraction: f32,
    ) -> V {
        for mineral in &class.minerals {
            if !mineral.placement.allows(radial_fraction) {
                continue;
            }
            let noise = fbm(
                world_pos.x,
                world_pos.y,
                world_pos.z,
                asteroid_seed.wrapping_add(mineral.seed_offset),
                MINERAL_OCTAVES,
                mineral.noise_frequency,
                MINERAL_LACUNARITY,
                MINERAL_GAIN,
            );
            // FBM returns [-1, 1].
            if noise > mineral.threshold {
                return mineral.voxel;
            }
        }
        class.base
    }
}

impl<V: VoxelType> ChunkGenerator<V> for AsteroidGenerator<V> {
    fn generate(&self, coord: IVec3, chunk: &mut Chunk<V>) {
        let chunk_world = coord.as_vec3() * CHUNK_SIZE as f32;

        for lx in 0..CHUNK_SIZE {
            for ly in 0..CHUNK_SIZE {
                for lz in 0..CHUNK_SIZE {
                    let world_pos =
                        chunk_world + Vec3::new(lx as f32 + 0.5, ly as f32 + 0.5, lz as f32 + 0.5);

                    for asteroid in &self.asteroids {
                        let dx = world_pos.x - asteroid.center.x;
                        let dy = (world_pos.y - asteroid.center.y) / asteroid.flatten_y;
                        let dz = world_pos.z - asteroid.center.z;
                        let dist = (dx * dx + dy * dy + dz * dz).sqrt();

                        // Quick reject: if too far, skip noise calculation.
                        // Max surface extent is radius + radius * amplitude.
                        let max_extent =
                            asteroid.radius + asteroid.radius * self.config.noise_amplitude;
                        if dist > max_extent + 1.0 {
                            continue;
                        }

                        // Voxels deep inside the asteroid (farther than noise can
                        // ever displace the surface inward) are always solid.
                        // This prevents FBM from carving internal cavities that
                        // look like transparent holes from the outside.
                        let inner_solid_radius =
                            asteroid.radius * (1.0 - self.config.noise_amplitude);
                        let solid = if dist < inner_solid_radius {
                            true
                        } else {
                            // Surface band: apply FBM displacement to decide solid vs air.
                            // Normalized coordinates for FBM sampling
                            let norm = world_pos / (asteroid.radius * 2.0);

                            let surface_noise = fbm(
                                norm.x,
                                norm.y,
                                norm.z,
                                asteroid.seed,
                                self.config.noise_octaves,
                                self.config.noise_frequency,
                                2.0, // lacunarity
                                0.5, // gain
                            ) * asteroid.radius
                                * self.config.noise_amplitude;

                            let density = asteroid.radius - dist + surface_noise;
                            density > 0.0
                        };

                        if solid {
                            let voxel = Self::determine_voxel(
                                &self.materials.classes[asteroid.class],
                                world_pos,
                                asteroid.seed,
                                dist / asteroid.radius,
                            );
                            chunk.set(lx, ly, lz, voxel);
                            // First asteroid wins for this voxel position
                            break;
                        }
                    }
                }
            }
        }
    }
}

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

    #[test]
    fn deterministic_generation() {
        let config = AsteroidConfig::default();
        let generator = AsteroidGenerator::new(config.clone());

        let coord = IVec3::new(0, 0, 0);

        let mut chunk_a = Chunk::<DefaultVoxel>::new();
        generator.generate(coord, &mut chunk_a);

        let mut chunk_b = Chunk::<DefaultVoxel>::new();
        generator.generate(coord, &mut chunk_b);

        for x in 0..CHUNK_SIZE {
            for y in 0..CHUNK_SIZE {
                for z in 0..CHUNK_SIZE {
                    assert_eq!(
                        chunk_a.get(x, y, z),
                        chunk_b.get(x, y, z),
                        "Voxel mismatch at ({x}, {y}, {z}): generation must be deterministic"
                    );
                }
            }
        }
    }

    #[test]
    fn empty_space_produces_air() {
        let config = AsteroidConfig {
            asteroid_count: 1,
            min_radius: 10.0,
            max_radius: 10.0,
            ..AsteroidConfig::default()
        };
        let generator = AsteroidGenerator::new(config);

        // Chunk very far from the origin asteroid (which is at Vec3::ZERO)
        let coord = IVec3::new(1000, 1000, 1000);
        let mut chunk = Chunk::<DefaultVoxel>::new();
        generator.generate(coord, &mut chunk);

        assert!(
            chunk.is_empty(),
            "Chunk far from any asteroid should be entirely air"
        );
    }

    #[test]
    fn asteroid_interior_has_solid_voxels() {
        let config = AsteroidConfig {
            asteroid_count: 1,
            min_radius: 30.0,
            max_radius: 30.0,
            ..AsteroidConfig::default()
        };
        let generator = AsteroidGenerator::new(config);

        // Chunk at origin — center of the first asteroid
        let coord = IVec3::new(0, 0, 0);
        let mut chunk = Chunk::<DefaultVoxel>::new();
        generator.generate(coord, &mut chunk);

        let solid_count = (0..CHUNK_SIZE)
            .flat_map(|x| {
                (0..CHUNK_SIZE).flat_map(move |y| (0..CHUNK_SIZE).map(move |z| (x, y, z)))
            })
            .filter(|&(x, y, z)| chunk.is_solid_at(x, y, z))
            .count();

        assert!(
            solid_count > 0,
            "Chunk at asteroid center should contain solid voxels, but found none"
        );
        // The center of a radius-30 asteroid should have many solid voxels
        assert!(
            solid_count > CHUNK_SIZE * CHUNK_SIZE,
            "Expected substantial solid voxels at asteroid center, got only {solid_count}"
        );
    }

    #[test]
    fn mineral_distribution_has_variety() {
        let config = AsteroidConfig {
            asteroid_count: 1,
            min_radius: 40.0,
            max_radius: 40.0,
            ..AsteroidConfig::default()
        };
        let generator = AsteroidGenerator::new(config);

        // Generate several chunks around the asteroid center to get a good sample
        let mut has_rock = false;
        let mut has_iron = false;
        let mut has_silicon = false;
        let mut has_rare = false;

        for cx in -1..=1 {
            for cy in -1..=1 {
                for cz in -1..=1 {
                    let coord = IVec3::new(cx, cy, cz);
                    let mut chunk = Chunk::<DefaultVoxel>::new();
                    generator.generate(coord, &mut chunk);

                    for x in 0..CHUNK_SIZE {
                        for y in 0..CHUNK_SIZE {
                            for z in 0..CHUNK_SIZE {
                                match chunk.get(x, y, z) {
                                    DefaultVoxel::Rock => has_rock = true,
                                    DefaultVoxel::IronOre => has_iron = true,
                                    DefaultVoxel::SiliconCrystal => has_silicon = true,
                                    DefaultVoxel::RareMineral => has_rare = true,
                                    DefaultVoxel::Air => {}
                                }
                            }
                        }
                    }
                }
            }
        }

        assert!(has_rock, "Should contain Rock voxels");
        assert!(has_iron, "Should contain IronOre voxels");
        assert!(has_silicon, "Should contain SiliconCrystal voxels");
        assert!(has_rare, "Should contain RareMineral voxels");
    }
}

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

    // ------------------------------------------------------------------
    // Frozen copy of the generator as it was before material sets existed.
    //
    // Saved worlds only store modified chunks; everything else is generated
    // again on load, so the default configuration must keep producing these
    // exact voxels. Do not "simplify" this reference to call the new code.
    // ------------------------------------------------------------------

    struct LegacyAsteroid {
        center: Vec3,
        radius: f32,
        seed: u32,
        flatten_y: f32,
    }

    fn legacy_build_asteroids(config: &AsteroidConfig) -> Vec<LegacyAsteroid> {
        let mut asteroids = Vec::with_capacity(config.asteroid_count);

        for i in 0..config.asteroid_count {
            let per_seed = config.seed.wrapping_add(i as u32 * 97 + 1);

            let (center, radius, flatten_y) = if i == 0 {
                let r = (config.min_radius + config.max_radius) * 0.5;
                (Vec3::ZERO, r, 1.0)
            } else {
                let hx = hash3(i as i32, 0, 0, per_seed);
                let hy = hash3(i as i32, 1, 0, per_seed);
                let hz = hash3(i as i32, 2, 0, per_seed);
                let hr = hash3(i as i32, 3, 0, per_seed);

                let spread_xz = config.max_radius * 10.0;
                let spread_y = config.max_radius * 5.0;

                let x = (hx * 2.0 - 1.0) * spread_xz;
                let y = (hy * 2.0 - 1.0) * spread_y;
                let z = (hz * 2.0 - 1.0) * spread_xz;

                let r = config.min_radius + hr * (config.max_radius - config.min_radius);

                (Vec3::new(x, y, z), r, 1.0_f32)
            };

            asteroids.push(LegacyAsteroid {
                center,
                radius,
                seed: per_seed,
                flatten_y,
            });
        }

        asteroids
    }

    fn legacy_determine_mineral(world_pos: Vec3, asteroid_seed: u32) -> DefaultVoxel {
        let mineral_octaves = 3;
        let mineral_freq = 5.0;
        let lacunarity = 2.0;
        let gain = 0.5;

        let rare_noise = fbm(
            world_pos.x,
            world_pos.y,
            world_pos.z,
            asteroid_seed.wrapping_add(100),
            mineral_octaves,
            mineral_freq,
            lacunarity,
            gain,
        );
        let crystal_noise = fbm(
            world_pos.x,
            world_pos.y,
            world_pos.z,
            asteroid_seed.wrapping_add(200),
            mineral_octaves,
            mineral_freq,
            lacunarity,
            gain,
        );
        let iron_noise = fbm(
            world_pos.x,
            world_pos.y,
            world_pos.z,
            asteroid_seed.wrapping_add(300),
            mineral_octaves,
            mineral_freq,
            lacunarity,
            gain,
        );

        if rare_noise > 0.55 {
            DefaultVoxel::RareMineral
        } else if crystal_noise > 0.30 {
            DefaultVoxel::SiliconCrystal
        } else if iron_noise > 0.20 {
            DefaultVoxel::IronOre
        } else {
            DefaultVoxel::Rock
        }
    }

    fn legacy_generate(
        config: &AsteroidConfig,
        asteroids: &[LegacyAsteroid],
        coord: IVec3,
        chunk: &mut Chunk<DefaultVoxel>,
    ) {
        let chunk_world = coord.as_vec3() * CHUNK_SIZE as f32;

        for lx in 0..CHUNK_SIZE {
            for ly in 0..CHUNK_SIZE {
                for lz in 0..CHUNK_SIZE {
                    let world_pos =
                        chunk_world + Vec3::new(lx as f32 + 0.5, ly as f32 + 0.5, lz as f32 + 0.5);

                    for asteroid in asteroids {
                        let dx = world_pos.x - asteroid.center.x;
                        let dy = (world_pos.y - asteroid.center.y) / asteroid.flatten_y;
                        let dz = world_pos.z - asteroid.center.z;
                        let dist = (dx * dx + dy * dy + dz * dz).sqrt();

                        let max_extent = asteroid.radius + asteroid.radius * config.noise_amplitude;
                        if dist > max_extent + 1.0 {
                            continue;
                        }

                        let inner_solid_radius = asteroid.radius * (1.0 - config.noise_amplitude);
                        if dist < inner_solid_radius {
                            let voxel = legacy_determine_mineral(world_pos, asteroid.seed);
                            chunk.set(lx, ly, lz, voxel);
                            break;
                        }

                        let norm = world_pos / (asteroid.radius * 2.0);

                        let surface_noise = fbm(
                            norm.x,
                            norm.y,
                            norm.z,
                            asteroid.seed,
                            config.noise_octaves,
                            config.noise_frequency,
                            2.0,
                            0.5,
                        ) * asteroid.radius
                            * config.noise_amplitude;

                        let density = asteroid.radius - dist + surface_noise;

                        if density > 0.0 {
                            let voxel = legacy_determine_mineral(world_pos, asteroid.seed);
                            chunk.set(lx, ly, lz, voxel);
                            break;
                        }
                    }
                }
            }
        }
    }

    /// Chunk coordinate containing a world position.
    fn chunk_of(world: Vec3) -> IVec3 {
        (world / CHUNK_SIZE as f32).floor().as_ivec3()
    }

    /// Chunks worth comparing for a configuration: around the origin, at the
    /// center of every asteroid, on every asteroid's surface band along each
    /// axis, and a few in empty space.
    fn pinned_coords(asteroids: &[LegacyAsteroid]) -> Vec<IVec3> {
        let mut coords = vec![
            IVec3::new(0, 0, 0),
            IVec3::new(-1, 0, 0),
            IVec3::new(0, -1, 0),
            IVec3::new(1, 1, 1),
            IVec3::new(2, 0, -1),
            IVec3::new(-3, 1, 2),
            IVec3::new(1000, 1000, 1000),
            IVec3::new(-40, 7, 13),
        ];
        for asteroid in asteroids {
            coords.push(chunk_of(asteroid.center));
            for axis in [Vec3::X, Vec3::Y, Vec3::Z] {
                coords.push(chunk_of(asteroid.center + axis * asteroid.radius));
                coords.push(chunk_of(asteroid.center - axis * asteroid.radius));
            }
        }
        coords
    }

    fn for_each_voxel(mut f: impl FnMut(usize, usize, usize)) {
        for x in 0..CHUNK_SIZE {
            for y in 0..CHUNK_SIZE {
                for z in 0..CHUNK_SIZE {
                    f(x, y, z);
                }
            }
        }
    }

    /// Asserts that `generator` matches the frozen legacy generator for
    /// `config`, and returns how many solid voxels were compared.
    fn assert_matches_legacy(config: &AsteroidConfig, generator: &AsteroidGenerator) -> usize {
        let legacy_asteroids = legacy_build_asteroids(config);

        assert_eq!(generator.asteroids.len(), legacy_asteroids.len());
        for (index, (new, old)) in generator
            .asteroids
            .iter()
            .zip(legacy_asteroids.iter())
            .enumerate()
        {
            assert_eq!(new.center, old.center, "center of asteroid {index}");
            assert_eq!(
                new.radius.to_bits(),
                old.radius.to_bits(),
                "radius of asteroid {index}"
            );
            assert_eq!(new.seed, old.seed, "seed of asteroid {index}");
            assert_eq!(
                new.flatten_y.to_bits(),
                old.flatten_y.to_bits(),
                "flatten of asteroid {index}"
            );
            assert_eq!(new.class, 0, "class of asteroid {index}");
        }

        let mut solid = 0;
        for coord in pinned_coords(&legacy_asteroids) {
            let mut expected = Chunk::<DefaultVoxel>::new();
            legacy_generate(config, &legacy_asteroids, coord, &mut expected);

            let mut actual = Chunk::<DefaultVoxel>::new();
            generator.generate(coord, &mut actual);

            for_each_voxel(|x, y, z| {
                let want = expected.get(x, y, z);
                let got = actual.get(x, y, z);
                assert_eq!(
                    got.to_byte(),
                    want.to_byte(),
                    "seed {} chunk {coord} voxel ({x}, {y}, {z}): default generation \
                     must stay byte-identical to the pre-material-set generator",
                    config.seed
                );
                if want.is_solid() {
                    solid += 1;
                }
            });
        }
        solid
    }

    #[test]
    fn default_config_is_byte_identical_to_legacy_generator() {
        let config = AsteroidConfig::default();
        let generator = AsteroidGenerator::new(config.clone());
        let solid = assert_matches_legacy(&config, &generator);
        assert!(
            solid > 10_000,
            "the pinned chunks must cover real asteroid volume, got {solid} solid voxels"
        );
    }

    #[test]
    fn other_configs_are_byte_identical_to_legacy_generator() {
        let configs = [
            AsteroidConfig {
                seed: 99,
                asteroid_count: 12,
                ..AsteroidConfig::default()
            },
            AsteroidConfig {
                seed: 7,
                asteroid_count: 5,
                min_radius: 15.0,
                max_radius: 80.0,
                ..AsteroidConfig::default()
            },
            AsteroidConfig {
                seed: u32::MAX - 3,
                asteroid_count: 3,
                min_radius: 10.0,
                max_radius: 10.0,
                noise_octaves: 2,
                noise_frequency: 1.5,
                noise_amplitude: 0.2,
                ..AsteroidConfig::default()
            },
        ];
        for config in configs {
            let generator = AsteroidGenerator::new(config.clone());
            let solid = assert_matches_legacy(&config, &generator);
            assert!(solid > 0, "seed {} compared no solid voxels", config.seed);
        }
    }

    #[test]
    fn explicit_default_materials_are_byte_identical_to_legacy_generator() {
        let config = AsteroidConfig::default();
        let generator = AsteroidGenerator::with_materials(
            config.clone(),
            AsteroidMaterials::single(AsteroidClass::<DefaultVoxel>::default()),
        );
        assert_matches_legacy(&config, &generator);
    }

    #[test]
    fn default_class_matches_documented_distribution() {
        let class = AsteroidClass::<DefaultVoxel>::default();
        assert_eq!(class.weight, 1.0);
        assert_eq!(class.base, DefaultVoxel::Rock);
        assert_eq!(class.radius_range, None);
        assert_eq!(
            class.minerals,
            vec![
                AsteroidMineral {
                    voxel: DefaultVoxel::RareMineral,
                    threshold: 0.55,
                    seed_offset: 100,
                    noise_frequency: 5.0,
                    placement: MineralPlacement::Anywhere,
                },
                AsteroidMineral {
                    voxel: DefaultVoxel::SiliconCrystal,
                    threshold: 0.30,
                    seed_offset: 200,
                    noise_frequency: 5.0,
                    placement: MineralPlacement::Anywhere,
                },
                AsteroidMineral {
                    voxel: DefaultVoxel::IronOre,
                    threshold: 0.20,
                    seed_offset: 300,
                    noise_frequency: 5.0,
                    placement: MineralPlacement::Anywhere,
                },
            ]
        );

        let materials = AsteroidMaterials::<DefaultVoxel>::default();
        assert_eq!(materials.classes, vec![class]);
        assert_eq!(materials.origin_class, None);
    }

    // ------------------------------------------------------------------
    // Custom palettes and classes
    // ------------------------------------------------------------------

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
    enum TestVoxel {
        #[default]
        Air,
        Stone,
        Ice,
        Metal,
    }

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

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

        fn color(&self) -> [f32; 4] {
            [1.0, 1.0, 1.0, 1.0]
        }

        fn to_byte(&self) -> u8 {
            match self {
                TestVoxel::Air => 0,
                TestVoxel::Stone => 1,
                TestVoxel::Ice => 2,
                TestVoxel::Metal => 3,
            }
        }

        fn from_byte(byte: u8) -> Self {
            match byte {
                1 => TestVoxel::Stone,
                2 => TestVoxel::Ice,
                3 => TestVoxel::Metal,
                _ => TestVoxel::Air,
            }
        }
    }

    fn single_asteroid_config(radius: f32) -> AsteroidConfig {
        AsteroidConfig {
            asteroid_count: 1,
            min_radius: radius,
            max_radius: radius,
            ..AsteroidConfig::default()
        }
    }

    fn weighted(weights: &[f32]) -> Vec<AsteroidClass<TestVoxel>> {
        weights
            .iter()
            .map(|&weight| AsteroidClass::new(TestVoxel::Stone).with_weight(weight))
            .collect()
    }

    #[test]
    fn generator_is_send_sync_for_custom_palettes() {
        fn assert_generator<V: VoxelType, G: ChunkGenerator<V>>() {}
        assert_generator::<TestVoxel, AsteroidGenerator<TestVoxel>>();
        assert_generator::<DefaultVoxel, AsteroidGenerator>();
    }

    #[test]
    fn mineral_placement_bands() {
        assert!(MineralPlacement::Anywhere.allows(0.0));
        assert!(MineralPlacement::Anywhere.allows(f32::NAN));
        assert_eq!(MineralPlacement::default(), MineralPlacement::Anywhere);

        let band = MineralPlacement::RadialBand {
            min: 0.25,
            max: 0.5,
        };
        assert!(band.allows(0.25));
        assert!(band.allows(0.5));
        assert!(band.allows(0.3));
        assert!(!band.allows(0.2));
        assert!(!band.allows(0.6));
        assert!(!band.allows(f32::NAN));

        let crust = MineralPlacement::RadialBand {
            min: 0.9,
            max: f32::INFINITY,
        };
        assert!(crust.allows(1.3));
        assert!(!crust.allows(0.5));

        let inverted = MineralPlacement::RadialBand { min: 0.8, max: 0.2 };
        assert!(!inverted.allows(0.5));
    }

    #[test]
    fn pick_class_follows_weights() {
        let classes = weighted(&[1.0, 3.0]);
        assert_eq!(pick_class(&classes, 0.0), 0);
        assert_eq!(pick_class(&classes, 0.2), 0);
        assert_eq!(pick_class(&classes, 0.3), 1);
        assert_eq!(pick_class(&classes, 0.99), 1);
        assert_eq!(pick_class(&classes, 1.0), 1);
    }

    #[test]
    fn pick_class_skips_unusable_weights() {
        let classes = weighted(&[0.0, 2.0, -1.0, f32::NAN, 2.0, f32::INFINITY]);
        assert_eq!(pick_class(&classes, 0.0), 1);
        assert_eq!(pick_class(&classes, 0.4), 1);
        assert_eq!(pick_class(&classes, 0.6), 4);
        // A roll of exactly 1.0 lands on the last usable class, not the last entry.
        assert_eq!(pick_class(&classes, 1.0), 4);
    }

    #[test]
    fn pick_class_without_usable_weights_uses_first_class() {
        assert_eq!(pick_class(&weighted(&[0.0, 0.0]), 0.7), 0);
        assert_eq!(pick_class(&weighted(&[f32::NAN, -2.0]), 0.7), 0);
        assert_eq!(pick_class(&weighted(&[]), 0.7), 0);
        assert_eq!(pick_class(&weighted(&[5.0]), 0.7), 0);
    }

    #[test]
    fn class_radius_range_falls_back_to_config() {
        let config = AsteroidConfig {
            min_radius: 20.0,
            max_radius: 60.0,
            ..AsteroidConfig::default()
        };
        assert_eq!(class_radius_range(&config, None), (20.0, 60.0));
        assert_eq!(class_radius_range(&config, Some((5.0, 9.0))), (5.0, 9.0));
        assert_eq!(class_radius_range(&config, Some((9.0, 5.0))), (5.0, 9.0));
        assert_eq!(class_radius_range(&config, Some((0.0, 9.0))), (20.0, 60.0));
        assert_eq!(class_radius_range(&config, Some((-1.0, 9.0))), (20.0, 60.0));
        assert_eq!(
            class_radius_range(&config, Some((5.0, f32::NAN))),
            (20.0, 60.0)
        );
        assert_eq!(
            class_radius_range(&config, Some((5.0, f32::INFINITY))),
            (20.0, 60.0)
        );
    }

    #[test]
    fn empty_material_set_generates_nothing() {
        let generator = AsteroidGenerator::with_materials(
            AsteroidConfig::default(),
            AsteroidMaterials::<TestVoxel>::new(Vec::new()),
        );
        assert_eq!(generator.asteroid_count(), 0);
        assert_eq!(generator.asteroid_class(0), None);

        let mut chunk = Chunk::<TestVoxel>::new();
        generator.generate(IVec3::ZERO, &mut chunk);
        assert!(chunk.is_empty());
    }

    #[test]
    fn class_without_minerals_is_made_of_its_base() {
        let generator = AsteroidGenerator::with_materials(
            single_asteroid_config(30.0),
            AsteroidMaterials::single(AsteroidClass::new(TestVoxel::Ice)),
        );

        let mut chunk = Chunk::<TestVoxel>::new();
        generator.generate(IVec3::ZERO, &mut chunk);

        let mut solid = 0;
        for_each_voxel(|x, y, z| {
            let voxel = chunk.get(x, y, z);
            assert!(
                voxel == TestVoxel::Ice || voxel == TestVoxel::Air,
                "unexpected {voxel:?} at ({x}, {y}, {z})"
            );
            if voxel == TestVoxel::Ice {
                solid += 1;
            }
        });
        assert!(solid > 0);
    }

    #[test]
    fn materials_do_not_change_asteroid_shape() {
        let config = AsteroidConfig::default();
        let default_generator = AsteroidGenerator::new(config.clone());
        let custom_generator = AsteroidGenerator::with_materials(
            config,
            AsteroidMaterials::new(vec![
                AsteroidClass::new(TestVoxel::Stone).with_mineral(AsteroidMineral::new(
                    TestVoxel::Metal,
                    0.1,
                    7,
                )),
                AsteroidClass::new(TestVoxel::Ice).with_weight(2.0),
            ]),
        );

        for (default_asteroid, custom_asteroid) in default_generator
            .asteroids
            .iter()
            .zip(custom_generator.asteroids.iter())
        {
            assert_eq!(default_asteroid.center, custom_asteroid.center);
            assert_eq!(default_asteroid.radius, custom_asteroid.radius);
            assert_eq!(default_asteroid.seed, custom_asteroid.seed);
        }

        for coord in [
            IVec3::new(0, 0, 0),
            IVec3::new(2, 0, 0),
            IVec3::new(0, -3, 0),
            IVec3::new(-2, 1, 1),
        ] {
            let mut default_chunk = Chunk::<DefaultVoxel>::new();
            default_generator.generate(coord, &mut default_chunk);
            let mut custom_chunk = Chunk::<TestVoxel>::new();
            custom_generator.generate(coord, &mut custom_chunk);

            for_each_voxel(|x, y, z| {
                assert_eq!(
                    default_chunk.is_solid_at(x, y, z),
                    custom_chunk.is_solid_at(x, y, z),
                    "solidity differs in chunk {coord} at ({x}, {y}, {z})"
                );
            });
        }
    }

    #[test]
    fn always_matching_mineral_replaces_the_base() {
        // A threshold below the noise range always matches.
        let generator = AsteroidGenerator::with_materials(
            single_asteroid_config(30.0),
            AsteroidMaterials::single(
                AsteroidClass::new(TestVoxel::Stone)
                    .with_mineral(AsteroidMineral::new(TestVoxel::Metal, -2.0, 1))
                    .with_mineral(AsteroidMineral::new(TestVoxel::Ice, -2.0, 2)),
            ),
        );

        let mut chunk = Chunk::<TestVoxel>::new();
        generator.generate(IVec3::ZERO, &mut chunk);

        let mut solid = 0;
        for_each_voxel(|x, y, z| {
            let voxel = chunk.get(x, y, z);
            // The first rule wins; the second rule and the base never show.
            assert!(voxel == TestVoxel::Metal || voxel == TestVoxel::Air);
            if voxel == TestVoxel::Metal {
                solid += 1;
            }
        });
        assert!(solid > 0);
    }

    #[test]
    fn unreachable_threshold_disables_a_mineral() {
        let generator = AsteroidGenerator::with_materials(
            single_asteroid_config(30.0),
            AsteroidMaterials::single(
                AsteroidClass::new(TestVoxel::Stone).with_mineral(AsteroidMineral::new(
                    TestVoxel::Metal,
                    1.0,
                    1,
                )),
            ),
        );

        let mut chunk = Chunk::<TestVoxel>::new();
        generator.generate(IVec3::ZERO, &mut chunk);

        for_each_voxel(|x, y, z| {
            assert_ne!(chunk.get(x, y, z), TestVoxel::Metal);
        });
    }

    #[test]
    fn radial_band_confines_a_mineral_to_its_depth() {
        let radius = 40.0_f32;
        let band_max = 0.3_f32;
        let generator = AsteroidGenerator::with_materials(
            single_asteroid_config(radius),
            AsteroidMaterials::single(AsteroidClass::new(TestVoxel::Stone).with_mineral(
                AsteroidMineral::new(TestVoxel::Metal, -2.0, 1).with_placement(
                    MineralPlacement::RadialBand {
                        min: 0.0,
                        max: band_max,
                    },
                ),
            )),
        );

        // The chunk at the origin lies fully inside the always-solid core of a
        // radius-40 asteroid (farthest voxel is ~26.8 units from the center,
        // the core reaches 26.4; a few corner voxels sit in the surface band).
        let mut chunk = Chunk::<TestVoxel>::new();
        generator.generate(IVec3::ZERO, &mut chunk);

        let mut metal = 0;
        let mut stone = 0;
        for_each_voxel(|x, y, z| {
            let pos = Vec3::new(x as f32 + 0.5, y as f32 + 0.5, z as f32 + 0.5);
            let fraction = pos.length() / radius;
            if (fraction - band_max).abs() < 1e-3 {
                return; // too close to the band edge to predict in a test
            }
            let voxel = chunk.get(x, y, z);
            if fraction < band_max {
                assert_eq!(
                    voxel,
                    TestVoxel::Metal,
                    "inside the band at ({x}, {y}, {z})"
                );
                metal += 1;
            } else {
                assert_ne!(
                    voxel,
                    TestVoxel::Metal,
                    "outside the band at ({x}, {y}, {z})"
                );
                if voxel == TestVoxel::Stone {
                    stone += 1;
                }
            }
        });
        assert!(metal > 0, "the band must contain voxels");
        assert!(
            stone > 0,
            "voxels outside the band must fall back to the base"
        );
    }

    #[test]
    fn classes_are_assigned_per_asteroid_and_deterministically() {
        let config = AsteroidConfig {
            asteroid_count: 64,
            ..AsteroidConfig::default()
        };
        let materials = AsteroidMaterials::new(vec![
            AsteroidClass::new(TestVoxel::Stone),
            AsteroidClass::new(TestVoxel::Ice),
            AsteroidClass::new(TestVoxel::Metal).with_weight(0.0),
        ]);

        let first = AsteroidGenerator::with_materials(config.clone(), materials.clone());
        let second = AsteroidGenerator::with_materials(config.clone(), materials.clone());
        assert_eq!(first.asteroid_count(), 64);
        assert_eq!(first.materials(), &materials);

        let mut counts = [0usize; 3];
        for index in 0..64 {
            let class = first.asteroid_class(index).expect("asteroid exists");
            assert_eq!(Some(class), second.asteroid_class(index));
            counts[class] += 1;
        }
        assert_eq!(first.asteroid_class(64), None);

        assert!(
            counts[0] > 0,
            "equal weights should both be drawn: {counts:?}"
        );
        assert!(
            counts[1] > 0,
            "equal weights should both be drawn: {counts:?}"
        );
        assert_eq!(counts[2], 0, "a zero-weight class is never drawn");

        // A different seed gives a different assignment.
        let other = AsteroidGenerator::with_materials(
            AsteroidConfig {
                seed: config.seed.wrapping_add(1),
                ..config
            },
            materials,
        );
        assert!(
            (0..64).any(|index| other.asteroid_class(index) != first.asteroid_class(index)),
            "class assignment must depend on the seed"
        );
    }

    #[test]
    fn each_asteroid_uses_only_its_class_composition() {
        let config = AsteroidConfig {
            asteroid_count: 24,
            ..AsteroidConfig::default()
        };
        let generator = AsteroidGenerator::with_materials(
            config,
            AsteroidMaterials::new(vec![
                AsteroidClass::new(TestVoxel::Stone),
                AsteroidClass::new(TestVoxel::Ice),
            ]),
        );

        let mut checked = [false; 2];
        for (index, asteroid) in generator.asteroids.iter().enumerate() {
            // Skip asteroids close enough to another one that the other could
            // claim voxels of this asteroid's center chunk.
            let overlapped = generator
                .asteroids
                .iter()
                .enumerate()
                .any(|(other_index, other)| {
                    other_index != index
                        && other.center.distance(asteroid.center)
                            < other.radius * 1.4 + asteroid.radius * 1.4 + 32.0
                });
            if overlapped {
                continue;
            }

            let expected = [TestVoxel::Stone, TestVoxel::Ice][asteroid.class];
            let mut chunk = Chunk::<TestVoxel>::new();
            generator.generate(chunk_of(asteroid.center), &mut chunk);

            let mut solid = 0;
            for_each_voxel(|x, y, z| {
                let voxel = chunk.get(x, y, z);
                if voxel != TestVoxel::Air {
                    assert_eq!(voxel, expected, "asteroid {index}");
                    solid += 1;
                }
            });
            assert!(solid > 0, "asteroid {index} center chunk should be solid");
            checked[asteroid.class] = true;
        }
        assert!(
            checked[0] && checked[1],
            "both classes should have been checked: {checked:?}"
        );
    }

    #[test]
    fn origin_class_is_forced_only_when_valid() {
        let classes = vec![
            AsteroidClass::new(TestVoxel::Stone),
            AsteroidClass::new(TestVoxel::Ice).with_weight(0.0),
        ];
        let config = AsteroidConfig {
            asteroid_count: 16,
            ..AsteroidConfig::default()
        };

        // Class 1 has no weight, so only the forced origin can use it.
        let forced = AsteroidGenerator::with_materials(
            config.clone(),
            AsteroidMaterials::new(classes.clone()).with_origin_class(1),
        );
        assert_eq!(forced.asteroid_class(0), Some(1));
        for index in 1..16 {
            assert_eq!(forced.asteroid_class(index), Some(0));
        }

        let mut chunk = Chunk::<TestVoxel>::new();
        forced.generate(IVec3::ZERO, &mut chunk);
        assert_eq!(chunk.get(0, 0, 0), TestVoxel::Ice);

        // An index outside the set is ignored instead of panicking.
        let out_of_range = AsteroidGenerator::with_materials(
            config,
            AsteroidMaterials::new(classes).with_origin_class(9),
        );
        assert_eq!(out_of_range.asteroid_class(0), Some(0));
    }

    #[test]
    fn class_radius_range_sizes_asteroids_without_moving_them() {
        let config = AsteroidConfig {
            asteroid_count: 16,
            ..AsteroidConfig::default()
        };
        let reference = AsteroidGenerator::new(config.clone());
        let small = AsteroidGenerator::with_materials(
            config,
            AsteroidMaterials::single(
                AsteroidClass::new(TestVoxel::Stone).with_radius_range(5.0, 6.0),
            ),
        );

        assert_eq!(small.asteroids[0].radius, 5.5);
        for (index, (asteroid, original)) in small
            .asteroids
            .iter()
            .zip(reference.asteroids.iter())
            .enumerate()
        {
            assert!(
                (5.0..=6.0).contains(&asteroid.radius),
                "asteroid {index} radius {}",
                asteroid.radius
            );
            assert_eq!(asteroid.center, original.center, "asteroid {index} moved");
        }
    }
}