use crate::error::{PcgError, PcgResult};
use crate::model::geometry::{GridPoint, GridSize};
use crate::model::room::RoomId;
use serde::{Deserialize, Serialize};
const MAX_GRID_CELLS: usize = 1_048_576;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Terrain {
pub room_id: RoomId,
pub grid_size: GridSize,
pub tiles: Grid2D<TileKind>,
pub reserved_zones: Vec<ReservedZone>,
pub connectivity_summary: ConnectivitySummary,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum TileKind {
Empty,
Floor,
Wall,
Obstacle,
Reserved,
Doorway,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Grid2D<T> {
pub width: u32,
pub height: u32,
pub data: Vec<T>,
}
impl<T: Clone> Grid2D<T> {
pub fn new(width: u32, height: u32, default_value: T) -> PcgResult<Self> {
let size = checked_grid_cells(width, height)?;
Ok(Self {
width,
height,
data: vec![default_value; size],
})
}
pub fn validate(&self) -> PcgResult<()> {
let size = checked_grid_cells(self.width, self.height)?;
if self.data.len() != size {
return Err(PcgError::terrain("Grid2D 数据长度与尺寸不一致"));
}
Ok(())
}
pub fn get(&self, x: i32, y: i32) -> Option<&T> {
if x < 0 || y < 0 {
return None;
}
let x = x as u32;
let y = y as u32;
if x >= self.width || y >= self.height {
return None;
}
let index = (y as usize)
.checked_mul(self.width as usize)?
.checked_add(x as usize)?;
self.data.get(index)
}
pub fn set(&mut self, x: i32, y: i32, value: T) -> bool {
if x < 0 || y < 0 {
return false;
}
let x = x as u32;
let y = y as u32;
if x >= self.width || y >= self.height {
return false;
}
let Some(index) = (y as usize)
.checked_mul(self.width as usize)
.and_then(|base| base.checked_add(x as usize))
else {
return false;
};
if index < self.data.len() {
self.data[index] = value;
true
} else {
false
}
}
}
fn checked_grid_cells(width: u32, height: u32) -> PcgResult<usize> {
if width == 0 || height == 0 {
return Err(PcgError::terrain("Grid2D 宽度和高度必须大于 0"));
}
let size = (width as usize)
.checked_mul(height as usize)
.ok_or_else(|| PcgError::terrain("Grid2D 尺寸乘法溢出"))?;
if size > MAX_GRID_CELLS {
return Err(PcgError::terrain(format!(
"Grid2D 尺寸过大: {}x{} = {},最大允许 {}",
width, height, size, MAX_GRID_CELLS
)));
}
Ok(size)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn grid_get_returns_none_when_index_calculation_overflows() {
let grid = Grid2D {
width: 65_536,
height: 65_537,
data: vec![TileKind::Floor],
};
assert_eq!(grid.get(0, 65_536), None);
}
#[test]
fn grid_set_returns_false_when_index_calculation_overflows() {
let mut grid = Grid2D {
width: 65_536,
height: 65_537,
data: vec![TileKind::Floor],
};
assert!(!grid.set(0, 65_536, TileKind::Wall));
assert_eq!(grid.data[0], TileKind::Floor);
}
#[test]
fn grid_new_rejects_excessive_size() {
let result = Grid2D::new(65_536, 65_536, TileKind::Wall);
assert!(result.is_err(), "异常尺寸不应 panic 或尝试巨量分配");
}
#[test]
fn grid_new_rejects_zero_dimensions() {
assert!(Grid2D::new(0, 1, TileKind::Wall).is_err());
assert!(Grid2D::new(1, 0, TileKind::Wall).is_err());
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ReservedZone {
pub id: String,
pub zone_type: String,
pub bounds: ReservedZoneBounds,
pub allow_items: bool,
pub allow_enemies: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ReservedZoneBounds {
Rect { min: GridPoint, max: GridPoint },
Circle { center: GridPoint, radius: u32 },
Polygon { points: Vec<GridPoint> },
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ConnectivitySummary {
pub all_doors_connected: bool,
pub walkable_tile_count: u32,
pub total_tile_count: u32,
pub connected_region_count: u32,
}