From a416d5d5f8511ac57aa4b71c8fe6a4cf8ba4b352 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Sat, 14 Sep 2019 18:57:32 -0600 Subject: [PATCH 1/6] Implement schematic struct to start on tree generation --- server/src/worldgen/mod.rs | 1 + server/src/worldgen/schematic.rs | 226 +++++++++++++++++++++++++++++++ 2 files changed, 227 insertions(+) create mode 100644 server/src/worldgen/schematic.rs diff --git a/server/src/worldgen/mod.rs b/server/src/worldgen/mod.rs index 169d3f561..a334288a0 100644 --- a/server/src/worldgen/mod.rs +++ b/server/src/worldgen/mod.rs @@ -10,6 +10,7 @@ mod composition; mod density_map; mod finishers; pub mod noise; +pub mod schematic; mod superflat; mod util; pub mod voronoi; diff --git a/server/src/worldgen/schematic.rs b/server/src/worldgen/schematic.rs new file mode 100644 index 000000000..f08ccef53 --- /dev/null +++ b/server/src/worldgen/schematic.rs @@ -0,0 +1,226 @@ +use feather_blocks::Block; +use feather_core::{Chunk, ChunkPosition}; + +/// A 3D schematic of some structure, such as a tree or building. +/// +/// Schematics are not resizable and have static dimensions. +/// +/// # Notes +/// * Positions in any parameter passed to a method here are +/// local to the schematic. (0, 0, 0) corresponds to the center +/// of the schematic, which is set in `new`. Negative indices +/// are allowed. +#[derive(Debug, Clone)] +pub struct Schematic { + /// 3D grid of blocks. Length of this vector + /// is always length * width * height. + blocks: Vec, + /// Length of this schematic (X axis). + length: usize, + /// Width of this schematic (Z axis). + width: usize, + /// Height of this schematic (Y axis). + height: usize, + /// Position of the center of this schematic. + center_x: usize, + center_y: usize, + center_z: usize, +} + +impl Schematic { + /// Creates a new, empty (all air) schematic with the given dimensions + /// and center offset. + pub fn new( + length: usize, + width: usize, + height: usize, + center_x: usize, + center_y: usize, + center_z: usize, + ) -> Self { + Self { + blocks: vec![Block::Air; length * width * height], + length, + width, + height, + center_x, + center_y, + center_z, + } + } + + /// Sets the block at the given location local to this schematic. + /// + /// Coordinates are relative to the center set in `new`. + pub fn set_block_at(&mut self, x: isize, y: isize, z: isize, block: Block) { + let index = self.index(x, y, z); + self.blocks[index] = block; + } + + /// Retrieves the block at the given location local to this schematic. + /// + /// Coordinates are relative to the center set in `new`. + pub fn block_at(&self, x: isize, y: isize, z: isize) -> Block { + let index = self.index(x, y, z); + self.blocks[index] + } + + /// Writes at least part of this schematic to the given chunk. + /// + /// The `x`, `y`, and `z` parameters are the absolute coordinates + /// of the center of this schematic. The schematic will then be projected + /// onto the chunk based on the chunk's position, writing the part + /// of the schematic that is inside the chunk. + /// + /// # Panics + /// Panics of either dimension of this schematic is greater + /// than the dimension of a chunk. (This may be implemented in the + /// future, but there is no need right now.) + pub fn write_to_chunk(&self, chunk: &mut Chunk, abs_x: isize, abs_y: isize, abs_z: isize) { + assert!(self.length <= 16); + assert!(self.width <= 16); + assert!(self.height <= 256); + + // This is a rather inefficient way of handling this. + // TODO: consider a faster algorithm by not checking + // for blocks we know are not within the chunk + + let length = self.length as isize; + let height = self.height as isize; + let width = self.width as isize; + + let center_x = self.center_x as isize; + let center_y = self.center_y as isize; + let center_z = self.center_z as isize; + + let min_x = -center_x; + let min_y = -center_y; + let min_z = -center_z; + + let max_x = length - center_x; + let max_y = height - center_y; + let max_z = width - center_z; + + // Go through each block in the schematic and find + // its coordinates local to the chunk. + for x in min_x..max_x { + for y in min_y..max_y { + for z in min_z..max_z { + // Compute absolute position of this block. + let ax = abs_x + x; + let ay = abs_y + y; + let az = abs_z + z; + + let block = self.block_at(x, y, z); + if block == Block::Air { + continue; // Don't set air blocks + } + + if ay < 0 || ay >= 256 { + continue; + } + + if let Some((chunk_x, chunk_z)) = coords_within_chunk(ax, az, chunk.position()) + { + chunk.set_block_at(chunk_x, ay as usize, chunk_z, block); + } + } + } + } + } + + fn index(&self, x: isize, y: isize, z: isize) -> usize { + let x = (x + self.center_x as isize) as usize; + let y = (y + self.center_y as isize) as usize; + let z = (z + self.center_z as isize) as usize; + + self.unoffsetted_index(x, y, z) + } + + fn unoffsetted_index(&self, x: usize, y: usize, z: usize) -> usize { + y * self.length * self.width + z * self.length + x + } +} + +fn coords_within_chunk(ax: isize, az: isize, chunk: ChunkPosition) -> Option<(usize, usize)> { + let ax = ax as i32; + let az = az as i32; + + if ax / 16 != chunk.x || az / 16 != chunk.z { + return None; // Not within chunk + } + + let mut offset_x = (ax - chunk.x * 16).abs(); + let mut offset_z = (az - chunk.z * 16).abs(); + + if ax < 0 { + offset_x = 15 - offset_x; + } + if az < 0 { + offset_z = 15 - offset_z; + } + + Some((offset_x as usize, offset_z as usize)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_set_and_get() { + let mut schem = Schematic::new(8, 8, 8, 4, 4, 4); + + schem.set_block_at(0, 0, 0, Block::Stone); + assert_eq!(schem.block_at(0, 0, 0), Block::Stone); + + schem.set_block_at(-4, -4, -4, Block::Sandstone); + assert_eq!(schem.block_at(-4, -4, -4), Block::Sandstone); + } + + #[test] + fn test_write_to_chunk() { + let mut schem = Schematic::new(8, 8, 8, 4, 4, 4); + + for x in -2..=2 { + for y in -2..=2 { + for z in -2..=2 { + schem.set_block_at(x, y, z, Block::Stone); + } + } + } + + let mut chunk = Chunk::new(ChunkPosition::new(1, 1)); + schem.write_to_chunk(&mut chunk, 0, 0, 0); + + // Nothing should have been written. + chunk + .sections() + .iter() + .for_each(|section| assert!(section.is_none())); + + // Now write... + schem.write_to_chunk(&mut chunk, 16, 16, 16); + + for x in 0..16 { + for y in 0..256 { + for z in 0..16 { + let block = if x < 3 && y >= 14 && y <= 18 && z < 3 { + Block::Stone + } else { + Block::Air + }; + + assert_eq!( + chunk.block_at(x, y, z), + block, + "failed at {} {} {}", + x, + y, + z + ); + } + } + } + } +} From 8ec312cb7c3ed7487eee3039951d10a585b202e1 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Sat, 14 Sep 2019 21:38:26 -0600 Subject: [PATCH 2/6] Implement oak tree schematic generator --- server/src/worldgen/finishers/clumped.rs | 4 +- server/src/worldgen/finishers/mod.rs | 1 + server/src/worldgen/finishers/single.rs | 4 +- server/src/worldgen/finishers/snow.rs | 4 +- server/src/worldgen/finishers/tree/mod.rs | 24 ++++++ .../src/worldgen/finishers/tree/schematic.rs | 84 +++++++++++++++++++ server/src/worldgen/finishers/tree/ty.rs | 74 ++++++++++++++++ server/src/worldgen/mod.rs | 2 +- server/src/worldgen/schematic.rs | 44 +++++++++- 9 files changed, 233 insertions(+), 8 deletions(-) create mode 100644 server/src/worldgen/finishers/tree/mod.rs create mode 100644 server/src/worldgen/finishers/tree/schematic.rs create mode 100644 server/src/worldgen/finishers/tree/ty.rs diff --git a/server/src/worldgen/finishers/clumped.rs b/server/src/worldgen/finishers/clumped.rs index 74e48a6c0..a6f14c461 100644 --- a/server/src/worldgen/finishers/clumped.rs +++ b/server/src/worldgen/finishers/clumped.rs @@ -1,5 +1,5 @@ use crate::worldgen::util::shuffle_seed_for_chunk; -use crate::worldgen::{ChunkBiomes, FinishingGenerator, TopBlocks}; +use crate::worldgen::{FinishingGenerator, NearbyBiomes, TopBlocks}; use feather_blocks::Block; use feather_core::{Biome, Chunk}; use rand::{Rng, SeedableRng}; @@ -14,7 +14,7 @@ impl FinishingGenerator for ClumpedFoliageFinisher { fn generate_for_chunk( &self, chunk: &mut Chunk, - biomes: &ChunkBiomes, + biomes: &NearbyBiomes, top_blocks: &TopBlocks, seed: u64, ) { diff --git a/server/src/worldgen/finishers/mod.rs b/server/src/worldgen/finishers/mod.rs index d9bfdb0c5..f09454a88 100644 --- a/server/src/worldgen/finishers/mod.rs +++ b/server/src/worldgen/finishers/mod.rs @@ -3,6 +3,7 @@ mod clumped; mod single; mod snow; +mod tree; pub use clumped::ClumpedFoliageFinisher; pub use single::SingleFoliageFinisher; diff --git a/server/src/worldgen/finishers/single.rs b/server/src/worldgen/finishers/single.rs index dc313c2c8..a5af1c3e8 100644 --- a/server/src/worldgen/finishers/single.rs +++ b/server/src/worldgen/finishers/single.rs @@ -1,5 +1,5 @@ use crate::worldgen::util::shuffle_seed_for_chunk; -use crate::worldgen::{ChunkBiomes, FinishingGenerator, TopBlocks}; +use crate::worldgen::{FinishingGenerator, NearbyBiomes, TopBlocks}; use feather_blocks::{Block, WaterData}; use feather_core::{Biome, Chunk}; use rand::{Rng, SeedableRng}; @@ -13,7 +13,7 @@ impl FinishingGenerator for SingleFoliageFinisher { fn generate_for_chunk( &self, chunk: &mut Chunk, - biomes: &ChunkBiomes, + biomes: &NearbyBiomes, top_blocks: &TopBlocks, seed: u64, ) { diff --git a/server/src/worldgen/finishers/snow.rs b/server/src/worldgen/finishers/snow.rs index aa0ff6f68..1c50402b7 100644 --- a/server/src/worldgen/finishers/snow.rs +++ b/server/src/worldgen/finishers/snow.rs @@ -1,4 +1,4 @@ -use crate::worldgen::{ChunkBiomes, FinishingGenerator, TopBlocks}; +use crate::worldgen::{FinishingGenerator, NearbyBiomes, TopBlocks}; use feather_blocks::{Block, SnowData}; use feather_core::{Biome, Chunk}; @@ -10,7 +10,7 @@ impl FinishingGenerator for SnowFinisher { fn generate_for_chunk( &self, chunk: &mut Chunk, - biomes: &ChunkBiomes, + biomes: &NearbyBiomes, top_blocks: &TopBlocks, _seed: u64, ) { diff --git a/server/src/worldgen/finishers/tree/mod.rs b/server/src/worldgen/finishers/tree/mod.rs new file mode 100644 index 000000000..328ea847b --- /dev/null +++ b/server/src/worldgen/finishers/tree/mod.rs @@ -0,0 +1,24 @@ +//! Tree generation. + +mod schematic; +mod ty; + +use crate::worldgen::{FinishingGenerator, NearbyBiomes, TopBlocks}; +use feather_core::Chunk; +pub use ty::TreeType; + +/// Finisher for generating trees, depending on biome. +#[derive(Default)] +pub struct TreeFinisher; + +impl FinishingGenerator for TreeFinisher { + fn generate_for_chunk( + &self, + chunk: &mut Chunk, + biomes: &NearbyBiomes, + top_blocks: &TopBlocks, + seed: u64, + ) { + unimplemented!() + } +} diff --git a/server/src/worldgen/finishers/tree/schematic.rs b/server/src/worldgen/finishers/tree/schematic.rs new file mode 100644 index 000000000..b10c344de --- /dev/null +++ b/server/src/worldgen/finishers/tree/schematic.rs @@ -0,0 +1,84 @@ +//! Generation of tree schematics. + +use super::TreeType; +use crate::worldgen::schematic::{Schematic, SchematicBuilder}; +use rand::{Rng, SeedableRng}; +use rand_xorshift::XorShiftRng; + +/// Generates a tree with the given type and seed. +pub fn generate_tree(ty: TreeType, seed: u64) -> Schematic { + let mut rng = XorShiftRng::seed_from_u64(seed); + match ty { + TreeType::Oak => generate_oak(&mut rng), + TreeType::DarkOak => generate_dark_oak(&mut rng), + TreeType::Birch => generate_birch(&mut rng), + TreeType::Spruce => generate_spruce(&mut rng), + TreeType::Acacia => generate_acacia(&mut rng), + TreeType::Jungle => generate_jungle(&mut rng), + } +} + +fn generate_oak(rng: &mut R) -> Schematic { + let ty = TreeType::Oak; + // TODO: tall oak variant + let mut tree = SchematicBuilder::new() + .with_dimensions(5, 7, 5) + .with_center(2, 0, 2) + .build(); + + // Logs + for y in 0..6 { + tree.set_block_at(0, y, 0, TreeType::Oak.log_block()); + } + + // Leaves + + // Bottom part (two 5x5 squares with random corners) + for x in -2isize..=2 { + for z in -2isize..=2 { + for y in 0..2 { + let y = y + 3; + + if x.abs() == 2 && z.abs() == 2 && rng.gen_bool(0.7) { + continue; // Variance in corner leaves + } + + tree.set_block_at(x, y, z, ty.leaf_block(manhattan(0, y, 0, x, y, z) as i32)); + } + } + } + // Top part + let positions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + for y in 5..=6 { + positions + .iter() + .for_each(|pos| tree.set_block_at(pos[0], y, pos[1], ty.leaf_block(1))); + } + tree.set_block_at(0, 6, 0, ty.leaf_block(1)); + + tree +} + +fn generate_dark_oak(_rng: &mut R) -> Schematic { + unimplemented!() +} + +fn generate_birch(_rng: &mut R) -> Schematic { + unimplemented!() +} + +fn generate_spruce(_rng: &mut R) -> Schematic { + unimplemented!() +} + +fn generate_acacia(_rng: &mut R) -> Schematic { + unimplemented!() +} + +fn generate_jungle(_rng: &mut R) -> Schematic { + unimplemented!() +} + +fn manhattan(x1: isize, y1: isize, z1: isize, x2: isize, y2: isize, z2: isize) -> isize { + (x2 - x1).abs() + (y2 - y1).abs() + (z2 - z1).abs() +} diff --git a/server/src/worldgen/finishers/tree/ty.rs b/server/src/worldgen/finishers/tree/ty.rs new file mode 100644 index 000000000..2d073a283 --- /dev/null +++ b/server/src/worldgen/finishers/tree/ty.rs @@ -0,0 +1,74 @@ +use feather_blocks::{ + AcaciaLeavesData, AcaciaLogAxis, AcaciaLogData, BirchLeavesData, BirchLogAxis, BirchLogData, + Block, DarkOakLeavesData, DarkOakLogAxis, DarkOakLogData, JungleLeavesData, JungleLogAxis, + JungleLogData, OakLeavesData, OakLogAxis, OakLogData, SpruceLeavesData, SpruceLogAxis, + SpruceLogData, +}; + +/// Type of a tree. +#[derive(Debug, Clone, Copy)] +pub enum TreeType { + Oak, + DarkOak, + Birch, + Spruce, + Acacia, + Jungle, +} + +impl TreeType { + /// Returns the block corresponding to a log of this tree. + pub fn log_block(self) -> Block { + match self { + TreeType::Oak => Block::OakLog(OakLogData { + axis: OakLogAxis::Y, + }), + TreeType::DarkOak => Block::DarkOakLog(DarkOakLogData { + axis: DarkOakLogAxis::Y, + }), + TreeType::Birch => Block::BirchLog(BirchLogData { + axis: BirchLogAxis::Y, + }), + TreeType::Spruce => Block::SpruceLog(SpruceLogData { + axis: SpruceLogAxis::Y, + }), + TreeType::Acacia => Block::AcaciaLog(AcaciaLogData { + axis: AcaciaLogAxis::Y, + }), + TreeType::Jungle => Block::JungleLog(JungleLogData { + axis: JungleLogAxis::Y, + }), + } + } + + /// Returns the block corresponding to a leaf of this tree, + /// at the given distance away from the nearest log. + pub fn leaf_block(self, distance: i32) -> Block { + match self { + TreeType::Oak => Block::OakLeaves(OakLeavesData { + distance, + persistent: true, + }), + TreeType::DarkOak => Block::DarkOakLeaves(DarkOakLeavesData { + distance, + persistent: true, + }), + TreeType::Birch => Block::BirchLeaves(BirchLeavesData { + distance, + persistent: true, + }), + TreeType::Spruce => Block::SpruceLeaves(SpruceLeavesData { + distance, + persistent: true, + }), + TreeType::Acacia => Block::AcaciaLeaves(AcaciaLeavesData { + distance, + persistent: true, + }), + TreeType::Jungle => Block::JungleLeaves(JungleLeavesData { + distance, + persistent: true, + }), + } + } +} diff --git a/server/src/worldgen/mod.rs b/server/src/worldgen/mod.rs index a334288a0..e33125e93 100644 --- a/server/src/worldgen/mod.rs +++ b/server/src/worldgen/mod.rs @@ -239,7 +239,7 @@ pub trait FinishingGenerator: Send + Sync { fn generate_for_chunk( &self, chunk: &mut Chunk, - biomes: &ChunkBiomes, + biomes: &NearbyBiomes, top_blocks: &TopBlocks, seed: u64, ); diff --git a/server/src/worldgen/schematic.rs b/server/src/worldgen/schematic.rs index f08ccef53..d4d03fb67 100644 --- a/server/src/worldgen/schematic.rs +++ b/server/src/worldgen/schematic.rs @@ -32,8 +32,8 @@ impl Schematic { /// and center offset. pub fn new( length: usize, - width: usize, height: usize, + width: usize, center_x: usize, center_y: usize, center_z: usize, @@ -163,6 +163,48 @@ fn coords_within_chunk(ax: isize, az: isize, chunk: ChunkPosition) -> Option<(us Some((offset_x as usize, offset_z as usize)) } +/// Builder construct for `Schematic`. +#[derive(Default)] +pub struct SchematicBuilder { + length: usize, + height: usize, + width: usize, + center_x: usize, + center_y: usize, + center_z: usize, +} + +impl SchematicBuilder { + pub fn new() -> Self { + Self::default() + } + + pub fn with_dimensions(mut self, length: usize, height: usize, width: usize) -> Self { + self.length = length; + self.height = height; + self.width = width; + self + } + + pub fn with_center(mut self, x: usize, y: usize, z: usize) -> Self { + self.center_x = x; + self.center_y = y; + self.center_z = z; + self + } + + pub fn build(self) -> Schematic { + Schematic::new( + self.length, + self.height, + self.width, + self.center_x, + self.center_y, + self.center_z, + ) + } +} + #[cfg(test)] mod tests { use super::*; From bacfeb7c9bb509b1721abe610d4eae01d8a283de Mon Sep 17 00:00:00 2001 From: caelunshun Date: Sat, 14 Sep 2019 23:16:53 -0600 Subject: [PATCH 3/6] Initial implementation: tree finisher --- server/src/worldgen/finishers/mod.rs | 1 + server/src/worldgen/finishers/tree/mod.rs | 148 +++++++++++++++++- .../src/worldgen/finishers/tree/schematic.rs | 2 +- server/src/worldgen/mod.rs | 17 +- server/src/worldgen/presence.rs | 93 +++++++++++ 5 files changed, 250 insertions(+), 11 deletions(-) create mode 100644 server/src/worldgen/presence.rs diff --git a/server/src/worldgen/finishers/mod.rs b/server/src/worldgen/finishers/mod.rs index f09454a88..1845dfc5b 100644 --- a/server/src/worldgen/finishers/mod.rs +++ b/server/src/worldgen/finishers/mod.rs @@ -8,3 +8,4 @@ mod tree; pub use clumped::ClumpedFoliageFinisher; pub use single::SingleFoliageFinisher; pub use snow::SnowFinisher; +pub use tree::TreeFinisher; diff --git a/server/src/worldgen/finishers/tree/mod.rs b/server/src/worldgen/finishers/tree/mod.rs index 328ea847b..c9a836acd 100644 --- a/server/src/worldgen/finishers/tree/mod.rs +++ b/server/src/worldgen/finishers/tree/mod.rs @@ -3,8 +3,15 @@ mod schematic; mod ty; +use crate::worldgen::presence::PresenceGrid; +use crate::worldgen::util::shuffle_seed_for_column; use crate::worldgen::{FinishingGenerator, NearbyBiomes, TopBlocks}; -use feather_core::Chunk; +use feather_core::{Biome, Chunk, ChunkPosition}; +use rand::distributions::{Distribution, WeightedIndex}; +use rand::{Rng, SeedableRng}; +use rand_xorshift::XorShiftRng; +use std::cmp; +use std::convert::TryFrom; pub use ty::TreeType; /// Finisher for generating trees, depending on biome. @@ -19,6 +26,143 @@ impl FinishingGenerator for TreeFinisher { top_blocks: &TopBlocks, seed: u64, ) { - unimplemented!() + // Presence grid for trees. + // We set values to `true` for + // any column in which a tree will be generated. + let mut tree_presences = PresenceGrid::new(); + + // Compute presence of trees for each column within this chunk + // and the 6 columns bordering it on each side. For columns with + // trees generated, do the following: + // * First, check if a tree is already generated within params.spread. + // If so, remove the tree. + // * Generate a tree schematic for the tree and apply it to the chunk. + for x in -6..16 + 6 { + for z in -6..16 + 6 { + let biome = biomes.biome_at(x, z); + let params = params_for_biome(biome); + + if compute_presence_for_column(chunk.position(), ¶ms, x, z, seed) { + if tree_presences.is_presence_within(x, z, params.spread) { + continue; + } + + tree_presences.set_presence_at(x, z, true); + + let column_seed = column_seed(seed, chunk.position(), x, z); + let mut rng = XorShiftRng::seed_from_u64(column_seed); + + // Choose tree type based on weights. + let possible_trees = params.possible_trees; + let index = possible_trees.weights.sample(&mut rng); + let tree = possible_trees.trees[index]; + + // Generate tree schematic and write it to the chunk. + let schematic = schematic::generate_tree(tree, seed); + let y = top_blocks.top_block_at( + cmp::min(15, usize::try_from(x).unwrap_or(0)), + cmp::min(15, usize::try_from(z).unwrap_or(0)), + ); // TODO + schematic.write_to_chunk( + chunk, + (chunk.position().x * 16) as isize + x, + y as isize, + (chunk.position().z * 16) as isize + z, + ); + } + } + } + } +} + +fn compute_presence_for_column( + center_chunk: ChunkPosition, + params: &TreeParams, + column_x: isize, + column_z: isize, + seed: u64, +) -> bool { + let seed = column_seed(seed, center_chunk, column_x, column_z); + let mut rng = XorShiftRng::seed_from_u64(seed); + + rng.gen_bool(params.frequency / 256.0) +} + +fn column_seed(seed: u64, center_chunk: ChunkPosition, column_x: isize, column_z: isize) -> u64 { + let chunk = ChunkPosition::new( + center_chunk.x + column_x as i32 / 16, + center_chunk.z + column_z as i32 / 16, + ); + + let mut local_x = column_x % 16; + let mut local_z = column_z % 16; + if column_x < 0 { + local_x = 16 - local_x; + } + if column_z < 0 { + local_z = 16 - column_z; + } + + shuffle_seed_for_column(seed, chunk, local_x as usize, local_z as usize) +} + +/// WeightedIndex for a biome's tree weights, with +/// the array of possible tree types corresponding +/// to samples from the weighted index. +#[derive(Debug)] +struct TreeWeights { + weights: WeightedIndex, + trees: &'static [TreeType], +} + +impl TreeWeights { + fn new(weights: &[f64], trees: &'static [TreeType]) -> Self { + Self { + weights: WeightedIndex::new(weights).unwrap(), + trees, + } + } +} + +/// Settings of a biome for tree generation. +#[derive(Debug)] +struct TreeParams { + /// Frequency of trees. Higher values mean more trees. + frequency: f64, + /// Minimum distance between two trees. + spread: u32, + /// Table of tree types possible for this biome + /// and their corresponding weights. The table + /// for each tree is in a `lazy_static` variable, + /// since initializing it requires an expensive + /// allocation. + possible_trees: &'static TreeWeights, +} + +lazy_static! { + static ref WEIGHTS_DEFAULT: TreeWeights = TreeWeights::new(&[1.0], &[TreeType::Oak]); + static ref WEIGHTS_FOREST: TreeWeights = TreeWeights::new(&[1.0], &[TreeType::Oak]); +} + +impl Default for TreeParams { + /// Tree parameters which generate zero trees. + fn default() -> Self { + Self { + frequency: 0.0, + spread: 0, + possible_trees: &WEIGHTS_DEFAULT, + } + } +} + +/// Returns the tree parameters for the given biome. +fn params_for_biome(biome: Biome) -> TreeParams { + match biome { + Biome::Forest | Biome::DarkForest => TreeParams { + frequency: 4.0, + spread: 4, + possible_trees: &WEIGHTS_FOREST, + }, + _ => TreeParams::default(), // TODO } } diff --git a/server/src/worldgen/finishers/tree/schematic.rs b/server/src/worldgen/finishers/tree/schematic.rs index b10c344de..7d364f800 100644 --- a/server/src/worldgen/finishers/tree/schematic.rs +++ b/server/src/worldgen/finishers/tree/schematic.rs @@ -6,7 +6,7 @@ use rand::{Rng, SeedableRng}; use rand_xorshift::XorShiftRng; /// Generates a tree with the given type and seed. -pub fn generate_tree(ty: TreeType, seed: u64) -> Schematic { +pub fn generate_tree(ty: TreeType, seed: u64) -> Schematic { let mut rng = XorShiftRng::seed_from_u64(seed); match ty { TreeType::Oak => generate_oak(&mut rng), diff --git a/server/src/worldgen/mod.rs b/server/src/worldgen/mod.rs index e33125e93..ce88c1242 100644 --- a/server/src/worldgen/mod.rs +++ b/server/src/worldgen/mod.rs @@ -9,13 +9,18 @@ mod biomes; mod composition; mod density_map; mod finishers; + +mod superflat; + pub mod noise; +pub mod presence; pub mod schematic; -mod superflat; mod util; pub mod voronoi; -use crate::worldgen::finishers::{ClumpedFoliageFinisher, SingleFoliageFinisher, SnowFinisher}; +use crate::worldgen::finishers::{ + ClumpedFoliageFinisher, SingleFoliageFinisher, SnowFinisher, TreeFinisher, +}; pub use biomes::{DistortedVoronoiBiomeGenerator, TwoLevelBiomeGenerator}; use bitvec::slice::BitSlice; use bitvec::vec::BitVec; @@ -107,6 +112,7 @@ impl ComposableGenerator { Box::new(SnowFinisher::default()), Box::new(SingleFoliageFinisher::default()), Box::new(ClumpedFoliageFinisher::default()), + Box::new(TreeFinisher::default()), ]; Self::new( TwoLevelBiomeGenerator::default(), @@ -171,12 +177,7 @@ impl WorldGenerator for ComposableGenerator { // Finishers. for finisher in &self.finishers { - finisher.generate_for_chunk( - &mut chunk, - &biomes.biomes[4], - &top_blocks, - seed_shuffler.gen(), - ); + finisher.generate_for_chunk(&mut chunk, &biomes, &top_blocks, seed_shuffler.gen()); } // TODO: correct lighting. diff --git a/server/src/worldgen/presence.rs b/server/src/worldgen/presence.rs new file mode 100644 index 000000000..4c822a084 --- /dev/null +++ b/server/src/worldgen/presence.rs @@ -0,0 +1,93 @@ +use bitvec::boxed::BitBox; + +/// A presence grid for a 3x3 area of chunks. +/// +/// "Presence" simply is used to describe whether +/// something exists at the given column; it is a boolean. +/// For example, the tree generator uses this to +/// indicate whether there is a tree stump at a given +/// column. +/// +/// Column positions are the same as `NearbyBiomes`. +#[derive(Debug, Clone)] +pub struct PresenceGrid { + /// Array of booleans with values set to `true` for + /// each coordinate presence has been set. + grid: BitBox, +} + +impl PresenceGrid { + /// Creates a new presence grid, with all values + /// initialized to `false`. + pub fn new() -> Self { + Self { + grid: bitbox!(0; 16 * 256 * 16 * 9), + } + } + + /// Retrieves whether there is presence in the given column, + /// relative to the center chunk. + pub fn is_presence_at(&self, x: isize, z: isize) -> bool { + let index = index(x, z); + + self.grid[index] + } + + /// Sets the presence value in the given column, + /// relative to the center chunk. + pub fn set_presence_at(&mut self, x: isize, z: isize, value: bool) { + let index = index(x, z); + + self.grid.set(index, value); + } + + /// Returns whether there is a presence value set to + /// `true` within the given distance. The distance function + /// is non-standard; it computes a square of length `distance * 2` + /// and checks for each column within this square. + pub fn is_presence_within(&self, x: isize, z: isize, distance: u32) -> bool { + let distance = distance as isize; + for offset_x in -distance..=distance { + for offset_z in -distance..=distance { + if offset_x == 0 && offset_z == 0 { + // Don't test the column itself. + continue; + } + + if self.is_presence_at(x + offset_x, z + offset_z) { + return true; + } + } + } + + false + } +} + +fn index(mut x: isize, mut z: isize) -> usize { + // Account for negatives + x += 16; + z += 16; + + (z * 16 * 3 + x) as usize +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_presence_grid() { + let mut grid = PresenceGrid::new(); + + assert!(!grid.is_presence_at(0, 0)); + grid.set_presence_at(0, 0, true); + assert!(grid.is_presence_at(0, 0)); + + grid.set_presence_at(-16, -16, true); + assert!(grid.is_presence_at(-16, -16)); + + assert!(grid.is_presence_within(-10, -10, 6)); + assert!(!grid.is_presence_within(5, -5, 2)); + } +} From 87c8ad89ebecfd7dbdf57638a3a46b7468283337 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Sun, 15 Sep 2019 10:14:03 -0600 Subject: [PATCH 4/6] Fix tree schematic --- server/src/worldgen/finishers/tree/mod.rs | 2 +- server/src/worldgen/finishers/tree/schematic.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/server/src/worldgen/finishers/tree/mod.rs b/server/src/worldgen/finishers/tree/mod.rs index c9a836acd..c369f142d 100644 --- a/server/src/worldgen/finishers/tree/mod.rs +++ b/server/src/worldgen/finishers/tree/mod.rs @@ -66,7 +66,7 @@ impl FinishingGenerator for TreeFinisher { schematic.write_to_chunk( chunk, (chunk.position().x * 16) as isize + x, - y as isize, + y as isize + 1, (chunk.position().z * 16) as isize + z, ); } diff --git a/server/src/worldgen/finishers/tree/schematic.rs b/server/src/worldgen/finishers/tree/schematic.rs index 7d364f800..ab574e072 100644 --- a/server/src/worldgen/finishers/tree/schematic.rs +++ b/server/src/worldgen/finishers/tree/schematic.rs @@ -39,7 +39,7 @@ fn generate_oak(rng: &mut R) -> Schematic { for y in 0..2 { let y = y + 3; - if x.abs() == 2 && z.abs() == 2 && rng.gen_bool(0.7) { + if x.abs() == 2 && z.abs() == 2 && rng.gen_bool(0.3) || x == 0 && z == 0 { continue; // Variance in corner leaves } From ba55640323f12dd8bf92a0d5fa532061a2673544 Mon Sep 17 00:00:00 2001 From: caelunshun Date: Sun, 15 Sep 2019 11:33:50 -0600 Subject: [PATCH 5/6] Fix column_seed() --- server/src/worldgen/finishers/tree/mod.rs | 27 +++++++---------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/server/src/worldgen/finishers/tree/mod.rs b/server/src/worldgen/finishers/tree/mod.rs index c369f142d..02122c419 100644 --- a/server/src/worldgen/finishers/tree/mod.rs +++ b/server/src/worldgen/finishers/tree/mod.rs @@ -8,7 +8,7 @@ use crate::worldgen::util::shuffle_seed_for_column; use crate::worldgen::{FinishingGenerator, NearbyBiomes, TopBlocks}; use feather_core::{Biome, Chunk, ChunkPosition}; use rand::distributions::{Distribution, WeightedIndex}; -use rand::{Rng, SeedableRng}; +use rand::{Rng, RngCore, SeedableRng}; use rand_xorshift::XorShiftRng; use std::cmp; use std::convert::TryFrom; @@ -29,7 +29,7 @@ impl FinishingGenerator for TreeFinisher { // Presence grid for trees. // We set values to `true` for // any column in which a tree will be generated. - let mut tree_presences = PresenceGrid::new(); + //let mut tree_presences = PresenceGrid::new(); // Compute presence of trees for each column within this chunk // and the 6 columns bordering it on each side. For columns with @@ -43,11 +43,11 @@ impl FinishingGenerator for TreeFinisher { let params = params_for_biome(biome); if compute_presence_for_column(chunk.position(), ¶ms, x, z, seed) { - if tree_presences.is_presence_within(x, z, params.spread) { + /*if tree_presences.is_presence_within(x, z, params.spread) { continue; } - tree_presences.set_presence_at(x, z, true); + tree_presences.set_presence_at(x, z, true);*/ let column_seed = column_seed(seed, chunk.position(), x, z); let mut rng = XorShiftRng::seed_from_u64(column_seed); @@ -89,21 +89,10 @@ fn compute_presence_for_column( } fn column_seed(seed: u64, center_chunk: ChunkPosition, column_x: isize, column_z: isize) -> u64 { - let chunk = ChunkPosition::new( - center_chunk.x + column_x as i32 / 16, - center_chunk.z + column_z as i32 / 16, - ); - - let mut local_x = column_x % 16; - let mut local_z = column_z % 16; - if column_x < 0 { - local_x = 16 - local_x; - } - if column_z < 0 { - local_z = 16 - column_z; - } + let abs_x = center_chunk.x * 16 + column_x as i32; + let abs_z = center_chunk.z * 16 + column_z as i32; - shuffle_seed_for_column(seed, chunk, local_x as usize, local_z as usize) + seed.wrapping_mul(((abs_x as u64) << 32) | abs_z as u64) } /// WeightedIndex for a biome's tree weights, with @@ -160,7 +149,7 @@ fn params_for_biome(biome: Biome) -> TreeParams { match biome { Biome::Forest | Biome::DarkForest => TreeParams { frequency: 4.0, - spread: 4, + spread: 2, possible_trees: &WEIGHTS_FOREST, }, _ => TreeParams::default(), // TODO From 983c1dc00cee71dc4c0ae434af99200be5f8800c Mon Sep 17 00:00:00 2001 From: caelunshun Date: Sun, 15 Sep 2019 15:50:37 -0600 Subject: [PATCH 6/6] Prevent trees from spawning next to each other --- server/src/worldgen/finishers/tree/mod.rs | 6 +++--- server/src/worldgen/presence.rs | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/server/src/worldgen/finishers/tree/mod.rs b/server/src/worldgen/finishers/tree/mod.rs index 02122c419..4b6b7e76e 100644 --- a/server/src/worldgen/finishers/tree/mod.rs +++ b/server/src/worldgen/finishers/tree/mod.rs @@ -29,7 +29,7 @@ impl FinishingGenerator for TreeFinisher { // Presence grid for trees. // We set values to `true` for // any column in which a tree will be generated. - //let mut tree_presences = PresenceGrid::new(); + let mut tree_presences = PresenceGrid::new(); // Compute presence of trees for each column within this chunk // and the 6 columns bordering it on each side. For columns with @@ -43,11 +43,11 @@ impl FinishingGenerator for TreeFinisher { let params = params_for_biome(biome); if compute_presence_for_column(chunk.position(), ¶ms, x, z, seed) { - /*if tree_presences.is_presence_within(x, z, params.spread) { + if tree_presences.is_presence_within(x, z, params.spread) { continue; } - tree_presences.set_presence_at(x, z, true);*/ + tree_presences.set_presence_at(x, z, true); let column_seed = column_seed(seed, chunk.position(), x, z); let mut rng = XorShiftRng::seed_from_u64(column_seed); diff --git a/server/src/worldgen/presence.rs b/server/src/worldgen/presence.rs index 4c822a084..c0ffc05a1 100644 --- a/server/src/worldgen/presence.rs +++ b/server/src/worldgen/presence.rs @@ -1,4 +1,4 @@ -use bitvec::boxed::BitBox; +use bitvec::vec::BitVec; /// A presence grid for a 3x3 area of chunks. /// @@ -13,7 +13,7 @@ use bitvec::boxed::BitBox; pub struct PresenceGrid { /// Array of booleans with values set to `true` for /// each coordinate presence has been set. - grid: BitBox, + grid: BitVec, } impl PresenceGrid { @@ -21,7 +21,7 @@ impl PresenceGrid { /// initialized to `false`. pub fn new() -> Self { Self { - grid: bitbox!(0; 16 * 256 * 16 * 9), + grid: BitVec::from_vec(vec![0u8; 16 * 16 * 9]), } }