bevy_cells 0.1.1

Bevy library for working with entities in grids.
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
use std::{
    cmp::Eq,
    hash::Hash,
    marker::PhantomData,
    ops::{Deref, DerefMut},
};

use super::{
    coords::{calculate_cell_index, calculate_chunk_coordinate},
    CellCoord, CellIndex, CellMap, CellMapLabel, Chunk, ChunkCoord, InChunk, InMap,
};
use aery::{
    edges::{CheckedDespawn, Unset, Withdraw},
    prelude::Set,
};
use bevy::{
    ecs::system::{Command, EntityCommands},
    prelude::{Bundle, Commands, Entity, With, World},
    utils::{hashbrown::hash_map::Entry, HashMap},
};

mod cell_batch;
mod cell_single;
mod chunk_batch;
mod chunk_single;
mod map;

use cell_batch::*;
use cell_single::*;
use chunk_batch::*;
use chunk_single::*;
use map::*;

/// Applies commands to a specific cell map.
pub struct CellCommands<'a, 'w, 's, L, const N: usize> {
    commands: &'a mut Commands<'w, 's>,
    phantom: PhantomData<L>,
}

impl<'a, 'w, 's, L, const N: usize> Deref for CellCommands<'a, 'w, 's, L, N>
where
    L: CellMapLabel + 'static,
{
    type Target = Commands<'w, 's>;

    fn deref(&self) -> &Self::Target {
        self.commands
    }
}

impl<'a, 'w, 's, L, const N: usize> DerefMut for CellCommands<'a, 'w, 's, L, N>
where
    L: CellMapLabel + 'static,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.commands
    }
}

pub trait CellCommandExt<'w, 's> {
    /// Gets the [CellCommands] to apply commands at the cell map level.
    fn cells<'a, L, const N: usize>(&'a mut self) -> CellCommands<'a, 'w, 's, L, N>
    where
        L: CellMapLabel + 'static;
}

impl<'w, 's> CellCommandExt<'w, 's> for Commands<'w, 's> {
    fn cells<L, const N: usize>(&mut self) -> CellCommands<'_, 'w, 's, L, N>
    where
        L: CellMapLabel + 'static,
    {
        CellCommands {
            commands: self,
            phantom: PhantomData,
        }
    }
}

impl<'a, 'w, 's, L, const N: usize> CellCommands<'a, 'w, 's, L, N>
where
    L: CellMapLabel + 'static,
{
    /// Spawns a cell and returns a handle to the underlying entity.
    /// This will despawn any cell that already exists in this coordinate
    pub fn spawn_cell<T>(&mut self, cell_c: [isize; N], bundle: T) -> EntityCommands<'w, 's, '_>
    where
        T: Bundle + 'static,
    {
        let cell_id = self.spawn(bundle).id();
        self.add(SpawnCell::<L, N> {
            cell_c,
            cell_id,
            label: std::marker::PhantomData,
        });
        self.entity(cell_id)
    }

    /// Spawns cells from the given iterator using the given function.
    /// This will despawn any cell that already exists in this coordinate
    pub fn spawn_cell_batch<F, B, IC>(&mut self, cell_cs: IC, bundle_f: F)
    where
        F: Fn([isize; N]) -> B + Send + 'static,
        B: Bundle + Send + 'static,
        IC: IntoIterator<Item = [isize; N]> + Send + 'static,
    {
        self.add(SpawnCellBatch::<L, F, B, IC, N> {
            cell_cs,
            bundle_f,
            label: std::marker::PhantomData,
        });
    }

    /// Despawns a cell.
    pub fn despawn_cell(&mut self, cell_c: [isize; N]) -> &mut Self {
        self.add(DespawnCell::<L, N> {
            cell_c,
            label: PhantomData,
        });
        self
    }

    /// Despawns cells from the given iterator.
    pub fn despawn_cell_batch<IC>(&mut self, cell_cs: IC)
    where
        IC: IntoIterator<Item = [isize; N]> + Send + 'static,
    {
        self.add(DespawnCellBatch::<L, IC, N> {
            cell_cs,
            label: std::marker::PhantomData,
        });
    }

    /// Moves a cell from one coordinate to another, overwriting and despawning any cell in the new coordinate.
    pub fn move_cell(&mut self, old_c: [isize; N], new_c: [isize; N]) -> &mut Self {
        self.add(MoveCell::<L, N> {
            old_c,
            new_c,
            label: PhantomData,
        });
        self
    }

    /// Move cells from the first coordinate to the second coordinate, despawning
    /// any cell found in the second coordinate.
    pub fn move_cell_batch<IC>(&mut self, cell_cs: IC)
    where
        IC: IntoIterator<Item = ([isize; N], [isize; N])> + Send + 'static,
    {
        self.add(MoveCellBatch::<L, IC, N> {
            cell_cs,
            label: std::marker::PhantomData,
        });
    }

    /// Swaps two cells if both exist, or just moves one cell if the other doesn't exist.
    pub fn swap_cells(&mut self, cell_c_1: [isize; N], cell_c_2: [isize; N]) -> &mut Self {
        self.add(SwapCell::<L, N> {
            cell_c_1,
            cell_c_2,
            label: PhantomData,
        });
        self
    }

    /// Swap cells from the first coordinate and the second coordinate
    pub fn swap_cell_batch<IC>(&mut self, cell_cs: IC)
    where
        IC: IntoIterator<Item = ([isize; N], [isize; N])> + Send + 'static,
    {
        self.add(SwapCellBatch::<L, IC, N> {
            cell_cs,
            label: std::marker::PhantomData,
        });
    }

    /// Manually spawn a chunk entity, note that this will overwrite and despawn existing chunks at this location.
    pub fn spawn_chunk<T>(&mut self, chunk_c: [isize; N], bundle: T) -> EntityCommands<'w, 's, '_>
    where
        T: Bundle + 'static,
    {
        let chunk_id = self.spawn(bundle).id();
        self.add(SpawnChunk::<L, N> {
            chunk_c,
            chunk_id,
            label: std::marker::PhantomData,
        });
        self.entity(chunk_id)
    }

    /// Spawns chunks from the given iterator using the given function.
    /// This will despawn any chunks (and their cells) that already exists in this coordinate
    pub fn spawn_chunk_batch_with<F, B, IC>(&mut self, chunk_cs: IC, bundle_f: F)
    where
        F: Fn([isize; N]) -> B + Send + 'static,
        B: Bundle + Send + 'static,
        IC: IntoIterator<Item = [isize; N]> + Send + 'static,
    {
        self.add(SpawnChunkBatch::<L, F, B, IC, N> {
            chunk_cs,
            bundle_f,
            label: std::marker::PhantomData,
        });
    }

    /// Recursively despawn a chunk and all it's cells.
    pub fn despawn_chunk(&mut self, chunk_c: [isize; N]) -> &mut Self {
        self.add(DespawnChunk::<L, N> {
            chunk_c,
            label: std::marker::PhantomData,
        });
        self
    }

    /// Despawns chunks (and their cells) from the given iterator.
    pub fn despawn_chunk_batch<IC>(&mut self, chunk_cs: IC)
    where
        IC: IntoIterator<Item = [isize; N]> + Send + 'static,
    {
        self.add(DespawnChunkBatch::<L, IC, N> {
            chunk_cs,
            label: std::marker::PhantomData,
        });
    }

    /// Recursively despawns a map and all it's chunks and cells.
    pub fn despawn_map(&mut self) -> &mut Self {
        self.add(DespawnMap::<L, N> { label: PhantomData });
        self
    }
}

/// Spawns a chunk in the world if needed, inserts the info into the map, and returns
/// and id for reinsertion
#[inline]
fn spawn_or_remove_chunk<L, const N: usize>(
    world: &mut World,
    map: &mut CellMap<L, N>,
    map_id: Entity,
    chunk_c: [isize; N],
) -> (Entity, Chunk)
where
    L: CellMapLabel + Send + 'static,
{
    if let Some(chunk_info) = remove_chunk::<L, N>(world, map, chunk_c) {
        chunk_info
    } else {
        let chunk_id = world.spawn(ChunkCoord::from(chunk_c)).id();
        map.chunks.insert(chunk_c.into(), chunk_id);
        Set::<InMap<L, N>>::new(chunk_id, map_id).apply(world);
        (chunk_id, Chunk::new(L::CHUNK_SIZE.pow(N as u32)))
    }
}

/// Removes a chunk from the world if it exists, and returns the info to reinsert it.
#[inline]
fn remove_chunk<L, const N: usize>(
    world: &mut World,
    map: &mut CellMap<L, N>,
    chunk_c: [isize; N],
) -> Option<(Entity, Chunk)>
where
    L: CellMapLabel + Send + 'static,
{
    map.chunks
        .get(&chunk_c.into())
        .cloned()
        .and_then(|chunk_id| world.get_entity_mut(chunk_id))
        .map(|mut chunk_e| (chunk_e.id(), chunk_e.take::<Chunk>().unwrap()))
}

/// Takes the map out of the world or spawns a new one and returns the entity id to return the map to.
#[inline]
fn spawn_or_remove_map<L, const N: usize>(world: &mut World) -> (Entity, CellMap<L, N>)
where
    L: CellMapLabel + Send + 'static,
{
    let map_info = remove_map::<L, N>(world);
    if let Some(map_info) = map_info {
        map_info
    } else {
        (world.spawn_empty().id(), CellMap::<L, N>::default())
    }
}

/// Takes the map out of the world if it exists.
#[inline]
fn remove_map<L, const N: usize>(world: &mut World) -> Option<(Entity, CellMap<L, N>)>
where
    L: CellMapLabel + Send + 'static,
{
    world
        .query_filtered::<Entity, With<CellMap<L, N>>>()
        .get_single_mut(world)
        .ok()
        .map(|map_id| {
            (
                map_id,
                world
                    .get_entity_mut(map_id)
                    .unwrap()
                    .take::<CellMap<L, N>>()
                    .unwrap(),
            )
        })
}

/// Inserts a cell into the world
pub fn insert_cell<L, const N: usize>(world: &mut World, cell_c: [isize; N], cell_id: Entity)
where
    L: CellMapLabel + Send + 'static,
{
    // Take the map out and get the id to reinsert it
    let (map_id, mut map) = spawn_or_remove_map::<L, N>(world);

    // Take the chunk out and get the id to reinsert it
    let chunk_c = calculate_chunk_coordinate(cell_c, L::CHUNK_SIZE);
    let (chunk_id, mut chunk) = spawn_or_remove_chunk::<L, N>(world, &mut map, map_id, chunk_c);

    // Insert the tile
    let cell_i = calculate_cell_index(cell_c, L::CHUNK_SIZE);

    if let Some(cell) = chunk.cells.get_mut(cell_i) {
        if let Some(old_cell_id) = cell.replace(cell_id) {
            world.despawn(old_cell_id);
        }
    }

    Set::<InChunk<L, N>>::new(cell_id, chunk_id).apply(world);

    world
        .get_entity_mut(cell_id)
        .unwrap()
        .insert((CellIndex::from(cell_i), CellCoord::<N>::new(cell_c)));

    world.get_entity_mut(chunk_id).unwrap().insert(chunk);
    world.get_entity_mut(map_id).unwrap().insert(map);
}

/// Take a cell from the world.
pub fn take_cell<L, const N: usize>(world: &mut World, cell_c: [isize; N]) -> Option<Entity>
where
    L: CellMapLabel + Send + 'static,
{
    // Get the map or return
    let (map_id, mut map) = remove_map::<L, N>(world)?;

    // Get the old chunk or return
    let chunk_c = calculate_chunk_coordinate(cell_c, L::CHUNK_SIZE);
    let (chunk_id, mut chunk) =
        if let Some(chunk_info) = remove_chunk::<L, N>(world, &mut map, chunk_c) {
            chunk_info
        } else {
            world.get_entity_mut(map_id).unwrap().insert(map);
            return None;
        };

    // Remove the old entity or return if the old entity is already deleted
    let cell_i = calculate_cell_index(cell_c, L::CHUNK_SIZE);

    let cell = if let Some(mut cell_e) = chunk
        .cells
        .get_mut(cell_i)
        .and_then(|cell| cell.take())
        .and_then(|cell_id| world.get_entity_mut(cell_id))
    {
        cell_e.remove::<(CellIndex, CellCoord)>();
        let cell_id = cell_e.id();
        Unset::<InChunk<L, N>>::new(cell_id, chunk_id).apply(world);
        Some(cell_id)
    } else {
        None
    };

    world.get_entity_mut(chunk_id).unwrap().insert(chunk);
    world.get_entity_mut(map_id).unwrap().insert(map);
    cell
}

/// Inserts a list of entities into the corresponding cells of a given cell map
pub fn insert_cell_batch<L, const N: usize>(
    world: &mut World,
    cells: impl IntoIterator<Item = ([isize; N], Entity)>,
) where
    L: CellMapLabel + Send + 'static,
{
    let chunked_cells = cells
        .into_iter()
        .group_by(|(cell_c, _)| calculate_chunk_coordinate(*cell_c, L::CHUNK_SIZE));

    // Remove the map, or spawn an entity to hold the map, then create an empty map
    let (map_id, mut map) = spawn_or_remove_map::<L, N>(world);

    // Get the chunks and entities from the map
    let cells_with_chunk = Vec::from_iter(chunked_cells.into_iter().map(|(chunk_c, cells)| {
        let (chunk_id, chunk) = spawn_or_remove_chunk::<L, N>(world, &mut map, map_id, chunk_c);
        (chunk_id, chunk, cells)
    }));

    for (chunk_id, mut chunk, cells) in cells_with_chunk {
        for (cell_c, cell_id) in cells {
            let cell_i = calculate_cell_index(cell_c, L::CHUNK_SIZE);

            if let Some(cell) = chunk.cells.get_mut(cell_i) {
                if let Some(old_cell_id) = cell.replace(cell_id) {
                    world.despawn(old_cell_id);
                }
            }

            Set::<InChunk<L, N>>::new(cell_id, chunk_id).apply(world);

            world
                .get_entity_mut(cell_id)
                .unwrap()
                .insert((CellIndex::from(cell_i), CellCoord::<N>::new(cell_c)));
        }

        world.get_entity_mut(chunk_id).unwrap().insert(chunk);
    }

    world.get_entity_mut(map_id).unwrap().insert(map);
}

/// Removes the cells from the cell map, returning the cell coordinates removed and their corresponding entities.
pub fn take_cell_batch<L, const N: usize>(
    world: &mut World,
    cells: impl IntoIterator<Item = [isize; N]>,
) -> Vec<([isize; N], Entity)>
where
    L: CellMapLabel + Send + 'static,
{
    // Group cells by chunk
    let chunked_cells = cells
        .into_iter()
        .group_by(|cell_c| calculate_chunk_coordinate(*cell_c, L::CHUNK_SIZE));

    // Remove the map, or return if it doesn't exist
    let (map_id, mut map) = if let Some(map_info) = remove_map::<L, N>(world) {
        map_info
    } else {
        return Vec::new();
    };

    // Get the chunks and entities from the map
    let cells_with_chunk = chunked_cells
        .into_iter()
        .filter_map(|(chunk_c, cells)| {
            remove_chunk(world, &mut map, chunk_c)
                .map(|chunk_info| (chunk_info.0, chunk_info.1, cells))
        })
        .map(|(chunk_id, chunk, cells)| {
            (
                chunk_id,
                chunk,
                cells.into_iter().collect::<Vec<[isize; N]>>(),
            )
        })
        .collect::<Vec<(Entity, Chunk, Vec<[isize; N]>)>>();

    let mut cell_ids = Vec::new();
    for (chunk_id, mut chunk, cells) in cells_with_chunk {
        for cell_c in cells {
            let cell_i = calculate_cell_index(cell_c, L::CHUNK_SIZE);

            if let Some(mut cell_e) = chunk
                .cells
                .get_mut(cell_i)
                .and_then(|cell| cell.take())
                .and_then(|cell_id| world.get_entity_mut(cell_id))
            {
                cell_e.remove::<(CellIndex, CellCoord)>();
                let cell_id = cell_e.id();
                Unset::<InChunk<L, N>>::new(cell_id, chunk_id).apply(world);
                cell_ids.push((cell_c, cell_id));
            }
        }

        world.get_entity_mut(chunk_id).unwrap().insert(chunk);
    }

    world.get_entity_mut(map_id).unwrap().insert(map);
    cell_ids
}

/// Insert the given entity into the map and have it treated as a chunk
pub fn insert_chunk<L, const N: usize>(world: &mut World, chunk_c: [isize; N], chunk_id: Entity)
where
    L: CellMapLabel + Send + 'static,
{
    let (map_id, mut map) = spawn_or_remove_map::<L, N>(world);

    // Despawn the chunk if it exists
    if let Some(chunk_id) = map.chunks.insert(chunk_c.into(), chunk_id) {
        CheckedDespawn(chunk_id).apply(world);
    }

    world.get_entity_mut(chunk_id).unwrap().insert((
        Chunk::new(L::CHUNK_SIZE.pow(N as u32)),
        ChunkCoord::from(chunk_c),
    ));
    Set::<InMap<L, N>>::new(chunk_id, map_id).apply(world);
    map.chunks.insert(chunk_c.into(), chunk_id);

    world.entity_mut(map_id).insert(map);
}

/// Remove the chunk from the map without despawning it.
/// # Note
/// This does not despawn or remove the cell entities, and reinsertion of this entity will not recreate the link to the chunk's cells.
/// If you wish to take the chunk and delete it's underlying cells, use (take_chunk_despawn_cells)[`take_chunk_despawn_cells`]
pub fn take_chunk<L, const N: usize>(world: &mut World, chunk_c: [isize; N]) -> Option<Entity>
where
    L: CellMapLabel + Send + 'static,
{
    // Get the map or return
    let (map_id, mut map) = remove_map::<L, N>(world)?;

    // Get the old chunk or return
    let chunk_id = if let Some(mut chunk_e) = map
        .chunks
        .remove(&chunk_c.into())
        .and_then(|chunk_id| world.get_entity_mut(chunk_id))
    {
        chunk_e.remove::<(Chunk, ChunkCoord)>();
        let chunk_id = chunk_e.id();
        Unset::<InMap<L, N>>::new(chunk_id, map_id).apply(world);
        Withdraw::<InChunk<L, N>>::new(chunk_id).apply(world);
        Some(chunk_id)
    } else {
        None
    };

    world.entity_mut(map_id).insert(map);

    chunk_id
}

/// Remove the chunk from the map without despawning it and despawns the cells in the chunk.
pub fn take_chunk_despawn_cells<L, const N: usize>(
    world: &mut World,
    chunk_c: [isize; N],
) -> Option<Entity>
where
    L: CellMapLabel + Send + 'static,
{
    // Get the map or return
    let (map_id, mut map) = remove_map::<L, N>(world)?;

    // Get the old chunk or return
    let chunk_id = if let Some(mut chunk_e) = map
        .chunks
        .remove(&chunk_c.into())
        .and_then(|chunk_id| world.get_entity_mut(chunk_id))
    {
        let (chunk, _) = chunk_e.take::<(Chunk, ChunkCoord)>().unwrap();
        let chunk_id = chunk_e.id();
        for cell_id in chunk.cells.into_iter().flatten() {
            world.despawn(cell_id);
        }
        Unset::<InMap<L, N>>::new(chunk_id, map_id).apply(world);
        Withdraw::<InChunk<L, N>>::new(chunk_id).apply(world);
        Some(chunk_id)
    } else {
        None
    };

    world.entity_mut(map_id).insert(map);

    chunk_id
}

/// Inserts a list of entities into map and treats them as chunks
pub fn insert_chunk_batch<L, const N: usize>(
    world: &mut World,
    chunks: impl IntoIterator<Item = ([isize; N], Entity)>,
) where
    L: CellMapLabel + Send + 'static,
{
    // Remove the map, or spawn an entity to hold the map, then create an empty map
    let (map_id, mut map) = spawn_or_remove_map::<L, N>(world);

    // Get the chunks and entities from the map
    for (chunk_c, chunk_id) in chunks.into_iter() {
        // Despawn the chunk if it exists
        if let Some(chunk_id) = map.chunks.insert(chunk_c.into(), chunk_id) {
            CheckedDespawn(chunk_id).apply(world);
        }

        world.get_entity_mut(chunk_id).unwrap().insert((
            Chunk::new(L::CHUNK_SIZE.pow(N as u32)),
            ChunkCoord::from(chunk_c),
        ));
        Set::<InMap<L, N>>::new(chunk_id, map_id).apply(world);
        map.chunks.insert(chunk_c.into(), chunk_id);
    }

    world.get_entity_mut(map_id).unwrap().insert(map);
}

/// Removes the chunks from the cell map, returning the chunk coordinates removed and their corresponding entities.
/// # Note
/// This does not despawn or remove the cell entities, and reinsertion of this entity will not recreate the link to the chunk's cells.
/// If you wish to take the chunk and delete it's underlying cells, use (take_chunk_batch_despawn_cells)[`take_chunk_batch_despawn_cells`]
pub fn take_chunk_batch<L, const N: usize>(
    world: &mut World,
    chunks: impl IntoIterator<Item = [isize; N]>,
) -> Vec<([isize; N], Entity)>
where
    L: CellMapLabel + Send + 'static,
{
    // Remove the map, or return if it doesn't exist
    let (map_id, mut map) = if let Some(map_info) = remove_map::<L, N>(world) {
        map_info
    } else {
        return Vec::new();
    };

    let mut chunk_ids = Vec::new();

    for chunk_c in chunks.into_iter() {
        // Get the old chunk or return
        if let Some(mut chunk_e) = map
            .chunks
            .remove(&chunk_c.into())
            .and_then(|chunk_id| world.get_entity_mut(chunk_id))
        {
            chunk_e.remove::<(Chunk, ChunkCoord)>();
            let chunk_id = chunk_e.id();
            Unset::<InMap<L, N>>::new(chunk_id, map_id).apply(world);
            Withdraw::<InChunk<L, N>>::new(chunk_id).apply(world);
            chunk_ids.push((chunk_c, chunk_id));
        };
    }

    world.get_entity_mut(map_id).unwrap().insert(map);
    chunk_ids
}

/// Removes the chunks from the cell map, returning the chunk coordinates removed and their corresponding entities.
/// Also despawns all cells in all the removed chunks.
pub fn take_chunk_batch_despawn_cells<L, const N: usize>(
    world: &mut World,
    chunks: impl IntoIterator<Item = [isize; N]>,
) -> Vec<([isize; N], Entity)>
where
    L: CellMapLabel + Send + 'static,
{
    // Remove the map, or return if it doesn't exist
    let (map_id, mut map) = if let Some(map_info) = remove_map::<L, N>(world) {
        map_info
    } else {
        return Vec::new();
    };

    let mut chunk_ids = Vec::new();

    for chunk_c in chunks.into_iter() {
        // Get the old chunk or return
        if let Some(mut chunk_e) = map
            .chunks
            .remove(&chunk_c.into())
            .and_then(|chunk_id| world.get_entity_mut(chunk_id))
        {
            let (chunk, _) = chunk_e.take::<(Chunk, ChunkCoord)>().unwrap();
            let chunk_id = chunk_e.id();
            for cell_id in chunk.cells.into_iter().flatten() {
                world.despawn(cell_id);
            }
            Unset::<InMap<L, N>>::new(chunk_id, map_id).apply(world);
            Withdraw::<InChunk<L, N>>::new(chunk_id).apply(world);
            chunk_ids.push((chunk_c, chunk_id));
        };
    }

    world.get_entity_mut(map_id).unwrap().insert(map);
    chunk_ids
}

trait GroupBy: Iterator {
    fn group_by<F, K>(
        self,
        f: F,
    ) -> bevy::utils::hashbrown::hash_map::IntoIter<
        K,
        std::vec::Vec<<Self as std::iter::Iterator>::Item>,
    >
    where
        F: Fn(&Self::Item) -> K,
        K: Eq + Hash;
}

impl<T> GroupBy for T
where
    T: Iterator,
{
    fn group_by<F, K>(
        self,
        f: F,
    ) -> bevy::utils::hashbrown::hash_map::IntoIter<
        K,
        std::vec::Vec<<T as std::iter::Iterator>::Item>,
    >
    where
        F: Fn(&Self::Item) -> K,
        K: Eq + Hash,
    {
        let mut map = HashMap::new();
        for item in self {
            let key = f(&item);
            match map.entry(key) {
                Entry::Vacant(v) => {
                    v.insert(vec![item]);
                }
                Entry::Occupied(mut o) => o.get_mut().push(item),
            }
        }
        map.into_iter()
    }
}