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
#[allow(clippy::module_inception)]
mod chunk;
pub mod loaded;
mod paletted_container;
pub mod unloaded;

use std::borrow::Cow;
use std::collections::hash_map::{Entry, OccupiedEntry, VacantEntry};
use std::fmt;

use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
pub use chunk::{MAX_HEIGHT, *};
pub use loaded::LoadedChunk;
use rustc_hash::FxHashMap;
pub use unloaded::UnloadedChunk;
use valence_math::{DVec3, Vec3};
use valence_nbt::Compound;
use valence_protocol::encode::{PacketWriter, WritePacket};
use valence_protocol::packets::play::particle_s2c::Particle;
use valence_protocol::packets::play::{ParticleS2c, PlaySoundS2c};
use valence_protocol::sound::{Sound, SoundCategory, SoundId};
use valence_protocol::{BiomePos, BlockPos, ChunkPos, CompressionThreshold, Encode, Ident, Packet};
use valence_registry::biome::{BiomeId, BiomeRegistry};
use valence_registry::DimensionTypeRegistry;
use valence_server_common::Server;

use super::bvh::GetChunkPos;
use super::message::Messages;
use super::{Layer, UpdateLayersPostClientSet, UpdateLayersPreClientSet};

/// A [`Component`] containing the [chunks](LoadedChunk) and [dimension
/// information](valence_registry::dimension_type::DimensionTypeId) of a
/// Minecraft world.
#[derive(Component, Debug)]
pub struct ChunkLayer {
    messages: ChunkLayerMessages,
    chunks: FxHashMap<ChunkPos, LoadedChunk>,
    info: ChunkLayerInfo,
}

/// Chunk layer information.
pub(crate) struct ChunkLayerInfo {
    dimension_type_name: Ident<String>,
    height: u32,
    min_y: i32,
    biome_registry_len: usize,
    threshold: CompressionThreshold,
}

impl fmt::Debug for ChunkLayerInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ChunkLayerInfo")
            .field("dimension_type_name", &self.dimension_type_name)
            .field("height", &self.height)
            .field("min_y", &self.min_y)
            .field("biome_registry_len", &self.biome_registry_len)
            .field("threshold", &self.threshold)
            // Ignore sky light mask and array.
            .finish()
    }
}

type ChunkLayerMessages = Messages<GlobalMsg, LocalMsg>;

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub(crate) enum GlobalMsg {
    /// Send packet data to all clients viewing the layer.
    Packet,
    /// Send packet data to all clients viewing the layer, except the client
    /// identified by `except`.
    PacketExcept { except: Entity },
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub(crate) enum LocalMsg {
    /// Send packet data to all clients viewing the layer in view of `pos`.
    PacketAt {
        pos: ChunkPos,
    },
    PacketAtExcept {
        pos: ChunkPos,
        except: Entity,
    },
    RadiusAt {
        center: BlockPos,
        radius_squared: u32,
    },
    RadiusAtExcept {
        center: BlockPos,
        radius_squared: u32,
        except: Entity,
    },
    /// Instruct clients to load or unload the chunk at `pos`. Loading and
    /// unloading are combined into a single message so that load/unload order
    /// is not lost when messages are sorted.
    ///
    /// Message content is a single byte indicating load (1) or unload (0).
    ChangeChunkState {
        pos: ChunkPos,
    },
    /// Message content is the data for a single biome in the "change biomes"
    /// packet.
    ChangeBiome {
        pos: ChunkPos,
    },
}

impl GetChunkPos for LocalMsg {
    fn chunk_pos(&self) -> ChunkPos {
        match *self {
            LocalMsg::PacketAt { pos } => pos,
            LocalMsg::PacketAtExcept { pos, .. } => pos,
            LocalMsg::RadiusAt { center, .. } => center.into(),
            LocalMsg::RadiusAtExcept { center, .. } => center.into(),
            LocalMsg::ChangeBiome { pos } => pos,
            LocalMsg::ChangeChunkState { pos } => pos,
        }
    }
}

impl ChunkLayer {
    pub(crate) const LOAD: u8 = 0;
    pub(crate) const UNLOAD: u8 = 1;
    pub(crate) const OVERWRITE: u8 = 2;

    /// Creates a new chunk layer.
    #[track_caller]
    pub fn new<N: Into<Ident<String>>>(
        dimension_type_name: N,
        dimensions: &DimensionTypeRegistry,
        biomes: &BiomeRegistry,
        server: &Server,
    ) -> Self {
        let dimension_type_name = dimension_type_name.into();

        let dim = &dimensions[dimension_type_name.as_str_ident()];

        assert!(
            (0..MAX_HEIGHT as i32).contains(&dim.height),
            "invalid dimension height of {}",
            dim.height
        );

        Self {
            messages: Messages::new(),
            chunks: Default::default(),
            info: ChunkLayerInfo {
                dimension_type_name,
                height: dim.height as u32,
                min_y: dim.min_y,
                biome_registry_len: biomes.iter().len(),
                threshold: server.compression_threshold(),
            },
        }
    }

    /// The name of the dimension this chunk layer is using.
    pub fn dimension_type_name(&self) -> Ident<&str> {
        self.info.dimension_type_name.as_str_ident()
    }

    /// The height of this instance's dimension.
    pub fn height(&self) -> u32 {
        self.info.height
    }

    /// The `min_y` of this instance's dimension.
    pub fn min_y(&self) -> i32 {
        self.info.min_y
    }

    /// Get a reference to the chunk at the given position, if it is loaded.
    pub fn chunk<P: Into<ChunkPos>>(&self, pos: P) -> Option<&LoadedChunk> {
        self.chunks.get(&pos.into())
    }

    /// Get a mutable reference to the chunk at the given position, if it is
    /// loaded.
    pub fn chunk_mut<P: Into<ChunkPos>>(&mut self, pos: P) -> Option<&mut LoadedChunk> {
        self.chunks.get_mut(&pos.into())
    }

    /// Insert a chunk into the instance at the given position. The previous
    /// chunk data is returned.
    pub fn insert_chunk<P: Into<ChunkPos>>(
        &mut self,
        pos: P,
        chunk: UnloadedChunk,
    ) -> Option<UnloadedChunk> {
        match self.chunk_entry(pos) {
            ChunkEntry::Occupied(mut oe) => Some(oe.insert(chunk)),
            ChunkEntry::Vacant(ve) => {
                ve.insert(chunk);
                None
            }
        }
    }

    /// Unload the chunk at the given position, if it is loaded. Returns the
    /// chunk if it was loaded.
    pub fn remove_chunk<P: Into<ChunkPos>>(&mut self, pos: P) -> Option<UnloadedChunk> {
        match self.chunk_entry(pos) {
            ChunkEntry::Occupied(oe) => Some(oe.remove()),
            ChunkEntry::Vacant(_) => None,
        }
    }

    /// Unload all chunks in this instance.
    pub fn clear_chunks(&mut self) {
        self.retain_chunks(|_, _| false)
    }

    /// Retain only the chunks for which the given predicate returns `true`.
    pub fn retain_chunks<F>(&mut self, mut f: F)
    where
        F: FnMut(ChunkPos, &mut LoadedChunk) -> bool,
    {
        self.chunks.retain(|pos, chunk| {
            if !f(*pos, chunk) {
                self.messages
                    .send_local_infallible(LocalMsg::ChangeChunkState { pos: *pos }, |b| {
                        b.push(Self::UNLOAD)
                    });

                false
            } else {
                true
            }
        });
    }

    /// Get a [`ChunkEntry`] for the given position.
    pub fn chunk_entry<P: Into<ChunkPos>>(&mut self, pos: P) -> ChunkEntry {
        match self.chunks.entry(pos.into()) {
            Entry::Occupied(oe) => ChunkEntry::Occupied(OccupiedChunkEntry {
                messages: &mut self.messages,
                entry: oe,
            }),
            Entry::Vacant(ve) => ChunkEntry::Vacant(VacantChunkEntry {
                height: self.info.height,
                messages: &mut self.messages,
                entry: ve,
            }),
        }
    }

    /// Get an iterator over all loaded chunks in the instance. The order of the
    /// chunks is undefined.
    pub fn chunks(&self) -> impl Iterator<Item = (ChunkPos, &LoadedChunk)> + Clone + '_ {
        self.chunks.iter().map(|(pos, chunk)| (*pos, chunk))
    }

    /// Get an iterator over all loaded chunks in the instance, mutably. The
    /// order of the chunks is undefined.
    pub fn chunks_mut(&mut self) -> impl Iterator<Item = (ChunkPos, &mut LoadedChunk)> + '_ {
        self.chunks.iter_mut().map(|(pos, chunk)| (*pos, chunk))
    }

    /// Optimizes the memory usage of the instance.
    pub fn shrink_to_fit(&mut self) {
        for (_, chunk) in self.chunks_mut() {
            chunk.shrink_to_fit();
        }

        self.chunks.shrink_to_fit();
        self.messages.shrink_to_fit();
    }

    pub fn block<P: Into<BlockPos>>(&self, pos: P) -> Option<BlockRef> {
        let pos = pos.into();

        let y = pos
            .y
            .checked_sub(self.info.min_y)
            .and_then(|y| y.try_into().ok())?;

        if y >= self.info.height {
            return None;
        }

        let chunk = self.chunk(pos)?;

        let x = pos.x.rem_euclid(16) as u32;
        let z = pos.z.rem_euclid(16) as u32;

        Some(chunk.block(x, y, z))
    }

    pub fn set_block<P, B>(&mut self, pos: P, block: B) -> Option<Block>
    where
        P: Into<BlockPos>,
        B: IntoBlock,
    {
        let pos = pos.into();

        let y = pos
            .y
            .checked_sub(self.info.min_y)
            .and_then(|y| y.try_into().ok())?;

        if y >= self.info.height {
            return None;
        }

        let chunk = self.chunk_mut(pos)?;

        let x = pos.x.rem_euclid(16) as u32;
        let z = pos.z.rem_euclid(16) as u32;

        Some(chunk.set_block(x, y, z, block))
    }

    pub fn block_entity_mut<P: Into<BlockPos>>(&mut self, pos: P) -> Option<&mut Compound> {
        let pos = pos.into();

        let y = pos
            .y
            .checked_sub(self.info.min_y)
            .and_then(|y| y.try_into().ok())?;

        if y >= self.info.height {
            return None;
        }

        let chunk = self.chunk_mut(pos)?;

        let x = pos.x.rem_euclid(16) as u32;
        let z = pos.z.rem_euclid(16) as u32;

        chunk.block_entity_mut(x, y, z)
    }

    pub fn biome<P: Into<BiomePos>>(&self, pos: P) -> Option<BiomeId> {
        let pos = pos.into();

        let y = pos
            .y
            .checked_sub(self.info.min_y / 4)
            .and_then(|y| y.try_into().ok())?;

        if y >= self.info.height / 4 {
            return None;
        }

        let chunk = self.chunk(pos)?;

        let x = pos.x.rem_euclid(4) as u32;
        let z = pos.z.rem_euclid(4) as u32;

        Some(chunk.biome(x, y, z))
    }

    pub fn set_biome<P: Into<BiomePos>>(&mut self, pos: P, biome: BiomeId) -> Option<BiomeId> {
        let pos = pos.into();

        let y = pos
            .y
            .checked_sub(self.info.min_y / 4)
            .and_then(|y| y.try_into().ok())?;

        if y >= self.info.height / 4 {
            return None;
        }

        let chunk = self.chunk_mut(pos)?;

        let x = pos.x.rem_euclid(4) as u32;
        let z = pos.z.rem_euclid(4) as u32;

        Some(chunk.set_biome(x, y, z, biome))
    }

    pub(crate) fn info(&self) -> &ChunkLayerInfo {
        &self.info
    }

    pub(crate) fn messages(&self) -> &ChunkLayerMessages {
        &self.messages
    }

    // TODO: move to `valence_particle`.
    /// Puts a particle effect at the given position in the world. The particle
    /// effect is visible to all players in the instance with the
    /// appropriate chunk in view.
    pub fn play_particle<P, O>(
        &mut self,
        particle: &Particle,
        long_distance: bool,
        position: P,
        offset: O,
        max_speed: f32,
        count: i32,
    ) where
        P: Into<DVec3>,
        O: Into<Vec3>,
    {
        let position = position.into();

        self.view_writer(position).write_packet(&ParticleS2c {
            particle: Cow::Borrowed(particle),
            long_distance,
            position,
            offset: offset.into(),
            max_speed,
            count,
        });
    }

    // TODO: move to `valence_sound`.
    /// Plays a sound effect at the given position in the world. The sound
    /// effect is audible to all players in the instance with the
    /// appropriate chunk in view.
    pub fn play_sound<P: Into<DVec3>>(
        &mut self,
        sound: Sound,
        category: SoundCategory,
        position: P,
        volume: f32,
        pitch: f32,
    ) {
        let position = position.into();

        self.view_writer(position).write_packet(&PlaySoundS2c {
            id: SoundId::Direct {
                id: sound.to_ident().into(),
                range: None,
            },
            category,
            position: (position * 8.0).as_ivec3(),
            volume,
            pitch,
            seed: rand::random(),
        });
    }
}

impl Layer for ChunkLayer {
    type ExceptWriter<'a> = ExceptWriter<'a>;

    type ViewWriter<'a> = ViewWriter<'a>;

    type ViewExceptWriter<'a> = ViewExceptWriter<'a>;

    type RadiusWriter<'a> = RadiusWriter<'a>;

    type RadiusExceptWriter<'a> = RadiusExceptWriter<'a>;

    fn except_writer(&mut self, except: Entity) -> Self::ExceptWriter<'_> {
        ExceptWriter {
            layer: self,
            except,
        }
    }

    fn view_writer(&mut self, pos: impl Into<ChunkPos>) -> Self::ViewWriter<'_> {
        ViewWriter {
            layer: self,
            pos: pos.into(),
        }
    }

    fn view_except_writer(
        &mut self,
        pos: impl Into<ChunkPos>,
        except: Entity,
    ) -> Self::ViewExceptWriter<'_> {
        ViewExceptWriter {
            layer: self,
            pos: pos.into(),
            except,
        }
    }

    fn radius_writer(
        &mut self,
        center: impl Into<BlockPos>,
        radius: u32,
    ) -> Self::RadiusWriter<'_> {
        RadiusWriter {
            layer: self,
            center: center.into(),
            radius,
        }
    }

    fn radius_except_writer(
        &mut self,
        center: impl Into<BlockPos>,
        radius: u32,
        except: Entity,
    ) -> Self::RadiusExceptWriter<'_> {
        RadiusExceptWriter {
            layer: self,
            center: center.into(),
            radius,
            except,
        }
    }
}

impl WritePacket for ChunkLayer {
    fn write_packet_fallible<P>(&mut self, packet: &P) -> anyhow::Result<()>
    where
        P: Packet + Encode,
    {
        self.messages.send_global(GlobalMsg::Packet, |b| {
            PacketWriter::new(b, self.info.threshold).write_packet_fallible(packet)
        })
    }

    fn write_packet_bytes(&mut self, bytes: &[u8]) {
        self.messages
            .send_global_infallible(GlobalMsg::Packet, |b| b.extend_from_slice(bytes));
    }
}

pub struct ExceptWriter<'a> {
    layer: &'a mut ChunkLayer,
    except: Entity,
}

impl WritePacket for ExceptWriter<'_> {
    fn write_packet_fallible<P>(&mut self, packet: &P) -> anyhow::Result<()>
    where
        P: Packet + Encode,
    {
        self.layer.messages.send_global(
            GlobalMsg::PacketExcept {
                except: self.except,
            },
            |b| PacketWriter::new(b, self.layer.info.threshold).write_packet_fallible(packet),
        )
    }

    fn write_packet_bytes(&mut self, bytes: &[u8]) {
        self.layer.messages.send_global_infallible(
            GlobalMsg::PacketExcept {
                except: self.except,
            },
            |b| b.extend_from_slice(bytes),
        )
    }
}

pub struct ViewWriter<'a> {
    layer: &'a mut ChunkLayer,
    pos: ChunkPos,
}

impl WritePacket for ViewWriter<'_> {
    fn write_packet_fallible<P>(&mut self, packet: &P) -> anyhow::Result<()>
    where
        P: Packet + Encode,
    {
        self.layer
            .messages
            .send_local(LocalMsg::PacketAt { pos: self.pos }, |b| {
                PacketWriter::new(b, self.layer.info.threshold).write_packet_fallible(packet)
            })
    }

    fn write_packet_bytes(&mut self, bytes: &[u8]) {
        self.layer
            .messages
            .send_local_infallible(LocalMsg::PacketAt { pos: self.pos }, |b| {
                b.extend_from_slice(bytes)
            });
    }
}

pub struct ViewExceptWriter<'a> {
    layer: &'a mut ChunkLayer,
    pos: ChunkPos,
    except: Entity,
}

impl WritePacket for ViewExceptWriter<'_> {
    fn write_packet_fallible<P>(&mut self, packet: &P) -> anyhow::Result<()>
    where
        P: Packet + Encode,
    {
        self.layer.messages.send_local(
            LocalMsg::PacketAtExcept {
                pos: self.pos,
                except: self.except,
            },
            |b| PacketWriter::new(b, self.layer.info.threshold).write_packet_fallible(packet),
        )
    }

    fn write_packet_bytes(&mut self, bytes: &[u8]) {
        self.layer.messages.send_local_infallible(
            LocalMsg::PacketAtExcept {
                pos: self.pos,
                except: self.except,
            },
            |b| b.extend_from_slice(bytes),
        );
    }
}

pub struct RadiusWriter<'a> {
    layer: &'a mut ChunkLayer,
    center: BlockPos,
    radius: u32,
}

impl WritePacket for RadiusWriter<'_> {
    fn write_packet_fallible<P>(&mut self, packet: &P) -> anyhow::Result<()>
    where
        P: Packet + Encode,
    {
        self.layer.messages.send_local(
            LocalMsg::RadiusAt {
                center: self.center,
                radius_squared: self.radius,
            },
            |b| PacketWriter::new(b, self.layer.info.threshold).write_packet_fallible(packet),
        )
    }

    fn write_packet_bytes(&mut self, bytes: &[u8]) {
        self.layer.messages.send_local_infallible(
            LocalMsg::RadiusAt {
                center: self.center,
                radius_squared: self.radius,
            },
            |b| b.extend_from_slice(bytes),
        );
    }
}

pub struct RadiusExceptWriter<'a> {
    layer: &'a mut ChunkLayer,
    center: BlockPos,
    radius: u32,
    except: Entity,
}

impl WritePacket for RadiusExceptWriter<'_> {
    fn write_packet_fallible<P>(&mut self, packet: &P) -> anyhow::Result<()>
    where
        P: Packet + Encode,
    {
        self.layer.messages.send_local(
            LocalMsg::RadiusAtExcept {
                center: self.center,
                radius_squared: self.radius,
                except: self.except,
            },
            |b| PacketWriter::new(b, self.layer.info.threshold).write_packet_fallible(packet),
        )
    }

    fn write_packet_bytes(&mut self, bytes: &[u8]) {
        self.layer.messages.send_local_infallible(
            LocalMsg::RadiusAtExcept {
                center: self.center,
                radius_squared: self.radius,
                except: self.except,
            },
            |b| b.extend_from_slice(bytes),
        );
    }
}

#[derive(Debug)]
pub enum ChunkEntry<'a> {
    Occupied(OccupiedChunkEntry<'a>),
    Vacant(VacantChunkEntry<'a>),
}

impl<'a> ChunkEntry<'a> {
    pub fn or_default(self) -> &'a mut LoadedChunk {
        match self {
            ChunkEntry::Occupied(oe) => oe.into_mut(),
            ChunkEntry::Vacant(ve) => ve.insert(UnloadedChunk::new()),
        }
    }
}

#[derive(Debug)]
pub struct OccupiedChunkEntry<'a> {
    messages: &'a mut ChunkLayerMessages,
    entry: OccupiedEntry<'a, ChunkPos, LoadedChunk>,
}

impl<'a> OccupiedChunkEntry<'a> {
    pub fn get(&self) -> &LoadedChunk {
        self.entry.get()
    }

    pub fn get_mut(&mut self) -> &mut LoadedChunk {
        self.entry.get_mut()
    }

    pub fn insert(&mut self, chunk: UnloadedChunk) -> UnloadedChunk {
        self.messages.send_local_infallible(
            LocalMsg::ChangeChunkState {
                pos: *self.entry.key(),
            },
            |b| b.push(ChunkLayer::OVERWRITE),
        );

        self.entry.get_mut().insert(chunk)
    }

    pub fn into_mut(self) -> &'a mut LoadedChunk {
        self.entry.into_mut()
    }

    pub fn key(&self) -> &ChunkPos {
        self.entry.key()
    }

    pub fn remove(self) -> UnloadedChunk {
        self.messages.send_local_infallible(
            LocalMsg::ChangeChunkState {
                pos: *self.entry.key(),
            },
            |b| b.push(ChunkLayer::UNLOAD),
        );

        self.entry.remove().remove()
    }

    pub fn remove_entry(mut self) -> (ChunkPos, UnloadedChunk) {
        let pos = *self.entry.key();
        let chunk = self.entry.get_mut().remove();

        self.messages.send_local_infallible(
            LocalMsg::ChangeChunkState {
                pos: *self.entry.key(),
            },
            |b| b.push(ChunkLayer::UNLOAD),
        );

        (pos, chunk)
    }
}

#[derive(Debug)]
pub struct VacantChunkEntry<'a> {
    height: u32,
    messages: &'a mut ChunkLayerMessages,
    entry: VacantEntry<'a, ChunkPos, LoadedChunk>,
}

impl<'a> VacantChunkEntry<'a> {
    pub fn insert(self, chunk: UnloadedChunk) -> &'a mut LoadedChunk {
        let mut loaded = LoadedChunk::new(self.height);
        loaded.insert(chunk);

        self.messages.send_local_infallible(
            LocalMsg::ChangeChunkState {
                pos: *self.entry.key(),
            },
            |b| b.push(ChunkLayer::LOAD),
        );

        self.entry.insert(loaded)
    }

    pub fn into_key(self) -> ChunkPos {
        *self.entry.key()
    }

    pub fn key(&self) -> &ChunkPos {
        self.entry.key()
    }
}

pub(super) fn build(app: &mut App) {
    app.add_systems(
        PostUpdate,
        (
            update_chunk_layers_pre_client.in_set(UpdateLayersPreClientSet),
            update_chunk_layers_post_client.in_set(UpdateLayersPostClientSet),
        ),
    );
}

fn update_chunk_layers_pre_client(mut layers: Query<&mut ChunkLayer>) {
    for layer in &mut layers {
        let layer = layer.into_inner();

        for (&pos, chunk) in &mut layer.chunks {
            chunk.update_pre_client(pos, &layer.info, &mut layer.messages);
        }

        layer.messages.ready();
    }
}

fn update_chunk_layers_post_client(mut layers: Query<&mut ChunkLayer>) {
    for mut layer in &mut layers {
        layer.messages.unready();
    }
}