summaryrefslogtreecommitdiff
path: root/src/sim/cell_manager/chunk.rs
blob: 3bf1e9fcb911f1f8368984eecef79fff171532ee (plain)
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
use fxhash::FxHashMap;
use glam::IVec2;

use crate::{
    config::{CELLS_IN_CHUNK, CHUNK_SIZE},
    content::materials::MaterialForm,
    sim::{cell::Cell, entity::EntityId, lib::marching_squares::Marchable},
};

pub struct Chunk {
    pub cells: Box<[Cell; CELLS_IN_CHUNK]>,
    pub cell_data: FxHashMap<usize, u16>,
    pub cell_entity: FxHashMap<usize, EntityId>,
    pub sleeping: bool,
    pub needs_texture_update: bool,
}

impl Chunk {
    #[inline]
    pub fn get_cell_at_local_position(&self, x: u8, y: u8) -> Cell {
        self.cells[x as usize + y as usize * CHUNK_SIZE as usize]
    }
    #[inline]
    pub fn set_cell_at_local_position(&mut self, x: u8, y: u8, cell: Cell) {
        self.cells[x as usize + y as usize * CHUNK_SIZE as usize] = cell;
    }

    #[inline]
    pub fn get_data_at_local_position(&self, x: u8, y: u8) -> Option<u16> {
        self.cell_data
            .get(&(x as usize + y as usize * CHUNK_SIZE as usize))
            .copied()
    }
    #[inline]
    pub fn set_data_at_local_position(&mut self, x: u8, y: u8, data: u16) {
        self.cell_data
            .insert(x as usize + y as usize * CHUNK_SIZE as usize, data);
    }

    #[inline]
    pub fn get_entity_at_local_position(&self, x: u8, y: u8) -> Option<EntityId> {
        self.cell_entity
            .get(&(x as usize + y as usize * CHUNK_SIZE as usize))
            .copied()
    }
    #[inline]
    pub fn set_entity_at_local_position(&mut self, x: u8, y: u8, entity_id: EntityId) {
        self.cell_entity
            .insert(x as usize + y as usize * CHUNK_SIZE as usize, entity_id);
    }

    pub fn void() -> Self {
        Chunk {
            cells: Box::new([Cell::void(); CELLS_IN_CHUNK]),
            cell_data: FxHashMap::default(),
            cell_entity: FxHashMap::default(),
            sleeping: true,
            needs_texture_update: true,
        }
    }
}

impl Marchable for Chunk {
    fn occupied(&self, pos: IVec2) -> bool {
        if pos.x < 0 || pos.x >= CHUNK_SIZE || pos.y < 0 || pos.y >= CHUNK_SIZE {
            false
        } else {
            // we only build a path for solid cells or settled powder cells
            let cell = self.get_cell_at_local_position(pos.x as u8, pos.y as u8);
            cell.material.def().form == MaterialForm::Solid || cell.settled() > 4
        }
    }
    fn size(&self) -> IVec2 {
        IVec2::new(CHUNK_SIZE, CHUNK_SIZE)
    }
}