Skip to main content

re_core/
tileset.rs

1//! 3D tile support: a [`TileSet`] is a reusable modular kit (floor, wall,
2//! corner, ramp …); a [`TileMap`] paints cells of one tileset onto an XZ grid.
3//!
4//! Convention: cell `(x, z)` covers the square from `(x*cell_w, 0, z*cell_d)`
5//! to `((x+1)*cell_w, 0, (z+1)*cell_d)`. Tiles are authored however you like;
6//! `Tile::offset` is applied on top of the cell transform, so a mesh that was
7//! modelled around its own centre aligns by offsetting it half a cell.
8
9use crate::id::{MaterialId, MeshId, TileSetId};
10use crate::transform::Transform;
11use serde::{Deserialize, Serialize};
12
13/// One variant inside a tileset.
14#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
15pub struct Tile {
16    pub name: String,
17    pub mesh: MeshId,
18    /// Extra transform applied after the cell placement (alignment, rotation …).
19    #[serde(default)]
20    pub offset: Transform,
21    /// Material used by every cell of this tile (falls back to the mesh's own
22    /// material handling when `None`).
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub material: Option<MaterialId>,
25    /// Procedural motion for every cell of this tile (viewer draw time).
26    #[serde(default, skip_serializing_if = "crate::motion::Motion::is_none")]
27    pub motion: crate::motion::Motion,
28}
29
30/// Reusable collection of tiles sharing a grid metric.
31#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
32pub struct TileSet {
33    pub name: String,
34    /// Cell size: `[width in X, depth in Z]`, meters.
35    pub cell: [f32; 2],
36    pub tiles: Vec<Tile>,
37}
38
39impl TileSet {
40    pub fn new(name: impl Into<String>, cell_w: f32, cell_d: f32) -> Self {
41        Self {
42            name: name.into(),
43            cell: [cell_w, cell_d],
44            tiles: Vec::new(),
45        }
46    }
47
48    /// Transform that moves the origin to the corner of cell `(x, z)`.
49    pub fn cell_transform(&self, x: i32, z: i32) -> Transform {
50        Transform {
51            translation: [x as f32 * self.cell[0], 0.0, z as f32 * self.cell[1]],
52            ..Transform::default()
53        }
54    }
55}
56
57/// A single painted cell. `tile` indexes [`TileSet::tiles`].
58#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
59pub struct TileCell {
60    pub x: i32,
61    pub z: i32,
62    pub tile: u32,
63}
64
65/// Painted grid referencing a tileset. Later entries win; painting an
66/// existing cell overwrites it in place.
67#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
68pub struct TileMap {
69    pub name: String,
70    pub tileset: TileSetId,
71    pub cells: Vec<TileCell>,
72}
73
74impl TileMap {
75    pub fn new(name: impl Into<String>, tileset: TileSetId) -> Self {
76        Self {
77            name: name.into(),
78            tileset,
79            cells: Vec::new(),
80        }
81    }
82
83    pub fn get(&self, x: i32, z: i32) -> Option<u32> {
84        self.cells
85            .iter()
86            .rev()
87            .find(|c| c.x == x && c.z == z)
88            .map(|c| c.tile)
89    }
90
91    /// Paint (or overwrite) one cell.
92    pub fn set(&mut self, x: i32, z: i32, tile: u32) {
93        if let Some(c) = self.cells.iter_mut().find(|c| c.x == x && c.z == z) {
94            c.tile = tile;
95        } else {
96            self.cells.push(TileCell { x, z, tile });
97        }
98    }
99
100    /// Remove one cell; returns whether anything was there.
101    pub fn erase(&mut self, x: i32, z: i32) -> bool {
102        let n = self.cells.len();
103        self.cells.retain(|c| !(c.x == x && c.z == z));
104        self.cells.len() != n
105    }
106
107    pub fn clear(&mut self) -> usize {
108        let n = self.cells.len();
109        self.cells.clear();
110        n
111    }
112
113    /// Inclusive bounds `(min_x, min_z, max_x, max_z)` of painted cells.
114    pub fn bounds(&self) -> Option<(i32, i32, i32, i32)> {
115        let mut it = self.cells.iter();
116        let first = it.next()?;
117        let (mut x0, mut z0, mut x1, mut z1) = (first.x, first.z, first.x, first.z);
118        for c in it {
119            x0 = x0.min(c.x);
120            z0 = z0.min(c.z);
121            x1 = x1.max(c.x);
122            z1 = z1.max(c.z);
123        }
124        Some((x0, z0, x1, z1))
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn paint_overwrite_erase() {
134        let mut m = TileMap::new("map", TileSetId(0));
135        m.set(0, 0, 0);
136        m.set(2, 3, 1);
137        assert_eq!(m.get(2, 3), Some(1));
138        m.set(2, 3, 0); // overwrite in place
139        assert_eq!(m.cells.len(), 2);
140        assert_eq!(m.get(2, 3), Some(0));
141        assert!(m.erase(0, 0));
142        assert!(!m.erase(0, 0));
143        assert_eq!(m.bounds(), Some((2, 3, 2, 3)));
144    }
145
146    #[test]
147    fn cell_transform_steps_by_cell_size() {
148        let ts = TileSet::new("kit", 2.0, 0.5);
149        let t = ts.cell_transform(3, -2);
150        assert_eq!(t.translation, [6.0, 0.0, -1.0]);
151    }
152}