1
0
Fork 0

Finish refactoring of map builders

This commit is contained in:
Timothy Warren 2021-12-15 11:36:17 -05:00
parent 71a07b301c
commit fc0843847e
5 changed files with 131 additions and 291 deletions

View File

@ -1,7 +1,7 @@
unstable_features = true
format_code_in_doc_comments = true
format_macro_matchers = true
format_strings = true
format_strings = false
imports_granularity = "Module"
group_imports = "StdExternalCrate"
use_field_init_shorthand = true

View File

@ -150,29 +150,18 @@ pub trait MetaMapBuilder {
fn build_map(&mut self, rng: &mut RandomNumberGenerator, build_data: &mut BuilderMap);
}
pub trait MapBuilder {
fn get_map(&self) -> Map;
fn get_starting_position(&self) -> Position;
fn get_snapshot_history(&self) -> Vec<Map>;
fn build_map(&mut self);
fn take_snapshot(&mut self);
fn get_spawn_list(&self) -> &Vec<(usize, String)>;
fn spawn_entities(&mut self, ecs: &mut World) {
for entity in self.get_spawn_list().iter() {
spawner::spawn_entity(ecs, &(&entity.0, &entity.1));
}
}
}
pub fn random_builder(new_depth: i32, rng: &mut RandomNumberGenerator) -> BuilderChain {
let mut builder = BuilderChain::new(new_depth);
builder
.start_with(VoronoiCellBuilder::pythagoras())
.with(WaveformCollapseBuilder::new())
.with(PrefabBuilder::vaults())
.with(AreaStartingPosition::new(XStart::Center, YStart::Center))
.with(CullUnreachable::new())
.with(VoronoiSpawning::new())
.with(PrefabBuilder::sectional(
prefab_builder::prefab_sections::UNDERGROUND_FORT,
))
.with(DistantExit::new());
builder

View File

@ -41,68 +41,6 @@ pub fn apply_vertical_tunnel(map: &mut Map, y1: i32, y2: i32, x: i32) {
}
}
/// Searches a map, removes unreachable areas and returns the most distant tile.
pub fn remove_unreachable_areas_returning_most_distant(map: &mut Map, start_idx: usize) -> usize {
map.populate_blocked();
let map_starts: Vec<usize> = vec![start_idx];
let dijkstra_map = rltk::DijkstraMap::new(
map.width as usize,
map.height as usize,
&map_starts,
map,
200.0,
);
let mut exit_tile = (0, 0.0f32);
for (i, tile) in map.tiles.iter_mut().enumerate() {
if *tile == TileType::Floor {
let distance_to_start = dijkstra_map.map[i];
// We can't get to this tile - so we'll make it a wall
if distance_to_start == std::f32::MAX {
*tile = TileType::Wall;
} else {
// If it is further away than our current exit candidate, move the exit
if distance_to_start > exit_tile.1 {
exit_tile.0 = i;
exit_tile.1 = distance_to_start;
}
}
}
}
exit_tile.0
}
/// Generates a Voronoi/cellular noise map of a region, and divides it into spawn regions.
#[allow(clippy::map_entry)]
pub fn generate_voronoi_spawn_regions(
map: &Map,
rng: &mut rltk::RandomNumberGenerator,
) -> HashMap<i32, Vec<usize>> {
let mut noise_areas: HashMap<i32, Vec<usize>> = HashMap::new();
let mut noise = rltk::FastNoise::seeded(rng.roll_dice(1, 65536) as u64);
noise.set_noise_type(rltk::NoiseType::Cellular);
noise.set_frequency(0.08);
noise.set_cellular_distance_function(rltk::CellularDistanceFunction::Manhattan);
for y in 1..map.height - 1 {
for x in 1..map.width - 1 {
let idx = map.xy_idx(x, y);
if map.tiles[idx] == TileType::Floor {
let cell_value_f = noise.get_noise(x as f32, y as f32) * 10240.0;
let cell_value = cell_value_f as i32;
if noise_areas.contains_key(&cell_value) {
noise_areas.get_mut(&cell_value).unwrap().push(idx);
} else {
noise_areas.insert(cell_value, vec![idx]);
}
}
}
}
noise_areas
}
pub fn draw_corridor(map: &mut Map, x1: i32, y1: i32, x2: i32, y2: i32) {
let mut x = x1;
let mut y = y1;

View File

@ -6,7 +6,7 @@ use std::collections::HashSet;
use rltk::RandomNumberGenerator;
use super::{remove_unreachable_areas_returning_most_distant, MapBuilder};
use crate::map_builders::{BuilderMap, InitialMapBuilder, MetaMapBuilder};
use crate::{Map, Position, TileType, SHOW_MAPGEN_VISUALIZER};
#[derive(PartialEq, Copy, Clone)]
@ -26,200 +26,102 @@ pub enum PrefabMode {
#[allow(dead_code)]
pub struct PrefabBuilder {
map: Map,
starting_position: Position,
depth: i32,
history: Vec<Map>,
mode: PrefabMode,
previous_builder: Option<Box<dyn MapBuilder>>,
spawn_list: Vec<(usize, String)>,
}
impl MapBuilder for PrefabBuilder {
fn get_map(&self) -> Map {
self.map.clone()
impl MetaMapBuilder for PrefabBuilder {
fn build_map(&mut self, rng: &mut RandomNumberGenerator, build_data: &mut BuilderMap) {
self.build(rng, build_data);
}
}
fn get_starting_position(&self) -> Position {
self.starting_position
}
fn get_snapshot_history(&self) -> Vec<Map> {
self.history.clone()
}
fn build_map(&mut self) {
self.build();
}
fn take_snapshot(&mut self) {
if SHOW_MAPGEN_VISUALIZER {
let mut snapshot = self.map.clone();
for v in snapshot.revealed_tiles.iter_mut() {
*v = true;
}
self.history.push(snapshot);
}
}
fn get_spawn_list(&self) -> &Vec<(usize, String)> {
&self.spawn_list
impl InitialMapBuilder for PrefabBuilder {
fn build_map(&mut self, rng: &mut RandomNumberGenerator, build_data: &mut BuilderMap) {
self.build(rng, build_data);
}
}
impl PrefabBuilder {
#[allow(dead_code)]
pub fn new(new_depth: i32, previous_builder: Option<Box<dyn MapBuilder>>) -> PrefabBuilder {
PrefabBuilder {
map: Map::new(new_depth),
starting_position: Position { x: 0, y: 0 },
depth: new_depth,
history: Vec::new(),
pub fn new() -> Box<PrefabBuilder> {
Box::new(PrefabBuilder {
mode: PrefabMode::RoomVaults,
previous_builder,
spawn_list: Vec::new(),
}
})
}
#[allow(dead_code)]
pub fn rex_level(new_depth: i32, template: &'static str) -> PrefabBuilder {
PrefabBuilder {
map: Map::new(new_depth),
starting_position: Position { x: 0, y: 0 },
depth: new_depth,
history: Vec::new(),
pub fn rex_level(template: &'static str) -> Box<PrefabBuilder> {
Box::new(PrefabBuilder {
mode: PrefabMode::RexLevel { template },
previous_builder: None,
spawn_list: Vec::new(),
}
})
}
#[allow(dead_code)]
pub fn constant(new_depth: i32, level: prefab_levels::PrefabLevel) -> PrefabBuilder {
PrefabBuilder {
map: Map::new(new_depth),
starting_position: Position { x: 0, y: 0 },
depth: new_depth,
history: Vec::new(),
pub fn constant(level: prefab_levels::PrefabLevel) -> Box<PrefabBuilder> {
Box::new(PrefabBuilder {
mode: PrefabMode::Constant { level },
previous_builder: None,
spawn_list: Vec::new(),
}
})
}
#[allow(dead_code)]
pub fn sectional(
new_depth: i32,
section: prefab_sections::PrefabSection,
previous_builder: Box<dyn MapBuilder>,
) -> PrefabBuilder {
PrefabBuilder {
map: Map::new(new_depth),
starting_position: Position { x: 0, y: 0 },
depth: new_depth,
history: Vec::new(),
pub fn sectional(section: prefab_sections::PrefabSection) -> Box<PrefabBuilder> {
Box::new(PrefabBuilder {
mode: PrefabMode::Sectional { section },
previous_builder: Some(previous_builder),
spawn_list: Vec::new(),
}
})
}
#[allow(dead_code)]
pub fn vaults(new_depth: i32, previous_builder: Box<dyn MapBuilder>) -> PrefabBuilder {
PrefabBuilder {
map: Map::new(new_depth),
starting_position: Position { x: 0, y: 0 },
depth: new_depth,
history: Vec::new(),
pub fn vaults() -> Box<PrefabBuilder> {
Box::new(PrefabBuilder {
mode: PrefabMode::RoomVaults,
previous_builder: Some(previous_builder),
spawn_list: Vec::new(),
}
})
}
fn build(&mut self) {
fn build(&mut self, rng: &mut RandomNumberGenerator, build_data: &mut BuilderMap) {
match self.mode {
PrefabMode::RexLevel { template } => self.load_rex_map(template),
PrefabMode::Constant { level } => self.load_ascii_map(&level),
PrefabMode::Sectional { section } => self.apply_sectional(&section),
PrefabMode::RoomVaults => self.apply_room_vaults(),
}
self.take_snapshot();
// Find a starting point; start at the middle and walk left until we find an open tile
let mut start_idx;
if self.starting_position.x == 0 {
self.starting_position = Position {
x: self.map.width / 2,
y: self.map.height / 2,
};
start_idx = self
.map
.xy_idx(self.starting_position.x, self.starting_position.y);
while self.map.tiles[start_idx] != TileType::Floor {
self.starting_position.x -= 1;
start_idx = self
.map
.xy_idx(self.starting_position.x, self.starting_position.y);
}
self.take_snapshot();
}
let mut has_exit = false;
for t in self.map.tiles.iter() {
if *t == TileType::DownStairs {
has_exit = true;
}
}
if !has_exit {
start_idx = self
.map
.xy_idx(self.starting_position.x, self.starting_position.y);
// Find all tiles we can reach from the starting point
let exit_tile =
remove_unreachable_areas_returning_most_distant(&mut self.map, start_idx);
self.take_snapshot();
// Place the stairs
self.map.tiles[exit_tile] = TileType::DownStairs;
self.take_snapshot();
PrefabMode::RexLevel { template } => self.load_rex_map(template, build_data),
PrefabMode::Constant { level } => self.load_ascii_map(&level, build_data),
PrefabMode::Sectional { section } => self.apply_sectional(&section, rng, build_data),
PrefabMode::RoomVaults => self.apply_room_vaults(rng, build_data),
}
build_data.take_snapshot();
}
fn char_to_map(&mut self, ch: char, idx: usize) {
fn char_to_map(&mut self, ch: char, idx: usize, build_data: &mut BuilderMap) {
match ch {
' ' => self.map.tiles[idx] = TileType::Floor,
'#' => self.map.tiles[idx] = TileType::Wall,
' ' => build_data.map.tiles[idx] = TileType::Floor,
'#' => build_data.map.tiles[idx] = TileType::Wall,
'@' => {
let x = idx as i32 % self.map.width;
let y = idx as i32 / self.map.width;
self.map.tiles[idx] = TileType::Floor;
self.starting_position = Position {
let x = idx as i32 % build_data.map.width;
let y = idx as i32 / build_data.map.width;
build_data.map.tiles[idx] = TileType::Floor;
build_data.starting_position = Some(Position {
x: x as i32,
y: y as i32,
};
});
}
'>' => self.map.tiles[idx] = TileType::DownStairs,
'>' => build_data.map.tiles[idx] = TileType::DownStairs,
'g' => {
self.map.tiles[idx] = TileType::Floor;
self.spawn_list.push((idx, "Goblin".to_string()));
build_data.map.tiles[idx] = TileType::Floor;
build_data.spawn_list.push((idx, "Goblin".to_string()));
}
'o' => {
self.map.tiles[idx] = TileType::Floor;
self.spawn_list.push((idx, "Orc".to_string()));
build_data.map.tiles[idx] = TileType::Floor;
build_data.spawn_list.push((idx, "Orc".to_string()));
}
'^' => {
self.map.tiles[idx] = TileType::Floor;
self.spawn_list.push((idx, "Bear Trap".to_string()));
build_data.map.tiles[idx] = TileType::Floor;
build_data.spawn_list.push((idx, "Bear Trap".to_string()));
}
'%' => {
self.map.tiles[idx] = TileType::Floor;
self.spawn_list.push((idx, "Rations".to_string()));
build_data.map.tiles[idx] = TileType::Floor;
build_data.spawn_list.push((idx, "Rations".to_string()));
}
'!' => {
self.map.tiles[idx] = TileType::Floor;
self.spawn_list.push((idx, "Health Potion".to_string()));
build_data.map.tiles[idx] = TileType::Floor;
build_data
.spawn_list
.push((idx, "Health Potion".to_string()));
}
_ => {
rltk::console::log(format!("Unknown glyph loading map: {}", (ch as u8) as char));
@ -228,17 +130,17 @@ impl PrefabBuilder {
}
#[allow(dead_code)]
fn load_rex_map(&mut self, path: &str) {
fn load_rex_map(&mut self, path: &str, build_data: &mut BuilderMap) {
let xp_file = rltk::rex::XpFile::from_resource(path).unwrap();
for layer in &xp_file.layers {
for y in 0..layer.height {
for x in 0..layer.width {
let cell = layer.get(x, y).unwrap();
if x < self.map.width as usize && y < self.map.height as usize {
let idx = self.map.xy_idx(x as i32, y as i32);
if x < build_data.map.width as usize && y < build_data.map.height as usize {
let idx = build_data.map.xy_idx(x as i32, y as i32);
// We're doing some nasty casting to make it easier to type things like '#' in the match
self.char_to_map(cell.ch as u8 as char, idx);
self.char_to_map(cell.ch as u8 as char, idx, build_data);
}
}
}
@ -259,95 +161,102 @@ impl PrefabBuilder {
}
#[allow(dead_code)]
fn load_ascii_map(&mut self, level: &prefab_levels::PrefabLevel) {
let string_vec = PrefabBuilder::read_ascii_to_vec(level.template);
fn load_ascii_map(&mut self, level: &prefab_levels::PrefabLevel, build_data: &mut BuilderMap) {
let string_vec = Self::read_ascii_to_vec(level.template);
let mut i = 0;
for ty in 0..level.height {
for tx in 0..level.width {
if tx < self.map.width as usize && ty < self.map.height as usize {
let idx = self.map.xy_idx(tx as i32, ty as i32);
self.char_to_map(string_vec[i], idx);
if tx < build_data.map.width as usize && ty < build_data.map.height as usize {
let idx = build_data.map.xy_idx(tx as i32, ty as i32);
self.char_to_map(string_vec[i], idx, build_data);
}
i += 1;
}
}
}
fn apply_previous_iteration<F>(&mut self, mut filter: F)
where
F: FnMut(i32, i32, &(usize, String)) -> bool,
fn apply_previous_iteration<F>(
&mut self,
mut filter: F,
_rng: &mut RandomNumberGenerator,
build_data: &mut BuilderMap,
) where
F: FnMut(i32, i32) -> bool,
{
// Build the map
let prev_builder = self.previous_builder.as_mut().unwrap();
prev_builder.build_map();
self.starting_position = prev_builder.get_starting_position();
self.map = prev_builder.get_map();
self.history = prev_builder.get_snapshot_history();
for e in prev_builder.get_spawn_list().iter() {
let idx = e.0;
let x = idx as i32 % self.map.width;
let y = idx as i32 / self.map.width;
if filter(x, y, e) {
self.spawn_list.push((idx, e.1.to_string()))
}
}
self.take_snapshot();
let width = build_data.map.width;
build_data.spawn_list.retain(|(idx, _name)| {
let x = *idx as i32 % width;
let y = *idx as i32 / width;
filter(x, y)
});
build_data.take_snapshot();
}
#[allow(dead_code)]
fn apply_sectional(&mut self, section: &prefab_sections::PrefabSection) {
fn apply_sectional(
&mut self,
section: &prefab_sections::PrefabSection,
rng: &mut RandomNumberGenerator,
build_data: &mut BuilderMap,
) {
use prefab_sections::*;
let string_vec = PrefabBuilder::read_ascii_to_vec(section.template);
let string_vec = Self::read_ascii_to_vec(section.template);
// Place the new section
let chunk_x = match section.placement.0 {
HorizontalPlacement::Left => 0,
HorizontalPlacement::Center => (self.map.width / 2) - (section.width as i32 / 2),
HorizontalPlacement::Right => (self.map.width - 1) - section.width as i32,
HorizontalPlacement::Center => (build_data.map.width / 2) - (section.width as i32 / 2),
HorizontalPlacement::Right => (build_data.map.width - 1) - section.width as i32,
};
let chunk_y = match section.placement.1 {
VerticalPlacement::Top => 0,
VerticalPlacement::Center => (self.map.height / 2) - (section.height as i32 / 2),
VerticalPlacement::Bottom => (self.map.height - 1) - section.height as i32,
VerticalPlacement::Center => (build_data.map.height / 2) - (section.height as i32 / 2),
VerticalPlacement::Bottom => (build_data.map.height - 1) - section.height as i32,
};
// Build the map
self.apply_previous_iteration(|x, y, _e| {
x < chunk_x
|| x > (chunk_x + section.width as i32)
|| y < chunk_y
|| y > (chunk_y + section.height as i32)
});
self.apply_previous_iteration(
|x, y| {
x < chunk_x
|| x > (chunk_x + section.width as i32)
|| y < chunk_y
|| y > (chunk_y + section.height as i32)
},
rng,
build_data,
);
let mut i = 0;
for ty in 0..section.height {
for tx in 0..section.width {
if tx > 0
&& tx < self.map.width as usize - 1
&& ty < self.map.height as usize - 1
&& tx < build_data.map.width as usize - 1
&& ty < build_data.map.height as usize - 1
&& ty > 0
{
let idx = self.map.xy_idx(tx as i32 + chunk_x, ty as i32 + chunk_y);
self.char_to_map(string_vec[i], idx);
let idx = build_data
.map
.xy_idx(tx as i32 + chunk_x, ty as i32 + chunk_y);
self.char_to_map(string_vec[i], idx, build_data);
}
i += 1;
}
}
self.take_snapshot();
build_data.take_snapshot();
}
fn apply_room_vaults(&mut self) {
fn apply_room_vaults(&mut self, rng: &mut RandomNumberGenerator, build_data: &mut BuilderMap) {
use prefab_rooms::*;
let mut rng = RandomNumberGenerator::new();
// Apply the previous builder, and keep all entities it spawns (for now)
self.apply_previous_iteration(|_x, _y, _e| true);
self.apply_previous_iteration(|_x, _y| true, rng, build_data);
// Do we want a vault at all?
let vault_roll = rng.roll_dice(1, 6) + self.depth;
let vault_roll = rng.roll_dice(1, 6) + build_data.map.depth;
if vault_roll < 4 {
return;
}
@ -358,7 +267,9 @@ impl PrefabBuilder {
// Filter the vault list down to ones that are applicable to the current depth
let mut possible_vaults: Vec<&PrefabRoom> = master_vault_list
.iter()
.filter(|v| self.depth >= v.first_depth && self.depth <= v.last_depth)
.filter(|v| {
build_data.map.depth >= v.first_depth && build_data.map.depth <= v.last_depth
})
.collect();
// Bail out if there's nothing to build
@ -382,20 +293,20 @@ impl PrefabBuilder {
let mut idx = 0usize;
loop {
let x = (idx % self.map.width as usize) as i32;
let y = (idx / self.map.width as usize) as i32;
let x = (idx % build_data.map.width as usize) as i32;
let y = (idx / build_data.map.width as usize) as i32;
// Check that we won't overflow the map
if x > 1
&& (x + vault.width as i32) < self.map.width - 2
&& (x + vault.width as i32) < build_data.map.width - 2
&& y > 1
&& (y + vault.height as i32) < self.map.height - 2
&& (y + vault.height as i32) < build_data.map.height - 2
{
let mut possible = true;
for ty in 0..vault.height as i32 {
for tx in 0..vault.width as i32 {
let idx = self.map.xy_idx(tx + x, ty + y);
if self.map.tiles[idx] != TileType::Floor {
let idx = build_data.map.xy_idx(tx + x, ty + y);
if build_data.map.tiles[idx] != TileType::Floor {
possible = false;
}
if used_tiles.contains(&idx) {
@ -411,7 +322,7 @@ impl PrefabBuilder {
}
idx += 1;
if idx >= self.map.tiles.len() - 1 {
if idx >= build_data.map.tiles.len() - 1 {
break;
}
}
@ -427,9 +338,9 @@ impl PrefabBuilder {
let chunk_x = pos.x;
let chunk_y = pos.y;
let width = self.map.width; // The borrow checker really doesn't like it
let height = self.map.height; // when we access `self` inside the `retain`
self.spawn_list.retain(|e| {
let width = build_data.map.width; // The borrow checker really doesn't like it
let height = build_data.map.height; // when we access `self` inside the `retain`
build_data.spawn_list.retain(|e| {
let idx = e.0 as i32;
let x = idx % width;
let y = idx / height;
@ -439,17 +350,19 @@ impl PrefabBuilder {
|| y > chunk_y + vault.height as i32
});
let string_vec = PrefabBuilder::read_ascii_to_vec(vault.template);
let string_vec = Self::read_ascii_to_vec(vault.template);
let mut i = 0;
for ty in 0..vault.height {
for tx in 0..vault.width {
let idx = self.map.xy_idx(tx as i32 + chunk_x, ty as i32 + chunk_y);
self.char_to_map(string_vec[i], idx);
let idx = build_data
.map
.xy_idx(tx as i32 + chunk_x, ty as i32 + chunk_y);
self.char_to_map(string_vec[i], idx, build_data);
used_tiles.insert(idx);
i += 1;
}
}
self.take_snapshot();
build_data.take_snapshot();
possible_vaults.remove(vault_index);
}

View File

@ -39,9 +39,9 @@ pub const SILLY_SMILE: PrefabRoom = PrefabRoom {
const SILLY_SMILE_MAP: &str = "
^ ^
#
#
###
###
";