enshwick 1.0.0-alpha.11

The Enshwick Loader's modding API for Enshrouded: the one crate mods are written against
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
//! Voxels of the server's world: what the ground and the building blocks
//! are made of, voxel by voxel.
//!
//! The world is a grid of voxels half a metre a side, counted from the
//! world's corner ([`VoxelPos`]). Each voxel is air, ground of a terrain
//! material ([`Terrain::materials`](crate::terrain::Terrain::materials)
//! lists them) or a building block's material, and is more or less full.
//! The server holds only some parts of the world in memory: a read
//! elsewhere fails with [`WorldError::NotLoaded`] and starts loading that
//! part, which is there to read about a second later. Every read can pull
//! a part of the world into memory, so a mod reads where it needs to, never
//! the whole world.
//! A read past the world's edge, or above the 1,024 metres the loader
//! takes, fails with [`WorldError::OutsideWorld`].
//!
//! Every read belongs on the server's game thread at a quiet moment, as the
//! world's writes do: from a game event, a
//! [`Scheduler`](crate::schedule::Scheduler) task or an action, never from
//! a filter or a hook inside a step; on a client, while it hosts a game.
//!
//! # Examples
//!
//! ```
//! use enshwick::voxels::{VoxelMaterial, VoxelPos, Voxels};
//!
//! fn ground(voxels: &Voxels, [x, y, z]: [f64; 3]) -> Result<String, enshwick::WorldError> {
//!     let Some(feet) = VoxelPos::from_metres([x, y - 0.5, z]) else {
//!         return Ok("outside the world".to_owned());
//!     };
//!     Ok(match voxels.sample(feet)?.material() {
//!         VoxelMaterial::Terrain(id) => format!("ground of material {id}"),
//!         VoxelMaterial::Building(id) => format!("a block of material {id}"),
//!         _ => "nothing".to_owned(),
//!     })
//! }
//!
//! fn init(load: &mut enshwick::Load<'_>) -> Result<Voxels, enshwick::Off> {
//!     Ok(load.voxels())
//! }
//! ```

use crate::WorldError;
use crate::abi;
use crate::{Host, Load};

/// The most voxels one [`Voxels::read`] takes: a box of 64 voxels, 32
/// metres, a side.
pub const READ_MAX: u64 = abi::Voxel::READ_MAX;

/// Voxels per metre on every axis, for turning a size in metres into
/// voxels.
pub const PER_METRE: f64 = 2.0;

/// A voxel's place in the world: its index on each axis from the world's
/// corner, half a metre a step, with y up.
///
/// # Examples
///
/// ```
/// use enshwick::voxels::VoxelPos;
///
/// let at = VoxelPos::from_metres([10.2, 4.0, 7.9]).ok_or("outside the world")?;
/// assert_eq!(at, VoxelPos::new(20, 8, 15));
/// assert_eq!(at.to_metres(), [10.0, 4.0, 7.5]);
/// # Ok::<(), &str>(())
/// ```
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    PartialEq,
    Eq,
    Hash,
    PartialOrd,
    Ord,
    serde::Serialize,
    serde::Deserialize,
)]
pub struct VoxelPos {
    x: u32,
    y: u32,
    z: u32,
}

impl VoxelPos {
    /// The voxel at these indices.
    ///
    /// # Examples
    ///
    /// See [`VoxelPos`].
    #[must_use]
    pub const fn new(x: u32, y: u32, z: u32) -> Self {
        Self { x, y, z }
    }

    /// The voxel holding the point `metres`, as world positions give it;
    /// `None` for a point below the world's corner, too far out or not a
    /// number.
    ///
    /// # Examples
    ///
    /// See [`VoxelPos`].
    #[must_use]
    pub fn from_metres(metres: [f64; 3]) -> Option<Self> {
        let [x, y, z] = metres.map(index);
        Some(Self::new(x?, y?, z?))
    }

    /// The lowest corner of the voxel, in metres.
    ///
    /// # Examples
    ///
    /// See [`VoxelPos`].
    #[must_use]
    pub fn to_metres(self) -> [f64; 3] {
        self.to_array().map(|axis| f64::from(axis) / PER_METRE)
    }

    /// The index along x.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(enshwick::voxels::VoxelPos::new(1, 2, 3).x(), 1);
    /// ```
    #[must_use]
    pub const fn x(self) -> u32 {
        self.x
    }

    /// The index along y, upwards.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(enshwick::voxels::VoxelPos::new(1, 2, 3).y(), 2);
    /// ```
    #[must_use]
    pub const fn y(self) -> u32 {
        self.y
    }

    /// The index along z.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(enshwick::voxels::VoxelPos::new(1, 2, 3).z(), 3);
    /// ```
    #[must_use]
    pub const fn z(self) -> u32 {
        self.z
    }

    /// The indices as `[x, y, z]`.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(enshwick::voxels::VoxelPos::new(1, 2, 3).to_array(), [1, 2, 3]);
    /// ```
    #[must_use]
    pub const fn to_array(self) -> [u32; 3] {
        [self.x, self.y, self.z]
    }
}

impl From<[u32; 3]> for VoxelPos {
    fn from([x, y, z]: [u32; 3]) -> Self {
        Self::new(x, y, z)
    }
}

impl From<VoxelPos> for [u32; 3] {
    fn from(at: VoxelPos) -> Self {
        at.to_array()
    }
}

/// The voxel index holding `metres` on one axis, below [`abi::Voxel::END`].
#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "the value is checked to lie in 0 to `Voxel::END` first"
)]
fn index(metres: f64) -> Option<u32> {
    let voxels = (metres * PER_METRE).floor();
    (voxels >= 0.0 && voxels < f64::from(abi::Voxel::END)).then_some(voxels as u32)
}

/// What a voxel is made of. The kinds are enshwick's names for the ranges
/// of the game's material ids.
///
/// # Examples
///
/// ```
/// use enshwick::voxels::VoxelMaterial;
///
/// fn is_ground(material: VoxelMaterial) -> bool {
///     matches!(material, VoxelMaterial::Terrain(_))
/// }
/// assert!(!is_ground(VoxelMaterial::Air));
/// ```
#[derive(
    Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
)]
#[non_exhaustive]
pub enum VoxelMaterial {
    /// Empty: no ground and no building.
    #[default]
    Air,
    /// Ground of the terrain material with this id, as
    /// [`TerrainTerraformingConfig::terrain_material`](crate::terrain::TerrainTerraformingConfig::terrain_material)
    /// has it.
    Terrain(u8),
    /// A building block of the building material with this id.
    Building(u8),
    /// A kind of voxel this version of the API does not know, with the
    /// game's material id.
    Unknown(u8),
}

/// One voxel of the world: its material and how full it is.
///
/// # Examples
///
/// ```
/// use enshwick::voxels::{Voxel, VoxelMaterial};
///
/// let rock = Voxel::new(VoxelMaterial::Terrain(9), 255);
/// assert!(!rock.is_air());
/// assert_eq!(rock.fill(), 255);
/// ```
#[derive(
    Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
)]
pub struct Voxel {
    material: VoxelMaterial,
    fill: u8,
}

impl Voxel {
    /// A voxel of `material`, `fill` full out of 255.
    ///
    /// # Examples
    ///
    /// See [`Voxel`].
    #[must_use]
    pub const fn new(material: VoxelMaterial, fill: u8) -> Self {
        Self { material, fill }
    }

    /// What it is made of.
    ///
    /// # Examples
    ///
    /// See the [module](self).
    #[must_use]
    pub const fn material(self) -> VoxelMaterial {
        self.material
    }

    /// How full it is, 0 to 255, which shapes the ground's surface between
    /// voxels; the game's building voxels carry 0. The name is enshwick's:
    /// the game does not name it.
    ///
    /// # Examples
    ///
    /// See [`Voxel`].
    #[must_use]
    pub const fn fill(self) -> u8 {
        self.fill
    }

    /// Whether it holds no ground and no building.
    ///
    /// # Examples
    ///
    /// See [`Voxel`].
    #[must_use]
    pub const fn is_air(self) -> bool {
        matches!(self.material, VoxelMaterial::Air)
    }

    /// The voxel the loader wrote.
    pub(crate) const fn from_abi(raw: abi::Voxel) -> Self {
        let material = match raw.kind {
            abi::Voxel::AIR => VoxelMaterial::Air,
            abi::Voxel::TERRAIN => VoxelMaterial::Terrain(raw.material),
            abi::Voxel::BUILDING => VoxelMaterial::Building(raw.material),
            _ => VoxelMaterial::Unknown(raw.material),
        };
        Self::new(material, raw.fill)
    }

    /// The voxel as the loader writes it, and reads it from a mod.
    #[cfg(any(test, feature = "test", feature = "unstable"))]
    pub(crate) const fn to_abi(self) -> abi::Voxel {
        let (kind, material) = match self.material {
            VoxelMaterial::Air => (abi::Voxel::AIR, 0),
            VoxelMaterial::Terrain(id) => (abi::Voxel::TERRAIN, id),
            VoxelMaterial::Building(id) => (abi::Voxel::BUILDING, id),
            VoxelMaterial::Unknown(id) => (u8::MAX, id),
        };
        abi::Voxel {
            kind,
            material,
            fill: self.fill,
            reserved: 0,
        }
    }
}

/// A box of voxels read from the world, from [`Voxels::read`].
///
/// # Examples
///
/// ```
/// use enshwick::voxels::{VoxelPos, Voxels};
///
/// fn solid(voxels: &Voxels, corner: VoxelPos) -> Result<usize, enshwick::WorldError> {
///     let block = voxels.read(corner, [4, 4, 4])?;
///     Ok(block.iter().filter(|(_, voxel)| !voxel.is_air()).count())
/// }
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(try_from = "Parts")]
pub struct VoxelBox {
    min: VoxelPos,
    size: [u32; 3],
    voxels: Vec<Voxel>,
}

/// A [`VoxelBox`] as serde reads it, before its voxels are counted.
#[derive(serde::Deserialize)]
struct Parts {
    min: VoxelPos,
    size: [u32; 3],
    voxels: Vec<Voxel>,
}

/// Why a [`VoxelBox`] read with serde was refused.
#[derive(Debug, thiserror::Error)]
#[error("a voxel box of {size:?} from {min:?} holding {held} voxels")]
struct VoxelBoxError {
    min: VoxelPos,
    size: [u32; 3],
    held: usize,
}

impl TryFrom<Parts> for VoxelBox {
    type Error = VoxelBoxError;

    fn try_from(parts: Parts) -> Result<Self, VoxelBoxError> {
        let (min, size, held) = (parts.min, parts.size, parts.voxels.len());
        Self::from_parts(min, size, parts.voxels).ok_or(VoxelBoxError { min, size, held })
    }
}

impl VoxelBox {
    /// The box of `size` from `min` holding `voxels`, x fastest, then y,
    /// then z; `None` unless there is one voxel for each place and the box
    /// ends below [`abi::Voxel::END`] on every axis.
    pub(crate) fn from_parts(min: VoxelPos, size: [u32; 3], voxels: Vec<Voxel>) -> Option<Self> {
        let within = (0..3).all(|axis| {
            min.to_array()[axis]
                .checked_add(size[axis])
                .is_some_and(|end| end <= abi::Voxel::END)
        });
        let count = size
            .iter()
            .try_fold(1usize, |count, &axis| count.checked_mul(axis as usize))?;
        (within && count == voxels.len()).then_some(Self { min, size, voxels })
    }

    /// The box turned a quarter turn about the vertical, keeping its
    /// corner: the voxel at (x, y, z) from the corner moves to
    /// (depth − 1 − z, y, x).
    #[cfg(feature = "unstable")]
    pub(crate) fn turned(&self) -> Self {
        let [width, height, depth] = self.size.map(|axis| axis as usize);
        let mut voxels = Vec::with_capacity(self.voxels.len());
        for new_z in 0..width {
            for y in 0..height {
                for new_x in 0..depth {
                    let (x, z) = (new_z, depth - 1 - new_x);
                    voxels.push(self.voxels[x + width * (y + height * z)]);
                }
            }
        }
        let [width, height, depth] = self.size;
        Self {
            min: self.min,
            size: [depth, height, width],
            voxels,
        }
    }

    /// The same voxels with the corner at `(0, 0, 0)`.
    #[cfg(feature = "unstable")]
    pub(crate) fn at_corner(self) -> Self {
        Self {
            min: VoxelPos::default(),
            ..self
        }
    }

    /// Copies `block`, which lies inside this box, into its place.
    #[cfg(feature = "unstable")]
    pub(crate) fn fill_from(&mut self, block: &Self) {
        let [width, height, _] = self.size.map(|axis| axis as usize);
        let [row, rows, _] = block.size.map(|axis| axis as usize);
        let [x, y, z] =
            [0, 1, 2].map(|axis| (block.min.to_array()[axis] - self.min.to_array()[axis]) as usize);
        for (index, source) in block.voxels.chunks_exact(row).enumerate() {
            let start = x + width * (y + index % rows + height * (z + index / rows));
            self.voxels[start..start + row].copy_from_slice(source);
        }
    }

    /// Its lowest corner.
    ///
    /// # Examples
    ///
    /// See [`VoxelBox::get`].
    #[must_use]
    pub const fn min(&self) -> VoxelPos {
        self.min
    }

    /// Its voxels along each axis.
    ///
    /// # Examples
    ///
    /// See [`VoxelBox::get`].
    #[must_use]
    pub const fn size(&self) -> [u32; 3] {
        self.size
    }

    /// The voxel at `at`, a place in the world; `None` outside the box.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::voxels::{Voxel, VoxelBox, VoxelPos};
    ///
    /// fn top(block: &VoxelBox) -> Option<Voxel> {
    ///     let [x, y, z] = block.min().to_array();
    ///     let [_, height, _] = block.size();
    ///     block.get(VoxelPos::new(x, y + height - 1, z))
    /// }
    /// ```
    #[must_use]
    pub fn get(&self, at: VoxelPos) -> Option<Voxel> {
        self.voxels.get(self.index(at)?).copied()
    }

    /// Sets the voxel at `at`, a place in the world; whether `at` lies in
    /// the box.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::voxels::{Voxel, VoxelBox, VoxelMaterial, VoxelPos};
    ///
    /// fn hollow(block: &mut VoxelBox) {
    ///     let [x, y, z] = block.min().to_array();
    ///     block.set(VoxelPos::new(x + 1, y + 1, z + 1), Voxel::new(VoxelMaterial::Air, 0));
    /// }
    /// ```
    pub fn set(&mut self, at: VoxelPos, voxel: Voxel) -> bool {
        let Some(slot) = self.index(at).and_then(|index| self.voxels.get_mut(index)) else {
            return false;
        };
        *slot = voxel;
        true
    }

    /// A box of `size` voxels from `min` holding `voxels`, x fastest, then
    /// y, then z, to write with
    /// `Transaction::write_voxels`;
    /// `None` for an empty box or `voxels` that do not fill it.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::voxels::{Voxel, VoxelBox, VoxelMaterial, VoxelPos};
    ///
    /// let stone = Voxel::new(VoxelMaterial::Building(0x83), 0);
    /// let pillar = VoxelBox::new(VoxelPos::new(200, 80, 200), [1, 4, 1], vec![stone; 4]);
    /// assert!(pillar.is_some());
    /// ```
    #[must_use]
    pub fn new(min: VoxelPos, size: [u32; 3], voxels: Vec<Voxel>) -> Option<Self> {
        let count = size
            .iter()
            .try_fold(1usize, |count, &axis| count.checked_mul(axis as usize))?;
        (count > 0 && count == voxels.len()).then_some(Self { min, size, voxels })
    }

    /// The same voxels with the box's lowest corner at `min`, to write
    /// what was read in one place somewhere else.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::voxels::{VoxelBox, VoxelPos};
    ///
    /// fn copy_up(block: &VoxelBox) -> VoxelBox {
    ///     let [x, y, z] = block.min().to_array();
    ///     block.clone().moved_to(VoxelPos::new(x, y + 20, z))
    /// }
    /// ```
    #[must_use]
    pub fn moved_to(self, min: VoxelPos) -> Self {
        Self { min, ..self }
    }

    /// The index of `at` in the voxels; `None` outside the box.
    fn index(&self, at: VoxelPos) -> Option<usize> {
        let mut index = 0usize;
        for axis in (0..3).rev() {
            let offset = at.to_array()[axis].checked_sub(self.min.to_array()[axis])?;
            if offset >= self.size[axis] {
                return None;
            }
            index = index * self.size[axis] as usize + offset as usize;
        }
        Some(index)
    }

    /// Every voxel, x fastest, then y, then z.
    ///
    /// # Examples
    ///
    /// ```
    /// fn all_air(block: &enshwick::voxels::VoxelBox) -> bool {
    ///     block.as_slice().iter().all(|voxel| voxel.is_air())
    /// }
    /// ```
    #[must_use]
    pub fn as_slice(&self) -> &[Voxel] {
        &self.voxels
    }

    /// Every voxel with its place in the world, x fastest, then y, then z.
    ///
    /// # Examples
    ///
    /// See [`VoxelBox`].
    #[must_use]
    pub fn iter(&self) -> Iter<'_> {
        Iter {
            block: self,
            next: 0,
        }
    }
}

impl<'a> IntoIterator for &'a VoxelBox {
    type Item = (VoxelPos, Voxel);
    type IntoIter = Iter<'a>;

    fn into_iter(self) -> Iter<'a> {
        self.iter()
    }
}

/// The voxels of a [`VoxelBox`] with their places, from [`VoxelBox::iter`].
///
/// # Examples
///
/// See [`VoxelBox`].
#[derive(Clone, Debug)]
pub struct Iter<'a> {
    block: &'a VoxelBox,
    next: usize,
}

impl Iterator for Iter<'_> {
    type Item = (VoxelPos, Voxel);

    fn next(&mut self) -> Option<Self::Item> {
        let voxel = *self.block.voxels.get(self.next)?;
        let [width, height, _] = self.block.size.map(|axis| axis as usize);
        let [x, y, z] = [
            self.next % width,
            self.next / width % height,
            self.next / (width * height),
        ]
        .map(|offset| u32::try_from(offset).unwrap_or(u32::MAX));
        let [min_x, min_y, min_z] = self.block.min.to_array();
        self.next += 1;
        Some((VoxelPos::new(min_x + x, min_y + y, min_z + z), voxel))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let left = self.block.voxels.len() - self.next;
        (left, Some(left))
    }
}

impl ExactSizeIterator for Iter<'_> {}

/// Voxel reads of the server's world; get it from [`Load::voxels`].
///
/// # Examples
///
/// See the [module](self).
#[derive(Clone, Copy, Debug)]
pub struct Voxels {
    host: Host,
}

impl Voxels {
    /// The reads through `host`.
    #[cfg(feature = "unstable")]
    pub(crate) const fn new(host: Host) -> Self {
        Self { host }
    }

    /// The voxels of the box of `size` voxels from `min`, its lowest corner.
    ///
    /// # Errors
    ///
    /// [`WorldError::Refused`] for an empty box, more than [`READ_MAX`]
    /// voxels or one past 2³⁰ voxels on an axis;
    /// [`WorldError::NotLoaded`] while part of the box is not loaded yet,
    /// which this read starts loading: try again in a second or so;
    /// [`WorldError::Missing`] before a world runs or on
    /// a game build without the read; [`WorldError::WrongThread`] off the
    /// game thread or inside a step; [`WorldError::OutsideWorld`] for a box
    /// past the world's edge or above the height the loader takes, 1,024
    /// metres.
    ///
    /// # Examples
    ///
    /// See [`VoxelBox`].
    pub fn read(&self, min: VoxelPos, size: [u32; 3]) -> Result<VoxelBox, WorldError> {
        let count = abi::Voxel::read_count(min.to_array(), size).ok_or(WorldError::Refused)?;
        let mut raw =
            vec![abi::Voxel::default(); usize::try_from(count).map_err(|_| WorldError::Refused)?];
        let corner = min.to_array();
        let status = (self.host.api().voxel_read)(
            self.host.handle(),
            &raw const corner,
            &raw const size,
            raw.as_mut_ptr(),
            count,
        );
        WorldError::from_status(status)?;
        Ok(VoxelBox {
            min,
            size,
            voxels: raw.into_iter().map(Voxel::from_abi).collect(),
        })
    }

    /// The voxel at `at`.
    ///
    /// # Errors
    ///
    /// As for [`Voxels::read`].
    ///
    /// # Examples
    ///
    /// See the [module](self).
    pub fn sample(&self, at: VoxelPos) -> Result<Voxel, WorldError> {
        let mut raw = abi::Voxel::default();
        let corner = at.to_array();
        let size = [1u32; 3];
        let status = (self.host.api().voxel_read)(
            self.host.handle(),
            &raw const corner,
            &raw const size,
            &raw mut raw,
            1,
        );
        WorldError::from_status(status).map(|()| Voxel::from_abi(raw))
    }
}

impl Load<'_> {
    /// The [`Voxels`] of the server's world; on a client, the built-in
    /// server's while it hosts a game.
    ///
    /// # Examples
    ///
    /// See the [module](self).
    #[must_use]
    pub fn voxels(&mut self) -> Voxels {
        Voxels { host: self.host() }
    }
}

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

    #[test]
    fn a_point_lies_in_the_voxel_below_it_on_every_axis() {
        assert_eq!(
            VoxelPos::from_metres([0.0, 0.49, 0.5]),
            Some(VoxelPos::new(0, 0, 1))
        );
        assert_eq!(VoxelPos::from_metres([-0.1, 0.0, 0.0]), None);
        assert_eq!(VoxelPos::from_metres([f64::NAN, 0.0, 0.0]), None);
        assert_eq!(VoxelPos::from_metres([0.0, 1e12, 0.0]), None);
    }

    #[test]
    fn every_material_survives_the_abi() {
        for material in [
            VoxelMaterial::Air,
            VoxelMaterial::Terrain(9),
            VoxelMaterial::Building(0x83),
            VoxelMaterial::Unknown(4),
        ] {
            let voxel = Voxel::new(material, 0x40);
            assert_eq!(Voxel::from_abi(voxel.to_abi()), voxel);
        }
    }

    #[test]
    fn serde_refuses_a_box_whose_count_or_end_is_wrong() {
        let short = VoxelBox {
            min: VoxelPos::new(0, 0, 0),
            size: [2, 1, 1],
            voxels: vec![Voxel::default()],
        };
        let bytes = postcard::to_allocvec(&short).unwrap();
        assert!(postcard::from_bytes::<VoxelBox>(&bytes).is_err());

        let past_the_end = VoxelBox {
            min: VoxelPos::new(abi::Voxel::END - 1, 0, 0),
            size: [2, 1, 1],
            voxels: vec![Voxel::default(); 2],
        };
        let bytes = postcard::to_allocvec(&past_the_end).unwrap();
        assert!(postcard::from_bytes::<VoxelBox>(&bytes).is_err());

        let wrapping = VoxelBox {
            min: VoxelPos::new(u32::MAX, 0, 0),
            size: [2, 1, 1],
            voxels: vec![Voxel::default(); 2],
        };
        let bytes = postcard::to_allocvec(&wrapping).unwrap();
        assert!(postcard::from_bytes::<VoxelBox>(&bytes).is_err());

        let fine = VoxelBox {
            min: VoxelPos::new(abi::Voxel::END - 2, 0, 0),
            size: [2, 1, 1],
            voxels: vec![Voxel::default(); 2],
        };
        let bytes = postcard::to_allocvec(&fine).unwrap();
        assert_eq!(postcard::from_bytes::<VoxelBox>(&bytes).unwrap(), fine);
    }

    #[test]
    #[cfg(feature = "unstable")]
    fn a_block_fills_its_place_row_by_row() {
        let mut whole = VoxelBox {
            min: VoxelPos::new(10, 10, 10),
            size: [4, 3, 2],
            voxels: vec![Voxel::default(); 24],
        };
        let rock = |i: u8| Voxel::new(VoxelMaterial::Terrain(i + 1), 255);
        let block = VoxelBox {
            min: VoxelPos::new(11, 11, 10),
            size: [2, 2, 2],
            voxels: (0..8).map(rock).collect(),
        };
        whole.fill_from(&block);
        for (at, voxel) in &block {
            assert_eq!(whole.get(at), Some(voxel), "{at:?}");
        }
        assert_eq!(whole.iter().filter(|(_, v)| !v.is_air()).count(), 8);
    }

    #[test]
    fn a_box_finds_each_voxel_where_iter_puts_it() {
        let size = [3, 2, 4];
        let voxels = (0..24)
            .map(|i| Voxel::new(VoxelMaterial::Terrain(i), i))
            .collect();
        let block = VoxelBox {
            min: VoxelPos::new(10, 20, 30),
            size,
            voxels,
        };
        assert_eq!(block.iter().len(), 24);
        for (at, voxel) in &block {
            assert_eq!(block.get(at), Some(voxel), "{at:?}");
        }
        assert_eq!(
            block.get(VoxelPos::new(11, 21, 32)).map(Voxel::fill),
            Some(1 + 3 + 2 * 6)
        );
        assert_eq!(block.get(VoxelPos::new(13, 20, 30)), None);
        assert_eq!(block.get(VoxelPos::new(9, 20, 30)), None);
    }
}