Compare commits
37 Commits
xpbd
...
asset-load
| Author | SHA1 | Date | |
|---|---|---|---|
| 3f174d4e2f | |||
| 601ede338f | |||
| ad39a93028 | |||
| 2e9f327c57 | |||
| f6e24f437a | |||
| deb778d6af | |||
| 370dc552b3 | |||
| f52b44d0dd | |||
| 898acc2822 | |||
| 0294ce6d24 | |||
| ba2dcf7129 | |||
| 8e92df8008 | |||
| 97f2497940 | |||
| e6e969f053 | |||
| 9a960bbec9 | |||
| fa0ae8509f | |||
| b175a2f1fd | |||
| 942f199f69 | |||
| 668bd13d1e | |||
| 7ff3638eff | |||
| 805f50e40f | |||
| daa2f0bcc9 | |||
| af65c0ba05 | |||
| 75da43c8f0 | |||
| 8cecad83c2 | |||
| 05f9fa3143 | |||
| c31c2fb908 | |||
| ee0b17f4b6 | |||
| f491739ee8 | |||
| d25d0de02d | |||
| 164283e152 | |||
| 70614be759 | |||
| 1a861f1a9a | |||
| dcf6fc5972 | |||
| 710eb80bf0 | |||
| bafdf016b9 | |||
| 7ca1fd33c5 |
8
.idea/.gitignore
generated
vendored
8
.idea/.gitignore
generated
vendored
@@ -1,8 +0,0 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
5
.idea/codeStyles/codeStyleConfig.xml
generated
5
.idea/codeStyles/codeStyleConfig.xml
generated
@@ -1,5 +0,0 @@
|
||||
<component name="ProjectCodeStyleConfiguration">
|
||||
<state>
|
||||
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
|
||||
</state>
|
||||
</component>
|
||||
8
.idea/modules.xml
generated
8
.idea/modules.xml
generated
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/phos-neo.iml" filepath="$PROJECT_DIR$/.idea/phos-neo.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
13
.idea/phos-neo.iml
generated
13
.idea/phos-neo.iml
generated
@@ -1,13 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="EMPTY_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/engine/world_generation/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/game/camera_system/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/game/main/src" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
6
.idea/vcs.xml
generated
6
.idea/vcs.xml
generated
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
2088
Cargo.lock
generated
2088
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -2,8 +2,10 @@
|
||||
resolver = "2"
|
||||
members = [
|
||||
"game/main",
|
||||
"game/buildings",
|
||||
"game/shared",
|
||||
"engine/world_generation",
|
||||
"engine/asset_loader"]
|
||||
"engine/asset_loader", "game/buildings", "game/shared"]
|
||||
|
||||
# Enable a small amount of optimization in debug mode
|
||||
[profile.dev]
|
||||
|
||||
@@ -6,6 +6,7 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
serde = "1.0.197"
|
||||
serde_json = "1.0.115"
|
||||
bevy = "0.13.2"
|
||||
serde = "1.0.204"
|
||||
serde_json = "1.0.120"
|
||||
bevy = "0.14.0"
|
||||
ron = "0.8.1"
|
||||
|
||||
@@ -6,63 +6,18 @@ pub mod macros {
|
||||
$plugin_name: ident,
|
||||
$loader_name: ident,
|
||||
$asset_type: ident,
|
||||
$asset_loadstate_name: ident,
|
||||
$extensions: expr,
|
||||
$($string_name: ident -> $handle_name: ident)* ;
|
||||
$($string_array_name: ident -> $handle_array_name: ident)* ?
|
||||
) => {
|
||||
use bevy::prelude::*;
|
||||
use bevy::asset::{AssetLoader, AssetEvent, LoadContext, AsyncReadExt, io::Reader};
|
||||
use bevy::asset::{AssetLoader, AssetEvent, AssetEvents, LoadContext, LoadState, AsyncReadExt, io::Reader};
|
||||
use bevy::utils::BoxedFuture;
|
||||
pub struct $plugin_name;
|
||||
impl Plugin for $plugin_name {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_asset::<$asset_type>()
|
||||
.init_asset_loader::<$loader_name>()
|
||||
.insert_resource($asset_loadstate_name::default())
|
||||
.add_systems(Update, finalize);
|
||||
}
|
||||
}
|
||||
|
||||
fn finalize(
|
||||
mut asset_events: EventReader<AssetEvent<$asset_type>>,
|
||||
mut assets: ResMut<Assets<$asset_type>>,
|
||||
mut load_state: ResMut<$asset_loadstate_name>,
|
||||
asset_server: Res<AssetServer>
|
||||
) {
|
||||
for event in asset_events.read() {
|
||||
match event {
|
||||
AssetEvent::Added { id } => load_state.added += 1,
|
||||
AssetEvent::LoadedWithDependencies { id } => {
|
||||
let asset = assets.get_mut(id.clone()).unwrap();
|
||||
|
||||
$(
|
||||
asset.$handle_name = asset_server.load(&asset.$string_name);
|
||||
)*
|
||||
$(
|
||||
for i in 0..asset.$string_array_name.len(){
|
||||
asset.$handle_array_name.push(asset_server.load(&asset.$string_array_name[i]));
|
||||
}
|
||||
)?
|
||||
load_state.loaded += 1;
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug, Default)]
|
||||
pub struct $asset_loadstate_name{
|
||||
pub loaded: u32,
|
||||
pub added: u32,
|
||||
}
|
||||
|
||||
impl $asset_loadstate_name{
|
||||
pub fn is_all_loaded(&self) -> bool{
|
||||
if self.added == 0{
|
||||
return false;
|
||||
}
|
||||
return self.loaded >= self.added;
|
||||
.init_asset_loader::<$loader_name>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,25 +31,33 @@ pub mod macros {
|
||||
|
||||
type Error = String;
|
||||
|
||||
fn load<'a>(
|
||||
async fn load<'a>(
|
||||
&'a self,
|
||||
reader: &'a mut Reader,
|
||||
reader: &'a mut Reader<'_>,
|
||||
_settings: &'a Self::Settings,
|
||||
_load_context: &'a mut LoadContext,
|
||||
) -> BoxedFuture<'a, Result<Self::Asset, Self::Error>> {
|
||||
return Box::pin(async move {
|
||||
let mut data: String = String::new();
|
||||
let read_result = reader.read_to_string(&mut data).await;
|
||||
if read_result.is_err() {
|
||||
return Err(read_result.err().unwrap().to_string());
|
||||
load_context: &'a mut LoadContext<'_>,
|
||||
) -> Result<Self::Asset, Self::Error> {
|
||||
let mut bytes = Vec::new();
|
||||
let read_result = reader.read_to_end(&mut bytes).await;
|
||||
if read_result.is_err() {
|
||||
return Err(read_result.err().unwrap().to_string());
|
||||
}
|
||||
let serialized: Result<Self::Asset, _> =
|
||||
ron::de::from_bytes::<Self::Asset>(&bytes);
|
||||
if serialized.is_err() {
|
||||
return Err(serialized.err().unwrap().to_string());
|
||||
}
|
||||
let mut asset = serialized.unwrap();
|
||||
$(
|
||||
|
||||
asset.$handle_name = load_context.load(&asset.$string_name);
|
||||
)*
|
||||
$(
|
||||
for i in 0..asset.$string_array_name.len(){
|
||||
asset.$handle_array_name.push(load_context.load(&asset.$string_array_name[i]));
|
||||
}
|
||||
let serialized: Result<Self::Asset, serde_json::Error> =
|
||||
serde_json::from_str(&data);
|
||||
if serialized.is_err() {
|
||||
return Err(serialized.err().unwrap().to_string());
|
||||
}
|
||||
return Ok(serialized.unwrap());
|
||||
});
|
||||
)?
|
||||
return Ok(asset);
|
||||
}
|
||||
|
||||
fn extensions(&self) -> &[&str] {
|
||||
|
||||
@@ -6,13 +6,18 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
bevy = "0.13.2"
|
||||
bevy = "0.14.0"
|
||||
noise = "0.9.0"
|
||||
serde = {version="1.0.197", features=["derive"]}
|
||||
serde = { version = "1.0.203", features = ["derive"] }
|
||||
serde_json = "1.0.115"
|
||||
asset_loader = {path = "../asset_loader"}
|
||||
asset_loader = { path = "../asset_loader" }
|
||||
rayon = "1.10.0"
|
||||
bevy-inspector-egui = "0.24.0"
|
||||
bevy-inspector-egui = "0.25.0"
|
||||
bevy_asset_loader = { version = "0.21.0", features = [
|
||||
"standard_dynamic_assets",
|
||||
"3d",
|
||||
] }
|
||||
ron = "0.8.1"
|
||||
|
||||
[features]
|
||||
tracing = ["bevy/trace_tracy"]
|
||||
33
engine/world_generation/src/biome_asset.rs
Normal file
33
engine/world_generation/src/biome_asset.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use asset_loader::create_asset_loader;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{prelude::NoiseConfig, tile_mapper::TileMapperAsset};
|
||||
|
||||
#[derive(Serialize, Deserialize, Asset, TypePath, Debug, Clone)]
|
||||
pub struct BiomeAsset {
|
||||
pub moisture: f32,
|
||||
pub temperature: f32,
|
||||
pub continentality: f32,
|
||||
pub name: String,
|
||||
#[serde(skip)]
|
||||
pub tile_mapper: Handle<TileMapperAsset>,
|
||||
pub tile_mapper_path: String,
|
||||
pub noise: NoiseConfig,
|
||||
}
|
||||
|
||||
impl BiomeAsset {
|
||||
pub fn distance(&self, data: Vec3) -> f32 {
|
||||
let a = Vec3::new(self.moisture, self.temperature, self.continentality);
|
||||
return (a - data).length();
|
||||
}
|
||||
}
|
||||
|
||||
create_asset_loader!(
|
||||
BiomeAssetPlugin,
|
||||
BiomeAssetLoader,
|
||||
BiomeAsset,
|
||||
&["biome", "biome.ron"],
|
||||
tile_mapper_path -> tile_mapper
|
||||
;
|
||||
?
|
||||
);
|
||||
@@ -1,34 +1,89 @@
|
||||
use asset_loader::create_asset_loader;
|
||||
use bevy::{
|
||||
asset::{Asset, Handle},
|
||||
reflect::TypePath,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use bevy::prelude::*;
|
||||
use bevy::render::render_resource::encase::rts_array::Length;
|
||||
|
||||
use crate::tile_mapper::TileMapperAsset;
|
||||
use crate::{biome_asset::BiomeAsset, map::biome_map::BiomeData};
|
||||
use bevy_asset_loader::prelude::*;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, TypePath, Asset)]
|
||||
#[derive(AssetCollection, Debug, Clone, Resource)]
|
||||
pub struct BiomePainterAsset {
|
||||
#[serde(skip)]
|
||||
pub biomes: Vec<Handle<TileMapperAsset>>,
|
||||
pub biomes_path: [String; 16],
|
||||
#[asset(key = "biomes", collection(typed))]
|
||||
pub biomes: Vec<Handle<BiomeAsset>>,
|
||||
}
|
||||
|
||||
impl BiomePainterAsset {
|
||||
pub fn sample_biome(&self, moisture: f32, temperature: f32) -> Handle<TileMapperAsset> {
|
||||
let x = (moisture.clamp(0., 1.) * 3.).ceil() as usize;
|
||||
let y = (temperature.clamp(0., 1.) * 3.).ceil() as usize;
|
||||
return self.biomes[x + y * 4].clone();
|
||||
pub fn sample_biome(&self, assets: &Assets<BiomeAsset>, data: &BiomeData) -> AssetId<BiomeAsset> {
|
||||
assert!(self.biomes.length() != 0, "There are no biomes");
|
||||
let mut biome = self.biomes.first().unwrap().id();
|
||||
let mut dist = f32::INFINITY;
|
||||
|
||||
for b in &self.biomes {
|
||||
let asset = assets.get(b.id()).unwrap();
|
||||
let d = asset.distance(data.into());
|
||||
if d < dist {
|
||||
biome = b.id();
|
||||
dist = d;
|
||||
}
|
||||
}
|
||||
|
||||
return biome;
|
||||
}
|
||||
|
||||
pub fn build(&self, assets: &Assets<BiomeAsset>) -> BiomePainter {
|
||||
let mut biomes = Vec::with_capacity(self.biomes.len());
|
||||
for b in &self.biomes {
|
||||
let asset = assets.get(b.id()).unwrap();
|
||||
biomes.push(asset.clone());
|
||||
}
|
||||
return BiomePainter { biomes };
|
||||
}
|
||||
}
|
||||
|
||||
create_asset_loader!(
|
||||
BiomePainterPlugin,
|
||||
BiomePainterLoader,
|
||||
BiomePainterAsset,
|
||||
BiomePainterLoadState,
|
||||
&["bimoes.json"],
|
||||
;
|
||||
biomes_path -> biomes
|
||||
?
|
||||
);
|
||||
#[derive(Resource)]
|
||||
pub struct BiomePainter {
|
||||
pub biomes: Vec<BiomeAsset>,
|
||||
}
|
||||
|
||||
impl BiomePainter {
|
||||
pub fn sample_biome(&self, data: &BiomeData) -> &BiomeAsset {
|
||||
assert!(self.biomes.length() != 0, "There are no biomes");
|
||||
let mut biome = &self.biomes[0];
|
||||
let mut dist = f32::INFINITY;
|
||||
|
||||
for b in &self.biomes {
|
||||
let d = b.distance(data.into());
|
||||
if d < dist {
|
||||
biome = b;
|
||||
dist = d;
|
||||
}
|
||||
}
|
||||
|
||||
return biome;
|
||||
}
|
||||
|
||||
pub fn sample_biome_index(&self, data: &BiomeData) -> usize {
|
||||
assert!(self.biomes.length() != 0, "There are no biomes");
|
||||
let mut biome = 0;
|
||||
let mut dist = f32::INFINITY;
|
||||
|
||||
for i in 0..self.biomes.len() {
|
||||
let d = self.biomes[i].distance(data.into());
|
||||
if d < dist {
|
||||
biome = i;
|
||||
dist = d;
|
||||
}
|
||||
}
|
||||
|
||||
return biome;
|
||||
}
|
||||
}
|
||||
|
||||
// create_asset_loader!(
|
||||
// BiomePainterPlugin,
|
||||
// BiomePainterLoader,
|
||||
// BiomePainterAsset,
|
||||
// BiomePainterLoadState,
|
||||
// &["bimoes.json"],
|
||||
// ;
|
||||
// biomes_path -> biomes
|
||||
// ?
|
||||
// );
|
||||
|
||||
34
engine/world_generation/src/consts.rs
Normal file
34
engine/world_generation/src/consts.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
use bevy::{
|
||||
prelude::*,
|
||||
render::{mesh::MeshVertexAttribute, render_resource::VertexFormat},
|
||||
};
|
||||
|
||||
use crate::hex_utils::{INNER_RADIUS, OUTER_RADIUS};
|
||||
|
||||
pub const TEX_MULTI: Vec2 = Vec2::new(1000., 1.);
|
||||
|
||||
pub const HEX_CORNERS: [Vec3; 6] = [
|
||||
Vec3::new(0., 0., OUTER_RADIUS),
|
||||
Vec3::new(INNER_RADIUS, 0., 0.5 * OUTER_RADIUS),
|
||||
Vec3::new(INNER_RADIUS, 0., -0.5 * OUTER_RADIUS),
|
||||
Vec3::new(0., 0., -OUTER_RADIUS),
|
||||
Vec3::new(-INNER_RADIUS, 0., -0.5 * OUTER_RADIUS),
|
||||
Vec3::new(-INNER_RADIUS, 0., 0.5 * OUTER_RADIUS),
|
||||
];
|
||||
|
||||
pub const HEX_NORMALS: [Vec3; 6] = [
|
||||
Vec3::new(INNER_RADIUS / 2., 0., (OUTER_RADIUS + 0.5 * OUTER_RADIUS) / 2.),
|
||||
Vec3::Z,
|
||||
Vec3::new(INNER_RADIUS / -2., 0., (OUTER_RADIUS + 0.5 * OUTER_RADIUS) / 2.),
|
||||
Vec3::new(INNER_RADIUS / -2., 0., (OUTER_RADIUS + 0.5 * OUTER_RADIUS) / -2.),
|
||||
Vec3::NEG_Z,
|
||||
Vec3::new(INNER_RADIUS / 2., 0., (OUTER_RADIUS + 0.5 * OUTER_RADIUS) / -2.),
|
||||
];
|
||||
|
||||
pub const ATTRIBUTE_PACKED_VERTEX_DATA: MeshVertexAttribute =
|
||||
MeshVertexAttribute::new("PackedVertexData", 988540817, VertexFormat::Uint32);
|
||||
pub const ATTRIBUTE_VERTEX_HEIGHT: MeshVertexAttribute =
|
||||
MeshVertexAttribute::new("VertexHeight", 988540717, VertexFormat::Float32);
|
||||
|
||||
pub const ATTRIBUTE_TEXTURE_INDEX: MeshVertexAttribute =
|
||||
MeshVertexAttribute::new("TextureIndex", 988540917, VertexFormat::Uint32);
|
||||
@@ -5,7 +5,7 @@ use bevy::prelude::*;
|
||||
|
||||
const CHUNK_TOTAL: usize = Chunk::SIZE * Chunk::SIZE;
|
||||
|
||||
pub fn generate_chunk_collider(chunk: &Chunk, map: &Map) -> (Vec<Vec3>, Vec<[u32; 3]>) {
|
||||
pub fn generate_chunk_collider(chunk: &MeshChunkData) -> (Vec<Vec3>, Vec<[u32; 3]>) {
|
||||
#[cfg(feature = "tracing")]
|
||||
let span = info_span!("generate_chunk_collider").entered();
|
||||
let vertex_count: usize = CHUNK_TOTAL * 6;
|
||||
@@ -14,9 +14,8 @@ pub fn generate_chunk_collider(chunk: &Chunk, map: &Map) -> (Vec<Vec3>, Vec<[u32
|
||||
for z in 0..Chunk::SIZE {
|
||||
for x in 0..Chunk::SIZE {
|
||||
let height = chunk.heights[x + z * Chunk::SIZE];
|
||||
let coord =
|
||||
HexCoord::from_offset(IVec2::new(x as i32, z as i32) + (chunk.chunk_offset * Chunk::SIZE as i32));
|
||||
let neighbors = map.get_neighbors(&coord);
|
||||
let coord = HexCoord::from_grid_pos(x, z);
|
||||
let neighbors = chunk.get_neighbors(&coord);
|
||||
let off_pos = Vec3::new(x as f32, height, z as f32);
|
||||
let tile_pos = offset3d_to_world(off_pos);
|
||||
create_tile_collider(tile_pos, &mut verts, &mut indices, &neighbors);
|
||||
@@ -25,7 +24,7 @@ pub fn generate_chunk_collider(chunk: &Chunk, map: &Map) -> (Vec<Vec3>, Vec<[u32
|
||||
return (verts, indices);
|
||||
}
|
||||
|
||||
fn create_tile_collider(pos: Vec3, verts: &mut Vec<Vec3>, indices: &mut Vec<[u32; 3]>, neighbors: &[Option<f32>; 6]) {
|
||||
fn create_tile_collider(pos: Vec3, verts: &mut Vec<Vec3>, indices: &mut Vec<[u32; 3]>, neighbors: &[f32; 6]) {
|
||||
let idx = verts.len() as u32;
|
||||
for i in 0..6 {
|
||||
let p = pos + HEX_CORNERS[i];
|
||||
@@ -39,20 +38,15 @@ fn create_tile_collider(pos: Vec3, verts: &mut Vec<Vec3>, indices: &mut Vec<[u32
|
||||
indices.push([idx + 2, idx + 3, idx + 4]);
|
||||
|
||||
for i in 0..neighbors.len() {
|
||||
let cur_n = neighbors[i];
|
||||
match cur_n {
|
||||
Some(n_height) => {
|
||||
if n_height < pos.y {
|
||||
create_tile_wall_collider(
|
||||
idx,
|
||||
Vec3::new(pos.x, n_height.min(pos.y - OUTER_RADIUS / 2.), pos.z),
|
||||
i,
|
||||
verts,
|
||||
indices,
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
let n_height = neighbors[i];
|
||||
if n_height < pos.y {
|
||||
create_tile_wall_collider(
|
||||
idx,
|
||||
Vec3::new(pos.x, n_height.min(pos.y - OUTER_RADIUS / 2.), pos.z),
|
||||
i,
|
||||
verts,
|
||||
indices,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
use crate::biome_painter::BiomePainterAsset;
|
||||
use crate::hex_utils::HexCoord;
|
||||
use crate::tile_manager::TileAsset;
|
||||
use crate::tile_mapper::TileMapperAsset;
|
||||
use crate::{hex_utils::offset3d_to_world, prelude::*};
|
||||
#[cfg(feature = "tracing")]
|
||||
use bevy::log::*;
|
||||
@@ -13,13 +10,7 @@ use bevy::{
|
||||
},
|
||||
};
|
||||
|
||||
pub fn generate_chunk_mesh(
|
||||
chunk: &Chunk,
|
||||
map: &Map,
|
||||
painter: &BiomePainterAsset,
|
||||
tiles: &Res<Assets<TileAsset>>,
|
||||
mappers: &Res<Assets<TileMapperAsset>>,
|
||||
) -> Mesh {
|
||||
pub fn generate_chunk_mesh(chunk: &MeshChunkData) -> Mesh {
|
||||
#[cfg(feature = "tracing")]
|
||||
let span = info_span!("generate_chunk_mesh").entered();
|
||||
|
||||
@@ -31,17 +22,12 @@ pub fn generate_chunk_mesh(
|
||||
|
||||
for z in 0..Chunk::SIZE {
|
||||
for x in 0..Chunk::SIZE {
|
||||
let height = chunk.heights[x + z * Chunk::SIZE];
|
||||
let moisture = chunk.moisture[x + z * Chunk::SIZE];
|
||||
let temperature = chunk.temperature[x + z * Chunk::SIZE];
|
||||
let idx = x + z * Chunk::SIZE;
|
||||
let height = chunk.heights[idx];
|
||||
let off_pos = Vec3::new(x as f32, height, z as f32);
|
||||
let tile_pos = offset3d_to_world(off_pos);
|
||||
let coord =
|
||||
HexCoord::from_offset(IVec2::new(x as i32, z as i32) + (chunk.chunk_offset * Chunk::SIZE as i32));
|
||||
let n = map.get_neighbors(&coord);
|
||||
let biome = mappers.get(painter.sample_biome(moisture, temperature));
|
||||
let tile_handle = biome.unwrap().sample_tile(height);
|
||||
let tile = tiles.get(tile_handle).unwrap();
|
||||
let coord = HexCoord::from_grid_pos(x, z);
|
||||
let n = chunk.get_neighbors(&coord);
|
||||
|
||||
create_tile(
|
||||
tile_pos,
|
||||
@@ -51,8 +37,8 @@ pub fn generate_chunk_mesh(
|
||||
&mut indices,
|
||||
&mut normals,
|
||||
// &mut tex,
|
||||
tile.texture_id,
|
||||
tile.side_texture_id,
|
||||
chunk.textures[idx][0],
|
||||
chunk.textures[idx][1],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -70,7 +56,7 @@ pub fn generate_chunk_mesh(
|
||||
|
||||
fn create_tile(
|
||||
pos: Vec3,
|
||||
neighbors: &[Option<f32>; 6],
|
||||
neighbors: &[f32; 6],
|
||||
verts: &mut Vec<Vec3>,
|
||||
uvs: &mut Vec<Vec2>,
|
||||
indices: &mut Vec<u32>,
|
||||
@@ -101,14 +87,9 @@ fn create_tile(
|
||||
indices.push(idx + 4);
|
||||
|
||||
for i in 0..neighbors.len() {
|
||||
let cur_n = neighbors[i];
|
||||
match cur_n {
|
||||
Some(n_height) => {
|
||||
if n_height < pos.y {
|
||||
create_tile_wall(pos, i, n_height, verts, uvs, indices, normals, side_tex_off);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
let n_height = neighbors[i];
|
||||
if n_height < pos.y {
|
||||
create_tile_wall(pos, i, n_height, verts, uvs, indices, normals, side_tex_off);
|
||||
}
|
||||
}
|
||||
}
|
||||
3
engine/world_generation/src/generators/mod.rs
Normal file
3
engine/world_generation/src/generators/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub mod chunk_colliders;
|
||||
pub mod mesh_generator;
|
||||
pub mod packed_mesh_generator;
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::biome_painter::BiomePainterAsset;
|
||||
use crate::hex_utils::HexCoord;
|
||||
use crate::prelude::*;
|
||||
use crate::tile_manager::TileAsset;
|
||||
use crate::tile_mapper::TileMapperAsset;
|
||||
use crate::{biome_asset::BiomeAsset, biome_painter::BiomePainterAsset};
|
||||
use bevy::{
|
||||
prelude::*,
|
||||
render::{
|
||||
@@ -16,6 +16,7 @@ pub fn generate_packed_chunk_mesh(
|
||||
map: &Map,
|
||||
painter: &BiomePainterAsset,
|
||||
tiles: &Res<Assets<TileAsset>>,
|
||||
biomes: &Res<Assets<BiomeAsset>>,
|
||||
mappers: &Res<Assets<TileMapperAsset>>,
|
||||
) -> Mesh {
|
||||
let vertex_count: usize = Chunk::SIZE * Chunk::SIZE * 6;
|
||||
@@ -26,13 +27,14 @@ pub fn generate_packed_chunk_mesh(
|
||||
for z in 0..Chunk::SIZE {
|
||||
for x in 0..Chunk::SIZE {
|
||||
let height = chunk.heights[x + z * Chunk::SIZE];
|
||||
let moisture = chunk.moisture[x + z * Chunk::SIZE];
|
||||
let temperature = chunk.temperature[x + z * Chunk::SIZE];
|
||||
let data = chunk.biome_data[x + z * Chunk::SIZE];
|
||||
let coord =
|
||||
HexCoord::from_offset(IVec2::new(x as i32, z as i32) + (chunk.chunk_offset * Chunk::SIZE as i32));
|
||||
let n = map.get_neighbors(&coord);
|
||||
let biome = mappers.get(painter.sample_biome(moisture, temperature));
|
||||
let tile_handle = biome.unwrap().sample_tile(height);
|
||||
let biome = biomes.get(painter.sample_biome(biomes, &data)).unwrap();
|
||||
|
||||
let mapper = mappers.get(biome.tile_mapper.id());
|
||||
let tile_handle = mapper.unwrap().sample_tile(height);
|
||||
let tile = tiles.get(tile_handle).unwrap();
|
||||
|
||||
create_packed_tile(
|
||||
@@ -1,18 +1,23 @@
|
||||
use bevy::math::IVec2;
|
||||
use bevy::math::{IVec2, UVec2};
|
||||
use bevy::prelude::{FloatExt, Vec2};
|
||||
use bevy::utils::default;
|
||||
use noise::{NoiseFn, SuperSimplex};
|
||||
use rayon::iter::{IntoParallelIterator, ParallelIterator};
|
||||
|
||||
use crate::biome_painter::BiomePainter;
|
||||
use crate::map::biome_map::{BiomeChunk, BiomeData, BiomeMap};
|
||||
use crate::prelude::*;
|
||||
|
||||
pub fn generate_heightmap(cfg: &GenerationConfig, seed: u32) -> Map {
|
||||
pub fn generate_heightmap(cfg: &GenerationConfig, seed: u32, painter: &BiomePainter) -> Map {
|
||||
let biomes = &generate_biomes(cfg, seed, painter);
|
||||
// let mut chunks: Vec<Chunk> = Vec::with_capacity(cfg.size.length_squared() as usize);
|
||||
let chunks = (0..cfg.size.y)
|
||||
.into_par_iter()
|
||||
.flat_map(|z| {
|
||||
(0..cfg.size.x)
|
||||
.into_par_iter()
|
||||
.map(move |x| generate_chunk(x as f64, z as f64, cfg, seed))
|
||||
(0..cfg.size.x).into_par_iter().map(move |x| {
|
||||
let biome_chunk = &biomes.chunks[x as usize + z as usize * cfg.size.x as usize];
|
||||
return generate_chunk(x, z, cfg, seed, &biome_chunk, painter);
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
return Map {
|
||||
@@ -23,48 +28,128 @@ pub fn generate_heightmap(cfg: &GenerationConfig, seed: u32) -> Map {
|
||||
};
|
||||
}
|
||||
|
||||
pub fn generate_chunk(chunk_x: f64, chunk_z: f64, cfg: &GenerationConfig, seed: u32) -> Chunk {
|
||||
let mut result: [f32; Chunk::SIZE * Chunk::SIZE] = [0.; Chunk::SIZE * Chunk::SIZE];
|
||||
let mut moisture = [0.; Chunk::SIZE * Chunk::SIZE];
|
||||
let mut temp = [0.; Chunk::SIZE * Chunk::SIZE];
|
||||
pub fn generate_biomes(cfg: &GenerationConfig, seed: u32, biome_painter: &BiomePainter) -> BiomeMap {
|
||||
let mut map = BiomeMap::new(cfg.size, biome_painter.biomes.len());
|
||||
map.chunks = (0..cfg.size.y)
|
||||
.into_par_iter()
|
||||
.flat_map(|y| {
|
||||
(0..cfg.size.x).into_par_iter().map(move |x| {
|
||||
return generate_biome_chunk(x as usize, y as usize, cfg, seed, biome_painter);
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
map.blend(cfg.biome_blend);
|
||||
return map;
|
||||
}
|
||||
|
||||
pub fn generate_biome_chunk(
|
||||
chunk_x: usize,
|
||||
chunk_y: usize,
|
||||
cfg: &GenerationConfig,
|
||||
seed: u32,
|
||||
biome_painter: &BiomePainter,
|
||||
) -> BiomeChunk {
|
||||
let mut chunk = BiomeChunk {
|
||||
offset: UVec2::new(chunk_x as u32, chunk_y as u32),
|
||||
data: [BiomeData::default(); Chunk::AREA],
|
||||
tiles: Vec::with_capacity(Chunk::AREA),
|
||||
};
|
||||
let noise_m = SuperSimplex::new(seed + 1);
|
||||
let noise_t = SuperSimplex::new(seed + 2);
|
||||
let noise_c = SuperSimplex::new(seed + 3);
|
||||
|
||||
for z in 0..Chunk::SIZE {
|
||||
for x in 0..Chunk::SIZE {
|
||||
let moisture = sample_point(
|
||||
x as f64 + chunk_x as f64 * Chunk::SIZE as f64,
|
||||
z as f64 + chunk_y as f64 * Chunk::SIZE as f64,
|
||||
&cfg.moisture_noise,
|
||||
&noise_m,
|
||||
cfg.size.as_vec2(),
|
||||
cfg.border_size,
|
||||
);
|
||||
let temperature = sample_point(
|
||||
x as f64 + chunk_x as f64 * Chunk::SIZE as f64,
|
||||
z as f64 + chunk_y as f64 * Chunk::SIZE as f64,
|
||||
&cfg.temperature_noise,
|
||||
&noise_t,
|
||||
cfg.size.as_vec2(),
|
||||
cfg.border_size,
|
||||
);
|
||||
let continentality = sample_point(
|
||||
x as f64 + chunk_x as f64 * Chunk::SIZE as f64,
|
||||
z as f64 + chunk_y as f64 * Chunk::SIZE as f64,
|
||||
&cfg.continent_noise,
|
||||
&noise_c,
|
||||
cfg.size.as_vec2(),
|
||||
cfg.border_size,
|
||||
);
|
||||
let data = BiomeData {
|
||||
moisture: moisture.clamp(0., 100.),
|
||||
temperature: temperature.clamp(0., 100.),
|
||||
continentality: continentality.clamp(0., 100.),
|
||||
};
|
||||
let mut b = vec![0.; biome_painter.biomes.len()];
|
||||
b[biome_painter.sample_biome_index(&data)] = 1.;
|
||||
|
||||
chunk.data[x + z * Chunk::SIZE] = data;
|
||||
chunk.tiles.push(b);
|
||||
}
|
||||
}
|
||||
|
||||
return chunk;
|
||||
}
|
||||
|
||||
pub fn generate_chunk(
|
||||
chunk_x: u32,
|
||||
chunk_z: u32,
|
||||
cfg: &GenerationConfig,
|
||||
seed: u32,
|
||||
biome_chunk: &BiomeChunk,
|
||||
biome_painter: &BiomePainter,
|
||||
) -> Chunk {
|
||||
let mut result: [f32; Chunk::SIZE * Chunk::SIZE] = [0.; Chunk::AREA];
|
||||
let mut data = [BiomeData::default(); Chunk::AREA];
|
||||
let mut biome_ids = [0; Chunk::AREA];
|
||||
let noise = SuperSimplex::new(seed);
|
||||
for z in 0..Chunk::SIZE {
|
||||
for x in 0..Chunk::SIZE {
|
||||
let sample = sample_point(
|
||||
x as f64 + chunk_x * Chunk::SIZE as f64,
|
||||
z as f64 + chunk_z * Chunk::SIZE as f64,
|
||||
&cfg,
|
||||
&noise,
|
||||
);
|
||||
result[x + z * Chunk::SIZE] = sample;
|
||||
moisture[x + z * Chunk::SIZE] = noise.get([
|
||||
(x as f64 + chunk_x * Chunk::SIZE as f64) / &cfg.noise_scale,
|
||||
(z as f64 + chunk_z * Chunk::SIZE as f64) / &cfg.noise_scale,
|
||||
]) as f32;
|
||||
temp[x + z * Chunk::SIZE] =
|
||||
sample_tempurature(z as f32 + chunk_z as f32 * Chunk::SIZE as f32, sample, &cfg, 100.);
|
||||
let biome_data = biome_chunk.get_biome_data(x, z);
|
||||
let biome_blend = biome_chunk.get_biome(x, z);
|
||||
let mut sample = 0.;
|
||||
for i in 0..biome_blend.len() {
|
||||
let blend = biome_blend[i];
|
||||
if blend == 0. {
|
||||
continue;
|
||||
}
|
||||
let biome = &biome_painter.biomes[i];
|
||||
sample += sample_point(
|
||||
x as f64 + chunk_x as f64 * Chunk::SIZE as f64,
|
||||
z as f64 + chunk_z as f64 * Chunk::SIZE as f64,
|
||||
&biome.noise,
|
||||
&noise,
|
||||
cfg.size.as_vec2(),
|
||||
cfg.border_size,
|
||||
) * blend;
|
||||
}
|
||||
let idx = x + z * Chunk::SIZE;
|
||||
biome_ids[idx] = biome_chunk.get_biome_id_dithered(x, z, &noise, cfg.biome_dither);
|
||||
result[idx] = sample;
|
||||
data[idx] = biome_data.clone();
|
||||
}
|
||||
}
|
||||
return Chunk {
|
||||
heights: result,
|
||||
moisture: moisture,
|
||||
temperature: temp,
|
||||
biome_data: data,
|
||||
biome_id: biome_ids,
|
||||
chunk_offset: IVec2::new(chunk_x as i32, chunk_z as i32),
|
||||
..default()
|
||||
};
|
||||
}
|
||||
|
||||
fn sample_tempurature(z: f32, height: f32, cfg: &GenerationConfig, equator: f32) -> f32 {
|
||||
let d = (equator - z).abs();
|
||||
let max_d = equator.max(cfg.get_total_height() as f32 - equator);
|
||||
let t_mod = d.remap(0., max_d, 0., 1.).clamp(0., 1.);
|
||||
|
||||
// let max_d = d.max()
|
||||
return (height.remap(0., 50., 0., 1.).clamp(0., 1.) + t_mod) / 2.;
|
||||
}
|
||||
|
||||
fn sample_point(x: f64, z: f64, cfg: &GenerationConfig, noise: &impl NoiseFn<f64, 2>) -> f32 {
|
||||
let x_s = x / cfg.noise_scale;
|
||||
let z_s = z / cfg.noise_scale;
|
||||
fn sample_point(x: f64, z: f64, cfg: &NoiseConfig, noise: &impl NoiseFn<f64, 2>, size: Vec2, border_size: f32) -> f32 {
|
||||
let x_s = x / cfg.scale;
|
||||
let z_s = z / cfg.scale;
|
||||
|
||||
let mut elevation: f64 = 0.;
|
||||
let mut first_layer: f64 = 0.;
|
||||
@@ -80,26 +165,25 @@ fn sample_point(x: f64, z: f64, cfg: &GenerationConfig, noise: &impl NoiseFn<f64
|
||||
first_layer = value;
|
||||
}
|
||||
if layer.first_layer_mask {
|
||||
elevation += mask(first_layer, value, cfg.sea_level);
|
||||
elevation += mask(first_layer, value);
|
||||
} else {
|
||||
elevation += value;
|
||||
}
|
||||
}
|
||||
|
||||
let outer = cfg.size.as_vec2() * Chunk::SIZE as f32;
|
||||
let outer = size * Chunk::SIZE as f32;
|
||||
|
||||
let p = Vec2::new(x as f32, z as f32);
|
||||
let d1 = p.x.min(p.y);
|
||||
let od = outer - p;
|
||||
let d2 = od.x.min(od.y);
|
||||
let d = d1.min(d2).min(cfg.border_size).remap(0., cfg.border_size, 0., 1.);
|
||||
let d = d1.min(d2).min(border_size).remap(0., border_size, 0., 1.);
|
||||
|
||||
return (elevation as f32) * d;
|
||||
}
|
||||
|
||||
fn mask(mask: f64, value: f64, sea_level: f64) -> f64 {
|
||||
let m = (mask - sea_level).max(0.);
|
||||
return value * m;
|
||||
fn mask(mask: f64, value: f64) -> f64 {
|
||||
return value * mask;
|
||||
}
|
||||
|
||||
fn sample_simple(x: f64, z: f64, cfg: &GeneratorLayer, noise: &impl NoiseFn<f64, 2>) -> f64 {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::prelude::Chunk;
|
||||
use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const OUTER_RADIUS: f32 = 1.;
|
||||
pub const INNER_RADIUS: f32 = OUTER_RADIUS * (SQRT_3 / 2.);
|
||||
@@ -52,11 +53,11 @@ pub fn tile_to_world_distance(dist: u32) -> f32 {
|
||||
return dist as f32 * (2. * INNER_RADIUS);
|
||||
}
|
||||
|
||||
pub fn get_tile_count(radius: u32) -> u32 {
|
||||
pub fn get_tile_count(radius: usize) -> usize {
|
||||
return 1 + 3 * (radius + 1) * radius;
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, Eq, PartialEq)]
|
||||
#[derive(Default, Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
|
||||
pub struct HexCoord {
|
||||
pub hex: IVec3,
|
||||
}
|
||||
@@ -220,4 +221,46 @@ impl HexCoord {
|
||||
self.get_neighbor(5),
|
||||
];
|
||||
}
|
||||
|
||||
pub fn hex_select(&self, radius: usize, include_center: bool) -> Vec<HexCoord> {
|
||||
assert!(radius != 0, "Radius cannot be zero");
|
||||
let mut result = Vec::with_capacity(get_tile_count(radius));
|
||||
|
||||
if include_center {
|
||||
result.push(*self);
|
||||
}
|
||||
|
||||
for k in 0..(radius + 1) {
|
||||
let mut p = self.scale(4, k);
|
||||
for i in 0..6 {
|
||||
for _j in 0..k {
|
||||
p = p.get_neighbor(i);
|
||||
result.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
pub fn select_ring(&self, radius: usize) -> Vec<HexCoord> {
|
||||
assert!(radius != 0, "Radius cannot be zero");
|
||||
let mut result = Vec::with_capacity(radius * 6);
|
||||
|
||||
let mut p = self.scale(4, radius);
|
||||
|
||||
if radius == 1 {
|
||||
result.push(*self);
|
||||
return result;
|
||||
}
|
||||
|
||||
for i in 0..6 {
|
||||
for _j in 0..radius {
|
||||
result.push(p);
|
||||
p = p.get_neighbor(i);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,159 +1,11 @@
|
||||
pub mod biome_painter;
|
||||
pub mod chunk_colliders;
|
||||
pub mod consts;
|
||||
pub mod generators;
|
||||
pub mod heightmap;
|
||||
pub mod hex_utils;
|
||||
pub mod mesh_generator;
|
||||
pub mod packed_mesh_generator;
|
||||
pub mod map;
|
||||
pub mod prelude;
|
||||
pub mod states;
|
||||
pub mod tile_manager;
|
||||
pub mod tile_mapper;
|
||||
|
||||
pub mod prelude {
|
||||
use crate::hex_utils::{tile_to_world_distance, HexCoord, INNER_RADIUS, OUTER_RADIUS, SHORT_DIAGONAL};
|
||||
use bevy::math::{IVec2, UVec2, Vec2, Vec3};
|
||||
use bevy::prelude::Resource;
|
||||
use bevy::prelude::*;
|
||||
use bevy::render::mesh::MeshVertexAttribute;
|
||||
use bevy::render::render_resource::VertexFormat;
|
||||
use bevy_inspector_egui::InspectorOptions;
|
||||
pub const TEX_MULTI: Vec2 = Vec2::new(1000., 1.);
|
||||
|
||||
pub const HEX_CORNERS: [Vec3; 6] = [
|
||||
Vec3::new(0., 0., OUTER_RADIUS),
|
||||
Vec3::new(INNER_RADIUS, 0., 0.5 * OUTER_RADIUS),
|
||||
Vec3::new(INNER_RADIUS, 0., -0.5 * OUTER_RADIUS),
|
||||
Vec3::new(0., 0., -OUTER_RADIUS),
|
||||
Vec3::new(-INNER_RADIUS, 0., -0.5 * OUTER_RADIUS),
|
||||
Vec3::new(-INNER_RADIUS, 0., 0.5 * OUTER_RADIUS),
|
||||
];
|
||||
|
||||
pub const HEX_NORMALS: [Vec3; 6] = [
|
||||
Vec3::new(INNER_RADIUS / 2., 0., (OUTER_RADIUS + 0.5 * OUTER_RADIUS) / 2.),
|
||||
Vec3::Z,
|
||||
Vec3::new(INNER_RADIUS / -2., 0., (OUTER_RADIUS + 0.5 * OUTER_RADIUS) / 2.),
|
||||
Vec3::new(INNER_RADIUS / -2., 0., (OUTER_RADIUS + 0.5 * OUTER_RADIUS) / -2.),
|
||||
Vec3::NEG_Z,
|
||||
Vec3::new(INNER_RADIUS / 2., 0., (OUTER_RADIUS + 0.5 * OUTER_RADIUS) / -2.),
|
||||
];
|
||||
|
||||
#[derive(Resource, Reflect, Default)]
|
||||
#[reflect(Resource)]
|
||||
pub struct GenerationConfig {
|
||||
pub noise_scale: f64,
|
||||
pub sea_level: f64,
|
||||
pub border_size: f32,
|
||||
pub size: UVec2,
|
||||
pub layers: Vec<GeneratorLayer>,
|
||||
}
|
||||
|
||||
impl GenerationConfig {
|
||||
pub fn get_total_width(&self) -> usize {
|
||||
return self.size.x as usize * Chunk::SIZE;
|
||||
}
|
||||
pub fn get_total_height(&self) -> usize {
|
||||
return self.size.y as usize * Chunk::SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Reflect, InspectorOptions)]
|
||||
pub struct GeneratorLayer {
|
||||
pub strength: f64,
|
||||
pub min_value: f64,
|
||||
pub base_roughness: f64,
|
||||
pub roughness: f64,
|
||||
pub persistence: f64,
|
||||
pub is_rigid: bool,
|
||||
pub weight: f64,
|
||||
pub weight_multi: f64,
|
||||
pub layers: usize,
|
||||
pub first_layer_mask: bool,
|
||||
}
|
||||
|
||||
pub struct Chunk {
|
||||
pub heights: [f32; Chunk::SIZE * Chunk::SIZE],
|
||||
pub moisture: [f32; Chunk::SIZE * Chunk::SIZE],
|
||||
pub temperature: [f32; Chunk::SIZE * Chunk::SIZE],
|
||||
pub chunk_offset: IVec2,
|
||||
}
|
||||
|
||||
impl Chunk {
|
||||
pub const SIZE: usize = 64;
|
||||
pub const WORLD_WIDTH: f32 = Chunk::SIZE as f32 * SHORT_DIAGONAL;
|
||||
pub const WORLD_HEIGHT: f32 = Chunk::SIZE as f32 * 1.5;
|
||||
pub const WORLD_SIZE: Vec2 = Vec2::new(Chunk::WORLD_WIDTH, Chunk::WORLD_HEIGHT);
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct Map {
|
||||
pub chunks: Vec<Chunk>,
|
||||
pub height: usize,
|
||||
pub width: usize,
|
||||
pub sea_level: f32,
|
||||
}
|
||||
|
||||
impl Map {
|
||||
pub fn get_neighbors(&self, pos: &HexCoord) -> [Option<f32>; 6] {
|
||||
let mut results: [Option<f32>; 6] = [None; 6];
|
||||
let w = self.width * Chunk::SIZE;
|
||||
let h = self.height * Chunk::SIZE;
|
||||
let n_tiles = pos.get_neighbors();
|
||||
for i in 0..6 {
|
||||
let n_tile = n_tiles[i];
|
||||
if !n_tile.is_in_bounds(h, w) {
|
||||
continue;
|
||||
}
|
||||
let c_idx = n_tile.to_chunk_index(self.width);
|
||||
let chunk = &self.chunks[c_idx];
|
||||
let local = n_tile.to_chunk_local_index();
|
||||
results[i] = Some(chunk.heights[local]);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
pub fn sample_height(&self, pos: &HexCoord) -> f32 {
|
||||
let chunk = &self.chunks[pos.to_chunk_index(self.width)];
|
||||
return chunk.heights[pos.to_chunk_local_index()];
|
||||
}
|
||||
|
||||
pub fn is_in_bounds(&self, pos: &HexCoord) -> bool {
|
||||
return pos.is_in_bounds(self.height * Chunk::SIZE, self.width * Chunk::SIZE);
|
||||
}
|
||||
|
||||
pub fn get_moisture(&self, pos: &HexCoord) -> f32 {
|
||||
let chunk = &self.chunks[pos.to_chunk_index(self.width)];
|
||||
return chunk.moisture[pos.to_chunk_local_index()];
|
||||
}
|
||||
|
||||
pub fn get_tempurature(&self, pos: &HexCoord) -> f32 {
|
||||
let chunk = &self.chunks[pos.to_chunk_index(self.width)];
|
||||
return chunk.temperature[pos.to_chunk_local_index()];
|
||||
}
|
||||
|
||||
pub fn get_center(&self) -> Vec3 {
|
||||
let w = self.get_world_width();
|
||||
let h = self.get_world_height();
|
||||
return Vec3::new(w / 2., self.sea_level, h / 2.);
|
||||
}
|
||||
|
||||
pub fn get_world_width(&self) -> f32 {
|
||||
return (self.width * Chunk::SIZE) as f32 * SHORT_DIAGONAL;
|
||||
}
|
||||
pub fn get_world_height(&self) -> f32 {
|
||||
return (self.height * Chunk::SIZE) as f32 * 1.5;
|
||||
}
|
||||
|
||||
pub fn get_world_size(&self) -> Vec2 {
|
||||
return Vec2::new(self.get_world_width(), self.get_world_height());
|
||||
}
|
||||
|
||||
pub fn set_height(&mut self, pos: &HexCoord, height: f32) {
|
||||
self.chunks[pos.to_chunk_index(self.width)].heights[pos.to_chunk_local_index()] = height;
|
||||
}
|
||||
}
|
||||
pub const ATTRIBUTE_PACKED_VERTEX_DATA: MeshVertexAttribute =
|
||||
MeshVertexAttribute::new("PackedVertexData", 988540817, VertexFormat::Uint32);
|
||||
pub const ATTRIBUTE_VERTEX_HEIGHT: MeshVertexAttribute =
|
||||
MeshVertexAttribute::new("VertexHeight", 988540717, VertexFormat::Float32);
|
||||
|
||||
pub const ATTRIBUTE_TEXTURE_INDEX: MeshVertexAttribute =
|
||||
MeshVertexAttribute::new("TextureIndex", 988540917, VertexFormat::Uint32);
|
||||
}
|
||||
pub mod biome_asset;
|
||||
|
||||
224
engine/world_generation/src/map/biome_map.rs
Normal file
224
engine/world_generation/src/map/biome_map.rs
Normal file
@@ -0,0 +1,224 @@
|
||||
use bevy::math::{UVec2, Vec3};
|
||||
use noise::NoiseFn;
|
||||
use rayon::iter::{IntoParallelIterator, ParallelIterator};
|
||||
|
||||
use super::chunk::Chunk;
|
||||
|
||||
pub struct BiomeMap {
|
||||
pub height: usize,
|
||||
pub width: usize,
|
||||
pub size: UVec2,
|
||||
pub biome_count: usize,
|
||||
pub chunks: Vec<BiomeChunk>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy)]
|
||||
pub struct BiomeData {
|
||||
pub moisture: f32,
|
||||
pub temperature: f32,
|
||||
pub continentality: f32,
|
||||
}
|
||||
|
||||
impl Into<Vec3> for &BiomeData {
|
||||
fn into(self) -> Vec3 {
|
||||
return Vec3::new(self.moisture, self.temperature, self.continentality);
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<Vec3> for BiomeData {
|
||||
fn into(self) -> Vec3 {
|
||||
return Vec3::new(self.moisture, self.temperature, self.continentality);
|
||||
}
|
||||
}
|
||||
|
||||
impl BiomeMap {
|
||||
pub fn new(size: UVec2, biome_count: usize) -> Self {
|
||||
let len = size.x as usize * size.y as usize * Chunk::AREA;
|
||||
return BiomeMap {
|
||||
size,
|
||||
height: size.y as usize * Chunk::SIZE,
|
||||
width: size.x as usize * Chunk::SIZE,
|
||||
biome_count,
|
||||
chunks: Vec::with_capacity(len),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn blend(&mut self, count: usize) {
|
||||
assert!(count != 0, "Count cannot be 0");
|
||||
for _ in 0..count {
|
||||
self.blend_once();
|
||||
}
|
||||
}
|
||||
|
||||
fn blend_once(&mut self) {
|
||||
let c: Vec<BiomeChunk> = (0..self.chunks.len())
|
||||
.into_par_iter()
|
||||
.map(|i| &self.chunks[i])
|
||||
.map(|chunk| {
|
||||
let tiles: Vec<_> = (0..Chunk::SIZE)
|
||||
.into_par_iter()
|
||||
.map(|y| {
|
||||
let mut new_tiles = Vec::with_capacity(self.width);
|
||||
for x in 0..Chunk::SIZE {
|
||||
let tx = x as u32 + chunk.offset.x * Chunk::SIZE as u32;
|
||||
let ty = y as u32 + chunk.offset.y * Chunk::SIZE as u32;
|
||||
let kernel = self.get_kernel(tx as i32, ty as i32);
|
||||
|
||||
let r = kernel
|
||||
.iter()
|
||||
.filter_map(|f| *f)
|
||||
.fold(vec![0.; self.biome_count], |a, b| {
|
||||
return a.iter().zip(b).map(|v| v.0 + v.1).collect();
|
||||
});
|
||||
|
||||
let sum: f32 = r.iter().sum();
|
||||
if sum == 0. {
|
||||
new_tiles.push(vec![0.; self.biome_count]);
|
||||
continue;
|
||||
}
|
||||
new_tiles.push(r.iter().map(|f| f / sum).collect());
|
||||
}
|
||||
return new_tiles;
|
||||
})
|
||||
.flatten()
|
||||
.collect();
|
||||
return BiomeChunk {
|
||||
offset: chunk.offset,
|
||||
tiles,
|
||||
data: chunk.data,
|
||||
};
|
||||
})
|
||||
.collect();
|
||||
self.chunks = c;
|
||||
}
|
||||
|
||||
fn get_kernel(&self, x: i32, y: i32) -> [Option<&Vec<f32>>; 9] {
|
||||
return [
|
||||
self.get_biome(x - 1, y - 1),
|
||||
self.get_biome(x, y - 1),
|
||||
self.get_biome(x + 1, y - 1),
|
||||
self.get_biome(x - 1, y),
|
||||
self.get_biome(x, y),
|
||||
self.get_biome(x + 1, y),
|
||||
self.get_biome(x - 1, y + 1),
|
||||
self.get_biome(x, y + 1),
|
||||
self.get_biome(x + 1, y + 1),
|
||||
];
|
||||
}
|
||||
|
||||
pub fn get_biome(&self, x: i32, y: i32) -> Option<&Vec<f32>> {
|
||||
if x < 0 || y < 0 {
|
||||
return None;
|
||||
}
|
||||
if x >= self.width as i32 || y >= self.height as i32 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let cx = (x as f32 / Chunk::SIZE as f32).floor() as usize;
|
||||
let cy = (y as f32 / Chunk::SIZE as f32).floor() as usize;
|
||||
|
||||
let chunk = &self.chunks[cx + cy * self.size.x as usize];
|
||||
return Some(chunk.get_biome(x as usize - cx * Chunk::SIZE, y as usize - cy * Chunk::SIZE));
|
||||
}
|
||||
|
||||
pub fn get_biome_id(&self, x: usize, y: usize) -> usize {
|
||||
let cx = (x as f32 / Chunk::SIZE as f32).floor() as usize;
|
||||
let cy = (y as f32 / Chunk::SIZE as f32).floor() as usize;
|
||||
|
||||
let chunk = &self.chunks[cx + cy * self.size.x as usize];
|
||||
|
||||
return chunk.get_biome_id(x - (cx * Chunk::SIZE), y - (cy * Chunk::SIZE));
|
||||
}
|
||||
|
||||
pub fn get_biome_data(&self, x: usize, y: usize) -> &BiomeData {
|
||||
let cx = (x as f32 / Chunk::SIZE as f32).floor() as usize;
|
||||
let cy = (y as f32 / Chunk::SIZE as f32).floor() as usize;
|
||||
|
||||
let chunk = &self.chunks[cx + cy * self.size.x as usize];
|
||||
|
||||
return chunk.get_biome_data(x - (cx * Chunk::SIZE), y - (cy * Chunk::SIZE));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct BiomeChunk {
|
||||
pub tiles: Vec<Vec<f32>>,
|
||||
pub offset: UVec2,
|
||||
pub data: [BiomeData; Chunk::AREA],
|
||||
}
|
||||
|
||||
impl BiomeChunk {
|
||||
pub fn get_biome(&self, x: usize, y: usize) -> &Vec<f32> {
|
||||
return &self.tiles[x as usize + y as usize * Chunk::SIZE];
|
||||
}
|
||||
|
||||
pub fn get_biome_data(&self, x: usize, y: usize) -> &BiomeData {
|
||||
return &self.data[x + y * Chunk::SIZE];
|
||||
}
|
||||
|
||||
pub fn get_biome_id(&self, x: usize, y: usize) -> usize {
|
||||
let b = self.get_biome(x, y);
|
||||
let mut max = 0.;
|
||||
let mut idx = 0;
|
||||
for i in 0..b.len() {
|
||||
let blend = b[i];
|
||||
if blend > max {
|
||||
max = blend;
|
||||
idx = i;
|
||||
}
|
||||
}
|
||||
return idx;
|
||||
}
|
||||
|
||||
pub fn get_biome_id_dithered(&self, x: usize, y: usize, noise: &impl NoiseFn<f64, 2>, scale: f64) -> usize {
|
||||
let cur_id = self.get_biome_id(x, y);
|
||||
let b = self.get_biome(x, y);
|
||||
let n = (noise.get([x as f64 / scale, y as f64 / scale]) as f32) * b[cur_id];
|
||||
for i in 0..b.len() {
|
||||
let blend = b[i];
|
||||
if blend == 0. {
|
||||
continue;
|
||||
}
|
||||
if n < blend {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return cur_id;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn biome_blend() {
|
||||
let mut biome = BiomeMap::new(UVec2::splat(4), 8);
|
||||
let w = biome.size.x as usize;
|
||||
let h = biome.size.y as usize;
|
||||
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let mut b = vec![0.; biome.biome_count];
|
||||
let idx = (x + y) % biome.biome_count;
|
||||
b[idx] = 1.;
|
||||
biome.chunks.push(generate_chunk(x, y, b));
|
||||
}
|
||||
}
|
||||
|
||||
biome.blend(8);
|
||||
assert!(biome.chunks.iter().all(|f| f.tiles.len() == Chunk::AREA), "Data Lost");
|
||||
}
|
||||
|
||||
fn generate_chunk(x: usize, y: usize, biome: Vec<f32>) -> BiomeChunk {
|
||||
let chunk = BiomeChunk {
|
||||
offset: UVec2::new(x as u32, y as u32),
|
||||
data: [BiomeData::default(); Chunk::AREA],
|
||||
tiles: (0..Chunk::AREA).into_iter().map(|_| biome.clone()).collect(),
|
||||
};
|
||||
|
||||
return chunk;
|
||||
}
|
||||
}
|
||||
76
engine/world_generation/src/map/chunk.rs
Normal file
76
engine/world_generation/src/map/chunk.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
use crate::hex_utils::SHORT_DIAGONAL;
|
||||
use bevy::prelude::*;
|
||||
|
||||
use super::biome_map::BiomeData;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Chunk {
|
||||
pub heights: [f32; Chunk::AREA],
|
||||
pub textures: [[u32; 2]; Chunk::AREA],
|
||||
pub biome_data: [BiomeData; Chunk::AREA],
|
||||
pub biome_id: [usize; Chunk::AREA],
|
||||
pub chunk_offset: IVec2,
|
||||
}
|
||||
|
||||
impl Default for Chunk {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
heights: [0.; Chunk::AREA],
|
||||
textures: [[0; 2]; Chunk::AREA],
|
||||
biome_data: [BiomeData::default(); Chunk::AREA],
|
||||
biome_id: [0; Chunk::AREA],
|
||||
chunk_offset: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Chunk {
|
||||
pub const SIZE: usize = 64;
|
||||
pub const AREA: usize = Chunk::SIZE * Chunk::SIZE;
|
||||
pub const WORLD_WIDTH: f32 = Chunk::SIZE as f32 * SHORT_DIAGONAL;
|
||||
pub const WORLD_HEIGHT: f32 = Chunk::SIZE as f32 * 1.5;
|
||||
pub const WORLD_SIZE: Vec2 = Vec2::new(Chunk::WORLD_WIDTH, Chunk::WORLD_HEIGHT);
|
||||
|
||||
pub fn get_pos_z_edge(&self) -> [f32; Chunk::SIZE] {
|
||||
let mut data = [0.; Chunk::SIZE];
|
||||
|
||||
for x in 0..Chunk::SIZE {
|
||||
let idx = x + (Chunk::SIZE - 1) * Chunk::SIZE;
|
||||
data[x] = self.heights[idx];
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
pub fn get_neg_z_edge(&self) -> [f32; Chunk::SIZE] {
|
||||
let mut data = [0.; Chunk::SIZE];
|
||||
|
||||
for x in 0..Chunk::SIZE {
|
||||
data[x] = self.heights[x];
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
pub fn get_pos_x_edge(&self) -> [f32; Chunk::SIZE] {
|
||||
let mut data = [0.; Chunk::SIZE];
|
||||
|
||||
for z in 0..Chunk::SIZE {
|
||||
let idx = (Chunk::SIZE - 1) + z * Chunk::SIZE;
|
||||
data[z] = self.heights[idx];
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
pub fn get_neg_x_edge(&self) -> [f32; Chunk::SIZE] {
|
||||
let mut data = [0.; Chunk::SIZE];
|
||||
|
||||
for z in 0..Chunk::SIZE {
|
||||
let idx = z * Chunk::SIZE;
|
||||
data[z] = self.heights[idx];
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
47
engine/world_generation/src/map/config.rs
Normal file
47
engine/world_generation/src/map/config.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
use bevy::prelude::*;
|
||||
use bevy_inspector_egui::InspectorOptions;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::chunk::Chunk;
|
||||
|
||||
#[derive(Resource, Reflect, Default)]
|
||||
#[reflect(Resource)]
|
||||
pub struct GenerationConfig {
|
||||
pub sea_level: f64,
|
||||
pub border_size: f32,
|
||||
pub biome_blend: usize,
|
||||
pub biome_dither: f64,
|
||||
pub moisture_noise: NoiseConfig,
|
||||
pub temperature_noise: NoiseConfig,
|
||||
pub continent_noise: NoiseConfig,
|
||||
pub size: UVec2,
|
||||
}
|
||||
|
||||
impl GenerationConfig {
|
||||
pub fn get_total_width(&self) -> usize {
|
||||
return self.size.x as usize * Chunk::SIZE;
|
||||
}
|
||||
pub fn get_total_height(&self) -> usize {
|
||||
return self.size.y as usize * Chunk::SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Default, Reflect, Clone, Debug)]
|
||||
pub struct NoiseConfig {
|
||||
pub scale: f64,
|
||||
pub layers: Vec<GeneratorLayer>,
|
||||
}
|
||||
|
||||
#[derive(Reflect, InspectorOptions, Serialize, Deserialize, Debug, Clone, Default)]
|
||||
pub struct GeneratorLayer {
|
||||
pub strength: f64,
|
||||
pub min_value: f64,
|
||||
pub base_roughness: f64,
|
||||
pub roughness: f64,
|
||||
pub persistence: f64,
|
||||
pub is_rigid: bool,
|
||||
pub weight: f64,
|
||||
pub weight_multi: f64,
|
||||
pub layers: usize,
|
||||
pub first_layer_mask: bool,
|
||||
}
|
||||
167
engine/world_generation/src/map/map.rs
Normal file
167
engine/world_generation/src/map/map.rs
Normal file
@@ -0,0 +1,167 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::hex_utils::*;
|
||||
|
||||
use super::{chunk::Chunk, mesh_chunk::MeshChunkData};
|
||||
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct Map {
|
||||
pub chunks: Vec<Chunk>,
|
||||
pub height: usize,
|
||||
pub width: usize,
|
||||
pub sea_level: f32,
|
||||
}
|
||||
|
||||
impl Map {
|
||||
pub fn get_chunk_mesh_data(&self, chunk_index: usize) -> MeshChunkData {
|
||||
#[cfg(feature = "tracing")]
|
||||
let _spawn_span = info_span!("Chunk Mesh Data").entered();
|
||||
let chunk = &self.chunks[chunk_index];
|
||||
|
||||
return MeshChunkData {
|
||||
heights: chunk.heights.clone(),
|
||||
textures: chunk.textures.clone(),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn get_neighbors(&self, pos: &HexCoord) -> [Option<f32>; 6] {
|
||||
let mut results: [Option<f32>; 6] = [None; 6];
|
||||
let w = self.width * Chunk::SIZE;
|
||||
let h = self.height * Chunk::SIZE;
|
||||
let n_tiles = pos.get_neighbors();
|
||||
for i in 0..6 {
|
||||
let n_tile = n_tiles[i];
|
||||
if !n_tile.is_in_bounds(h, w) {
|
||||
continue;
|
||||
}
|
||||
let c_idx = n_tile.to_chunk_index(self.width);
|
||||
let chunk = &self.chunks[c_idx];
|
||||
let local = n_tile.to_chunk_local_index();
|
||||
results[i] = Some(chunk.heights[local]);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
pub fn sample_height(&self, pos: &HexCoord) -> f32 {
|
||||
let chunk = &self.chunks[pos.to_chunk_index(self.width)];
|
||||
return chunk.heights[pos.to_chunk_local_index()];
|
||||
}
|
||||
|
||||
pub fn sample_height_mut(&mut self, pos: &HexCoord) -> &mut f32 {
|
||||
let chunk = &mut self.chunks[pos.to_chunk_index(self.width)];
|
||||
return &mut chunk.heights[pos.to_chunk_local_index()];
|
||||
}
|
||||
|
||||
pub fn is_in_bounds(&self, pos: &HexCoord) -> bool {
|
||||
return pos.is_in_bounds(self.height * Chunk::SIZE, self.width * Chunk::SIZE);
|
||||
}
|
||||
|
||||
pub fn get_moisture(&self, pos: &HexCoord) -> f32 {
|
||||
let chunk = &self.chunks[pos.to_chunk_index(self.width)];
|
||||
return chunk.biome_data[pos.to_chunk_local_index()].moisture;
|
||||
}
|
||||
|
||||
pub fn get_tempurature(&self, pos: &HexCoord) -> f32 {
|
||||
let chunk = &self.chunks[pos.to_chunk_index(self.width)];
|
||||
return chunk.biome_data[pos.to_chunk_local_index()].temperature;
|
||||
}
|
||||
|
||||
pub fn get_center(&self) -> Vec3 {
|
||||
let w = self.get_world_width();
|
||||
let h = self.get_world_height();
|
||||
return Vec3::new(w / 2., self.sea_level, h / 2.);
|
||||
}
|
||||
|
||||
pub fn get_world_width(&self) -> f32 {
|
||||
return (self.width * Chunk::SIZE) as f32 * SHORT_DIAGONAL;
|
||||
}
|
||||
pub fn get_world_height(&self) -> f32 {
|
||||
return (self.height * Chunk::SIZE) as f32 * 1.5;
|
||||
}
|
||||
|
||||
pub fn get_world_size(&self) -> Vec2 {
|
||||
return Vec2::new(self.get_world_width(), self.get_world_height());
|
||||
}
|
||||
|
||||
pub fn set_height(&mut self, pos: &HexCoord, height: f32) {
|
||||
self.chunks[pos.to_chunk_index(self.width)].heights[pos.to_chunk_local_index()] = height;
|
||||
}
|
||||
|
||||
pub fn create_crater(&mut self, pos: &HexCoord, radius: usize, depth: f32) -> Vec<usize> {
|
||||
assert!(radius != 0, "Radius cannot be zero");
|
||||
let width = self.width;
|
||||
|
||||
let mut chunks = self.hex_select_mut(pos, radius, true, |p, h, r| {
|
||||
let d = (r as f32) / (radius as f32);
|
||||
let cur = *h;
|
||||
let h2 = cur - depth;
|
||||
*h = h2.lerp(cur, d * d).max(0.);
|
||||
|
||||
return p.to_chunk_index(width);
|
||||
});
|
||||
|
||||
chunks.dedup();
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
pub fn hex_select<OP, Ret>(&self, center: &HexCoord, radius: usize, include_center: bool, op: OP) -> Vec<Ret>
|
||||
where
|
||||
OP: (Fn(&HexCoord, f32, usize) -> Ret) + Sync + Send,
|
||||
{
|
||||
assert!(radius != 0, "Radius cannot be zero");
|
||||
|
||||
if include_center {
|
||||
let h = self.sample_height(¢er);
|
||||
(op)(¢er, h, 0);
|
||||
}
|
||||
|
||||
let mut result = Vec::with_capacity(get_tile_count(radius));
|
||||
|
||||
for k in 0..(radius + 1) {
|
||||
let mut p = center.scale(4, k);
|
||||
for i in 0..6 {
|
||||
for _j in 0..k {
|
||||
p = p.get_neighbor(i);
|
||||
let h = self.sample_height(&p);
|
||||
result.push((op)(&p, h, k));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
pub fn hex_select_mut<OP, Ret>(
|
||||
&mut self,
|
||||
center: &HexCoord,
|
||||
radius: usize,
|
||||
include_center: bool,
|
||||
op: OP,
|
||||
) -> Vec<Ret>
|
||||
where
|
||||
OP: (Fn(&HexCoord, &mut f32, usize) -> Ret) + Sync + Send,
|
||||
{
|
||||
assert!(radius != 0, "Radius cannot be zero");
|
||||
|
||||
if include_center {
|
||||
let h = self.sample_height_mut(¢er);
|
||||
(op)(¢er, h, 0);
|
||||
}
|
||||
|
||||
let mut result = Vec::with_capacity(get_tile_count(radius));
|
||||
|
||||
for k in 0..(radius + 1) {
|
||||
let mut p = center.scale(4, k);
|
||||
for i in 0..6 {
|
||||
for _j in 0..k {
|
||||
p = p.get_neighbor(i);
|
||||
let h = self.sample_height_mut(&p);
|
||||
result.push((op)(&p, h, k));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
24
engine/world_generation/src/map/mesh_chunk.rs
Normal file
24
engine/world_generation/src/map/mesh_chunk.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
use crate::hex_utils::HexCoord;
|
||||
|
||||
use super::chunk::Chunk;
|
||||
|
||||
pub struct MeshChunkData {
|
||||
pub heights: [f32; Chunk::AREA],
|
||||
pub textures: [[u32; 2]; Chunk::AREA],
|
||||
}
|
||||
|
||||
impl MeshChunkData {
|
||||
pub fn get_neighbors(&self, coord: &HexCoord) -> [f32; 6] {
|
||||
let mut data = [0.; 6];
|
||||
let n_tiles = coord.get_neighbors();
|
||||
for i in 0..6 {
|
||||
let n = n_tiles[i];
|
||||
if !n.is_in_bounds(Chunk::SIZE, Chunk::SIZE) {
|
||||
continue;
|
||||
}
|
||||
data[i] = self.heights[n.to_index(Chunk::SIZE)];
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
5
engine/world_generation/src/map/mod.rs
Normal file
5
engine/world_generation/src/map/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
pub mod chunk;
|
||||
pub mod mesh_chunk;
|
||||
pub mod config;
|
||||
pub mod map;
|
||||
pub mod biome_map;
|
||||
6
engine/world_generation/src/prelude.rs
Normal file
6
engine/world_generation/src/prelude.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
pub use crate::consts::*;
|
||||
pub use crate::map::chunk::*;
|
||||
pub use crate::map::config::*;
|
||||
pub use crate::map::map::*;
|
||||
pub use crate::map::mesh_chunk::*;
|
||||
pub use crate::states::*;
|
||||
11
engine/world_generation/src/states.rs
Normal file
11
engine/world_generation/src/states.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
#[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum GeneratorState {
|
||||
Startup,
|
||||
GenerateHeightmap,
|
||||
SpawnMap,
|
||||
Idle,
|
||||
Regenerate,
|
||||
}
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
use asset_loader::create_asset_loader;
|
||||
use bevy::{
|
||||
asset::{Asset, Handle},
|
||||
ecs::system::Resource,
|
||||
reflect::TypePath,
|
||||
};
|
||||
use bevy::{asset::Asset, ecs::system::Resource, reflect::TypePath};
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[derive(Resource, Debug)]
|
||||
pub struct TileManager {
|
||||
@@ -24,7 +20,7 @@ impl TileManager {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, TypePath, Asset)]
|
||||
#[derive(Serialize, Deserialize, Debug, TypePath, Asset, Clone)]
|
||||
pub struct TileAsset {
|
||||
#[serde(skip)]
|
||||
pub id: usize,
|
||||
@@ -37,4 +33,4 @@ pub struct TileAsset {
|
||||
pub side_texture: String,
|
||||
}
|
||||
|
||||
create_asset_loader!(TileAssetPlugin, TileAssetLoader, TileAsset, TileAssetLoadState, &["tile.json"],;?);
|
||||
create_asset_loader!(TileAssetPlugin, TileAssetLoader, TileAsset, &["tile", "tile.ron"],;?);
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
use asset_loader::create_asset_loader;
|
||||
use bevy::prelude::*;
|
||||
use bevy::{
|
||||
asset::{Asset, Handle},
|
||||
reflect::TypePath,
|
||||
};
|
||||
use bevy::{asset::Asset, reflect::TypePath};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::tile_manager::TileAsset;
|
||||
@@ -19,14 +16,14 @@ pub struct TileMapperAsset {
|
||||
}
|
||||
|
||||
impl TileMapperAsset {
|
||||
pub fn sample_tile(&self, height: f32) -> Handle<TileAsset> {
|
||||
pub fn sample_tile(&self, height: f32) -> AssetId<TileAsset> {
|
||||
for i in 0..self.thresholds.len() {
|
||||
let t = self.thresholds[i];
|
||||
if t >= height {
|
||||
return self.tiles[i].clone();
|
||||
return self.tiles[i].id();
|
||||
}
|
||||
}
|
||||
return self.tiles.last().unwrap().clone();
|
||||
return self.tiles.last().unwrap().id();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,8 +31,7 @@ create_asset_loader!(
|
||||
TileMapperAssetPlugin,
|
||||
TileMapperAssetLoader,
|
||||
TileMapperAsset,
|
||||
TileMapperLoadState,
|
||||
&["mapper.json"],;
|
||||
&["mapper", "mapper.ron"],;
|
||||
tiles_path -> tiles
|
||||
?
|
||||
);
|
||||
|
||||
23
game/buildings/Cargo.toml
Normal file
23
game/buildings/Cargo.toml
Normal file
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "buildings"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
bevy = "0.14.0"
|
||||
world_generation = { path = "../../engine/world_generation" }
|
||||
shared = { path = "../shared" }
|
||||
bevy_rapier3d = "0.27.0"
|
||||
serde = { version = "1.0.204", features = ["derive"] }
|
||||
asset_loader = { path = "../../engine/asset_loader" }
|
||||
serde_json = "1.0.120"
|
||||
ron = "0.8.1"
|
||||
bevy_asset_loader = { version = "0.21.0", features = [
|
||||
"standard_dynamic_assets",
|
||||
"3d",
|
||||
] }
|
||||
|
||||
[features]
|
||||
tracing = []
|
||||
29
game/buildings/src/assets/building_asset.rs
Normal file
29
game/buildings/src/assets/building_asset.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
use asset_loader::create_asset_loader;
|
||||
use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use shared::resource::ResourceIdentifier;
|
||||
|
||||
use crate::footprint::BuildingFootprint;
|
||||
|
||||
#[derive(Asset, TypePath, Debug, Serialize, Deserialize)]
|
||||
pub struct BuildingAsset {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub footprint: BuildingFootprint,
|
||||
pub prefab_path: String,
|
||||
#[serde(skip)]
|
||||
pub prefab: Handle<Scene>,
|
||||
|
||||
pub cost: Vec<ResourceIdentifier>,
|
||||
pub consumption: Vec<ResourceIdentifier>,
|
||||
pub production: Vec<ResourceIdentifier>,
|
||||
}
|
||||
|
||||
create_asset_loader!(
|
||||
BuildingAssetPlugin,
|
||||
BuildingAssetLoader,
|
||||
BuildingAsset,
|
||||
&["building", "building.ron"],
|
||||
prefab_path -> prefab
|
||||
;?
|
||||
);
|
||||
11
game/buildings/src/assets/building_database.rs
Normal file
11
game/buildings/src/assets/building_database.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
use bevy::{asset::Handle, prelude::Resource};
|
||||
|
||||
use super::building_asset::BuildingAsset;
|
||||
use bevy::prelude::*;
|
||||
use bevy_asset_loader::prelude::*;
|
||||
|
||||
#[derive(Resource, AssetCollection)]
|
||||
pub struct BuildingDatabase {
|
||||
#[asset(key = "buildings", collection(typed))]
|
||||
pub buildings: Vec<Handle<BuildingAsset>>,
|
||||
}
|
||||
2
game/buildings/src/assets/mod.rs
Normal file
2
game/buildings/src/assets/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod building_asset;
|
||||
pub mod building_database;
|
||||
22
game/buildings/src/build_queue.rs
Normal file
22
game/buildings/src/build_queue.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use bevy::prelude::Resource;
|
||||
use shared::building::BuildingIdentifier;
|
||||
use world_generation::hex_utils::HexCoord;
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct BuildQueue {
|
||||
pub queue: Vec<QueueEntry>,
|
||||
}
|
||||
|
||||
impl Default for BuildQueue {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
queue: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub struct QueueEntry {
|
||||
pub building: BuildingIdentifier,
|
||||
pub pos: HexCoord,
|
||||
}
|
||||
107
game/buildings/src/building_plugin.rs
Normal file
107
game/buildings/src/building_plugin.rs
Normal file
@@ -0,0 +1,107 @@
|
||||
use bevy::{prelude::*, window::PrimaryWindow};
|
||||
use bevy_asset_loader::loading_state::{
|
||||
config::{ConfigureLoadingState, LoadingStateConfig},
|
||||
LoadingStateAppExt,
|
||||
};
|
||||
use bevy_rapier3d::{pipeline::QueryFilter, plugin::RapierContext};
|
||||
use shared::{
|
||||
despawn::Despawn,
|
||||
states::{AssetLoadState, GameplayState},
|
||||
tags::MainCamera,
|
||||
};
|
||||
use world_generation::{hex_utils::HexCoord, map::map::Map};
|
||||
|
||||
use crate::{
|
||||
assets::{building_asset::BuildingAssetPlugin, building_database::BuildingDatabase},
|
||||
build_queue::{BuildQueue, QueueEntry},
|
||||
};
|
||||
|
||||
pub struct BuildingPugin;
|
||||
|
||||
impl Plugin for BuildingPugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.insert_resource(BuildQueue::default());
|
||||
app.add_plugins(BuildingAssetPlugin);
|
||||
|
||||
app.configure_loading_state(
|
||||
LoadingStateConfig::new(AssetLoadState::Loading).load_collection::<BuildingDatabase>(),
|
||||
);
|
||||
|
||||
app.add_systems(Startup, init.run_if(in_state(AssetLoadState::Loading)));
|
||||
app.add_systems(Update, hq_placement.run_if(in_state(GameplayState::PlaceHQ)));
|
||||
|
||||
app.add_systems(PreUpdate, process_build_queue.run_if(in_state(GameplayState::Playing)));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct IndicatorCube(Handle<Mesh>, Handle<StandardMaterial>);
|
||||
|
||||
fn init(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>) {
|
||||
let cube = Cuboid::from_size(Vec3::splat(1.));
|
||||
let mesh_handle = meshes.add(cube);
|
||||
let mat_handle = materials.add(Color::WHITE);
|
||||
commands.insert_resource(IndicatorCube(mesh_handle, mat_handle));
|
||||
}
|
||||
|
||||
fn hq_placement(
|
||||
cam_query: Query<(&GlobalTransform, &Camera), With<MainCamera>>,
|
||||
mut commands: Commands,
|
||||
window: Query<&Window, With<PrimaryWindow>>,
|
||||
mouse: Res<ButtonInput<MouseButton>>,
|
||||
rapier_context: Res<RapierContext>,
|
||||
map: Res<Map>,
|
||||
indicator: Res<IndicatorCube>,
|
||||
mut build_queue: ResMut<BuildQueue>,
|
||||
mut next_state: ResMut<NextState<GameplayState>>,
|
||||
) {
|
||||
let win = window.single();
|
||||
let (cam_transform, camera) = cam_query.single();
|
||||
let Some(cursor_pos) = win.cursor_position() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(cam_ray) = camera.viewport_to_world(cam_transform, cursor_pos) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let collision = rapier_context.cast_ray(
|
||||
cam_ray.origin,
|
||||
cam_ray.direction.into(),
|
||||
500.,
|
||||
true,
|
||||
QueryFilter::only_fixed(),
|
||||
);
|
||||
|
||||
if let Some((_e, dist)) = collision {
|
||||
let contact_point = cam_ray.get_point(dist);
|
||||
let contact_coord = HexCoord::from_world_pos(contact_point);
|
||||
let positions = map.hex_select(&contact_coord, 3, true, |pos, h, _| pos.to_world(h));
|
||||
show_indicators(positions, &mut commands, &indicator);
|
||||
|
||||
if mouse.just_pressed(MouseButton::Left) {
|
||||
build_queue.queue.push(QueueEntry {
|
||||
building: 0.into(),
|
||||
pos: contact_coord,
|
||||
});
|
||||
|
||||
next_state.set(GameplayState::Playing);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn show_indicators(positions: Vec<Vec3>, commands: &mut Commands, indicator: &IndicatorCube) {
|
||||
for p in positions {
|
||||
commands.spawn((
|
||||
PbrBundle {
|
||||
mesh: indicator.0.clone(),
|
||||
material: indicator.1.clone(),
|
||||
transform: Transform::from_translation(p),
|
||||
..default()
|
||||
},
|
||||
Despawn,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn process_build_queue(mut queue: ResMut<BuildQueue>) {}
|
||||
98
game/buildings/src/buildings_map.rs
Normal file
98
game/buildings/src/buildings_map.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
use bevy::prelude::*;
|
||||
use world_generation::hex_utils::HexCoord;
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct BuildingMap {
|
||||
pub chunks: Vec<BuildingChunk>,
|
||||
}
|
||||
|
||||
impl BuildingMap {
|
||||
pub fn new(size: UVec2) -> Self {
|
||||
let mut db = BuildingMap {
|
||||
chunks: Vec::with_capacity(size.length_squared() as usize),
|
||||
};
|
||||
|
||||
for y in 0..size.y as i32 {
|
||||
for x in 0..size.x as i32 {
|
||||
let offset = IVec2::new(x, y);
|
||||
let index = (x + y * size.x as i32) as usize;
|
||||
db.chunks.push(BuildingChunk::new(offset, index));
|
||||
}
|
||||
}
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
pub fn get_buildings_in_range(&self, coord: &HexCoord, radius: usize) -> Option<Vec<&BuildingEntry>> {
|
||||
assert!(radius != 0, "Radius cannot be zero");
|
||||
todo!();
|
||||
}
|
||||
|
||||
pub fn get_building(&self, coord: &HexCoord) -> Option<&BuildingEntry> {
|
||||
todo!();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BuildingChunk {
|
||||
pub entries: Vec<BuildingChunk>,
|
||||
pub index: usize,
|
||||
pub offset: IVec2,
|
||||
}
|
||||
|
||||
impl BuildingChunk {
|
||||
pub fn new(offset: IVec2, index: usize) -> Self {
|
||||
return BuildingChunk {
|
||||
entries: Vec::new(),
|
||||
index,
|
||||
offset,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn get_building(&self, coord: &HexCoord) -> Option<&BuildingEntry> {
|
||||
todo!();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BuildingEntry {
|
||||
pub coord: HexCoord,
|
||||
pub entity: Entity,
|
||||
pub is_main: bool,
|
||||
pub main_entity: Option<Entity>,
|
||||
pub has_children: bool,
|
||||
pub child_entities: Option<Vec<Entity>>,
|
||||
}
|
||||
|
||||
impl BuildingEntry {
|
||||
pub fn new(coord: HexCoord, entity: Entity) -> Self {
|
||||
return BuildingEntry {
|
||||
coord,
|
||||
entity,
|
||||
child_entities: None,
|
||||
has_children: false,
|
||||
main_entity: None,
|
||||
is_main: true,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn new_with_children(coord: HexCoord, entity: Entity, children: Vec<Entity>) -> BuildingEntry {
|
||||
return BuildingEntry {
|
||||
coord,
|
||||
entity,
|
||||
child_entities: Some(children),
|
||||
has_children: true,
|
||||
main_entity: None,
|
||||
is_main: true,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn new_with_parent(coord: HexCoord, entity: Entity, main: Entity) -> BuildingEntry {
|
||||
return BuildingEntry {
|
||||
coord,
|
||||
entity,
|
||||
child_entities: None,
|
||||
has_children: false,
|
||||
main_entity: Some(main),
|
||||
is_main: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
32
game/buildings/src/footprint.rs
Normal file
32
game/buildings/src/footprint.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
use bevy::math::{IVec2, Vec3Swizzles};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use world_generation::hex_utils::HexCoord;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct BuildingFootprint {
|
||||
pub footprint: Vec<IVec2>,
|
||||
}
|
||||
|
||||
impl BuildingFootprint {
|
||||
pub fn get_footprint(&self, center: &HexCoord) -> Vec<HexCoord> {
|
||||
let c = center.hex.xy();
|
||||
return self.footprint.iter().map(|p| HexCoord::from_hex(*p + c)).collect();
|
||||
}
|
||||
|
||||
pub fn get_footprint_rotated(&self, center: &HexCoord, rotation: i32) -> Vec<HexCoord> {
|
||||
let c = center.hex.xy();
|
||||
return self
|
||||
.footprint
|
||||
.iter()
|
||||
.map(|p| HexCoord::from_hex(*p + c).rotate_around(center, rotation))
|
||||
.collect();
|
||||
}
|
||||
|
||||
pub fn get_neighbors(&self, center: &HexCoord) -> Vec<HexCoord> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
pub fn get_neighbors_rotated(&self, center: &HexCoord, rotation: i32) -> Vec<HexCoord> {
|
||||
todo!();
|
||||
}
|
||||
}
|
||||
6
game/buildings/src/lib.rs
Normal file
6
game/buildings/src/lib.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
pub mod assets;
|
||||
pub mod build_queue;
|
||||
pub mod building_plugin;
|
||||
pub mod buildings_map;
|
||||
pub mod footprint;
|
||||
pub use building_plugin::*;
|
||||
@@ -7,14 +7,20 @@ build = "build.rs"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
bevy = "0.13.2"
|
||||
bevy-inspector-egui = "0.23.4"
|
||||
iyes_perf_ui = "0.2.3"
|
||||
bevy = "0.14.0"
|
||||
bevy-inspector-egui = "0.25.0"
|
||||
iyes_perf_ui = "0.3.0"
|
||||
noise = "0.8.2"
|
||||
world_generation ={path="../../engine/world_generation"}
|
||||
bevy_rapier3d = { version = "0.25.0", features = [ "simd-stable", "debug-render-3d","parallel" ] }
|
||||
world_generation = { path = "../../engine/world_generation" }
|
||||
bevy_rapier3d = { version = "0.27.0", features = ["simd-stable", "parallel"] }
|
||||
rayon = "1.10.0"
|
||||
|
||||
buildings = { path = "../buildings" }
|
||||
shared = { path = "../shared" }
|
||||
bevy_asset_loader = { version = "0.21.0", features = [
|
||||
"standard_dynamic_assets",
|
||||
"3d",
|
||||
] }
|
||||
ron = "0.8.1"
|
||||
|
||||
[features]
|
||||
tracing = ["bevy/trace_tracy", "world_generation/tracing"]
|
||||
tracing = ["bevy/trace_tracy", "world_generation/tracing", "buildings/tracing"]
|
||||
|
||||
Submodule game/main/assets updated: 896ed4eede...3bb0aaab5b
@@ -1,9 +1,10 @@
|
||||
use bevy::core_pipeline::experimental::taa::{TemporalAntiAliasBundle, TemporalAntiAliasPlugin};
|
||||
use bevy::core_pipeline::prepass::DepthPrepass;
|
||||
use bevy::input::mouse::{MouseMotion, MouseScrollUnit, MouseWheel};
|
||||
use bevy::pbr::ScreenSpaceAmbientOcclusionBundle;
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::CursorGrabMode;
|
||||
use bevy_rapier3d::plugin::RapierContext;
|
||||
use shared::states::MenuState;
|
||||
use shared::tags::MainCamera;
|
||||
use world_generation::hex_utils::HexCoord;
|
||||
use world_generation::prelude::Map;
|
||||
|
||||
@@ -17,8 +18,8 @@ impl Plugin for PhosCameraPlugin {
|
||||
|
||||
app.add_systems(PreStartup, setup);
|
||||
|
||||
app.add_systems(Update, rts_camera_system);
|
||||
app.add_systems(PostUpdate, limit_camera_bounds);
|
||||
app.add_systems(Update, rts_camera_system.run_if(in_state(MenuState::InGame)));
|
||||
app.add_systems(PostUpdate, limit_camera_bounds.run_if(in_state(MenuState::InGame)));
|
||||
//Free Cam
|
||||
//app.add_systems(Update, (grab_mouse, (update_camera, update_camera_mouse).chain()));
|
||||
|
||||
@@ -34,6 +35,8 @@ fn setup(mut commands: Commands, mut msaa: ResMut<Msaa>) {
|
||||
..default()
|
||||
},
|
||||
PhosCamera::default(),
|
||||
MainCamera,
|
||||
DepthPrepass,
|
||||
PhosCameraTargets::default(),
|
||||
))
|
||||
.insert(TemporalAntiAliasBundle::default());
|
||||
@@ -196,6 +199,9 @@ fn rts_camera_system(
|
||||
cam_targets.anim_time = cam_targets.anim_time.min(1.);
|
||||
}
|
||||
cam_pos.y = f32::lerp(cam_pos.y, desired_height, cam_targets.anim_time);
|
||||
if cam_pos.y < min_height {
|
||||
cam_pos.y = min_height;
|
||||
}
|
||||
let t = cam_pos.y.remap(cam_cfg.min_height, cam_cfg.max_height, 0., 1.);
|
||||
|
||||
if cam_targets.rotate_time < 1. {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
use bevy::prelude::*;
|
||||
use world_generation::{
|
||||
hex_utils::{tile_to_world_distance, SHORT_DIAGONAL},
|
||||
prelude::Chunk,
|
||||
};
|
||||
use world_generation::{hex_utils::SHORT_DIAGONAL, prelude::Chunk};
|
||||
|
||||
#[derive(Component, Reflect)]
|
||||
#[reflect(Component)]
|
||||
@@ -19,8 +16,8 @@ impl Default for PhosCamera {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
min_height: 10.,
|
||||
max_height: 120.,
|
||||
speed: 30.,
|
||||
max_height: 420.,
|
||||
speed: 100.,
|
||||
zoom_speed: 0.3,
|
||||
min_angle: (20. as f32).to_radians(),
|
||||
max_angle: 1.,
|
||||
|
||||
@@ -20,8 +20,10 @@ fn main() {
|
||||
primary_window: Some(Window {
|
||||
title: "Phos".into(),
|
||||
name: Some("phos".into()),
|
||||
// resolution: (1920., 1080.).into(),
|
||||
#[cfg(debug_assertions)]
|
||||
resolution: (1920., 1080.).into(),
|
||||
present_mode: PresentMode::AutoNoVsync,
|
||||
#[cfg(not(debug_assertions))]
|
||||
mode: bevy::window::WindowMode::BorderlessFullscreen,
|
||||
..default()
|
||||
}),
|
||||
|
||||
@@ -1,29 +1,26 @@
|
||||
use bevy::ecs::world::CommandQueue;
|
||||
use bevy::prelude::*;
|
||||
use bevy_rapier3d::geometry::{Collider, TriMeshFlags};
|
||||
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
|
||||
use world_generation::{
|
||||
biome_painter::BiomePainterAsset,
|
||||
chunk_colliders::generate_chunk_collider,
|
||||
hex_utils::{self, offset_to_world, SHORT_DIAGONAL},
|
||||
mesh_generator::generate_chunk_mesh,
|
||||
prelude::{Chunk, Map},
|
||||
tile_manager::TileAsset,
|
||||
tile_mapper::TileMapperAsset,
|
||||
};
|
||||
use bevy::tasks::*;
|
||||
use bevy::utils::futures;
|
||||
use bevy_rapier3d::geometry::Collider;
|
||||
use bevy_rapier3d::geometry::TriMeshFlags;
|
||||
use world_generation::prelude::Map;
|
||||
use world_generation::states::GeneratorState;
|
||||
|
||||
use crate::prelude::RebuildChunk;
|
||||
use crate::{
|
||||
prelude::{ChunkAtlas, PhosChunk, PhosChunkRegistry},
|
||||
utlis::render_distance_system::RenderDistanceVisibility,
|
||||
prelude::{PhosChunk, PhosChunkRegistry},
|
||||
utlis::chunk_utils::prepare_chunk_mesh,
|
||||
};
|
||||
|
||||
use super::prelude::CurrentBiomePainter;
|
||||
pub struct ChunkRebuildPlugin;
|
||||
|
||||
impl Plugin for ChunkRebuildPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.insert_resource(ChunkRebuildQueue::default());
|
||||
app.init_resource::<PhosChunkRegistry>();
|
||||
app.add_systems(PreUpdate, chunk_rebuilder);
|
||||
app.add_systems(PreUpdate, chunk_rebuilder.run_if(in_state(GeneratorState::SpawnMap)));
|
||||
app.add_systems(PostUpdate, collider_task_resolver);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,65 +31,61 @@ pub struct ChunkRebuildQueue {
|
||||
|
||||
fn chunk_rebuilder(
|
||||
mut commands: Commands,
|
||||
mut queue: ResMut<ChunkRebuildQueue>,
|
||||
mut chunks: ResMut<PhosChunkRegistry>,
|
||||
atlas: Res<ChunkAtlas>,
|
||||
chunk_query: Query<(Entity, &PhosChunk), (With<RebuildChunk>, Without<ChunkRebuildTask>)>,
|
||||
heightmap: Res<Map>,
|
||||
tile_assets: Res<Assets<TileAsset>>,
|
||||
tile_mappers: Res<Assets<TileMapperAsset>>,
|
||||
mut meshes: ResMut<Assets<Mesh>>,
|
||||
biome_painters: Res<Assets<BiomePainterAsset>>,
|
||||
painter: Res<CurrentBiomePainter>,
|
||||
) {
|
||||
if queue.queue.len() == 0 {
|
||||
return;
|
||||
}
|
||||
queue.queue.dedup();
|
||||
let pool = AsyncComputeTaskPool::get();
|
||||
|
||||
for chunk_index in &queue.queue {
|
||||
let chunk = chunks.chunks[*chunk_index];
|
||||
commands.entity(chunk).despawn();
|
||||
}
|
||||
for (chunk_entity, idx) in &chunk_query {
|
||||
#[cfg(feature = "tracing")]
|
||||
let _spawn_span = info_span!("Rebuild Chunk").entered();
|
||||
|
||||
let b_painter = biome_painters.get(painter.handle.clone());
|
||||
let chunk_index = idx.index;
|
||||
let chunk_data = heightmap.get_chunk_mesh_data(chunk_index);
|
||||
let chunk_offset = heightmap.chunks[chunk_index].chunk_offset;
|
||||
|
||||
let cur_painter = b_painter.unwrap();
|
||||
|
||||
let chunk_meshes: Vec<_> = queue
|
||||
.queue
|
||||
.par_iter()
|
||||
.map(|idx| {
|
||||
let chunk = &heightmap.chunks[*idx];
|
||||
let mesh = generate_chunk_mesh(chunk, &heightmap, cur_painter, &tile_assets, &tile_mappers);
|
||||
let (col_verts, col_indicies) = generate_chunk_collider(chunk, &heightmap);
|
||||
let collider =
|
||||
Collider::trimesh_with_flags(col_verts, col_indicies, TriMeshFlags::MERGE_DUPLICATE_VERTICES);
|
||||
return (
|
||||
mesh,
|
||||
collider,
|
||||
offset_to_world(chunk.chunk_offset * Chunk::SIZE as i32, 0.),
|
||||
hex_utils::offset_to_index(chunk.chunk_offset, heightmap.width),
|
||||
let task = pool.spawn(async move {
|
||||
#[cfg(feature = "tracing")]
|
||||
let _spawn_span = info_span!("Rebuild Task").entered();
|
||||
let mut queue = CommandQueue::default();
|
||||
let (mesh, collider_data, _, _) = prepare_chunk_mesh(&chunk_data, chunk_offset, chunk_index);
|
||||
#[cfg(feature = "tracing")]
|
||||
let trimesh_span = info_span!("Chunk Trimesh").entered();
|
||||
let c = Collider::trimesh_with_flags(
|
||||
collider_data.0,
|
||||
collider_data.1,
|
||||
TriMeshFlags::DELETE_DUPLICATE_TRIANGLES,
|
||||
);
|
||||
})
|
||||
.collect();
|
||||
#[cfg(feature = "tracing")]
|
||||
drop(trimesh_span);
|
||||
queue.push(move |world: &mut World| {
|
||||
world.entity_mut(chunk_entity).insert(c).remove::<ChunkRebuildTask>();
|
||||
});
|
||||
|
||||
for (mesh, collider, pos, index) in chunk_meshes {
|
||||
let chunk = commands.spawn((
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.add(mesh),
|
||||
material: atlas.chunk_material_handle.clone(),
|
||||
transform: Transform::from_translation(pos),
|
||||
..default()
|
||||
},
|
||||
PhosChunk::new(index),
|
||||
RenderDistanceVisibility::default().with_offset(Vec3::new(
|
||||
(Chunk::SIZE / 2) as f32 * SHORT_DIAGONAL,
|
||||
0.,
|
||||
(Chunk::SIZE / 2) as f32 * 1.5,
|
||||
)),
|
||||
collider,
|
||||
));
|
||||
chunks.chunks[index] = chunk.id();
|
||||
return (queue, mesh);
|
||||
});
|
||||
|
||||
commands
|
||||
.entity(chunk_entity)
|
||||
.insert(ChunkRebuildTask { task })
|
||||
.remove::<RebuildChunk>();
|
||||
}
|
||||
queue.queue.clear();
|
||||
}
|
||||
|
||||
fn collider_task_resolver(
|
||||
mut chunks: Query<(&mut ChunkRebuildTask, &Handle<Mesh>), With<PhosChunk>>,
|
||||
mut commands: Commands,
|
||||
mut meshes: ResMut<Assets<Mesh>>,
|
||||
) {
|
||||
for (mut task, mesh_handle) in &mut chunks {
|
||||
if let Some((mut c, mesh)) = futures::check_ready(&mut task.task) {
|
||||
commands.append(&mut c);
|
||||
meshes.insert(mesh_handle, mesh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
struct ChunkRebuildTask {
|
||||
pub task: Task<(CommandQueue, Mesh)>,
|
||||
}
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
#[cfg(feature = "tracing")]
|
||||
use bevy::log::*;
|
||||
use bevy::{asset::LoadState, pbr::ExtendedMaterial, prelude::*};
|
||||
use bevy::{
|
||||
pbr::{ExtendedMaterial, NotShadowCaster},
|
||||
prelude::*,
|
||||
};
|
||||
use bevy_asset_loader::prelude::*;
|
||||
|
||||
use bevy_inspector_egui::quick::ResourceInspectorPlugin;
|
||||
use bevy_rapier3d::geometry::Collider;
|
||||
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
|
||||
use shared::states::{AssetLoadState, GameplayState, MenuState};
|
||||
use world_generation::{
|
||||
biome_asset::{BiomeAsset, BiomeAssetPlugin},
|
||||
biome_painter::*,
|
||||
chunk_colliders::generate_chunk_collider,
|
||||
heightmap::generate_heightmap,
|
||||
hex_utils::{self, offset_to_world, SHORT_DIAGONAL},
|
||||
mesh_generator::generate_chunk_mesh,
|
||||
hex_utils::{offset_to_index, SHORT_DIAGONAL},
|
||||
prelude::*,
|
||||
tile_manager::*,
|
||||
tile_mapper::*,
|
||||
@@ -17,92 +21,137 @@ use world_generation::{
|
||||
|
||||
use crate::{
|
||||
camera_system::components::*,
|
||||
prelude::{ChunkAtlas, PhosChunk, PhosChunkRegistry, PhosMap},
|
||||
shader_extensions::chunk_material::ChunkMaterial,
|
||||
utlis::render_distance_system::RenderDistanceVisibility,
|
||||
prelude::{PhosAssets, PhosChunk, PhosChunkRegistry},
|
||||
shader_extensions::{
|
||||
chunk_material::ChunkMaterial,
|
||||
water_material::{WaterMaterial, WaterSettings},
|
||||
},
|
||||
utlis::{
|
||||
chunk_utils::{paint_map, prepare_chunk_mesh_with_collider},
|
||||
render_distance_system::RenderDistanceVisibility,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
chunk_rebuild::ChunkRebuildPlugin, prelude::CurrentBiomePainter, terraforming_test::TerraFormingTestPlugin,
|
||||
};
|
||||
use super::{chunk_rebuild::ChunkRebuildPlugin, terraforming_test::TerraFormingTestPlugin};
|
||||
|
||||
pub struct MapInitPlugin;
|
||||
|
||||
impl Plugin for MapInitPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.insert_state(GeneratorState::Startup);
|
||||
app.insert_state(AssetLoadState::Loading);
|
||||
|
||||
//Assets
|
||||
app.add_plugins(TileAssetPlugin);
|
||||
app.add_plugins(TileMapperAssetPlugin);
|
||||
app.add_plugins(BiomeAssetPlugin);
|
||||
|
||||
app.add_plugins(ResourceInspectorPlugin::<GenerationConfig>::default());
|
||||
app.add_plugins(ResourceInspectorPlugin::<WaterInspect>::default());
|
||||
app.register_type::<ExtendedMaterial<StandardMaterial, WaterMaterial>>();
|
||||
app.register_asset_reflect::<ExtendedMaterial<StandardMaterial, WaterMaterial>>();
|
||||
app.add_plugins((
|
||||
ResourceInspectorPlugin::<PhosMap>::default(),
|
||||
ResourceInspectorPlugin::<GenerationConfig>::default(),
|
||||
ChunkRebuildPlugin,
|
||||
TerraFormingTestPlugin,
|
||||
MaterialPlugin::<ExtendedMaterial<StandardMaterial, ChunkMaterial>>::default(),
|
||||
MaterialPlugin::<ExtendedMaterial<StandardMaterial, WaterMaterial>> {
|
||||
prepass_enabled: false,
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
|
||||
app.add_systems(Startup, (load_textures, load_tiles));
|
||||
app.add_systems(PostStartup, create_map);
|
||||
app.configure_loading_state(
|
||||
LoadingStateConfig::new(AssetLoadState::Loading)
|
||||
.with_dynamic_assets_file::<StandardDynamicAssetCollection>("phos.assets.ron")
|
||||
.load_collection::<PhosAssets>()
|
||||
.load_collection::<BiomePainterAsset>(),
|
||||
);
|
||||
|
||||
app.add_systems(Startup, load_textures.run_if(in_state(AssetLoadState::FinalizeAssets)));
|
||||
|
||||
app.add_systems(
|
||||
Update,
|
||||
create_heightmap.run_if(in_state(GeneratorState::GenerateHeightmap)),
|
||||
);
|
||||
|
||||
// app.add_systems(
|
||||
// Update,
|
||||
// check_asset_load.run_if(in_state(AssetLoadState::FinalizeAssets)),
|
||||
// );
|
||||
app.add_systems(
|
||||
Update,
|
||||
(finalize_texture, finalize_biome_painter).run_if(in_state(AssetLoadState::FinalizeAssets)),
|
||||
);
|
||||
app.add_systems(
|
||||
Update,
|
||||
finalize_biome_painter
|
||||
.run_if(in_state(AssetLoadState::FinalizeAssets))
|
||||
.run_if(in_state(AssetLoadState::LoadComplete)),
|
||||
);
|
||||
app.add_systems(Update, despawn_map.run_if(in_state(GeneratorState::Regenerate)));
|
||||
app.add_systems(
|
||||
Update,
|
||||
spawn_map
|
||||
.run_if(in_state(AssetLoadState::LoadComplete))
|
||||
.run_if(in_state(GeneratorState::SpawnMap)),
|
||||
);
|
||||
|
||||
app.add_systems(Update, finalize_texture);
|
||||
app.add_systems(PostUpdate, (despawn_map, spawn_map).chain());
|
||||
app.insert_resource(TileManager::default());
|
||||
app.insert_resource(PhosMap::default());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource, Reflect, Default)]
|
||||
#[reflect(Resource)]
|
||||
struct WaterInspect(Handle<ExtendedMaterial<StandardMaterial, WaterMaterial>>);
|
||||
|
||||
fn load_textures(
|
||||
mut commands: Commands,
|
||||
asset_server: Res<AssetServer>,
|
||||
mut standard_materials: ResMut<Assets<StandardMaterial>>,
|
||||
mut atlas: ResMut<PhosAssets>,
|
||||
mut water_materials: ResMut<Assets<ExtendedMaterial<StandardMaterial, WaterMaterial>>>,
|
||||
) {
|
||||
let main_tex = asset_server.load("textures/world/stack.png");
|
||||
|
||||
let water_material = standard_materials.add(StandardMaterial {
|
||||
base_color: Color::AQUAMARINE.with_a(0.5),
|
||||
alpha_mode: AlphaMode::Blend,
|
||||
..default()
|
||||
});
|
||||
commands.insert_resource(ChunkAtlas {
|
||||
handle: main_tex.clone(),
|
||||
is_loaded: false,
|
||||
chunk_material_handle: Handle::default(),
|
||||
water_material: water_material,
|
||||
let water_material = water_materials.add(ExtendedMaterial {
|
||||
base: StandardMaterial {
|
||||
base_color: Color::srgba(0., 0.5, 1., 0.8),
|
||||
alpha_mode: AlphaMode::Blend,
|
||||
..Default::default()
|
||||
},
|
||||
extension: WaterMaterial {
|
||||
settings: WaterSettings {
|
||||
offset: 0.5,
|
||||
scale: 100.,
|
||||
..Default::default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
});
|
||||
commands.insert_resource(WaterInspect(water_material.clone()));
|
||||
atlas.water_material = water_material;
|
||||
}
|
||||
|
||||
fn load_tiles(mut commands: Commands, asset_server: Res<AssetServer>) {
|
||||
let handle: Handle<BiomePainterAsset> = asset_server.load("biome_painters/terra.biomes.json");
|
||||
commands.insert_resource(CurrentBiomePainter { handle });
|
||||
fn finalize_biome_painter(
|
||||
mut commands: Commands,
|
||||
mut next_generator_state: ResMut<NextState<GeneratorState>>,
|
||||
biome_painter: Res<BiomePainterAsset>,
|
||||
biomes: Res<Assets<BiomeAsset>>,
|
||||
) {
|
||||
let biome_painter = biome_painter.build(&biomes);
|
||||
commands.insert_resource(biome_painter);
|
||||
next_generator_state.set(GeneratorState::GenerateHeightmap);
|
||||
println!("Finalize Biome");
|
||||
}
|
||||
|
||||
fn finalize_texture(
|
||||
asset_server: Res<AssetServer>,
|
||||
mut atlas: ResMut<ChunkAtlas>,
|
||||
mut map: ResMut<PhosMap>,
|
||||
mut atlas: ResMut<PhosAssets>,
|
||||
mut images: ResMut<Assets<Image>>,
|
||||
painter: Res<CurrentBiomePainter>,
|
||||
painter_load: Res<BiomePainterLoadState>,
|
||||
tile_load: Res<TileAssetLoadState>,
|
||||
mut chunk_materials: ResMut<Assets<ExtendedMaterial<StandardMaterial, ChunkMaterial>>>,
|
||||
mapper_load: Res<TileMapperLoadState>,
|
||||
mut next_load_state: ResMut<NextState<AssetLoadState>>,
|
||||
) {
|
||||
if atlas.is_loaded {
|
||||
return;
|
||||
}
|
||||
println!("Finalize Tex");
|
||||
let image = images.get_mut(atlas.handle.id()).unwrap();
|
||||
|
||||
if !painter_load.is_all_loaded() || !tile_load.is_all_loaded() || !mapper_load.is_all_loaded() {
|
||||
return;
|
||||
}
|
||||
|
||||
if asset_server.load_state(atlas.handle.clone()) != LoadState::Loaded {
|
||||
return;
|
||||
}
|
||||
if asset_server.load_state(painter.handle.clone()) != LoadState::Loaded {
|
||||
return;
|
||||
}
|
||||
let image = images.get_mut(&atlas.handle).unwrap();
|
||||
|
||||
let array_layers = 14;
|
||||
let array_layers = image.height() / image.width();
|
||||
image.reinterpret_stacked_2d_as_array(array_layers);
|
||||
|
||||
atlas.is_loaded = true;
|
||||
let chunk_material = chunk_materials.add(ExtendedMaterial {
|
||||
base: StandardMaterial::default(),
|
||||
extension: ChunkMaterial {
|
||||
@@ -110,135 +159,105 @@ fn finalize_texture(
|
||||
},
|
||||
});
|
||||
atlas.chunk_material_handle = chunk_material;
|
||||
map.ready = true;
|
||||
map.regenerate = true;
|
||||
|
||||
next_load_state.set(AssetLoadState::LoadComplete);
|
||||
}
|
||||
|
||||
fn create_map(mut commands: Commands, mut cam: Query<(&mut Transform, Entity), With<PhosCamera>>) {
|
||||
fn create_heightmap(
|
||||
mut commands: Commands,
|
||||
mut cam: Query<(&mut Transform, Entity), With<PhosCamera>>,
|
||||
mut next_state: ResMut<NextState<GeneratorState>>,
|
||||
biome_painter: Res<BiomePainter>,
|
||||
) {
|
||||
let config = GenerationConfig {
|
||||
layers: vec![
|
||||
GeneratorLayer {
|
||||
biome_blend: 16,
|
||||
biome_dither: 16.,
|
||||
continent_noise: NoiseConfig {
|
||||
scale: 500.,
|
||||
layers: vec![GeneratorLayer {
|
||||
base_roughness: 2.14,
|
||||
roughness: 0.87,
|
||||
strength: 8.3,
|
||||
min_value: -0.2,
|
||||
strength: 100.,
|
||||
min_value: 0.,
|
||||
persistence: 0.77,
|
||||
is_rigid: false,
|
||||
weight: 0.,
|
||||
weight_multi: 0.,
|
||||
layers: 4,
|
||||
layers: 1,
|
||||
first_layer_mask: false,
|
||||
},
|
||||
GeneratorLayer {
|
||||
base_roughness: 2.85,
|
||||
roughness: 2.,
|
||||
strength: -0.23,
|
||||
min_value: -0.,
|
||||
persistence: 1.,
|
||||
}],
|
||||
},
|
||||
moisture_noise: NoiseConfig {
|
||||
scale: 500.,
|
||||
layers: vec![GeneratorLayer {
|
||||
base_roughness: 2.14,
|
||||
roughness: 0.87,
|
||||
strength: 100.,
|
||||
min_value: 0.,
|
||||
persistence: 0.77,
|
||||
is_rigid: false,
|
||||
weight: 0.,
|
||||
weight_multi: 0.,
|
||||
layers: 4,
|
||||
layers: 1,
|
||||
first_layer_mask: false,
|
||||
},
|
||||
GeneratorLayer {
|
||||
base_roughness: 2.6,
|
||||
roughness: 4.,
|
||||
strength: 3.1,
|
||||
}],
|
||||
},
|
||||
temperature_noise: NoiseConfig {
|
||||
scale: 500.,
|
||||
layers: vec![GeneratorLayer {
|
||||
base_roughness: 2.14,
|
||||
roughness: 0.87,
|
||||
strength: 100.,
|
||||
min_value: 0.,
|
||||
persistence: 1.57,
|
||||
is_rigid: true,
|
||||
weight: 1.,
|
||||
weight_multi: 0.35,
|
||||
layers: 4,
|
||||
first_layer_mask: true,
|
||||
},
|
||||
GeneratorLayer {
|
||||
base_roughness: 3.87,
|
||||
roughness: 5.8,
|
||||
strength: -1.,
|
||||
min_value: 0.,
|
||||
persistence: 0.,
|
||||
is_rigid: true,
|
||||
weight: 1.,
|
||||
weight_multi: 4.57,
|
||||
layers: 3,
|
||||
first_layer_mask: true,
|
||||
},
|
||||
GeneratorLayer {
|
||||
base_roughness: 3.87,
|
||||
roughness: 5.8,
|
||||
strength: -1.5,
|
||||
min_value: 0.,
|
||||
persistence: 0.3,
|
||||
is_rigid: true,
|
||||
weight: 1.,
|
||||
weight_multi: 4.57,
|
||||
layers: 3,
|
||||
persistence: 0.77,
|
||||
is_rigid: false,
|
||||
weight: 0.,
|
||||
weight_multi: 0.,
|
||||
layers: 1,
|
||||
first_layer_mask: false,
|
||||
},
|
||||
],
|
||||
noise_scale: 450.,
|
||||
}],
|
||||
},
|
||||
sea_level: 8.5,
|
||||
border_size: 64.,
|
||||
size: UVec2::splat(1024 / Chunk::SIZE as u32),
|
||||
size: UVec2::splat(16),
|
||||
// size: UVec2::splat(1),
|
||||
};
|
||||
let heightmap = generate_heightmap(&config, 4);
|
||||
let heightmap = generate_heightmap(&config, 42069, &biome_painter);
|
||||
|
||||
let (mut cam_t, cam_entity) = cam.single_mut();
|
||||
cam_t.translation = heightmap.get_center();
|
||||
|
||||
commands.entity(cam_entity).insert(CameraBounds::from_size(config.size));
|
||||
|
||||
commands.insert_resource(heightmap);
|
||||
commands.insert_resource(config);
|
||||
next_state.set(GeneratorState::SpawnMap);
|
||||
}
|
||||
|
||||
fn spawn_map(
|
||||
heightmap: Res<Map>,
|
||||
mut heightmap: ResMut<Map>,
|
||||
mut commands: Commands,
|
||||
mut meshes: ResMut<Assets<Mesh>>,
|
||||
atlas: Res<ChunkAtlas>,
|
||||
mut map: ResMut<PhosMap>,
|
||||
atlas: Res<PhosAssets>,
|
||||
tile_assets: Res<Assets<TileAsset>>,
|
||||
tile_mappers: Res<Assets<TileMapperAsset>>,
|
||||
biome_painters: Res<Assets<BiomePainterAsset>>,
|
||||
painter: Res<CurrentBiomePainter>,
|
||||
mut generator_state: ResMut<NextState<GeneratorState>>,
|
||||
cur_game_state: Res<State<MenuState>>,
|
||||
mut game_state: ResMut<NextState<MenuState>>,
|
||||
mut gameplay_state: ResMut<NextState<GameplayState>>,
|
||||
biome_painter: Res<BiomePainter>,
|
||||
) {
|
||||
if !map.ready || !map.regenerate {
|
||||
return;
|
||||
}
|
||||
let b_painter = biome_painters.get(painter.handle.clone());
|
||||
map.regenerate = false;
|
||||
|
||||
let cur_painter = b_painter.unwrap();
|
||||
paint_map(&mut heightmap, &biome_painter, &tile_assets, &tile_mappers);
|
||||
|
||||
let chunk_meshes: Vec<_> = heightmap
|
||||
.chunks
|
||||
.par_iter()
|
||||
.map(|chunk: &Chunk| {
|
||||
#[cfg(feature = "tracing")]
|
||||
let _gen_mesh = info_span!("Generate Chunk").entered();
|
||||
let mesh = generate_chunk_mesh(chunk, &heightmap, cur_painter, &tile_assets, &tile_mappers);
|
||||
let (col_verts, col_indicies) = generate_chunk_collider(chunk, &heightmap);
|
||||
let collider: Collider;
|
||||
{
|
||||
#[cfg(feature = "tracing")]
|
||||
let _collider_span = info_span!("Create Collider Trimesh").entered();
|
||||
collider = Collider::trimesh(col_verts, col_indicies);
|
||||
}
|
||||
return (
|
||||
mesh,
|
||||
collider,
|
||||
offset_to_world(chunk.chunk_offset * Chunk::SIZE as i32, 0.),
|
||||
hex_utils::offset_to_index(chunk.chunk_offset, heightmap.width),
|
||||
);
|
||||
let index = offset_to_index(chunk.chunk_offset, heightmap.width);
|
||||
return prepare_chunk_mesh_with_collider(&heightmap.get_chunk_mesh_data(index), chunk.chunk_offset, index);
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut registry = PhosChunkRegistry::new(chunk_meshes.len());
|
||||
|
||||
{
|
||||
#[cfg(feature = "tracing")]
|
||||
let _spawn_span = info_span!("Spawn Chunks").entered();
|
||||
@@ -264,33 +283,40 @@ fn spawn_map(
|
||||
}
|
||||
}
|
||||
|
||||
commands.spawn((PbrBundle {
|
||||
transform: Transform::from_translation(heightmap.get_center()),
|
||||
mesh: meshes.add(
|
||||
Plane3d::default()
|
||||
.mesh()
|
||||
.size(heightmap.get_world_width(), heightmap.get_world_height()),
|
||||
),
|
||||
material: atlas.water_material.clone(),
|
||||
..default()
|
||||
},));
|
||||
commands.spawn((
|
||||
MaterialMeshBundle {
|
||||
transform: Transform::from_translation(heightmap.get_center()),
|
||||
mesh: meshes.add(
|
||||
Plane3d::default()
|
||||
.mesh()
|
||||
.size(heightmap.get_world_width(), heightmap.get_world_height()),
|
||||
),
|
||||
material: atlas.water_material.clone(),
|
||||
..default()
|
||||
},
|
||||
NotShadowCaster,
|
||||
));
|
||||
|
||||
commands.insert_resource(registry);
|
||||
generator_state.set(GeneratorState::Idle);
|
||||
if cur_game_state.get() != &MenuState::InGame {
|
||||
game_state.set(MenuState::InGame);
|
||||
gameplay_state.set(GameplayState::PlaceHQ);
|
||||
}
|
||||
}
|
||||
|
||||
fn despawn_map(
|
||||
mut commands: Commands,
|
||||
mut heightmap: ResMut<Map>,
|
||||
cfg: Res<GenerationConfig>,
|
||||
map: Res<PhosMap>,
|
||||
chunks: Query<Entity, With<PhosChunk>>,
|
||||
mut next_state: ResMut<NextState<GeneratorState>>,
|
||||
biome_painter: Res<BiomePainter>,
|
||||
) {
|
||||
if !map.regenerate {
|
||||
return;
|
||||
}
|
||||
for chunk in chunks.iter() {
|
||||
commands.entity(chunk).despawn();
|
||||
}
|
||||
|
||||
*heightmap = generate_heightmap(&cfg, 4);
|
||||
*heightmap = generate_heightmap(&cfg, 4, &biome_painter);
|
||||
next_state.set(GeneratorState::SpawnMap);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,2 @@
|
||||
use bevy::prelude::*;
|
||||
use world_generation::biome_painter::BiomePainterAsset;
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct CurrentBiomePainter {
|
||||
pub handle: Handle<BiomePainterAsset>,
|
||||
}
|
||||
|
||||
@@ -1,32 +1,33 @@
|
||||
use bevy::{prelude::*, window::PrimaryWindow};
|
||||
use bevy_rapier3d::{pipeline::QueryFilter, plugin::RapierContext};
|
||||
use world_generation::{hex_utils::HexCoord, prelude::Map};
|
||||
use world_generation::{hex_utils::HexCoord, prelude::Map, states::GeneratorState};
|
||||
|
||||
use crate::{camera_system::components::PhosCamera, prelude::PhosChunkRegistry};
|
||||
|
||||
use super::chunk_rebuild::ChunkRebuildQueue;
|
||||
use crate::{
|
||||
camera_system::components::PhosCamera,
|
||||
prelude::{PhosChunkRegistry, RebuildChunk},
|
||||
};
|
||||
|
||||
pub struct TerraFormingTestPlugin;
|
||||
|
||||
impl Plugin for TerraFormingTestPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(Update, deform);
|
||||
app.add_systems(Update, deform.run_if(in_state(GeneratorState::Idle)));
|
||||
}
|
||||
}
|
||||
|
||||
fn deform(
|
||||
cam_query: Query<(&GlobalTransform, &Camera), With<PhosCamera>>,
|
||||
mut commands: Commands,
|
||||
window: Query<&Window, With<PrimaryWindow>>,
|
||||
mouse: Res<ButtonInput<MouseButton>>,
|
||||
rapier_context: Res<RapierContext>,
|
||||
mut heightmap: ResMut<Map>,
|
||||
mut rebuild: ResMut<ChunkRebuildQueue>,
|
||||
time: Res<Time>,
|
||||
chunks: Res<PhosChunkRegistry>,
|
||||
) {
|
||||
let mut multi = 0.;
|
||||
if mouse.pressed(MouseButton::Left) {
|
||||
if mouse.just_pressed(MouseButton::Left) {
|
||||
multi = 1.;
|
||||
} else if mouse.pressed(MouseButton::Right) {
|
||||
} else if mouse.just_pressed(MouseButton::Right) {
|
||||
multi = -1.;
|
||||
}
|
||||
|
||||
@@ -47,27 +48,20 @@ fn deform(
|
||||
let collision = rapier_context.cast_ray(
|
||||
cam_ray.origin,
|
||||
cam_ray.direction.into(),
|
||||
100.,
|
||||
500.,
|
||||
true,
|
||||
QueryFilter::only_fixed(),
|
||||
);
|
||||
|
||||
if let Some((_, dist)) = collision {
|
||||
if let Some((e, dist)) = collision {
|
||||
#[cfg(feature = "tracing")]
|
||||
let span = info_span!("Deform Mesh").entered();
|
||||
let contact_point = cam_ray.get_point(dist);
|
||||
let contact_coord = HexCoord::from_world_pos(contact_point);
|
||||
let cur_height = heightmap.sample_height(&contact_coord);
|
||||
heightmap.set_height(&contact_coord, cur_height + 1. * time.delta_seconds() * multi);
|
||||
let cur_chunk = contact_coord.to_chunk_index(heightmap.width);
|
||||
|
||||
if contact_coord.is_on_chunk_edge() {
|
||||
let neighbors = contact_coord.get_neighbors();
|
||||
let mut other_chunks: Vec<_> = neighbors
|
||||
.iter()
|
||||
.map(|c| c.to_chunk_index(heightmap.width))
|
||||
.filter(|c| c != &cur_chunk)
|
||||
.collect();
|
||||
rebuild.queue.append(&mut other_chunks);
|
||||
let modified_chunks = heightmap.create_crater(&contact_coord, 5, 5. * multi);
|
||||
for c in modified_chunks {
|
||||
commands.entity(chunks.chunks[c]).insert(RebuildChunk);
|
||||
}
|
||||
rebuild.queue.push(cur_chunk);
|
||||
commands.entity(e).insert(RebuildChunk);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,31 +1,38 @@
|
||||
use crate::camera_system::camera_plugin::PhosCameraPlugin;
|
||||
use crate::camera_system::components::PhosCamera;
|
||||
use crate::map_rendering::chunk_rebuild::ChunkRebuildPlugin;
|
||||
use crate::map_rendering::map_init::MapInitPlugin;
|
||||
use crate::shader_extensions::chunk_material::ChunkMaterial;
|
||||
use crate::utlis::render_distance_system::RenderDistancePlugin;
|
||||
use bevy::pbr::ExtendedMaterial;
|
||||
use bevy::{
|
||||
pbr::{wireframe::WireframeConfig, CascadeShadowConfig},
|
||||
prelude::*,
|
||||
};
|
||||
use bevy_asset_loader::prelude::*;
|
||||
use bevy_rapier3d::dynamics::{Ccd, RigidBody, Velocity};
|
||||
use bevy_rapier3d::geometry::Collider;
|
||||
use bevy_rapier3d::plugin::{NoUserData, RapierPhysicsPlugin};
|
||||
use buildings::BuildingPugin;
|
||||
use iyes_perf_ui::prelude::*;
|
||||
use world_generation::biome_painter::BiomePainterPlugin;
|
||||
use world_generation::tile_manager::TileAssetPlugin;
|
||||
use world_generation::tile_mapper::TileMapperAssetPlugin;
|
||||
use shared::states::{GameplayState, MenuState};
|
||||
use shared::{despawn::DespawnPuglin, states::AssetLoadState};
|
||||
|
||||
pub struct PhosGamePlugin;
|
||||
|
||||
impl Plugin for PhosGamePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.insert_state(AssetLoadState::Loading);
|
||||
app.insert_state(MenuState::Loading);
|
||||
app.insert_state(GameplayState::Waiting);
|
||||
|
||||
app.add_loading_state(
|
||||
LoadingState::new(AssetLoadState::Loading).continue_to_state(AssetLoadState::FinalizeAssets),
|
||||
);
|
||||
|
||||
app.add_plugins((
|
||||
PhosCameraPlugin,
|
||||
MapInitPlugin,
|
||||
MaterialPlugin::<ExtendedMaterial<StandardMaterial, ChunkMaterial>>::default(),
|
||||
RenderDistancePlugin,
|
||||
// BuildingPugin,
|
||||
DespawnPuglin,
|
||||
));
|
||||
|
||||
//Systems - Startup
|
||||
@@ -40,17 +47,13 @@ impl Plugin for PhosGamePlugin {
|
||||
.add_plugins(bevy::diagnostic::SystemInformationDiagnosticsPlugin)
|
||||
.add_plugins(PerfUiPlugin);
|
||||
|
||||
//Assets
|
||||
app.add_plugins(TileAssetPlugin);
|
||||
app.add_plugins(TileMapperAssetPlugin);
|
||||
app.add_plugins(BiomePainterPlugin);
|
||||
//Physics
|
||||
app.add_plugins(RapierPhysicsPlugin::<NoUserData>::default());
|
||||
// app.add_plugins(RapierDebugRenderPlugin::default());
|
||||
|
||||
app.insert_resource(WireframeConfig {
|
||||
global: false,
|
||||
default_color: Color::hex("FF0064").unwrap(),
|
||||
default_color: Srgba::hex("FF0064").unwrap().into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -78,7 +81,7 @@ fn init_game(mut commands: Commands, mut materials: ResMut<Assets<StandardMateri
|
||||
});
|
||||
|
||||
let sphere_mat = StandardMaterial {
|
||||
base_color: Color::CYAN,
|
||||
base_color: Color::srgb(1., 1., 0.),
|
||||
..default()
|
||||
};
|
||||
let handle = materials.add(sphere_mat);
|
||||
|
||||
@@ -2,23 +2,18 @@ use bevy::asset::Handle;
|
||||
use bevy::pbr::ExtendedMaterial;
|
||||
use bevy::prelude::*;
|
||||
use bevy::prelude::{Component, Image, Resource};
|
||||
use bevy::reflect::Reflect;
|
||||
use bevy_asset_loader::asset_collection::AssetCollection;
|
||||
use world_generation::biome_painter::BiomePainterAsset;
|
||||
|
||||
use crate::shader_extensions::chunk_material::ChunkMaterial;
|
||||
use crate::shader_extensions::water_material::WaterMaterial;
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct ChunkAtlas {
|
||||
#[derive(AssetCollection, Resource, Default)]
|
||||
pub struct PhosAssets {
|
||||
#[asset(key = "chunk_atlas")]
|
||||
pub handle: Handle<Image>,
|
||||
pub chunk_material_handle: Handle<ExtendedMaterial<StandardMaterial, ChunkMaterial>>,
|
||||
pub water_material: Handle<StandardMaterial>,
|
||||
pub is_loaded: bool,
|
||||
}
|
||||
|
||||
#[derive(Resource, Default, Reflect)]
|
||||
#[reflect(Resource)]
|
||||
pub struct PhosMap {
|
||||
pub ready: bool,
|
||||
pub regenerate: bool,
|
||||
pub water_material: Handle<ExtendedMaterial<StandardMaterial, WaterMaterial>>,
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
@@ -44,3 +39,6 @@ impl PhosChunkRegistry {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct RebuildChunk;
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
pub mod chunk_material;
|
||||
pub mod water_material;
|
||||
|
||||
52
game/main/src/shader_extensions/water_material.rs
Normal file
52
game/main/src/shader_extensions/water_material.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
use bevy::asset::Asset;
|
||||
use bevy::math::VectorSpace;
|
||||
use bevy::pbr::MaterialExtension;
|
||||
use bevy::prelude::*;
|
||||
use bevy::reflect::Reflect;
|
||||
use bevy::render::render_resource::{AsBindGroup, ShaderRef, ShaderType};
|
||||
|
||||
#[derive(Asset, Reflect, AsBindGroup, Debug, Clone, Default)]
|
||||
pub struct WaterMaterial {
|
||||
#[uniform(100)]
|
||||
pub settings: WaterSettings,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, ShaderType, Reflect)]
|
||||
pub struct WaterSettings {
|
||||
pub offset: f32,
|
||||
pub scale: f32,
|
||||
pub deep_color: Vec3,
|
||||
}
|
||||
|
||||
impl Default for WaterSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
offset: 0.0,
|
||||
scale: 1.0,
|
||||
deep_color: Vec3::ZERO,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MaterialExtension for WaterMaterial {
|
||||
fn fragment_shader() -> ShaderRef {
|
||||
"shaders/world/water.wgsl".into()
|
||||
}
|
||||
|
||||
// fn specialize(
|
||||
// _pipeline: &bevy::pbr::MaterialExtensionPipeline,
|
||||
// descriptor: &mut bevy::render::render_resource::RenderPipelineDescriptor,
|
||||
// layout: &bevy::render::mesh::MeshVertexBufferLayout,
|
||||
// _key: bevy::pbr::MaterialExtensionKey<Self>,
|
||||
// ) -> Result<(), bevy::render::render_resource::SpecializedMeshPipelineError> {
|
||||
// let vertex_layout = layout.get_layout(&[
|
||||
// // Mesh::ATTRIBUTE_POSITION.at_shader_location(0),
|
||||
// // Mesh::ATTRIBUTE_UV_0.at_shader_location(1),
|
||||
// // Mesh::ATTRIBUTE_NORMAL.at_shader_location(2),
|
||||
// ATTRIBUTE_PACKED_VERTEX_DATA.at_shader_location(7),
|
||||
// ATTRIBUTE_VERTEX_HEIGHT.at_shader_location(8),
|
||||
// ])?;
|
||||
// descriptor.vertex.buffers = vec![vertex_layout];
|
||||
// Ok(())
|
||||
// }
|
||||
}
|
||||
82
game/main/src/utlis/chunk_utils.rs
Normal file
82
game/main/src/utlis/chunk_utils.rs
Normal file
@@ -0,0 +1,82 @@
|
||||
#[cfg(feature = "tracing")]
|
||||
use bevy::log::*;
|
||||
use bevy::{
|
||||
asset::Assets,
|
||||
ecs::system::Res,
|
||||
math::{IVec2, Vec3},
|
||||
render::mesh::Mesh,
|
||||
};
|
||||
use bevy_rapier3d::geometry::{Collider, TriMeshFlags};
|
||||
use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator};
|
||||
use world_generation::{
|
||||
biome_painter::BiomePainter,
|
||||
generators::{chunk_colliders::generate_chunk_collider, mesh_generator::generate_chunk_mesh},
|
||||
hex_utils::offset_to_world,
|
||||
prelude::{Chunk, Map, MeshChunkData},
|
||||
tile_manager::TileAsset,
|
||||
tile_mapper::TileMapperAsset,
|
||||
};
|
||||
|
||||
pub fn paint_map(
|
||||
map: &mut Map,
|
||||
painter: &BiomePainter,
|
||||
tiles: &Res<Assets<TileAsset>>,
|
||||
mappers: &Res<Assets<TileMapperAsset>>,
|
||||
) {
|
||||
map.chunks.par_iter_mut().for_each(|chunk: &mut Chunk| {
|
||||
paint_chunk(chunk, painter, tiles, mappers);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn paint_chunk(
|
||||
chunk: &mut Chunk,
|
||||
painter: &BiomePainter,
|
||||
tiles: &Res<Assets<TileAsset>>,
|
||||
mappers: &Res<Assets<TileMapperAsset>>,
|
||||
) {
|
||||
for z in 0..Chunk::SIZE {
|
||||
for x in 0..Chunk::SIZE {
|
||||
let idx = x + z * Chunk::SIZE;
|
||||
let height = chunk.heights[idx];
|
||||
let biome_id = chunk.biome_id[idx];
|
||||
let biome = &painter.biomes[biome_id];
|
||||
let mapper = mappers.get(biome.tile_mapper.id());
|
||||
let tile_handle = mapper.unwrap().sample_tile(height);
|
||||
let tile = tiles.get(tile_handle).unwrap();
|
||||
chunk.textures[idx] = [tile.texture_id, tile.side_texture_id];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prepare_chunk_mesh(
|
||||
chunk: &MeshChunkData,
|
||||
chunk_offset: IVec2,
|
||||
chunk_index: usize,
|
||||
) -> (Mesh, (Vec<Vec3>, Vec<[u32; 3]>), Vec3, usize) {
|
||||
#[cfg(feature = "tracing")]
|
||||
let _gen_mesh = info_span!("Generate Chunk").entered();
|
||||
let mesh = generate_chunk_mesh(chunk);
|
||||
let col_data = generate_chunk_collider(chunk);
|
||||
|
||||
return (
|
||||
mesh,
|
||||
col_data,
|
||||
offset_to_world(chunk_offset * Chunk::SIZE as i32, 0.),
|
||||
chunk_index,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn prepare_chunk_mesh_with_collider(
|
||||
chunk: &MeshChunkData,
|
||||
chunk_offset: IVec2,
|
||||
chunk_index: usize,
|
||||
) -> (Mesh, Collider, Vec3, usize) {
|
||||
let (mesh, (col_verts, col_indicies), pos, index) = prepare_chunk_mesh(chunk, chunk_offset, chunk_index);
|
||||
let collider: Collider;
|
||||
{
|
||||
#[cfg(feature = "tracing")]
|
||||
let _collider_span = info_span!("Create Collider Trimesh").entered();
|
||||
collider = Collider::trimesh_with_flags(col_verts, col_indicies, TriMeshFlags::DELETE_DUPLICATE_TRIANGLES);
|
||||
}
|
||||
return (mesh, collider, pos, index);
|
||||
}
|
||||
@@ -1 +1,2 @@
|
||||
pub mod chunk_utils;
|
||||
pub mod render_distance_system;
|
||||
|
||||
@@ -34,7 +34,6 @@ impl Default for RenderDistanceSettings {
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct RenderDistanceVisibility {
|
||||
pub distance_multiplier: f32,
|
||||
pub offset: Vec3,
|
||||
}
|
||||
|
||||
@@ -43,19 +42,11 @@ impl RenderDistanceVisibility {
|
||||
self.offset = offset;
|
||||
return self;
|
||||
}
|
||||
|
||||
pub fn with_multiplier(mut self, distance_multiplier: f32) -> Self {
|
||||
self.distance_multiplier = distance_multiplier;
|
||||
return self;
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RenderDistanceVisibility {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
distance_multiplier: 1.,
|
||||
offset: Vec3::ZERO,
|
||||
}
|
||||
Self { offset: Vec3::ZERO }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +57,7 @@ fn render_distance_system(
|
||||
) {
|
||||
let camera = camera_query.single();
|
||||
for (t, mut vis, r) in objects.iter_mut() {
|
||||
let dist = (camera.translation - (t.translation + r.offset)).length() * r.distance_multiplier;
|
||||
let dist = (camera.translation - (t.translation + r.offset)).length();
|
||||
if settings.render_distance < dist {
|
||||
*vis = Visibility::Hidden;
|
||||
} else {
|
||||
|
||||
14
game/shared/Cargo.toml
Normal file
14
game/shared/Cargo.toml
Normal file
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "shared"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
bevy = "0.14.0"
|
||||
serde = { version = "1.0.204", features = ["derive"] }
|
||||
|
||||
|
||||
[features]
|
||||
tracing = []
|
||||
10
game/shared/src/building.rs
Normal file
10
game/shared/src/building.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct BuildingIdentifier(u32);
|
||||
|
||||
impl From<u32> for BuildingIdentifier {
|
||||
fn from(value: u32) -> Self {
|
||||
return BuildingIdentifier(value);
|
||||
}
|
||||
}
|
||||
47
game/shared/src/despawn.rs
Normal file
47
game/shared/src/despawn.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
use crate::states::MenuState;
|
||||
use bevy::prelude::*;
|
||||
|
||||
pub struct DespawnPuglin;
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct DespawnAt(f32);
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct DespawnAfter(Timer);
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct Despawn;
|
||||
|
||||
impl Plugin for DespawnPuglin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(PostUpdate, despawn_at);
|
||||
app.add_systems(
|
||||
PreUpdate,
|
||||
(despawn, despawn_after).run_if(not(in_state(MenuState::Paused))),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn despawn_at(mut commands: Commands, time: Res<Time>, entities: Query<(Entity, &DespawnAt), Without<DespawnAfter>>) {
|
||||
for (entity, at) in entities.iter() {
|
||||
let d = at.0 - time.elapsed_seconds();
|
||||
commands
|
||||
.entity(entity)
|
||||
.insert(DespawnAfter(Timer::from_seconds(d, TimerMode::Once)));
|
||||
}
|
||||
}
|
||||
|
||||
fn despawn_after(mut commands: Commands, mut entities: Query<(&mut DespawnAfter, Entity)>, time: Res<Time>) {
|
||||
for (mut after, entity) in &mut entities.iter_mut() {
|
||||
after.0.tick(time.delta());
|
||||
if after.0.finished() {
|
||||
commands.entity(entity).despawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn despawn(mut commands: Commands, entities: Query<Entity, With<Despawn>>) {
|
||||
for entity in entities.iter() {
|
||||
commands.entity(entity).despawn();
|
||||
}
|
||||
}
|
||||
5
game/shared/src/lib.rs
Normal file
5
game/shared/src/lib.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
pub mod building;
|
||||
pub mod despawn;
|
||||
pub mod resource;
|
||||
pub mod states;
|
||||
pub mod tags;
|
||||
7
game/shared/src/resource.rs
Normal file
7
game/shared/src/resource.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ResourceIdentifier {
|
||||
pub id: u32,
|
||||
pub qty: u32,
|
||||
}
|
||||
24
game/shared/src/states.rs
Normal file
24
game/shared/src/states.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
#[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum MenuState {
|
||||
Loading,
|
||||
Startup,
|
||||
MainMenu,
|
||||
InGame,
|
||||
Paused,
|
||||
}
|
||||
|
||||
#[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum GameplayState {
|
||||
Waiting,
|
||||
PlaceHQ,
|
||||
Playing,
|
||||
}
|
||||
|
||||
#[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum AssetLoadState {
|
||||
Loading,
|
||||
FinalizeAssets,
|
||||
LoadComplete,
|
||||
}
|
||||
3
game/shared/src/tags.rs
Normal file
3
game/shared/src/tags.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
use bevy::prelude::*;
|
||||
#[derive(Component)]
|
||||
pub struct MainCamera;
|
||||
@@ -1,2 +1,4 @@
|
||||
hard_tabs=true
|
||||
max_width=120
|
||||
hard_tabs = true
|
||||
max_width = 120
|
||||
brace_style = "AlwaysNextLine"
|
||||
control_brace_style = "AlwaysNextLine"
|
||||
Reference in New Issue
Block a user