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
use super::*;
use crate::util::DHashSet;
use common::spiral::Spiral2d;
use std::ops::Range;

pub const TILE_SIZE: u32 = 6;
pub const ZONE_SIZE: u32 = 16;
pub const ZONE_RADIUS: u32 = 16;
pub const TILE_RADIUS: u32 = ZONE_SIZE * ZONE_RADIUS;
#[allow(dead_code)]
pub const MAX_BLOCK_RADIUS: u32 = TILE_SIZE * TILE_RADIUS;

pub struct TileGrid {
    pub(crate) bounds: Aabr<i32>, // Inclusive
    zones: Grid<Option<Grid<Option<Tile>>>>,
}

impl Default for TileGrid {
    fn default() -> Self {
        Self {
            bounds: Aabr::new_empty(Vec2::zero()),
            zones: Grid::populate_from(Vec2::broadcast(ZONE_RADIUS as i32 * 2 + 1), |_| None),
        }
    }
}

impl TileGrid {
    pub fn get_known(&self, tpos: Vec2<i32>) -> Option<&Tile> {
        let tpos = tpos + TILE_RADIUS as i32;
        self.zones
            .get(tpos.map(|e| e.div_euclid(ZONE_SIZE as i32)))
            .and_then(|zone| {
                zone.as_ref()?
                    .get(tpos.map(|e| e.rem_euclid(ZONE_SIZE as i32)))
            })
            .and_then(|tile| tile.as_ref())
    }

    pub fn get(&self, tpos: Vec2<i32>) -> &Tile {
        static EMPTY: Tile = Tile::empty();
        self.get_known(tpos).unwrap_or(&EMPTY)
    }

    // WILL NOT EXPAND BOUNDS!
    pub fn get_mut(&mut self, tpos: Vec2<i32>) -> Option<&mut Tile> {
        let tpos = tpos + TILE_RADIUS as i32;
        self.zones
            .get_mut(tpos.map(|e| e.div_euclid(ZONE_SIZE as i32)))
            .and_then(|zone| {
                zone.get_or_insert_with(|| {
                    Grid::populate_from(Vec2::broadcast(ZONE_SIZE as i32), |_| None)
                })
                .get_mut(tpos.map(|e| e.rem_euclid(ZONE_SIZE as i32)))
                .map(|tile| tile.get_or_insert_with(Tile::empty))
            })
    }

    pub fn set(&mut self, tpos: Vec2<i32>, tile: Tile) -> Option<Tile> {
        self.bounds.expand_to_contain_point(tpos);
        self.get_mut(tpos).map(|t| std::mem::replace(t, tile))
    }

    pub fn find_near<R>(
        &self,
        tpos: Vec2<i32>,
        mut f: impl FnMut(Vec2<i32>, &Tile) -> Option<R>,
    ) -> Option<(R, Vec2<i32>)> {
        const MAX_SEARCH_RADIUS_BLOCKS: u32 = 70;
        const MAX_SEARCH_CELLS: u32 = ((MAX_SEARCH_RADIUS_BLOCKS / TILE_SIZE) * 2 + 1).pow(2);
        Spiral2d::new()
            .take(MAX_SEARCH_CELLS as usize)
            .map(|r| tpos + r)
            .find_map(|tpos| f(tpos, self.get(tpos)).zip(Some(tpos)))
    }

    pub fn grow_aabr(
        &self,
        center: Vec2<i32>,
        area_range: Range<u32>,
        min_dims: Extent2<u32>,
    ) -> Result<Aabr<i32>, Aabr<i32>> {
        let mut aabr = Aabr {
            min: center,
            max: center + 1,
        };

        if !self.get(center).is_empty() {
            return Err(aabr);
        };

        let mut last_growth = 0;
        for i in 0..32 {
            if i - last_growth >= 4
                || aabr.size().product()
                    + if i % 2 == 0 {
                        aabr.size().h
                    } else {
                        aabr.size().w
                    }
                    > area_range.end as i32
            {
                break;
            } else {
                // `center.sum()` to avoid biasing certain directions
                match (i + center.sum().abs()) % 4 {
                    0 if (aabr.min.y..aabr.max.y + 1)
                        .all(|y| self.get(Vec2::new(aabr.max.x, y)).is_empty()) =>
                    {
                        aabr.max.x += 1;
                        last_growth = i;
                    },
                    1 if (aabr.min.x..aabr.max.x + 1)
                        .all(|x| self.get(Vec2::new(x, aabr.max.y)).is_empty()) =>
                    {
                        aabr.max.y += 1;
                        last_growth = i;
                    },
                    2 if (aabr.min.y..aabr.max.y + 1)
                        .all(|y| self.get(Vec2::new(aabr.min.x - 1, y)).is_empty()) =>
                    {
                        aabr.min.x -= 1;
                        last_growth = i;
                    },
                    3 if (aabr.min.x..aabr.max.x + 1)
                        .all(|x| self.get(Vec2::new(x, aabr.min.y - 1)).is_empty()) =>
                    {
                        aabr.min.y -= 1;
                        last_growth = i;
                    },
                    _ => {},
                }
            }
        }

        if aabr.size().product() as u32 >= area_range.start
            && aabr.size().w as u32 >= min_dims.w
            && aabr.size().h as u32 >= min_dims.h
        {
            Ok(aabr)
        } else {
            Err(aabr)
        }
    }

    #[allow(dead_code)]
    pub fn grow_organic(
        &self,
        rng: &mut impl Rng,
        center: Vec2<i32>,
        area_range: Range<u32>,
    ) -> Result<DHashSet<Vec2<i32>>, DHashSet<Vec2<i32>>> {
        let mut tiles = DHashSet::default();
        let mut open = Vec::new();

        tiles.insert(center);
        open.push(center);

        while tiles.len() < area_range.end as usize && !open.is_empty() {
            let tile = open.remove(rng.gen_range(0..open.len()));

            for &rpos in CARDINALS.iter() {
                let neighbor = tile + rpos;

                if self.get(neighbor).is_empty() && !tiles.contains(&neighbor) {
                    tiles.insert(neighbor);
                    open.push(neighbor);
                }
            }
        }

        if tiles.len() >= area_range.start as usize {
            Ok(tiles)
        } else {
            Err(tiles)
        }
    }
}

#[derive(Clone, PartialEq)]
pub enum TileKind {
    Empty,
    Hazard(HazardKind),
    Field,
    Plaza,
    Road { a: u16, b: u16, w: u16 },
    Path,
    Building,
    Castle,
    Wall(Dir),
    Tower(RoofKind),
    Keep(KeepKind),
    Gate,
    GnarlingFortification,
    Bridge,
    AdletStronghold,
    DwarvenMine,
}

use std::fmt;
impl fmt::Display for TileKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            TileKind::Empty => write!(f, "Empty"),
            TileKind::Hazard(_) => write!(f, "Hazard"),
            TileKind::Field => write!(f, "Field"),
            TileKind::Plaza => write!(f, "Plaza"),
            TileKind::Road { a: _, b: _, w: _ } => write!(f, "Road"),
            TileKind::Path => write!(f, "Path"),
            TileKind::Building => write!(f, "Building"),
            TileKind::Castle => write!(f, "Castle"),
            TileKind::Wall(_) => write!(f, "Wall"),
            TileKind::Tower(_) => write!(f, "Tower"),
            TileKind::Keep(_) => write!(f, "Keep"),
            TileKind::Gate => write!(f, "Gate"),
            TileKind::GnarlingFortification => write!(f, "GnarlingFortification"),
            TileKind::Bridge => write!(f, "Bridge"),
            TileKind::AdletStronghold => write!(f, "AdletStronghold"),
            TileKind::DwarvenMine => write!(f, "DwarvenMine"),
        }
    }
}

#[derive(Clone, PartialEq)]
pub struct Tile {
    pub kind: TileKind,
    pub plot: Option<Id<Plot>>,
    pub(crate) hard_alt: Option<i32>,
}

impl Tile {
    pub const fn empty() -> Self {
        Self {
            kind: TileKind::Empty,
            plot: None,
            hard_alt: None,
        }
    }

    /// Create a tile that is not associated with any plot.
    pub const fn free(kind: TileKind) -> Self {
        Self {
            kind,
            plot: None,
            hard_alt: None,
        }
    }

    pub fn is_empty(&self) -> bool { self.kind == TileKind::Empty }

    pub fn is_natural(&self) -> bool {
        matches!(
            self.kind,
            TileKind::Empty | TileKind::Hazard(_) | TileKind::AdletStronghold
        )
    }

    pub fn is_road(&self) -> bool {
        matches!(
            self.kind,
            TileKind::Plaza | TileKind::Road { .. } | TileKind::Path
        )
    }

    pub fn is_obstacle(&self) -> bool {
        matches!(self.kind, TileKind::Hazard(_)) || self.is_building()
    }

    pub fn is_building(&self) -> bool {
        matches!(
            self.kind,
            TileKind::Building | TileKind::Castle | TileKind::Wall(_)
        )
    }
}

#[derive(Copy, Clone, PartialEq)]
pub enum HazardKind {
    Water,
    Hill { gradient: f32 },
}

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum KeepKind {
    Middle,
    Corner,
    Wall(Dir),
}

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum RoofKind {
    Parapet,
    Pyramid,
}