Compare commits
61 Commits
asset-load
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| cb95db862c | |||
| 5b4e96177c | |||
| 8e2dc04a6f | |||
| 327e4b2739 | |||
| 74450bdcd3 | |||
| 2ad50f7ac8 | |||
| 9800d1fd74 | |||
| 358b88e7fe | |||
| 953650e394 | |||
| 4cfe2d9079 | |||
| 55e9b5d845 | |||
| b14f2ef99f | |||
| ea271c25d0 | |||
| 6caeb6c579 | |||
| fe98627186 | |||
| 576ea96e9b | |||
| ba7b3abc25 | |||
| 4271167752 | |||
| 00468aa18d | |||
| c5a3d1c401 | |||
| c315c206f4 | |||
| 7a30ebc19a | |||
| 3e12fcadbc | |||
| 9120c70b80 | |||
| f2ff8f7bc4 | |||
| b3c44c5351 | |||
| f6f20d8c1b | |||
| 9dd0191ca2 | |||
| 1e981dd1ff | |||
| 280b21298b | |||
| 1d17d0917e | |||
| cc3e43da16 | |||
| b61dacf5e2 | |||
| 3531f9f68f | |||
| 06ffb2bd3e | |||
| 5e7ab32138 | |||
| 5adfbd5de5 | |||
| 47c0732f23 | |||
| 5ad54ca844 | |||
| b156a33a54 | |||
| 805fb3feb6 | |||
| 0c81742f11 | |||
| d58570f646 | |||
| 2d1fb78ab8 | |||
| 9613e3ae0d | |||
| f98173d00a | |||
| 343778a883 | |||
| 1dc6329252 | |||
| 77fa421bb2 | |||
| 25b6ad1099 | |||
| b96b0c5c66 | |||
| a8409e5720 | |||
| 911cf8d5c3 | |||
| f7a3a56a0a | |||
| bde25435ec | |||
| 59090fd3fb | |||
| f337b78bee | |||
| 29f480b8a7 | |||
| b73ef8c0c8 | |||
| 8d2a3b9c81 | |||
| d007aeab7d |
24
.github/workflows/rust.yml
vendored
Normal file
24
.github/workflows/rust.yml
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
name: Rust
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install deps
|
||||
run: sudo apt install libasound2-dev libudev-dev
|
||||
- name: Build
|
||||
run: cargo build
|
||||
- name: Run tests
|
||||
run: cargo test
|
||||
13
.vscode/launch.json
vendored
13
.vscode/launch.json
vendored
@@ -12,14 +12,19 @@
|
||||
"name": "Debug",
|
||||
"program": "${workspaceRoot}/target/debug/phos.exe",
|
||||
"args": [],
|
||||
"cwd": "${workspaceRoot}/target/debug",
|
||||
"cwd": "${workspaceRoot}/game/main",
|
||||
"preLaunchTask": "Build",
|
||||
// "environment": [
|
||||
"environment": [
|
||||
// {
|
||||
// "name": "RUST_BACKTRACE",
|
||||
// "value": "1"
|
||||
// }
|
||||
// ]
|
||||
// },
|
||||
{
|
||||
//Set Asset Folder
|
||||
"name": "CARGO_MANIFEST_DIR",
|
||||
"value": "${workspaceRoot}\\game\\main"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
2388
Cargo.lock
generated
2388
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -5,7 +5,7 @@ members = [
|
||||
"game/buildings",
|
||||
"game/shared",
|
||||
"engine/world_generation",
|
||||
"engine/asset_loader", "game/buildings", "game/shared"]
|
||||
"engine/asset_loader", "game/buildings", "game/shared", "game/units", "engine/data", "game/resources", "engine/asset_loader_proc"]
|
||||
|
||||
# Enable a small amount of optimization in debug mode
|
||||
[profile.dev]
|
||||
|
||||
@@ -3,10 +3,11 @@ name = "asset_loader"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
serde = "1.0.204"
|
||||
serde_json = "1.0.120"
|
||||
bevy = "0.14.0"
|
||||
bevy = "0.15.1"
|
||||
ron = "0.8.1"
|
||||
|
||||
@@ -1,69 +1 @@
|
||||
pub mod macros {
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! create_asset_loader {
|
||||
(
|
||||
$plugin_name: ident,
|
||||
$loader_name: ident,
|
||||
$asset_type: 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, 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>();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct $loader_name;
|
||||
|
||||
impl AssetLoader for $loader_name {
|
||||
type Asset = $asset_type;
|
||||
|
||||
type Settings = ();
|
||||
|
||||
type Error = String;
|
||||
|
||||
async fn load<'a>(
|
||||
&'a self,
|
||||
reader: &'a mut Reader<'_>,
|
||||
_settings: &'a Self::Settings,
|
||||
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]));
|
||||
}
|
||||
)?
|
||||
return Ok(asset);
|
||||
}
|
||||
|
||||
fn extensions(&self) -> &[&str] {
|
||||
$extensions
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
pub mod macros;
|
||||
|
||||
66
engine/asset_loader/src/macros.rs
Normal file
66
engine/asset_loader/src/macros.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
#[macro_export]
|
||||
macro_rules! create_asset_loader {
|
||||
(
|
||||
$plugin_name: ident,
|
||||
$loader_name: ident,
|
||||
$asset_type: 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, 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>();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct $loader_name;
|
||||
|
||||
impl AssetLoader for $loader_name {
|
||||
type Asset = $asset_type;
|
||||
|
||||
type Settings = ();
|
||||
|
||||
type Error = String;
|
||||
|
||||
async fn load(
|
||||
&self,
|
||||
reader: & mut dyn bevy::asset::io::Reader,
|
||||
_: &Self::Settings,
|
||||
load_context: &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]));
|
||||
}
|
||||
)?
|
||||
return Ok(asset);
|
||||
}
|
||||
|
||||
fn extensions(&self) -> &[&str] {
|
||||
$extensions
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
13
engine/asset_loader_proc/Cargo.toml
Normal file
13
engine/asset_loader_proc/Cargo.toml
Normal file
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "asset_loader_proc"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
serde = "1.0.204"
|
||||
serde_json = "1.0.120"
|
||||
bevy = "0.15.1"
|
||||
ron = "0.8.1"
|
||||
1
engine/asset_loader_proc/src/lib.rs
Normal file
1
engine/asset_loader_proc/src/lib.rs
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
6
engine/data/Cargo.toml
Normal file
6
engine/data/Cargo.toml
Normal file
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "data"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
1
engine/data/src/lib.rs
Normal file
1
engine/data/src/lib.rs
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
0
engine/data/src/spacial-grid.rs
Normal file
0
engine/data/src/spacial-grid.rs
Normal file
@@ -6,18 +6,20 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
bevy = "0.14.0"
|
||||
bevy = "0.15.1"
|
||||
noise = "0.9.0"
|
||||
serde = { version = "1.0.203", features = ["derive"] }
|
||||
serde_json = "1.0.115"
|
||||
asset_loader = { path = "../asset_loader" }
|
||||
rayon = "1.10.0"
|
||||
bevy-inspector-egui = "0.25.0"
|
||||
bevy_asset_loader = { version = "0.21.0", features = [
|
||||
bevy-inspector-egui = "0.28.1"
|
||||
bevy_asset_loader = { version = "0.22.0", features = [
|
||||
"standard_dynamic_assets",
|
||||
"3d",
|
||||
] }
|
||||
ron = "0.8.1"
|
||||
image = "0.25.2"
|
||||
num = "0.4.3"
|
||||
|
||||
[features]
|
||||
tracing = ["bevy/trace_tracy"]
|
||||
|
||||
@@ -38,7 +38,7 @@ impl BiomePainterAsset {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct BiomePainter {
|
||||
pub biomes: Vec<BiomeAsset>,
|
||||
}
|
||||
|
||||
@@ -16,6 +16,21 @@ pub const HEX_CORNERS: [Vec3; 6] = [
|
||||
Vec3::new(-INNER_RADIUS, 0., 0.5 * OUTER_RADIUS),
|
||||
];
|
||||
|
||||
pub const WATER_HEX_CORNERS: [Vec3; 12] = [
|
||||
Vec3::new(0., 0., OUTER_RADIUS),
|
||||
Vec3::new(INNER_RADIUS / 2.0, 0., 0.75 * OUTER_RADIUS),
|
||||
Vec3::new(INNER_RADIUS, 0., 0.5 * OUTER_RADIUS),
|
||||
Vec3::new(INNER_RADIUS, 0., 0.),
|
||||
Vec3::new(INNER_RADIUS, 0., -0.5 * OUTER_RADIUS),
|
||||
Vec3::new(INNER_RADIUS / 2.0, 0., -0.75 * OUTER_RADIUS),
|
||||
Vec3::new(0., 0., -OUTER_RADIUS),
|
||||
Vec3::new(-INNER_RADIUS / 2.0, 0., -0.75 * OUTER_RADIUS),
|
||||
Vec3::new(-INNER_RADIUS, 0., -0.5 * OUTER_RADIUS),
|
||||
Vec3::new(-INNER_RADIUS, 0., 0.),
|
||||
Vec3::new(-INNER_RADIUS, 0., 0.5 * OUTER_RADIUS),
|
||||
Vec3::new(-INNER_RADIUS / 2.0, 0., 0.75 * OUTER_RADIUS),
|
||||
];
|
||||
|
||||
pub const HEX_NORMALS: [Vec3; 6] = [
|
||||
Vec3::new(INNER_RADIUS / 2., 0., (OUTER_RADIUS + 0.5 * OUTER_RADIUS) / 2.),
|
||||
Vec3::Z,
|
||||
@@ -26,9 +41,9 @@ pub const HEX_NORMALS: [Vec3; 6] = [
|
||||
];
|
||||
|
||||
pub const ATTRIBUTE_PACKED_VERTEX_DATA: MeshVertexAttribute =
|
||||
MeshVertexAttribute::new("PackedVertexData", 988540817, VertexFormat::Uint32);
|
||||
MeshVertexAttribute::new("PackedVertexData", 7, VertexFormat::Uint32);
|
||||
pub const ATTRIBUTE_VERTEX_HEIGHT: MeshVertexAttribute =
|
||||
MeshVertexAttribute::new("VertexHeight", 988540717, VertexFormat::Float32);
|
||||
MeshVertexAttribute::new("VertexHeight", 8, VertexFormat::Float32);
|
||||
|
||||
pub const ATTRIBUTE_TEXTURE_INDEX: MeshVertexAttribute =
|
||||
MeshVertexAttribute::new("TextureIndex", 988540917, VertexFormat::Uint32);
|
||||
|
||||
@@ -31,7 +31,7 @@ fn create_tile_collider(pos: Vec3, verts: &mut Vec<Vec3>, indices: &mut Vec<[u32
|
||||
verts.push(p);
|
||||
}
|
||||
|
||||
//Top Surfave
|
||||
//Top Surface
|
||||
indices.push([idx, idx + 1, idx + 5]);
|
||||
indices.push([idx + 1, idx + 2, idx + 5]);
|
||||
indices.push([idx + 2, idx + 4, idx + 5]);
|
||||
@@ -54,7 +54,7 @@ fn create_tile_collider(pos: Vec3, verts: &mut Vec<Vec3>, indices: &mut Vec<[u32
|
||||
fn create_tile_wall_collider(idx: u32, pos: Vec3, dir: usize, verts: &mut Vec<Vec3>, indices: &mut Vec<[u32; 3]>) {
|
||||
let idx2 = verts.len() as u32;
|
||||
|
||||
verts.push(pos + HEX_CORNERS[dir]);
|
||||
verts.push(pos + HEX_CORNERS[(dir) % 6]);
|
||||
verts.push(pos + HEX_CORNERS[(dir + 1) % 6]);
|
||||
|
||||
let off = dir as u32;
|
||||
|
||||
@@ -94,6 +94,148 @@ fn create_tile(
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_chunk_water_mesh(chunk: &MeshChunkData, sealevel: f32, map_width: usize, map_height: usize) -> Mesh {
|
||||
#[cfg(feature = "tracing")]
|
||||
let _gen_mesh = info_span!("Generate Water Surface Mesh").entered();
|
||||
let vertex_count: usize = Chunk::SIZE * Chunk::SIZE * 7;
|
||||
let mut verts = Vec::with_capacity(vertex_count);
|
||||
let mut uvs = Vec::with_capacity(vertex_count);
|
||||
let mut indices = Vec::with_capacity(vertex_count);
|
||||
let mut normals = Vec::with_capacity(vertex_count);
|
||||
|
||||
for z in 0..Chunk::SIZE {
|
||||
for x in 0..Chunk::SIZE {
|
||||
let idx = x + z * Chunk::SIZE;
|
||||
let height = chunk.heights[idx];
|
||||
if height > sealevel {
|
||||
continue;
|
||||
}
|
||||
let off_pos = Vec3::new(x as f32, sealevel, z as f32);
|
||||
let tile_pos = offset3d_to_world(off_pos);
|
||||
let coord = HexCoord::from_grid_pos(x, z);
|
||||
let (n, neighbor_has_land) = chunk.get_neighbors_with_water_info(&coord);
|
||||
|
||||
create_tile_water_surface(
|
||||
tile_pos,
|
||||
chunk.distance_to_land[idx],
|
||||
&n,
|
||||
neighbor_has_land,
|
||||
&mut verts,
|
||||
&mut uvs,
|
||||
&mut indices,
|
||||
&mut normals,
|
||||
);
|
||||
}
|
||||
}
|
||||
let mesh = Mesh::new(
|
||||
PrimitiveTopology::TriangleList,
|
||||
RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD,
|
||||
)
|
||||
.with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, verts)
|
||||
.with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
|
||||
.with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
|
||||
.with_inserted_indices(Indices::U32(indices));
|
||||
return mesh;
|
||||
}
|
||||
|
||||
fn create_tile_water_surface(
|
||||
pos: Vec3,
|
||||
dist_to_land: f32,
|
||||
neighbors: &[(f32, Option<f32>); 6],
|
||||
neighbor_has_land: bool,
|
||||
verts: &mut Vec<Vec3>,
|
||||
uvs: &mut Vec<Vec2>,
|
||||
indices: &mut Vec<u32>,
|
||||
normals: &mut Vec<Vec3>,
|
||||
) {
|
||||
if !neighbor_has_land {
|
||||
crate_tile_water_inner_surface(pos, dist_to_land, neighbors, verts, uvs, indices, normals);
|
||||
return;
|
||||
}
|
||||
crate_tile_water_shore_surface(pos, dist_to_land, neighbors, verts, uvs, indices, normals);
|
||||
}
|
||||
|
||||
fn crate_tile_water_inner_surface(
|
||||
pos: Vec3,
|
||||
dist_to_land: f32,
|
||||
neighbors: &[(f32, Option<f32>); 6],
|
||||
verts: &mut Vec<Vec3>,
|
||||
uvs: &mut Vec<Vec2>,
|
||||
indices: &mut Vec<u32>,
|
||||
normals: &mut Vec<Vec3>,
|
||||
) {
|
||||
//todo: share verts
|
||||
let idx = verts.len() as u32;
|
||||
for i in 0..6 {
|
||||
let p = pos + HEX_CORNERS[i];
|
||||
verts.push(p);
|
||||
let n1 = if let Some(v) = neighbors[i].1 { v } else { dist_to_land };
|
||||
let n2 = if let Some(v) = neighbors[(i + 5) % 6].1 {
|
||||
v
|
||||
} else {
|
||||
dist_to_land
|
||||
};
|
||||
let d = (n1 + n2 + dist_to_land) / 3.0;
|
||||
uvs.push(Vec2::new(0.0, d.remap(0., 4., 1.0, 0.0)));
|
||||
normals.push(Vec3::Y);
|
||||
}
|
||||
for i in 0..3 {
|
||||
let off = i * 2;
|
||||
indices.push(off + idx);
|
||||
indices.push(((off + 1) % 6) + idx);
|
||||
indices.push(((off + 2) % 6) + idx);
|
||||
}
|
||||
indices.push(idx);
|
||||
indices.push(idx + 2);
|
||||
indices.push(idx + 4);
|
||||
}
|
||||
|
||||
fn crate_tile_water_shore_surface(
|
||||
pos: Vec3,
|
||||
dist_to_land: f32,
|
||||
neighbors: &[(f32, Option<f32>); 6],
|
||||
verts: &mut Vec<Vec3>,
|
||||
uvs: &mut Vec<Vec2>,
|
||||
indices: &mut Vec<u32>,
|
||||
normals: &mut Vec<Vec3>,
|
||||
) {
|
||||
let idx = verts.len() as u32;
|
||||
//todo: only use triangle fan when on shoreline
|
||||
verts.push(pos);
|
||||
uvs.push(Vec2::new(0.0, dist_to_land.remap(0., 4., 1.0, 0.0)));
|
||||
normals.push(Vec3::Y);
|
||||
for i in 0..12 {
|
||||
let p = pos + WATER_HEX_CORNERS[i];
|
||||
verts.push(p);
|
||||
let ni = i / 2;
|
||||
let n = neighbors[ni];
|
||||
let nn = neighbors[(ni + 5) % 6];
|
||||
let mut uv = Vec2::new(0.0, dist_to_land.remap(0., 4., 1.0, 0.0));
|
||||
|
||||
if nn.0 > pos.y || n.0 > pos.y {
|
||||
uv.x = 1.0;
|
||||
}
|
||||
if ni * 2 != i {
|
||||
if n.0 <= pos.y {
|
||||
uv.x = 0.0;
|
||||
}
|
||||
let d = if let Some(v) = n.1 { v } else { dist_to_land };
|
||||
uv.y = ((d + dist_to_land) / 2.0).remap(0., 4., 1.0, 0.0);
|
||||
} else {
|
||||
let d = if let Some(v) = n.1 { v } else { dist_to_land };
|
||||
let d2 = if let Some(v) = nn.1 { v } else { dist_to_land };
|
||||
uv.y = ((d + d2 + dist_to_land) / 3.0).remap(0., 4., 1.0, 0.0);
|
||||
}
|
||||
|
||||
indices.push(idx);
|
||||
indices.push(idx + 1 + i as u32);
|
||||
indices.push(idx + 1 + ((i as u32 + 1) % 12));
|
||||
|
||||
uvs.push(uv);
|
||||
normals.push(Vec3::Y);
|
||||
}
|
||||
}
|
||||
|
||||
fn create_tile_wall(
|
||||
pos: Vec3,
|
||||
dir: usize,
|
||||
@@ -135,3 +277,60 @@ fn create_tile_wall(
|
||||
uvs.push((Vec2::new(0., pos.y - height) / TEX_MULTI) + tex_off);
|
||||
uvs.push((Vec2::new(1., pos.y - height) / TEX_MULTI) + tex_off);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn generate_tile_wall() {
|
||||
let mut verts = Vec::new();
|
||||
let mut uvs = Vec::new();
|
||||
let mut normals = Vec::new();
|
||||
let mut indices = Vec::new();
|
||||
|
||||
create_tile_wall(
|
||||
Vec3::ZERO,
|
||||
3,
|
||||
5.0,
|
||||
&mut verts,
|
||||
&mut uvs,
|
||||
&mut indices,
|
||||
&mut normals,
|
||||
Vec2::new(3.0, 0.0),
|
||||
);
|
||||
|
||||
assert!(verts.len() == 4, "Number of verts don't match");
|
||||
assert!(uvs.len() == 4, "Number of uvs don't match");
|
||||
assert!(normals.len() == 4, "Number of normals don't match");
|
||||
assert!(indices.len() == 6, "Number of normals don't match");
|
||||
|
||||
let index = uvs[0].x.floor();
|
||||
assert!(index == 3.0, "Texture Index could not be decoded");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generate_tile() {
|
||||
let mut verts = Vec::new();
|
||||
let mut uvs = Vec::new();
|
||||
let mut normals = Vec::new();
|
||||
let mut indices = Vec::new();
|
||||
|
||||
//4 side faces
|
||||
let nbors = [2.0, 2.0, 0.0, 0.0, 0.0, 0.0];
|
||||
|
||||
create_tile(Vec3::Y, &nbors, &mut verts, &mut uvs, &mut indices, &mut normals, 3, 7);
|
||||
|
||||
assert!(verts.len() == (6 + 4 * 4), "Number of verts don't match");
|
||||
assert!(uvs.len() == (6 + 4 * 4), "Number of uvs don't match");
|
||||
assert!(normals.len() == (6 + 4 * 4), "Number of normals don't match");
|
||||
//12 tris for surface, 6 tris per side
|
||||
assert!(indices.len() == (12 + 4 * 6), "Number of indicies don't match");
|
||||
|
||||
let top_index = uvs[0].x.floor();
|
||||
assert!(top_index == 3.0, "Top Texture Index could not be decoded");
|
||||
let side_index = uvs[6].x.floor();
|
||||
assert!(side_index == 7.0, "Top Texture Index could not be decoded");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
use crate::hex_utils::HexCoord;
|
||||
use crate::hex_utils::{offset3d_to_world, 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::{
|
||||
@@ -11,14 +8,7 @@ use bevy::{
|
||||
},
|
||||
};
|
||||
|
||||
pub fn generate_packed_chunk_mesh(
|
||||
chunk: &Chunk,
|
||||
map: &Map,
|
||||
painter: &BiomePainterAsset,
|
||||
tiles: &Res<Assets<TileAsset>>,
|
||||
biomes: &Res<Assets<BiomeAsset>>,
|
||||
mappers: &Res<Assets<TileMapperAsset>>,
|
||||
) -> Mesh {
|
||||
pub fn generate_packed_chunk_mesh(chunk: &MeshChunkData) -> Mesh {
|
||||
let vertex_count: usize = Chunk::SIZE * Chunk::SIZE * 6;
|
||||
let mut packed_data = Vec::with_capacity(vertex_count);
|
||||
let mut indices = Vec::with_capacity(vertex_count);
|
||||
@@ -26,16 +16,10 @@ 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 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 = 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();
|
||||
let idx = x + z * Chunk::SIZE;
|
||||
let height = chunk.heights[idx];
|
||||
let coord = HexCoord::from_grid_pos(x, z);
|
||||
let n = chunk.get_neighbors(&coord);
|
||||
|
||||
create_packed_tile(
|
||||
UVec2::new(x as u32, z as u32),
|
||||
@@ -44,8 +28,8 @@ pub fn generate_packed_chunk_mesh(
|
||||
&mut packed_data,
|
||||
&mut indices,
|
||||
&mut heights,
|
||||
tile.texture_id,
|
||||
tile.side_texture_id,
|
||||
chunk.textures[idx][0],
|
||||
chunk.textures[idx][1],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -63,7 +47,7 @@ pub fn generate_packed_chunk_mesh(
|
||||
fn create_packed_tile(
|
||||
offset: UVec2,
|
||||
height: f32,
|
||||
neighbors: &[Option<f32>; 6],
|
||||
neighbors: &[f32; 6],
|
||||
packed_data: &mut Vec<u32>,
|
||||
indices: &mut Vec<u32>,
|
||||
heights: &mut Vec<f32>,
|
||||
@@ -83,9 +67,7 @@ fn create_packed_tile(
|
||||
}
|
||||
|
||||
for i in 0..neighbors.len() {
|
||||
let cur_n = neighbors[i];
|
||||
match cur_n {
|
||||
Some(n_height) => {
|
||||
let n_height = neighbors[i];
|
||||
if n_height < height {
|
||||
create_packed_tile_wall(
|
||||
offset,
|
||||
@@ -99,9 +81,6 @@ fn create_packed_tile(
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn create_packed_tile_wall(
|
||||
|
||||
@@ -1,31 +1,51 @@
|
||||
use core::f32;
|
||||
|
||||
use bevy::math::{IVec2, UVec2};
|
||||
use bevy::prelude::{FloatExt, Vec2};
|
||||
use bevy::utils::default;
|
||||
use noise::{NoiseFn, SuperSimplex};
|
||||
use noise::{NoiseFn, Simplex, 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, painter: &BiomePainter) -> Map {
|
||||
let biomes = &generate_biomes(cfg, seed, painter);
|
||||
pub fn generate_heightmap(cfg: &GenerationConfig, seed: u32, painter: &BiomePainter) -> (Map, BiomeMap) {
|
||||
let biomes = generate_biomes(cfg, seed, painter);
|
||||
let biomes_borrow = &biomes;
|
||||
// let mut chunks: Vec<Chunk> = Vec::with_capacity(cfg.size.length_squared() as usize);
|
||||
let chunks = (0..cfg.size.y)
|
||||
let chunks: Vec<Chunk> = (0..cfg.size.y)
|
||||
.into_par_iter()
|
||||
.flat_map(|z| {
|
||||
(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];
|
||||
let biome_chunk = &biomes_borrow.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 {
|
||||
let mut min = f32::MAX;
|
||||
let mut max = f32::MIN;
|
||||
for chunk in &chunks {
|
||||
if chunk.min_level < min {
|
||||
min = chunk.min_level;
|
||||
}
|
||||
if chunk.max_level > max {
|
||||
max = chunk.max_level;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
Map {
|
||||
chunks,
|
||||
height: cfg.size.y as usize,
|
||||
width: cfg.size.x as usize,
|
||||
sea_level: cfg.sea_level as f32,
|
||||
};
|
||||
sealevel: cfg.sea_level as f32,
|
||||
min_level: min,
|
||||
max_level: max,
|
||||
biome_count: painter.biomes.len(),
|
||||
},
|
||||
biomes,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn generate_biomes(cfg: &GenerationConfig, seed: u32, biome_painter: &BiomePainter) -> BiomeMap {
|
||||
@@ -54,9 +74,9 @@ pub fn generate_biome_chunk(
|
||||
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);
|
||||
let noise_m = Simplex::new(seed + 1);
|
||||
let noise_t = Simplex::new(seed + 2);
|
||||
let noise_c = Simplex::new(seed + 3);
|
||||
|
||||
for z in 0..Chunk::SIZE {
|
||||
for x in 0..Chunk::SIZE {
|
||||
@@ -67,6 +87,7 @@ pub fn generate_biome_chunk(
|
||||
&noise_m,
|
||||
cfg.size.as_vec2(),
|
||||
cfg.border_size,
|
||||
100.0,
|
||||
);
|
||||
let temperature = sample_point(
|
||||
x as f64 + chunk_x as f64 * Chunk::SIZE as f64,
|
||||
@@ -75,6 +96,7 @@ pub fn generate_biome_chunk(
|
||||
&noise_t,
|
||||
cfg.size.as_vec2(),
|
||||
cfg.border_size,
|
||||
50.0,
|
||||
);
|
||||
let continentality = sample_point(
|
||||
x as f64 + chunk_x as f64 * Chunk::SIZE as f64,
|
||||
@@ -83,6 +105,7 @@ pub fn generate_biome_chunk(
|
||||
&noise_c,
|
||||
cfg.size.as_vec2(),
|
||||
cfg.border_size,
|
||||
0.0,
|
||||
);
|
||||
let data = BiomeData {
|
||||
moisture: moisture.clamp(0., 100.),
|
||||
@@ -100,6 +123,30 @@ pub fn generate_biome_chunk(
|
||||
return chunk;
|
||||
}
|
||||
|
||||
pub fn generate_noise_map(size: UVec2, seed: u32, cfg: &NoiseConfig, border_size: f32) -> Vec<f32> {
|
||||
let noise = SuperSimplex::new(seed);
|
||||
|
||||
let data: Vec<_> = (0..(size.y as usize * Chunk::SIZE))
|
||||
.into_par_iter()
|
||||
.flat_map(|y| {
|
||||
let mut row = Vec::with_capacity(size.x as usize * Chunk::SIZE);
|
||||
for x in 0..row.capacity() {
|
||||
row.push(sample_point(
|
||||
x as f64,
|
||||
y as f64,
|
||||
cfg,
|
||||
&noise,
|
||||
size.as_vec2(),
|
||||
border_size,
|
||||
0.0,
|
||||
));
|
||||
}
|
||||
return row;
|
||||
})
|
||||
.collect();
|
||||
return data;
|
||||
}
|
||||
|
||||
pub fn generate_chunk(
|
||||
chunk_x: u32,
|
||||
chunk_z: u32,
|
||||
@@ -111,7 +158,9 @@ pub fn generate_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);
|
||||
let noise = Simplex::new(seed);
|
||||
let mut min = f32::MAX;
|
||||
let mut max = f32::MIN;
|
||||
for z in 0..Chunk::SIZE {
|
||||
for x in 0..Chunk::SIZE {
|
||||
let biome_data = biome_chunk.get_biome_data(x, z);
|
||||
@@ -130,29 +179,44 @@ pub fn generate_chunk(
|
||||
&noise,
|
||||
cfg.size.as_vec2(),
|
||||
cfg.border_size,
|
||||
0.0,
|
||||
) * 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;
|
||||
if sample > max {
|
||||
max = sample;
|
||||
}
|
||||
if sample < min {
|
||||
min = sample;
|
||||
}
|
||||
data[idx] = biome_data.clone();
|
||||
}
|
||||
}
|
||||
return Chunk {
|
||||
heights: result,
|
||||
biome_data: data,
|
||||
biome_id: biome_ids,
|
||||
chunk_offset: IVec2::new(chunk_x as i32, chunk_z as i32),
|
||||
max_level: max,
|
||||
min_level: min,
|
||||
..default()
|
||||
};
|
||||
}
|
||||
|
||||
fn sample_point(x: f64, z: f64, cfg: &NoiseConfig, noise: &impl NoiseFn<f64, 2>, size: Vec2, border_size: f32) -> f32 {
|
||||
fn sample_point(
|
||||
x: f64,
|
||||
z: f64,
|
||||
cfg: &NoiseConfig,
|
||||
noise: &impl NoiseFn<f64, 2>,
|
||||
size: Vec2,
|
||||
border_size: f32,
|
||||
border_value: 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.;
|
||||
for i in 0..cfg.layers.len() {
|
||||
let value: f64;
|
||||
let layer = &cfg.layers[i];
|
||||
@@ -161,14 +225,11 @@ fn sample_point(x: f64, z: f64, cfg: &NoiseConfig, noise: &impl NoiseFn<f64, 2>,
|
||||
} else {
|
||||
value = sample_simple(x_s, z_s, layer, noise);
|
||||
}
|
||||
if i == 0 {
|
||||
first_layer = value;
|
||||
}
|
||||
if layer.first_layer_mask {
|
||||
elevation += mask(first_layer, value);
|
||||
} else {
|
||||
elevation += value;
|
||||
}
|
||||
|
||||
if border_size == 0.0 {
|
||||
return elevation as f32;
|
||||
}
|
||||
|
||||
let outer = size * Chunk::SIZE as f32;
|
||||
@@ -179,11 +240,7 @@ fn sample_point(x: f64, z: f64, cfg: &NoiseConfig, noise: &impl NoiseFn<f64, 2>,
|
||||
let d2 = od.x.min(od.y);
|
||||
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) -> f64 {
|
||||
return value * mask;
|
||||
return border_value.lerp(elevation as f32, d);
|
||||
}
|
||||
|
||||
fn sample_simple(x: f64, z: f64, cfg: &GeneratorLayer, noise: &impl NoiseFn<f64, 2>) -> f64 {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
use crate::prelude::Chunk;
|
||||
use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -53,15 +55,21 @@ pub fn tile_to_world_distance(dist: u32) -> f32 {
|
||||
return dist as f32 * (2. * INNER_RADIUS);
|
||||
}
|
||||
|
||||
pub fn get_tile_count(radius: usize) -> usize {
|
||||
pub fn get_tile_count_in_range(radius: usize) -> usize {
|
||||
return 1 + 3 * (radius + 1) * radius;
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Default, Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize, Hash)]
|
||||
pub struct HexCoord {
|
||||
pub hex: IVec3,
|
||||
}
|
||||
|
||||
impl Display for HexCoord {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!("HexCoord{}", self.hex))
|
||||
}
|
||||
}
|
||||
|
||||
impl HexCoord {
|
||||
pub const DIRECTIONS: [IVec3; 6] = [
|
||||
IVec3::new(0, 1, -1),
|
||||
@@ -136,6 +144,7 @@ impl HexCoord {
|
||||
};
|
||||
}
|
||||
|
||||
/// Converts this coordinate to it's chunk local equivalent
|
||||
pub fn to_chunk(&self) -> HexCoord {
|
||||
let c_pos = self.to_chunk_pos();
|
||||
let off = self.to_offset();
|
||||
@@ -156,14 +165,20 @@ impl HexCoord {
|
||||
return IVec2::new(self.hex.x + (self.hex.y / 2), self.hex.y);
|
||||
}
|
||||
|
||||
/// Convert the current coordiante to an index
|
||||
pub fn to_index(&self, width: usize) -> usize {
|
||||
return ((self.hex.x + self.hex.y * width as i32) + (self.hex.y / 2)) as usize;
|
||||
}
|
||||
|
||||
/// Gets the index of this coord in the chunk array.
|
||||
///
|
||||
/// [`width`] is in number of chunks
|
||||
pub fn to_chunk_index(&self, width: usize) -> usize {
|
||||
let pos = self.to_chunk_pos();
|
||||
return (pos.x + pos.y * width as i32) as usize;
|
||||
}
|
||||
|
||||
/// Gets the index of this tile in the chunk
|
||||
pub fn to_chunk_local_index(&self) -> usize {
|
||||
return self.to_chunk().to_index(Chunk::SIZE);
|
||||
}
|
||||
@@ -224,7 +239,7 @@ impl HexCoord {
|
||||
|
||||
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));
|
||||
let mut result = Vec::with_capacity(get_tile_count_in_range(radius));
|
||||
|
||||
if include_center {
|
||||
result.push(*self);
|
||||
@@ -243,16 +258,47 @@ impl HexCoord {
|
||||
return result;
|
||||
}
|
||||
|
||||
pub fn hex_select_bounded(
|
||||
&self,
|
||||
radius: usize,
|
||||
include_center: bool,
|
||||
height: usize,
|
||||
width: usize,
|
||||
) -> Vec<HexCoord> {
|
||||
assert!(radius != 0, "Radius cannot be zero");
|
||||
let mut result = Vec::with_capacity(get_tile_count_in_range(radius));
|
||||
|
||||
if include_center {
|
||||
if self.is_in_bounds(height, width) {
|
||||
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);
|
||||
if p.is_in_bounds(height, width) {
|
||||
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;
|
||||
}
|
||||
// if radius == 1 {
|
||||
// result.push(*self);
|
||||
// return result;
|
||||
// }
|
||||
|
||||
for i in 0..6 {
|
||||
for _j in 0..radius {
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
use bevy::math::{UVec2, Vec3};
|
||||
use bevy::{
|
||||
math::{UVec2, Vec3},
|
||||
prelude::Resource,
|
||||
};
|
||||
use noise::NoiseFn;
|
||||
use rayon::iter::{IntoParallelIterator, ParallelIterator};
|
||||
|
||||
use super::chunk::Chunk;
|
||||
|
||||
#[derive(Clone, Resource)]
|
||||
pub struct BiomeMap {
|
||||
pub height: usize,
|
||||
pub width: usize,
|
||||
@@ -130,6 +134,15 @@ impl BiomeMap {
|
||||
return chunk.get_biome_id(x - (cx * Chunk::SIZE), y - (cy * Chunk::SIZE));
|
||||
}
|
||||
|
||||
pub fn get_biome_id_dithered(&self, x: usize, y: usize, noise: &impl NoiseFn<f64, 2>, scale: f64) -> 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_dithered(x - (cx * Chunk::SIZE), y - (cy * Chunk::SIZE), noise, scale);
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -149,7 +162,7 @@ pub struct BiomeChunk {
|
||||
|
||||
impl BiomeChunk {
|
||||
pub fn get_biome(&self, x: usize, y: usize) -> &Vec<f32> {
|
||||
return &self.tiles[x as usize + y as usize * Chunk::SIZE];
|
||||
return &self.tiles[x + y * Chunk::SIZE];
|
||||
}
|
||||
|
||||
pub fn get_biome_data(&self, x: usize, y: usize) -> &BiomeData {
|
||||
@@ -171,16 +184,18 @@ impl BiomeChunk {
|
||||
}
|
||||
|
||||
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 mut 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];
|
||||
let n = (noise.get([x as f64 / scale, y as f64 / scale]) as f32 - 0.5)/ 2.0;
|
||||
let mut max = b[cur_id] + n;
|
||||
for i in 0..b.len() {
|
||||
let blend = b[i];
|
||||
if blend == 0. {
|
||||
continue;
|
||||
}
|
||||
if n < blend {
|
||||
return i;
|
||||
if blend > max {
|
||||
max = blend + n;
|
||||
cur_id = i;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
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_data: [BiomeData; Chunk::AREA],
|
||||
pub biome_id: [usize; Chunk::AREA],
|
||||
pub chunk_offset: IVec2,
|
||||
pub min_level: f32,
|
||||
pub max_level: f32,
|
||||
}
|
||||
|
||||
impl Default for Chunk {
|
||||
@@ -17,9 +18,11 @@ impl Default for Chunk {
|
||||
Self {
|
||||
heights: [0.; Chunk::AREA],
|
||||
textures: [[0; 2]; Chunk::AREA],
|
||||
biome_data: [BiomeData::default(); Chunk::AREA],
|
||||
// biome_data: [BiomeData::default(); Chunk::AREA],
|
||||
biome_id: [0; Chunk::AREA],
|
||||
chunk_offset: Default::default(),
|
||||
min_level: 0.0,
|
||||
max_level: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::chunk::Chunk;
|
||||
|
||||
#[derive(Resource, Reflect, Default)]
|
||||
#[derive(Resource, Reflect, Default, Clone)]
|
||||
#[reflect(Resource)]
|
||||
pub struct GenerationConfig {
|
||||
pub sea_level: f64,
|
||||
@@ -43,5 +43,4 @@ pub struct GeneratorLayer {
|
||||
pub weight: f64,
|
||||
pub weight_multi: f64,
|
||||
pub layers: usize,
|
||||
pub first_layer_mask: bool,
|
||||
}
|
||||
|
||||
@@ -2,28 +2,86 @@ use bevy::prelude::*;
|
||||
|
||||
use crate::hex_utils::*;
|
||||
|
||||
use super::{chunk::Chunk, mesh_chunk::MeshChunkData};
|
||||
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,
|
||||
pub sealevel: f32,
|
||||
pub min_level: f32,
|
||||
pub max_level: f32,
|
||||
pub biome_count: usize,
|
||||
}
|
||||
|
||||
impl Map {
|
||||
pub fn get_tile_count(&self) -> usize {
|
||||
return self.get_tile_width() * self.get_tile_height();
|
||||
}
|
||||
|
||||
pub fn get_tile_width(&self) -> usize {
|
||||
return self.width * Chunk::SIZE;
|
||||
}
|
||||
|
||||
pub fn get_tile_height(&self) -> usize {
|
||||
return self.height * Chunk::SIZE;
|
||||
}
|
||||
|
||||
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 {
|
||||
min_height: self.min_level,
|
||||
sealevel: self.sealevel,
|
||||
heights: chunk.heights.clone(),
|
||||
textures: chunk.textures.clone(),
|
||||
distance_to_land: self.get_distance_from_land(chunk.chunk_offset, 4),
|
||||
};
|
||||
}
|
||||
|
||||
fn get_distance_from_land(&self, chunk_offset: IVec2, range: usize) -> [f32; Chunk::AREA] {
|
||||
#[cfg(feature = "tracing")]
|
||||
let _spawn_span = info_span!("Chunk Land Dist Data").entered();
|
||||
let mut dists = [0.0; Chunk::AREA];
|
||||
let cx = chunk_offset.x as usize * Chunk::SIZE;
|
||||
let cz = chunk_offset.y as usize * Chunk::SIZE;
|
||||
for z in 0..Chunk::SIZE {
|
||||
for x in 0..Chunk::SIZE {
|
||||
let coord = HexCoord::from_grid_pos(x + cx, z + cz);
|
||||
let index = coord.to_chunk_local_index();
|
||||
|
||||
if !self.is_in_bounds(&coord) {
|
||||
warn!("Coord is not in bounds!?");
|
||||
}
|
||||
|
||||
//Current tile is land tile
|
||||
if self.sample_height(&coord) > self.sealevel {
|
||||
dists[index] = 0.0;
|
||||
continue;
|
||||
}
|
||||
|
||||
//Find closest land tile
|
||||
if let Some(d) = self.hex_select_first(&coord, range, false, |_t, h, r| {
|
||||
if h > self.sealevel {
|
||||
return Some(r as f32);
|
||||
}
|
||||
return None;
|
||||
}) {
|
||||
dists[index] = d;
|
||||
} else {
|
||||
dists[index] = range as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
return dists;
|
||||
}
|
||||
|
||||
pub fn get_neighbors(&self, pos: &HexCoord) -> [Option<f32>; 6] {
|
||||
let mut results: [Option<f32>; 6] = [None; 6];
|
||||
let w = self.width * Chunk::SIZE;
|
||||
@@ -43,11 +101,21 @@ impl Map {
|
||||
}
|
||||
|
||||
pub fn sample_height(&self, pos: &HexCoord) -> f32 {
|
||||
assert!(
|
||||
self.is_in_bounds(pos),
|
||||
"The provided coordinate is not within the map bounds"
|
||||
);
|
||||
|
||||
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 {
|
||||
assert!(
|
||||
self.is_in_bounds(pos),
|
||||
"The provided coordinate is not within the map bounds"
|
||||
);
|
||||
|
||||
let chunk = &mut self.chunks[pos.to_chunk_index(self.width)];
|
||||
return &mut chunk.heights[pos.to_chunk_local_index()];
|
||||
}
|
||||
@@ -56,20 +124,28 @@ impl Map {
|
||||
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_biome_id(&self, pos: &HexCoord) -> usize {
|
||||
assert!(
|
||||
self.is_in_bounds(pos),
|
||||
"The provided coordinate is not within the map bounds"
|
||||
);
|
||||
|
||||
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;
|
||||
return chunk.biome_id[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.);
|
||||
return Vec3::new(w / 2., self.sealevel, h / 2.);
|
||||
}
|
||||
|
||||
pub fn get_center_with_height(&self) -> Vec3 {
|
||||
let w = self.get_world_width();
|
||||
let h = self.get_world_height();
|
||||
let mut pos = Vec3::new(w / 2., self.sealevel, h / 2.);
|
||||
pos.y = self.sample_height(&HexCoord::from_world_pos(pos));
|
||||
return pos;
|
||||
}
|
||||
|
||||
pub fn get_world_width(&self) -> f32 {
|
||||
@@ -87,22 +163,19 @@ impl Map {
|
||||
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> {
|
||||
pub fn create_crater(&mut self, pos: &HexCoord, radius: usize, depth: f32) -> Vec<(HexCoord, f32)> {
|
||||
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 tiles = 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);
|
||||
return (*p, *h);
|
||||
});
|
||||
|
||||
chunks.dedup();
|
||||
|
||||
return chunks;
|
||||
return tiles;
|
||||
}
|
||||
|
||||
pub fn hex_select<OP, Ret>(&self, center: &HexCoord, radius: usize, include_center: bool, op: OP) -> Vec<Ret>
|
||||
@@ -111,27 +184,106 @@ impl Map {
|
||||
{
|
||||
assert!(radius != 0, "Radius cannot be zero");
|
||||
|
||||
let mut result = if include_center {
|
||||
Vec::with_capacity(get_tile_count_in_range(radius) + 1)
|
||||
} else {
|
||||
Vec::with_capacity(get_tile_count_in_range(radius))
|
||||
};
|
||||
if include_center {
|
||||
let h = self.sample_height(¢er);
|
||||
(op)(¢er, h, 0);
|
||||
result.push((op)(center, 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);
|
||||
if self.is_in_bounds(&p) {
|
||||
let h = self.sample_height(&p);
|
||||
result.push((op)(&p, h, k));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
pub fn hex_select_first<OP, Ret>(
|
||||
&self,
|
||||
center: &HexCoord,
|
||||
radius: usize,
|
||||
include_center: bool,
|
||||
op: OP,
|
||||
) -> Option<Ret>
|
||||
where
|
||||
OP: (Fn(&HexCoord, f32, usize) -> Option<Ret>) + Sync + Send,
|
||||
{
|
||||
assert!(radius != 0, "Radius cannot be zero");
|
||||
|
||||
if include_center {
|
||||
let h = self.sample_height(¢er);
|
||||
let r = (op)(center, h, 0);
|
||||
if r.is_some() {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
if self.is_in_bounds(&p) {
|
||||
let h = self.sample_height(&p);
|
||||
let r = (op)(&p, h, k);
|
||||
if r.is_some() {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return None;
|
||||
}
|
||||
|
||||
pub fn ring_select_first<OP, Ret>(
|
||||
&self,
|
||||
center: &HexCoord,
|
||||
start_radius: usize,
|
||||
end_radius: usize,
|
||||
op: OP,
|
||||
) -> Option<Ret>
|
||||
where
|
||||
OP: (Fn(&HexCoord, f32, usize) -> Option<Ret>) + Sync + Send,
|
||||
{
|
||||
assert!(start_radius != 0, "Start radius cannot be zero");
|
||||
assert!(
|
||||
start_radius > end_radius,
|
||||
"Start radius cannot be lower than end radius"
|
||||
);
|
||||
|
||||
for k in start_radius..(end_radius + 1) {
|
||||
let mut p = center.scale(4, k);
|
||||
for i in 0..6 {
|
||||
for _j in 0..k {
|
||||
p = p.get_neighbor(i);
|
||||
if self.is_in_bounds(&p) {
|
||||
let h = self.sample_height(&p);
|
||||
let r = (op)(&p, h, k);
|
||||
if r.is_some() {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return None;
|
||||
}
|
||||
|
||||
pub fn hex_select_mut<OP, Ret>(
|
||||
&mut self,
|
||||
center: &HexCoord,
|
||||
@@ -144,23 +296,28 @@ impl Map {
|
||||
{
|
||||
assert!(radius != 0, "Radius cannot be zero");
|
||||
|
||||
let mut result = if include_center {
|
||||
Vec::with_capacity(get_tile_count_in_range(radius) + 1)
|
||||
} else {
|
||||
Vec::with_capacity(get_tile_count_in_range(radius))
|
||||
};
|
||||
if include_center {
|
||||
let h = self.sample_height_mut(¢er);
|
||||
(op)(¢er, h, 0);
|
||||
result.push((op)(center, 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);
|
||||
if self.is_in_bounds(&p) {
|
||||
let h = self.sample_height_mut(&p);
|
||||
result.push((op)(&p, h, k));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
153
engine/world_generation/src/map/map_utils.rs
Normal file
153
engine/world_generation/src/map/map_utils.rs
Normal file
@@ -0,0 +1,153 @@
|
||||
use std::ops::Add;
|
||||
|
||||
use bevy::{asset::AssetLoader, math::VectorSpace, prelude::*};
|
||||
use image::ImageBuffer;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::hex_utils::HexCoord;
|
||||
|
||||
use super::{biome_map::BiomeMap, chunk::Chunk, map::Map};
|
||||
|
||||
pub fn render_image(
|
||||
size: UVec2,
|
||||
data: &Vec<f32>,
|
||||
color1: LinearRgba,
|
||||
color2: LinearRgba,
|
||||
) -> ImageBuffer<image::Rgba<u8>, Vec<u8>> {
|
||||
let mut image = ImageBuffer::new(size.x * Chunk::SIZE as u32, size.y * Chunk::SIZE as u32);
|
||||
update_image(size, data, color1, color2, &mut image);
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
pub fn update_image(
|
||||
size: UVec2,
|
||||
data: &Vec<f32>,
|
||||
color1: LinearRgba,
|
||||
color2: LinearRgba,
|
||||
image: &mut ImageBuffer<image::Rgba<u8>, Vec<u8>>,
|
||||
) {
|
||||
let min = *data.iter().min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or(&0.0);
|
||||
let max = *data.iter().min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap_or(&1.0);
|
||||
|
||||
let w = size.x * Chunk::SIZE as u32;
|
||||
|
||||
image.par_enumerate_pixels_mut().for_each(|(x, y, pixel)| {
|
||||
let idx = (y * w + x) as usize;
|
||||
let v = data[idx];
|
||||
let t = v.remap(min, max, 0.0, 1.0);
|
||||
let col = LinearRgba::lerp(color1, color2, t);
|
||||
*pixel = to_pixel(&col);
|
||||
});
|
||||
}
|
||||
|
||||
fn to_pixel(col: &LinearRgba) -> image::Rgba<u8> {
|
||||
return image::Rgba([
|
||||
(col.red * 255.0) as u8,
|
||||
(col.green * 255.0) as u8,
|
||||
(col.blue * 255.0) as u8,
|
||||
255,
|
||||
]);
|
||||
}
|
||||
pub fn render_map(map: &Map, smooth: f32) -> ImageBuffer<image::Rgba<u8>, Vec<u8>> {
|
||||
let mut image = ImageBuffer::new(
|
||||
map.width as u32 * Chunk::SIZE as u32,
|
||||
map.height as u32 * Chunk::SIZE as u32,
|
||||
);
|
||||
update_map(map, smooth, &mut image);
|
||||
return image;
|
||||
}
|
||||
pub fn update_map(map: &Map, smooth: f32, image: &mut ImageBuffer<image::Rgba<u8>, Vec<u8>>) {
|
||||
image.par_enumerate_pixels_mut().for_each(|(x, y, pixel)| {
|
||||
let coord = HexCoord::from_grid_pos(x as usize, y as usize);
|
||||
let right = coord.get_neighbor(1);
|
||||
let height = map.sample_height(&coord);
|
||||
|
||||
let mut color = Hsla::hsl(138.0, 1.0, 0.4);
|
||||
if height < map.sealevel {
|
||||
color.hue = 217.0;
|
||||
}
|
||||
|
||||
if map.is_in_bounds(&right) {
|
||||
let h2 = map.sample_height(&right);
|
||||
color = get_height_color_blend(color, height, h2, smooth);
|
||||
}
|
||||
|
||||
*pixel = to_pixel(&color.into());
|
||||
});
|
||||
}
|
||||
|
||||
fn get_height_color_blend(base_color: Hsla, height: f32, height2: f32, smooth: f32) -> Hsla {
|
||||
let mut color = base_color;
|
||||
let mut d = height2 - height;
|
||||
if smooth == 0.0 || d.abs() > smooth {
|
||||
if d > 0.0 {
|
||||
color.lightness += 0.1;
|
||||
} else if d < 0.0 {
|
||||
color.lightness -= 0.1;
|
||||
}
|
||||
} else {
|
||||
if d.abs() <= smooth {
|
||||
d /= smooth;
|
||||
if d > 0.0 {
|
||||
let c2: LinearRgba = color.with_lightness(color.lightness + 0.1).into();
|
||||
color = LinearRgba::lerp(color.into(), c2, d).into();
|
||||
} else {
|
||||
let c2: LinearRgba = color.with_lightness(color.lightness - 0.1).into();
|
||||
color = LinearRgba::lerp(color.into(), c2, d.abs()).into();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return color;
|
||||
}
|
||||
|
||||
pub fn render_biome_noise_map(map: &BiomeMap, multi: Vec3) -> ImageBuffer<image::Rgba<u8>, Vec<u8>> {
|
||||
let mut image = ImageBuffer::new(map.width as u32, map.height as u32);
|
||||
update_biome_noise_map(map, multi, &mut image);
|
||||
return image;
|
||||
}
|
||||
|
||||
pub fn update_biome_noise_map(map: &BiomeMap, multi: Vec3, image: &mut ImageBuffer<image::Rgba<u8>, Vec<u8>>) {
|
||||
image.par_enumerate_pixels_mut().for_each(|(x, y, pixel)| {
|
||||
let tile = map.get_biome_data(x as usize, y as usize);
|
||||
|
||||
let color = LinearRgba::rgb(
|
||||
(tile.temperature / 100.0) * multi.x,
|
||||
(tile.continentality / 100.0) * multi.y,
|
||||
(tile.moisture / 100.0) * multi.z,
|
||||
);
|
||||
*pixel = to_pixel(&color);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn render_biome_map(map: &Map, biome_map: &BiomeMap) -> ImageBuffer<image::Rgba<u8>, Vec<u8>> {
|
||||
let mut image = ImageBuffer::new(
|
||||
map.width as u32 * Chunk::SIZE as u32,
|
||||
map.height as u32 * Chunk::SIZE as u32,
|
||||
);
|
||||
update_biome_map(map, biome_map, &mut image);
|
||||
return image;
|
||||
}
|
||||
|
||||
pub fn update_biome_map(map: &Map, biome_map: &BiomeMap, image: &mut ImageBuffer<image::Rgba<u8>, Vec<u8>>) {
|
||||
let map_biome_count = map.biome_count as f32;
|
||||
image.par_enumerate_pixels_mut().for_each(|(x, y, pixel)| {
|
||||
let coord = HexCoord::from_grid_pos(x as usize, y as usize);
|
||||
let biome_blend = biome_map.get_biome(x as i32, y as i32).unwrap();
|
||||
let right = coord.get_neighbor(1);
|
||||
let mut color = Oklaba::BLACK;
|
||||
for i in 0..biome_blend.len() {
|
||||
let mut c: Oklaba = Hsla::hsl((i as f32 / map_biome_count) * 360.0, 0.8, 0.7).into();
|
||||
c *= biome_blend[i];
|
||||
color = Oklaba::add(c, color.into()).into();
|
||||
}
|
||||
if map.is_in_bounds(&right) {
|
||||
let h1 = map.sample_height(&coord);
|
||||
let h2 = map.sample_height(&right);
|
||||
color = get_height_color_blend(color.into(), h1, h2, 0.5).into();
|
||||
}
|
||||
|
||||
*pixel = to_pixel(&color.into());
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,7 @@
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use bevy::math::IVec2;
|
||||
|
||||
use crate::hex_utils::HexCoord;
|
||||
|
||||
use super::chunk::Chunk;
|
||||
@@ -5,11 +9,14 @@ use super::chunk::Chunk;
|
||||
pub struct MeshChunkData {
|
||||
pub heights: [f32; Chunk::AREA],
|
||||
pub textures: [[u32; 2]; Chunk::AREA],
|
||||
pub min_height: f32,
|
||||
pub sealevel: f32,
|
||||
pub distance_to_land: [f32; Chunk::AREA],
|
||||
}
|
||||
|
||||
impl MeshChunkData {
|
||||
pub fn get_neighbors(&self, coord: &HexCoord) -> [f32; 6] {
|
||||
let mut data = [0.; 6];
|
||||
let mut data = [self.min_height; 6];
|
||||
let n_tiles = coord.get_neighbors();
|
||||
for i in 0..6 {
|
||||
let n = n_tiles[i];
|
||||
@@ -21,4 +28,58 @@ impl MeshChunkData {
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
pub fn get_neighbors_with_water_info(&self, coord: &HexCoord) -> ([(f32, Option<f32>); 6], bool) {
|
||||
let mut has_land = false;
|
||||
let mut data = [(self.min_height, None); 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;
|
||||
}
|
||||
let idx = n.to_index(Chunk::SIZE);
|
||||
data[i] = (self.heights[idx], Some(self.distance_to_land[idx]));
|
||||
if data[i].0 > self.sealevel {
|
||||
has_land = true;
|
||||
}
|
||||
}
|
||||
return (data, has_land);
|
||||
}
|
||||
|
||||
pub fn caluclate_water_distances(data: &mut Vec<MeshChunkData>, height: usize, width: usize, range: usize) {
|
||||
let mut open: VecDeque<(HexCoord, f32, usize)> = VecDeque::new();
|
||||
let mut closed: Vec<(HexCoord, f32)> = Vec::new();
|
||||
for z in 0..height {
|
||||
for x in 0..width {
|
||||
let chunk = &mut data[z * height + x];
|
||||
chunk.prepare_chunk_open(x * Chunk::SIZE, z * Chunk::SIZE, &mut open);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_chunk_open(&mut self, offset_x: usize, offset_z: usize, open: &mut VecDeque<(HexCoord, f32, usize)>) {
|
||||
for z in 0..Chunk::SIZE {
|
||||
for x in 0..Chunk::SIZE {
|
||||
let coord = HexCoord::from_grid_pos(x + offset_x, z + offset_z);
|
||||
let idx = coord.to_chunk_local_index();
|
||||
let h = self.heights[idx];
|
||||
self.distance_to_land[idx] = if h > self.sealevel { 0.0 } else { 4.0 };
|
||||
if h > self.sealevel {
|
||||
open.push_back((coord, h, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_chunk_borders(
|
||||
&mut self,
|
||||
chunks: &Vec<MeshChunkData>,
|
||||
offset: IVec2,
|
||||
open: &mut VecDeque<(HexCoord, f32, usize)>,
|
||||
closed: &mut Vec<(HexCoord, f32)>,
|
||||
) {
|
||||
self.prepare_chunk_open(offset.x as usize * Chunk::SIZE, offset.y as usize * Chunk::SIZE, open);
|
||||
todo!("Fill closed list with bordering tiles")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,3 +3,4 @@ pub mod mesh_chunk;
|
||||
pub mod config;
|
||||
pub mod map;
|
||||
pub mod biome_map;
|
||||
pub mod map_utils;
|
||||
@@ -7,5 +7,5 @@ pub enum GeneratorState {
|
||||
SpawnMap,
|
||||
Idle,
|
||||
Regenerate,
|
||||
Cleanup,
|
||||
}
|
||||
|
||||
|
||||
@@ -6,15 +6,15 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
bevy = "0.14.0"
|
||||
bevy = "0.15.1"
|
||||
world_generation = { path = "../../engine/world_generation" }
|
||||
shared = { path = "../shared" }
|
||||
bevy_rapier3d = "0.27.0"
|
||||
bevy_rapier3d = "0.28.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 = [
|
||||
bevy_asset_loader = { version = "0.22.0", features = [
|
||||
"standard_dynamic_assets",
|
||||
"3d",
|
||||
] }
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
use asset_loader::create_asset_loader;
|
||||
use bevy::prelude::*;
|
||||
use bevy::{
|
||||
gltf::{GltfMesh, GltfNode},
|
||||
prelude::*,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use shared::resource::ResourceIdentifier;
|
||||
use shared::{component_defination::ComponentDefination, identifiers::ResourceIdentifier, prefab_defination::*};
|
||||
|
||||
use crate::footprint::BuildingFootprint;
|
||||
use crate::{
|
||||
buildings::{
|
||||
conduit_building::ResourceConduitInfo, factory_building::FactoryBuildingInfo,
|
||||
resource_gathering::ResourceGatheringBuildingInfo,
|
||||
},
|
||||
footprint::BuildingFootprint,
|
||||
prelude::Building,
|
||||
};
|
||||
|
||||
#[derive(Asset, TypePath, Debug, Serialize, Deserialize)]
|
||||
pub struct BuildingAsset {
|
||||
@@ -12,11 +22,108 @@ pub struct BuildingAsset {
|
||||
pub footprint: BuildingFootprint,
|
||||
pub prefab_path: String,
|
||||
#[serde(skip)]
|
||||
pub prefab: Handle<Scene>,
|
||||
pub prefab: Handle<Gltf>,
|
||||
pub base_mesh_path: String,
|
||||
|
||||
pub cost: Vec<ResourceIdentifier>,
|
||||
pub consumption: Vec<ResourceIdentifier>,
|
||||
pub production: Vec<ResourceIdentifier>,
|
||||
|
||||
pub health: u32,
|
||||
|
||||
pub building_type: BuildingType,
|
||||
pub components: Option<Vec<ComponentDefination>>,
|
||||
}
|
||||
|
||||
impl BuildingAsset {
|
||||
pub fn spawn(
|
||||
&self,
|
||||
pos: Vec3,
|
||||
rot: Quat,
|
||||
gltf: &Gltf,
|
||||
commands: &mut Commands,
|
||||
meshes: &Assets<GltfMesh>,
|
||||
nodes: &Assets<GltfNode>,
|
||||
) -> Option<Entity> {
|
||||
let base_node = &gltf.named_nodes[&self.base_mesh_path.clone().into_boxed_str()];
|
||||
if let Some(node) = nodes.get(base_node.id()) {
|
||||
if let Some(mesh_handle) = &node.mesh {
|
||||
if let Some(gltf_mesh) = meshes.get(mesh_handle.id()) {
|
||||
let (mesh, mat) = gltf_mesh.unpack();
|
||||
let mut entity = commands.spawn((
|
||||
Mesh3d(mesh),
|
||||
MeshMaterial3d(mat),
|
||||
Transform::from_translation(pos).with_rotation(rot),
|
||||
Building,
|
||||
));
|
||||
entity.with_children(|b| {
|
||||
for child in &node.children {
|
||||
let child_node = nodes.get(child.id());
|
||||
if child_node.is_none() {
|
||||
continue;
|
||||
}
|
||||
self.process_node(child_node.unwrap(), meshes, nodes, b, &node.name);
|
||||
}
|
||||
});
|
||||
if let Some(component) = self.get_component_def(&format!("/{0}", &node.name)) {
|
||||
component.apply(&mut entity);
|
||||
}
|
||||
return Some(entity.id());
|
||||
}
|
||||
}
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
fn process_node(
|
||||
&self,
|
||||
node: &GltfNode,
|
||||
meshes: &Assets<GltfMesh>,
|
||||
nodes: &Assets<GltfNode>,
|
||||
commands: &mut ChildBuilder,
|
||||
parent: &String,
|
||||
) -> Option<Entity> {
|
||||
let path = format!("{0}/{1}", parent, node.name);
|
||||
if let Some(mesh) = &node.mesh {
|
||||
if let Some(gltf_mesh) = meshes.get(mesh.id()) {
|
||||
let (mesh, mat) = gltf_mesh.unpack();
|
||||
let mut entity = commands.spawn((Mesh3d(mesh), MeshMaterial3d(mat), node.transform, Building));
|
||||
entity.with_children(|b| {
|
||||
for child in &node.children {
|
||||
let child_node = nodes.get(child.id());
|
||||
if child_node.is_none() {
|
||||
continue;
|
||||
}
|
||||
self.process_node(child_node.unwrap(), meshes, nodes, b, &path);
|
||||
}
|
||||
});
|
||||
if let Some(component) = self.get_component_def(&path) {
|
||||
component.apply(&mut entity);
|
||||
}
|
||||
return Some(entity.id());
|
||||
}
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
fn get_component_def(&self, path: &String) -> Option<&ComponentDefination> {
|
||||
if let Some(components) = &self.components {
|
||||
for c in components {
|
||||
if c.path.ends_with(path) {
|
||||
return Some(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, TypePath)]
|
||||
pub enum BuildingType {
|
||||
Basic,
|
||||
Gathering(ResourceGatheringBuildingInfo),
|
||||
FactoryBuildingInfo(FactoryBuildingInfo),
|
||||
ResourceConduit(ResourceConduitInfo),
|
||||
}
|
||||
|
||||
create_asset_loader!(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
use bevy::prelude::Resource;
|
||||
use shared::building::BuildingIdentifier;
|
||||
use world_generation::hex_utils::HexCoord;
|
||||
|
||||
@@ -1,19 +1,35 @@
|
||||
use bevy::{prelude::*, window::PrimaryWindow};
|
||||
use std::f32::consts::E;
|
||||
|
||||
use bevy::{
|
||||
ecs::world::CommandQueue,
|
||||
gltf::{GltfMesh, GltfNode},
|
||||
prelude::*,
|
||||
window::PrimaryWindow,
|
||||
};
|
||||
use bevy_asset_loader::loading_state::{
|
||||
config::{ConfigureLoadingState, LoadingStateConfig},
|
||||
LoadingStateAppExt,
|
||||
};
|
||||
use bevy_rapier3d::{pipeline::QueryFilter, plugin::RapierContext};
|
||||
use bevy_rapier3d::{parry::transformation::utils::transform, pipeline::QueryFilter, plugin::RapierContext};
|
||||
use shared::{
|
||||
despawn::Despawn,
|
||||
events::TileModifiedEvent,
|
||||
resources::TileUnderCursor,
|
||||
states::{AssetLoadState, GameplayState},
|
||||
tags::MainCamera,
|
||||
};
|
||||
use world_generation::{hex_utils::HexCoord, map::map::Map};
|
||||
use world_generation::{
|
||||
heightmap, hex_utils::HexCoord, map::map::Map, prelude::GenerationConfig, states::GeneratorState,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
assets::{building_asset::BuildingAssetPlugin, building_database::BuildingDatabase},
|
||||
assets::{
|
||||
building_asset::{BuildingAsset, BuildingAssetPlugin},
|
||||
building_database::BuildingDatabase,
|
||||
},
|
||||
build_queue::{BuildQueue, QueueEntry},
|
||||
buildings_map::{BuildingEntry, BuildingMap},
|
||||
prelude::Building,
|
||||
};
|
||||
|
||||
pub struct BuildingPugin;
|
||||
@@ -27,13 +43,36 @@ impl Plugin for BuildingPugin {
|
||||
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(Update, init.run_if(in_state(AssetLoadState::Loading)));
|
||||
app.add_systems(
|
||||
Update,
|
||||
hq_placement.run_if(in_state(GameplayState::PlaceHQ).and_then(in_state(GeneratorState::Idle))),
|
||||
);
|
||||
app.add_systems(
|
||||
PreUpdate,
|
||||
prepare_building_map.run_if(in_state(GeneratorState::SpawnMap)),
|
||||
);
|
||||
app.add_systems(Update, regernerate.run_if(in_state(GeneratorState::Regenerate)));
|
||||
app.add_systems(
|
||||
PostUpdate,
|
||||
update_building_heights.run_if(in_state(GeneratorState::Idle)),
|
||||
);
|
||||
|
||||
app.add_systems(PreUpdate, process_build_queue.run_if(in_state(GameplayState::Playing)));
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_building_map(mut commands: Commands, cfg: Res<GenerationConfig>) {
|
||||
commands.insert_resource(BuildingMap::new(cfg.size));
|
||||
}
|
||||
|
||||
fn regernerate(mut commands: Commands, buildings: Query<Entity, With<Building>>, cfg: Res<GenerationConfig>) {
|
||||
for e in buildings.iter() {
|
||||
commands.entity(e).despawn();
|
||||
}
|
||||
commands.insert_resource(BuildingMap::new(cfg.size));
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct IndicatorCube(Handle<Mesh>, Handle<StandardMaterial>);
|
||||
|
||||
@@ -45,44 +84,22 @@ fn init(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials:
|
||||
}
|
||||
|
||||
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>,
|
||||
tile_under_cursor: Res<TileUnderCursor>,
|
||||
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));
|
||||
if let Some(contact) = tile_under_cursor.0 {
|
||||
let positions = map.hex_select(&contact.tile, 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,
|
||||
pos: contact.tile,
|
||||
});
|
||||
|
||||
next_state.set(GameplayState::Playing);
|
||||
@@ -93,15 +110,73 @@ fn hq_placement(
|
||||
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()
|
||||
},
|
||||
Mesh3d(indicator.0.clone()),
|
||||
MeshMaterial3d(indicator.1.clone()),
|
||||
Transform::from_translation(p),
|
||||
Despawn,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn process_build_queue(mut queue: ResMut<BuildQueue>) {}
|
||||
fn process_build_queue(
|
||||
mut queue: ResMut<BuildQueue>,
|
||||
mut commands: Commands,
|
||||
db: Res<BuildingDatabase>,
|
||||
building_assets: Res<Assets<BuildingAsset>>,
|
||||
gltf_assets: Res<Assets<Gltf>>,
|
||||
gltf_meshes: Res<Assets<GltfMesh>>,
|
||||
gltf_nodes: Res<Assets<GltfNode>>,
|
||||
mut building_map: ResMut<BuildingMap>,
|
||||
heightmap: Res<Map>,
|
||||
) {
|
||||
for item in &queue.queue {
|
||||
let handle = &db.buildings[item.building.0];
|
||||
if let Some(building) = building_assets.get(handle.id()) {
|
||||
let h = heightmap.sample_height(&item.pos);
|
||||
println!("Spawning {} at {}", building.name, item.pos);
|
||||
if let Some(gltf) = gltf_assets.get(building.prefab.id()) {
|
||||
let e = building.spawn(
|
||||
item.pos.to_world(h),
|
||||
Quat::IDENTITY,
|
||||
gltf,
|
||||
&mut commands,
|
||||
&gltf_meshes,
|
||||
&gltf_nodes,
|
||||
);
|
||||
if let Some(b) = e {
|
||||
building_map.add_building(BuildingEntry::new(item.pos, b));
|
||||
}
|
||||
} else {
|
||||
warn!("Failed to spawn building");
|
||||
}
|
||||
}
|
||||
}
|
||||
queue.queue.clear();
|
||||
}
|
||||
|
||||
fn update_building_heights(
|
||||
mut tile_updates: EventReader<TileModifiedEvent>,
|
||||
building_map: Res<BuildingMap>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
for event in tile_updates.read() {
|
||||
match event {
|
||||
TileModifiedEvent::HeightChanged(coord, new_height) => {
|
||||
if let Some(building) = building_map.get_building(coord) {
|
||||
let mut queue = CommandQueue::default();
|
||||
let e = building.entity.clone();
|
||||
let h = *new_height;
|
||||
queue.push(move |world: &mut World| {
|
||||
let mut emut = world.entity_mut(e);
|
||||
if let Some(mut transform) = emut.get_mut::<Transform>() {
|
||||
transform.translation.y = h;
|
||||
}
|
||||
});
|
||||
|
||||
commands.append(&mut queue);
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
3
game/buildings/src/buildings/basic_building.rs
Normal file
3
game/buildings/src/buildings/basic_building.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct BasicBuildingInfo {}
|
||||
6
game/buildings/src/buildings/conduit_building.rs
Normal file
6
game/buildings/src/buildings/conduit_building.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ResourceConduitInfo {
|
||||
pub range: usize,
|
||||
pub connection_range: usize,
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ResourceIdentifier {
|
||||
pub id: u32,
|
||||
pub qty: u32,
|
||||
pub struct FactoryBuildingInfo {
|
||||
pub units_to_build: Vec<()>
|
||||
}
|
||||
5
game/buildings/src/buildings/mod.rs
Normal file
5
game/buildings/src/buildings/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
pub mod basic_building;
|
||||
pub mod conduit_building;
|
||||
pub mod factory_building;
|
||||
pub mod resource_gathering;
|
||||
pub mod tech_building;
|
||||
8
game/buildings/src/buildings/resource_gathering.rs
Normal file
8
game/buildings/src/buildings/resource_gathering.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use shared::identifiers::ResourceIdentifier;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ResourceGatheringBuildingInfo {
|
||||
pub resources_to_gather: Vec<ResourceIdentifier>,
|
||||
pub gather_range: usize,
|
||||
}
|
||||
9
game/buildings/src/buildings/tech_building.rs
Normal file
9
game/buildings/src/buildings/tech_building.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use shared::{building::BuildingIdentifier, StatusEffect};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct TechBuildingInfo {
|
||||
pub effect_range: usize,
|
||||
pub buildings_to_unlock: Vec<BuildingIdentifier>,
|
||||
pub buffs: Vec<StatusEffect>,
|
||||
}
|
||||
@@ -1,14 +1,16 @@
|
||||
use bevy::prelude::*;
|
||||
use world_generation::hex_utils::HexCoord;
|
||||
use world_generation::{hex_utils::HexCoord, prelude::Chunk};
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct BuildingMap {
|
||||
pub chunks: Vec<BuildingChunk>,
|
||||
pub size: UVec2,
|
||||
}
|
||||
|
||||
impl BuildingMap {
|
||||
pub fn new(size: UVec2) -> Self {
|
||||
let mut db = BuildingMap {
|
||||
size,
|
||||
chunks: Vec::with_capacity(size.length_squared() as usize),
|
||||
};
|
||||
|
||||
@@ -23,18 +25,39 @@ impl BuildingMap {
|
||||
return db;
|
||||
}
|
||||
|
||||
pub fn get_buildings_in_range(&self, coord: &HexCoord, radius: usize) -> Option<Vec<&BuildingEntry>> {
|
||||
pub fn get_buildings_in_range(&self, coord: &HexCoord, radius: usize) -> Vec<&BuildingEntry> {
|
||||
assert!(radius != 0, "Radius cannot be zero");
|
||||
todo!();
|
||||
|
||||
let w = self.size.x as usize * Chunk::SIZE;
|
||||
let h = self.size.y as usize * Chunk::SIZE;
|
||||
let coords = coord.hex_select_bounded(radius, true, h, w);
|
||||
return self.get_buildings_in_coords(coords);
|
||||
}
|
||||
|
||||
pub fn get_buildings_in_coords(&self, coords: Vec<HexCoord>) -> Vec<&BuildingEntry> {
|
||||
let mut result = Vec::new();
|
||||
for coord in &coords {
|
||||
if let Some(buidling) = self.get_building(coord) {
|
||||
result.push(buidling);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
pub fn get_building(&self, coord: &HexCoord) -> Option<&BuildingEntry> {
|
||||
todo!();
|
||||
let chunk = &self.chunks[coord.to_chunk_index(self.size.x as usize)];
|
||||
return chunk.get_building(coord);
|
||||
}
|
||||
|
||||
pub fn add_building(&mut self, entry: BuildingEntry) {
|
||||
let chunk = &mut self.chunks[entry.coord.to_chunk_index(self.size.x as usize)];
|
||||
chunk.add_building(entry);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BuildingChunk {
|
||||
pub entries: Vec<BuildingChunk>,
|
||||
pub entries: Vec<BuildingEntry>,
|
||||
pub index: usize,
|
||||
pub offset: IVec2,
|
||||
}
|
||||
@@ -49,7 +72,11 @@ impl BuildingChunk {
|
||||
}
|
||||
|
||||
pub fn get_building(&self, coord: &HexCoord) -> Option<&BuildingEntry> {
|
||||
todo!();
|
||||
return self.entries.iter().find(|b| &b.coord == coord);
|
||||
}
|
||||
|
||||
pub fn add_building(&mut self, entry: BuildingEntry) {
|
||||
self.entries.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,4 +3,6 @@ pub mod build_queue;
|
||||
pub mod building_plugin;
|
||||
pub mod buildings_map;
|
||||
pub mod footprint;
|
||||
pub mod prelude;
|
||||
mod buildings;
|
||||
pub use building_plugin::*;
|
||||
|
||||
3
game/buildings/src/prelude.rs
Normal file
3
game/buildings/src/prelude.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
use bevy::prelude::*;
|
||||
#[derive(Component)]
|
||||
pub struct Building;
|
||||
@@ -7,20 +7,33 @@ build = "build.rs"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
bevy = "0.14.0"
|
||||
bevy-inspector-egui = "0.25.0"
|
||||
iyes_perf_ui = "0.3.0"
|
||||
bevy = { version = "0.15.1", features = ["file_watcher"] }
|
||||
bevy-inspector-egui = "0.28.1"
|
||||
# iyes_perf_ui = "0.3.0"
|
||||
noise = "0.8.2"
|
||||
world_generation = { path = "../../engine/world_generation" }
|
||||
bevy_rapier3d = { version = "0.27.0", features = ["simd-stable", "parallel"] }
|
||||
bevy_rapier3d = { version = "0.28.0", features = [
|
||||
"simd-stable",
|
||||
"parallel",
|
||||
"debug-render-3d",
|
||||
] }
|
||||
rayon = "1.10.0"
|
||||
buildings = { path = "../buildings" }
|
||||
units = { path = "../units" }
|
||||
shared = { path = "../shared" }
|
||||
bevy_asset_loader = { version = "0.21.0", features = [
|
||||
bevy_asset_loader = { version = "0.22.0", features = [
|
||||
"standard_dynamic_assets",
|
||||
"3d",
|
||||
] }
|
||||
ron = "0.8.1"
|
||||
image = "0.25.2"
|
||||
# bevy_lunex = "0.2.4"
|
||||
|
||||
[features]
|
||||
tracing = ["bevy/trace_tracy", "world_generation/tracing", "buildings/tracing"]
|
||||
tracing = [
|
||||
"bevy/trace_tracy",
|
||||
"world_generation/tracing",
|
||||
"buildings/tracing",
|
||||
"units/tracing",
|
||||
"shared/tracing",
|
||||
]
|
||||
|
||||
Submodule game/main/assets updated: 3bb0aaab5b...f1c26c1519
@@ -13,6 +13,10 @@ where
|
||||
|
||||
for path in fs::read_dir(from).unwrap() {
|
||||
let path = path.unwrap().path();
|
||||
println!("{path:?}");
|
||||
if path.starts_with("assets/raw_assets") {
|
||||
continue;
|
||||
}
|
||||
let to = to.clone().join(path.file_name().unwrap());
|
||||
|
||||
if path.is_file() {
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
use bevy::core_pipeline::experimental::taa::{TemporalAntiAliasBundle, TemporalAntiAliasPlugin};
|
||||
use bevy::core_pipeline::experimental::taa::{TemporalAntiAliasBundle, TemporalAntiAliasPlugin, TemporalAntiAliasing};
|
||||
use bevy::core_pipeline::prepass::DepthPrepass;
|
||||
use bevy::input::mouse::{MouseMotion, MouseScrollUnit, MouseWheel};
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::CursorGrabMode;
|
||||
use shared::states::MenuState;
|
||||
use bevy::window::{CursorGrabMode, PrimaryWindow};
|
||||
use shared::sets::GameplaySet;
|
||||
use shared::tags::MainCamera;
|
||||
use world_generation::hex_utils::HexCoord;
|
||||
use world_generation::prelude::Map;
|
||||
use world_generation::states::GeneratorState;
|
||||
|
||||
use super::components::*;
|
||||
|
||||
@@ -15,127 +16,98 @@ pub struct PhosCameraPlugin;
|
||||
impl Plugin for PhosCameraPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.register_type::<PhosCamera>();
|
||||
app.register_type::<PhosOrbitCamera>();
|
||||
|
||||
app.add_systems(PreStartup, setup);
|
||||
|
||||
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()));
|
||||
app.add_systems(Update, orbit_camera_upate.in_set(GameplaySet));
|
||||
|
||||
app.add_systems(Update, init_bounds.run_if(in_state(GeneratorState::SpawnMap)));
|
||||
|
||||
app.add_plugins(TemporalAntiAliasPlugin);
|
||||
}
|
||||
}
|
||||
|
||||
fn setup(mut commands: Commands, mut msaa: ResMut<Msaa>) {
|
||||
fn init_bounds(
|
||||
mut commands: Commands,
|
||||
mut cam: Query<(&mut Transform, Entity), With<PhosCamera>>,
|
||||
heightmap: Res<Map>,
|
||||
) {
|
||||
let (mut cam_t, cam_entity) = cam.single_mut();
|
||||
cam_t.translation = heightmap.get_center();
|
||||
commands
|
||||
.entity(cam_entity)
|
||||
.insert(CameraBounds::from_size(heightmap.get_world_size()))
|
||||
.insert(PhosOrbitCamera {
|
||||
target: heightmap.get_center_with_height(),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
|
||||
fn setup(mut commands: Commands) {
|
||||
commands
|
||||
.spawn((
|
||||
Camera3dBundle {
|
||||
transform: Transform::from_xyz(0., 30., 0.).looking_to(Vec3::Z, Vec3::Y),
|
||||
..default()
|
||||
},
|
||||
Camera3d::default(),
|
||||
Transform::from_xyz(0., 30., 0.).looking_to(Vec3::NEG_Z, Vec3::Y),
|
||||
PhosCamera::default(),
|
||||
MainCamera,
|
||||
DepthPrepass,
|
||||
PhosCameraTargets::default(),
|
||||
PhosOrbitCamera::default(),
|
||||
TemporalAntiAliasing::default(),
|
||||
))
|
||||
.insert(TemporalAntiAliasBundle::default());
|
||||
.insert(Msaa::Off);
|
||||
// .insert(RenderLayers::layer(0))
|
||||
|
||||
*msaa = Msaa::Off;
|
||||
}
|
||||
fn update_camera(
|
||||
mut cam_query: Query<(&PhosCamera, &mut Transform)>,
|
||||
keyboard_input: Res<ButtonInput<KeyCode>>,
|
||||
time: Res<Time>,
|
||||
windows: Query<&Window>,
|
||||
) {
|
||||
let window = windows.single();
|
||||
if window.cursor.grab_mode != CursorGrabMode::Locked {
|
||||
return;
|
||||
}
|
||||
let (cam, mut transform) = cam_query.single_mut();
|
||||
|
||||
let mut move_vec = Vec3::ZERO;
|
||||
if keyboard_input.pressed(KeyCode::KeyA) {
|
||||
move_vec += Vec3::NEG_X;
|
||||
}
|
||||
if keyboard_input.pressed(KeyCode::KeyD) {
|
||||
move_vec += Vec3::X;
|
||||
}
|
||||
if keyboard_input.pressed(KeyCode::KeyW) {
|
||||
move_vec += Vec3::NEG_Z;
|
||||
}
|
||||
if keyboard_input.pressed(KeyCode::KeyS) {
|
||||
move_vec += Vec3::Z;
|
||||
// *msaa = Msaa::Off;
|
||||
}
|
||||
|
||||
let rot = transform.rotation;
|
||||
move_vec = (rot * move_vec.normalize_or_zero()) * cam.speed * time.delta_seconds();
|
||||
|
||||
if keyboard_input.pressed(KeyCode::ShiftLeft) {
|
||||
move_vec += Vec3::from(transform.down());
|
||||
}
|
||||
if keyboard_input.pressed(KeyCode::Space) {
|
||||
move_vec += Vec3::from(transform.up());
|
||||
}
|
||||
|
||||
transform.translation += move_vec.normalize_or_zero() * cam.speed * time.delta_seconds();
|
||||
}
|
||||
|
||||
fn update_camera_mouse(
|
||||
mut cam_query: Query<&mut Transform, With<PhosCamera>>,
|
||||
mut mouse_move: EventReader<MouseMotion>,
|
||||
time: Res<Time>,
|
||||
windows: Query<&Window>,
|
||||
) {
|
||||
let window = windows.single();
|
||||
if window.cursor.grab_mode != CursorGrabMode::Locked {
|
||||
return;
|
||||
}
|
||||
let mut transform = cam_query.single_mut();
|
||||
|
||||
for ev in mouse_move.read() {
|
||||
let (mut yaw, mut pitch, _) = transform.rotation.to_euler(EulerRot::YXZ);
|
||||
match window.cursor.grab_mode {
|
||||
CursorGrabMode::None => (),
|
||||
_ => {
|
||||
// Using smallest of height or width ensures equal vertical and horizontal sensitivity
|
||||
pitch -= ev.delta.y.to_radians() * time.delta_seconds() * 5.;
|
||||
yaw -= ev.delta.x.to_radians() * time.delta_seconds() * 5.;
|
||||
}
|
||||
}
|
||||
|
||||
pitch = pitch.clamp(-1.54, 1.54);
|
||||
|
||||
// Order is important to prevent unintended roll
|
||||
transform.rotation = Quat::from_axis_angle(Vec3::Y, yaw) * Quat::from_axis_angle(Vec3::X, pitch);
|
||||
}
|
||||
}
|
||||
|
||||
fn grab_mouse(mut windows: Query<&mut Window>, mouse: Res<ButtonInput<MouseButton>>, key: Res<ButtonInput<KeyCode>>) {
|
||||
let mut window = windows.single_mut();
|
||||
|
||||
if mouse.just_pressed(MouseButton::Middle) {
|
||||
window.cursor.visible = false;
|
||||
window.cursor.grab_mode = CursorGrabMode::Locked;
|
||||
}
|
||||
|
||||
if key.just_pressed(KeyCode::Escape) {
|
||||
window.cursor.visible = true;
|
||||
window.cursor.grab_mode = CursorGrabMode::None;
|
||||
}
|
||||
}
|
||||
|
||||
fn rts_camera_system(
|
||||
mut cam_query: Query<(&mut Transform, &PhosCamera, &mut PhosCameraTargets)>,
|
||||
fn orbit_camera_upate(
|
||||
mut cam_query: Query<(&mut Transform, &PhosCamera, &mut PhosOrbitCamera, &CameraBounds)>,
|
||||
mut wheel: EventReader<MouseWheel>,
|
||||
mut mouse_motion: EventReader<MouseMotion>,
|
||||
mouse: Res<ButtonInput<MouseButton>>,
|
||||
mut window_query: Query<&mut Window, With<PrimaryWindow>>,
|
||||
key: Res<ButtonInput<KeyCode>>,
|
||||
time: Res<Time>,
|
||||
heightmap: Res<Map>,
|
||||
map: Res<Map>,
|
||||
#[cfg(debug_assertions)] mut gizmos: Gizmos,
|
||||
) {
|
||||
let (mut cam, cam_cfg, mut cam_targets) = cam_query.single_mut();
|
||||
let (mut transform, config, mut orbit, bounds) = cam_query.single_mut();
|
||||
let mut window = window_query.single_mut();
|
||||
|
||||
let target = orbit.target;
|
||||
let mut cam_pos = target;
|
||||
|
||||
//Apply Camera Dist
|
||||
cam_pos -= orbit.forward * orbit.distance;
|
||||
|
||||
if mouse.pressed(MouseButton::Middle) {
|
||||
let mut orbit_move = Vec2::ZERO;
|
||||
for e in mouse_motion.read() {
|
||||
orbit_move += e.delta;
|
||||
}
|
||||
orbit_move *= config.pan_speed * time.delta_secs() * -1.0;
|
||||
let rot_y = Quat::from_axis_angle(Vec3::Y, orbit_move.x);
|
||||
let right = orbit.forward.cross(Vec3::Y).normalize();
|
||||
let rot_x = Quat::from_axis_angle(right, orbit_move.y);
|
||||
orbit.forward = rot_x * rot_y * orbit.forward;
|
||||
// orbit.forward.y = orbit.forward.y.clamp(-0.9, 0.0);
|
||||
orbit.forward = orbit.forward.normalize();
|
||||
window.cursor_options.grab_mode = CursorGrabMode::Locked;
|
||||
window.cursor_options.visible = false;
|
||||
} else {
|
||||
window.cursor_options.grab_mode = CursorGrabMode::None;
|
||||
window.cursor_options.visible = true;
|
||||
}
|
||||
if key.pressed(KeyCode::KeyE) {
|
||||
let rot = Quat::from_axis_angle(Vec3::Y, f32::to_radians(config.speed) * time.delta_secs());
|
||||
orbit.forward = rot * orbit.forward;
|
||||
} else if key.pressed(KeyCode::KeyQ) {
|
||||
let rot = Quat::from_axis_angle(Vec3::Y, f32::to_radians(-config.speed) * time.delta_secs());
|
||||
orbit.forward = rot * orbit.forward;
|
||||
}
|
||||
|
||||
let mut cam_move = Vec3::ZERO;
|
||||
let mut cam_pos = cam.translation;
|
||||
|
||||
if key.pressed(KeyCode::KeyA) {
|
||||
cam_move.x = 1.;
|
||||
@@ -150,13 +122,26 @@ fn rts_camera_system(
|
||||
}
|
||||
|
||||
let move_speed = if key.pressed(KeyCode::ShiftLeft) {
|
||||
cam_cfg.speed * 2.
|
||||
config.speed * 2.0
|
||||
} else {
|
||||
cam_cfg.speed
|
||||
config.speed
|
||||
};
|
||||
|
||||
cam_move = cam_move.normalize_or_zero() * move_speed * time.delta_seconds();
|
||||
cam_pos -= cam_move;
|
||||
if cam_move != Vec3::ZERO {
|
||||
cam_move = cam_move.normalize();
|
||||
let move_fwd = Vec3::new(orbit.forward.x, 0., orbit.forward.z).normalize();
|
||||
let move_rot = Quat::from_rotation_arc(Vec3::NEG_Z, move_fwd);
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
gizmos.arrow(orbit.target, orbit.target + move_fwd, LinearRgba::WHITE.with_alpha(0.5));
|
||||
gizmos.arrow(orbit.target, orbit.target - (move_rot * cam_move), LinearRgba::BLUE);
|
||||
}
|
||||
orbit.target -= (move_rot * cam_move) * move_speed * time.delta_secs();
|
||||
orbit.target.y = sample_ground(orbit.target, &map);
|
||||
|
||||
orbit.target.x = orbit.target.x.clamp(bounds.min.x, bounds.max.x);
|
||||
orbit.target.z = orbit.target.z.clamp(bounds.min.y, bounds.max.y);
|
||||
}
|
||||
|
||||
let mut scroll = 0.0;
|
||||
for e in wheel.read() {
|
||||
@@ -166,53 +151,20 @@ fn rts_camera_system(
|
||||
}
|
||||
}
|
||||
|
||||
let ground_height = sample_ground(cam.translation, &heightmap);
|
||||
orbit.distance -= scroll * time.delta_secs() * config.zoom_speed;
|
||||
orbit.distance = orbit.distance.clamp(config.min_height, config.max_height);
|
||||
|
||||
cam_targets.height -= scroll;
|
||||
if cam_targets.height > cam_cfg.max_height {
|
||||
cam_targets.height = cam_cfg.max_height;
|
||||
}
|
||||
// let ground_below_cam = sample_ground(cam_pos, &map) + config.min_height;
|
||||
// if cam_pos.y <= ground_below_cam {
|
||||
// cam_pos.y = ground_below_cam;
|
||||
// }
|
||||
|
||||
let min_height = ground_height + cam_cfg.min_height;
|
||||
// if cam_pos.y < target.y {
|
||||
// cam_pos.y = target.y;
|
||||
// }
|
||||
|
||||
if min_height != cam_targets.last_height {
|
||||
cam_targets.last_height = min_height;
|
||||
cam_targets.anim_time = 0.;
|
||||
cam_targets.rotate_time = 0.;
|
||||
}
|
||||
|
||||
if scroll != 0. {
|
||||
cam_targets.anim_time = 0.;
|
||||
cam_targets.rotate_time = 0.;
|
||||
if cam_targets.height < min_height {
|
||||
cam_targets.height = min_height;
|
||||
}
|
||||
}
|
||||
|
||||
let desired_height = if cam_targets.height < min_height {
|
||||
min_height
|
||||
} else {
|
||||
cam_targets.height
|
||||
};
|
||||
if cam_targets.anim_time < 1. {
|
||||
cam_targets.anim_time += time.delta_seconds() * cam_cfg.zoom_speed;
|
||||
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. {
|
||||
cam_targets.rotate_time += time.delta_seconds();
|
||||
cam_targets.rotate_time = cam_targets.rotate_time.min(1.);
|
||||
}
|
||||
let angle = cam_cfg.min_angle.lerp(cam_cfg.max_angle, t);
|
||||
let rot = Quat::from_axis_angle(Vec3::X, -angle);
|
||||
cam.rotation = rot;
|
||||
|
||||
cam.translation = cam_pos;
|
||||
transform.translation = cam_pos;
|
||||
transform.look_at(target, Vec3::Y);
|
||||
}
|
||||
|
||||
fn sample_ground(pos: Vec3, heightmap: &Map) -> f32 {
|
||||
@@ -221,7 +173,7 @@ fn sample_ground(pos: Vec3, heightmap: &Map) -> f32 {
|
||||
let mut ground_height = if heightmap.is_in_bounds(&tile_under) {
|
||||
heightmap.sample_height(&tile_under)
|
||||
} else {
|
||||
heightmap.sea_level
|
||||
heightmap.sealevel
|
||||
};
|
||||
|
||||
for n in neighbors {
|
||||
@@ -231,19 +183,8 @@ fn sample_ground(pos: Vec3, heightmap: &Map) -> f32 {
|
||||
}
|
||||
}
|
||||
}
|
||||
if ground_height < heightmap.sea_level {
|
||||
ground_height = heightmap.sea_level;
|
||||
if ground_height < heightmap.sealevel {
|
||||
ground_height = heightmap.sealevel;
|
||||
}
|
||||
return ground_height;
|
||||
}
|
||||
|
||||
fn limit_camera_bounds(mut cam_query: Query<(&mut Transform, &CameraBounds)>) {
|
||||
let (mut tranform, bounds) = cam_query.single_mut();
|
||||
|
||||
let mut pos = tranform.translation;
|
||||
|
||||
pos.x = pos.x.clamp(bounds.min.x, bounds.max.x);
|
||||
pos.z = pos.z.clamp(bounds.min.y, bounds.max.y);
|
||||
|
||||
tranform.translation = pos;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use bevy::prelude::*;
|
||||
use bevy::{math::Direction3d, prelude::*};
|
||||
use rayon::str;
|
||||
use world_generation::{hex_utils::SHORT_DIAGONAL, prelude::Chunk};
|
||||
|
||||
#[derive(Component, Reflect)]
|
||||
@@ -8,6 +9,7 @@ pub struct PhosCamera {
|
||||
pub max_height: f32,
|
||||
pub speed: f32,
|
||||
pub zoom_speed: f32,
|
||||
pub pan_speed: Vec2,
|
||||
pub min_angle: f32,
|
||||
pub max_angle: f32,
|
||||
}
|
||||
@@ -18,30 +20,26 @@ impl Default for PhosCamera {
|
||||
min_height: 10.,
|
||||
max_height: 420.,
|
||||
speed: 100.,
|
||||
zoom_speed: 0.3,
|
||||
pan_speed: Vec2::new(0.8, 0.5),
|
||||
zoom_speed: 20.,
|
||||
min_angle: (20. as f32).to_radians(),
|
||||
max_angle: 1.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct PhosCameraTargets {
|
||||
pub height: f32,
|
||||
#[derive(Component, Reflect)]
|
||||
pub struct PhosOrbitCamera {
|
||||
pub target: Vec3,
|
||||
pub distance: f32,
|
||||
pub forward: Vec3,
|
||||
pub last_height: f32,
|
||||
pub anim_time: f32,
|
||||
pub rotate_time: f32,
|
||||
}
|
||||
|
||||
impl Default for PhosCameraTargets {
|
||||
impl Default for PhosOrbitCamera {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
height: Default::default(),
|
||||
forward: Vec3::Z,
|
||||
last_height: Default::default(),
|
||||
anim_time: Default::default(),
|
||||
rotate_time: Default::default(),
|
||||
target: Default::default(),
|
||||
distance: 40.0,
|
||||
forward: Vec3::new(0.0, -0.5, 0.5).normalize(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,14 +51,11 @@ pub struct CameraBounds {
|
||||
}
|
||||
|
||||
impl CameraBounds {
|
||||
pub fn from_size(size: UVec2) -> Self {
|
||||
pub fn from_size(world_size: Vec2) -> Self {
|
||||
let padding = Chunk::WORLD_SIZE;
|
||||
return Self {
|
||||
min: Vec2::ZERO - padding,
|
||||
max: Vec2::new(
|
||||
(size.x as usize * Chunk::SIZE) as f32 * SHORT_DIAGONAL,
|
||||
(size.y * Chunk::SIZE as u32) as f32 * 1.5,
|
||||
) + padding,
|
||||
max: world_size + padding,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use std::env;
|
||||
|
||||
use bevy::image::{ImageAddressMode, ImageFilterMode, ImageSamplerDescriptor};
|
||||
use bevy::pbr::wireframe::WireframePlugin;
|
||||
use bevy::prelude::*;
|
||||
use bevy::render::texture::{ImageAddressMode, ImageFilterMode, ImageSamplerDescriptor};
|
||||
use bevy::window::PresentMode;
|
||||
use bevy_inspector_egui::quick::WorldInspectorPlugin;
|
||||
use phos::PhosGamePlugin;
|
||||
@@ -10,6 +12,7 @@ mod map_rendering;
|
||||
mod phos;
|
||||
mod prelude;
|
||||
mod shader_extensions;
|
||||
mod ui;
|
||||
mod utlis;
|
||||
|
||||
fn main() {
|
||||
@@ -36,6 +39,11 @@ fn main() {
|
||||
mag_filter: ImageFilterMode::Nearest,
|
||||
..default()
|
||||
},
|
||||
})
|
||||
.set(AssetPlugin {
|
||||
#[cfg(not(debug_assertions))]
|
||||
watch_for_changes_override: Some(true),
|
||||
..Default::default()
|
||||
}),
|
||||
WorldInspectorPlugin::new(),
|
||||
WireframePlugin,
|
||||
|
||||
@@ -4,6 +4,8 @@ use bevy::tasks::*;
|
||||
use bevy::utils::futures;
|
||||
use bevy_rapier3d::geometry::Collider;
|
||||
use bevy_rapier3d::geometry::TriMeshFlags;
|
||||
use shared::events::ChunkModifiedEvent;
|
||||
use shared::events::TileModifiedEvent;
|
||||
use world_generation::prelude::Map;
|
||||
use world_generation::states::GeneratorState;
|
||||
|
||||
@@ -17,29 +19,26 @@ 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.run_if(in_state(GeneratorState::SpawnMap)));
|
||||
app.add_event::<ChunkModifiedEvent>();
|
||||
app.add_event::<TileModifiedEvent>();
|
||||
app.add_systems(PreUpdate, chunk_rebuilder.run_if(in_state(GeneratorState::Idle)));
|
||||
app.add_systems(PostUpdate, collider_task_resolver);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct ChunkRebuildQueue {
|
||||
pub queue: Vec<usize>,
|
||||
}
|
||||
|
||||
fn chunk_rebuilder(
|
||||
mut commands: Commands,
|
||||
chunk_query: Query<(Entity, &PhosChunk), (With<RebuildChunk>, Without<ChunkRebuildTask>)>,
|
||||
heightmap: Res<Map>,
|
||||
) {
|
||||
let pool = AsyncComputeTaskPool::get();
|
||||
let map_size = UVec2::new(heightmap.width as u32, heightmap.height as u32);
|
||||
|
||||
for (chunk_entity, idx) in &chunk_query {
|
||||
#[cfg(feature = "tracing")]
|
||||
let _spawn_span = info_span!("Rebuild Chunk").entered();
|
||||
|
||||
info!("Rebuilding Chunk");
|
||||
let chunk_index = idx.index;
|
||||
let chunk_data = heightmap.get_chunk_mesh_data(chunk_index);
|
||||
let chunk_offset = heightmap.chunks[chunk_index].chunk_offset;
|
||||
@@ -48,7 +47,8 @@ fn chunk_rebuilder(
|
||||
#[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);
|
||||
let (mesh, water_mesh, collider_data, _, _) =
|
||||
prepare_chunk_mesh(&chunk_data, chunk_data.sealevel, chunk_offset, chunk_index, map_size);
|
||||
#[cfg(feature = "tracing")]
|
||||
let trimesh_span = info_span!("Chunk Trimesh").entered();
|
||||
let c = Collider::trimesh_with_flags(
|
||||
@@ -73,14 +73,14 @@ fn chunk_rebuilder(
|
||||
}
|
||||
|
||||
fn collider_task_resolver(
|
||||
mut chunks: Query<(&mut ChunkRebuildTask, &Handle<Mesh>), With<PhosChunk>>,
|
||||
mut chunks: Query<(&mut ChunkRebuildTask, &Mesh3d), 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);
|
||||
meshes.insert(mesh_handle.id(), mesh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ use bevy::log::*;
|
||||
use bevy::{
|
||||
pbr::{ExtendedMaterial, NotShadowCaster},
|
||||
prelude::*,
|
||||
render::render_resource::{ColorTargetState, FragmentState, RenderPipelineDescriptor},
|
||||
};
|
||||
use bevy_asset_loader::prelude::*;
|
||||
|
||||
@@ -14,25 +15,22 @@ use world_generation::{
|
||||
biome_painter::*,
|
||||
heightmap::generate_heightmap,
|
||||
hex_utils::{offset_to_index, SHORT_DIAGONAL},
|
||||
map::biome_map::BiomeMap,
|
||||
prelude::*,
|
||||
tile_manager::*,
|
||||
tile_mapper::*,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
camera_system::components::*,
|
||||
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,
|
||||
},
|
||||
utlis::chunk_utils::{paint_map, prepare_chunk_mesh_with_collider},
|
||||
};
|
||||
|
||||
use super::{chunk_rebuild::ChunkRebuildPlugin, terraforming_test::TerraFormingTestPlugin};
|
||||
use super::{chunk_rebuild::ChunkRebuildPlugin, render_distance_system::RenderDistanceVisibility};
|
||||
|
||||
pub struct MapInitPlugin;
|
||||
|
||||
@@ -47,12 +45,11 @@ impl Plugin for MapInitPlugin {
|
||||
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((
|
||||
ChunkRebuildPlugin,
|
||||
TerraFormingTestPlugin,
|
||||
// TerraFormingTestPlugin,
|
||||
MaterialPlugin::<ExtendedMaterial<StandardMaterial, ChunkMaterial>>::default(),
|
||||
MaterialPlugin::<ExtendedMaterial<StandardMaterial, WaterMaterial>> {
|
||||
prepass_enabled: false,
|
||||
@@ -67,65 +64,49 @@ impl Plugin for MapInitPlugin {
|
||||
.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)),
|
||||
(finalize_texture, setup_materials, finalize_biome_painter)
|
||||
.run_if(in_state(AssetLoadState::FinalizeAssets)),
|
||||
);
|
||||
|
||||
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)),
|
||||
spawn_map.run_if(in_state(AssetLoadState::LoadComplete).and_then(in_state(GeneratorState::SpawnMap))),
|
||||
);
|
||||
|
||||
app.insert_resource(TileManager::default());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource, Reflect, Default)]
|
||||
#[reflect(Resource)]
|
||||
struct WaterInspect(Handle<ExtendedMaterial<StandardMaterial, WaterMaterial>>);
|
||||
|
||||
fn load_textures(
|
||||
mut commands: Commands,
|
||||
mut atlas: ResMut<PhosAssets>,
|
||||
fn setup_materials(
|
||||
mut phos_assets: ResMut<PhosAssets>,
|
||||
mut water_materials: ResMut<Assets<ExtendedMaterial<StandardMaterial, WaterMaterial>>>,
|
||||
) {
|
||||
let water_material = water_materials.add(ExtendedMaterial {
|
||||
base: StandardMaterial {
|
||||
base_color: Color::srgba(0., 0.5, 1., 0.8),
|
||||
base_color: Color::srgb(0., 0.878, 1.),
|
||||
alpha_mode: AlphaMode::Blend,
|
||||
metallic: 1.0,
|
||||
..Default::default()
|
||||
},
|
||||
extension: WaterMaterial {
|
||||
settings: WaterSettings {
|
||||
offset: 0.5,
|
||||
scale: 100.,
|
||||
offset: -4.97,
|
||||
scale: 1.,
|
||||
deep_color: LinearRgba::rgb(0.0, 0.04, 0.085).into(),
|
||||
..Default::default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
});
|
||||
commands.insert_resource(WaterInspect(water_material.clone()));
|
||||
atlas.water_material = water_material;
|
||||
phos_assets.water_material = water_material;
|
||||
}
|
||||
|
||||
fn finalize_biome_painter(
|
||||
@@ -134,10 +115,9 @@ fn finalize_biome_painter(
|
||||
biome_painter: Res<BiomePainterAsset>,
|
||||
biomes: Res<Assets<BiomeAsset>>,
|
||||
) {
|
||||
let biome_painter = biome_painter.build(&biomes);
|
||||
commands.insert_resource(biome_painter);
|
||||
let painter = biome_painter.build(&biomes);
|
||||
commands.insert_resource(painter);
|
||||
next_generator_state.set(GeneratorState::GenerateHeightmap);
|
||||
println!("Finalize Biome");
|
||||
}
|
||||
|
||||
fn finalize_texture(
|
||||
@@ -146,7 +126,6 @@ fn finalize_texture(
|
||||
mut chunk_materials: ResMut<Assets<ExtendedMaterial<StandardMaterial, ChunkMaterial>>>,
|
||||
mut next_load_state: ResMut<NextState<AssetLoadState>>,
|
||||
) {
|
||||
println!("Finalize Tex");
|
||||
let image = images.get_mut(atlas.handle.id()).unwrap();
|
||||
|
||||
let array_layers = image.height() / image.width();
|
||||
@@ -165,15 +144,14 @@ fn finalize_texture(
|
||||
|
||||
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 {
|
||||
biome_blend: 16,
|
||||
biome_dither: 16.,
|
||||
biome_blend: 32,
|
||||
biome_dither: 10.,
|
||||
continent_noise: NoiseConfig {
|
||||
scale: 500.,
|
||||
scale: 800.,
|
||||
layers: vec![GeneratorLayer {
|
||||
base_roughness: 2.14,
|
||||
roughness: 0.87,
|
||||
@@ -184,11 +162,10 @@ fn create_heightmap(
|
||||
weight: 0.,
|
||||
weight_multi: 0.,
|
||||
layers: 1,
|
||||
first_layer_mask: false,
|
||||
}],
|
||||
},
|
||||
moisture_noise: NoiseConfig {
|
||||
scale: 500.,
|
||||
scale: 900.,
|
||||
layers: vec![GeneratorLayer {
|
||||
base_roughness: 2.14,
|
||||
roughness: 0.87,
|
||||
@@ -199,11 +176,10 @@ fn create_heightmap(
|
||||
weight: 0.,
|
||||
weight_multi: 0.,
|
||||
layers: 1,
|
||||
first_layer_mask: false,
|
||||
}],
|
||||
},
|
||||
temperature_noise: NoiseConfig {
|
||||
scale: 500.,
|
||||
scale: 700.,
|
||||
layers: vec![GeneratorLayer {
|
||||
base_roughness: 2.14,
|
||||
roughness: 0.87,
|
||||
@@ -214,7 +190,6 @@ fn create_heightmap(
|
||||
weight: 0.,
|
||||
weight_multi: 0.,
|
||||
layers: 1,
|
||||
first_layer_mask: false,
|
||||
}],
|
||||
},
|
||||
sea_level: 8.5,
|
||||
@@ -222,13 +197,10 @@ fn create_heightmap(
|
||||
size: UVec2::splat(16),
|
||||
// size: UVec2::splat(1),
|
||||
};
|
||||
let heightmap = generate_heightmap(&config, 42069, &biome_painter);
|
||||
let (heightmap, biome_map) = 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(biome_map);
|
||||
commands.insert_resource(config);
|
||||
next_state.set(GeneratorState::SpawnMap);
|
||||
}
|
||||
@@ -248,16 +220,26 @@ fn spawn_map(
|
||||
) {
|
||||
paint_map(&mut heightmap, &biome_painter, &tile_assets, &tile_mappers);
|
||||
|
||||
//Prepare Mesh Data
|
||||
let map_size = UVec2::new(heightmap.width as u32, heightmap.height as u32);
|
||||
let chunk_meshes: Vec<_> = heightmap
|
||||
.chunks
|
||||
.par_iter()
|
||||
.map(|chunk: &Chunk| {
|
||||
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);
|
||||
return prepare_chunk_mesh_with_collider(
|
||||
&heightmap.get_chunk_mesh_data(index),
|
||||
heightmap.sealevel,
|
||||
chunk.chunk_offset,
|
||||
index,
|
||||
map_size,
|
||||
);
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut registry = PhosChunkRegistry::new(chunk_meshes.len());
|
||||
|
||||
//Spawn Chunks
|
||||
{
|
||||
#[cfg(feature = "tracing")]
|
||||
let _spawn_span = info_span!("Spawn Chunks").entered();
|
||||
@@ -266,36 +248,32 @@ fn spawn_map(
|
||||
0.,
|
||||
(Chunk::SIZE / 2) as f32 * 1.5,
|
||||
);
|
||||
for (mesh, collider, pos, index) in chunk_meshes {
|
||||
for (chunk_mesh, water_mesh, collider, pos, index) in chunk_meshes {
|
||||
// let mesh_handle = meshes.a
|
||||
let chunk = commands.spawn((
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.add(mesh),
|
||||
material: atlas.chunk_material_handle.clone(),
|
||||
transform: Transform::from_translation(pos),
|
||||
..default()
|
||||
},
|
||||
let chunk = commands
|
||||
.spawn((
|
||||
Mesh3d(meshes.add(chunk_mesh)),
|
||||
MeshMaterial3d(atlas.chunk_material_handle.clone()),
|
||||
Transform::from_translation(pos),
|
||||
PhosChunk::new(index),
|
||||
RenderDistanceVisibility::default().with_offset(visibility_offset),
|
||||
collider,
|
||||
));
|
||||
registry.chunks.push(chunk.id());
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
},
|
||||
))
|
||||
.id();
|
||||
let water = commands
|
||||
.spawn((
|
||||
Mesh3d(meshes.add(water_mesh)),
|
||||
MeshMaterial3d(atlas.water_material.clone()),
|
||||
Transform::from_translation(pos),
|
||||
PhosChunk::new(index),
|
||||
NotShadowCaster,
|
||||
));
|
||||
RenderDistanceVisibility::default().with_offset(visibility_offset),
|
||||
))
|
||||
.id();
|
||||
registry.chunks.push(chunk);
|
||||
registry.waters.push(water);
|
||||
}
|
||||
}
|
||||
|
||||
commands.insert_resource(registry);
|
||||
generator_state.set(GeneratorState::Idle);
|
||||
@@ -308,6 +286,7 @@ fn spawn_map(
|
||||
fn despawn_map(
|
||||
mut commands: Commands,
|
||||
mut heightmap: ResMut<Map>,
|
||||
mut biome_map: ResMut<BiomeMap>,
|
||||
cfg: Res<GenerationConfig>,
|
||||
chunks: Query<Entity, With<PhosChunk>>,
|
||||
mut next_state: ResMut<NextState<GeneratorState>>,
|
||||
@@ -317,6 +296,6 @@ fn despawn_map(
|
||||
commands.entity(chunk).despawn();
|
||||
}
|
||||
|
||||
*heightmap = generate_heightmap(&cfg, 4, &biome_painter);
|
||||
(*heightmap, *biome_map) = generate_heightmap(&cfg, 4, &biome_painter);
|
||||
next_state.set(GeneratorState::SpawnMap);
|
||||
}
|
||||
|
||||
@@ -2,3 +2,4 @@ pub mod chunk_rebuild;
|
||||
pub mod map_init;
|
||||
pub mod prelude;
|
||||
pub mod terraforming_test;
|
||||
pub mod render_distance_system;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use bevy::prelude::*;
|
||||
use shared::tags::MainCamera;
|
||||
|
||||
use crate::camera_system::components::PhosCamera;
|
||||
|
||||
@@ -52,12 +53,13 @@ impl Default for RenderDistanceVisibility {
|
||||
|
||||
fn render_distance_system(
|
||||
mut objects: Query<(&Transform, &mut Visibility, &RenderDistanceVisibility)>,
|
||||
camera_query: Query<&Transform, With<PhosCamera>>,
|
||||
camera_query: Query<&Transform, With<MainCamera>>,
|
||||
settings: Res<RenderDistanceSettings>,
|
||||
) {
|
||||
let camera = camera_query.single();
|
||||
let cam_pos = Vec3::new(camera.translation.x, 0.0, camera.translation.z);
|
||||
for (t, mut vis, r) in objects.iter_mut() {
|
||||
let dist = (camera.translation - (t.translation + r.offset)).length();
|
||||
let dist = (cam_pos - (t.translation + r.offset)).length();
|
||||
if settings.render_distance < dist {
|
||||
*vis = Visibility::Hidden;
|
||||
} else {
|
||||
@@ -1,5 +1,10 @@
|
||||
use bevy::{prelude::*, window::PrimaryWindow};
|
||||
use bevy::{prelude::*, utils::hashbrown::HashSet, window::PrimaryWindow};
|
||||
use bevy_rapier3d::{pipeline::QueryFilter, plugin::RapierContext};
|
||||
use shared::{
|
||||
events::{ChunkModifiedEvent, TileModifiedEvent},
|
||||
resources::TileUnderCursor,
|
||||
states::GameplayState,
|
||||
};
|
||||
use world_generation::{hex_utils::HexCoord, prelude::Map, states::GeneratorState};
|
||||
|
||||
use crate::{
|
||||
@@ -11,18 +16,23 @@ pub struct TerraFormingTestPlugin;
|
||||
|
||||
impl Plugin for TerraFormingTestPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(Update, deform.run_if(in_state(GeneratorState::Idle)));
|
||||
app.add_systems(
|
||||
Update,
|
||||
deform
|
||||
.run_if(in_state(GeneratorState::Idle))
|
||||
.run_if(in_state(GameplayState::Playing)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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>,
|
||||
chunks: Res<PhosChunkRegistry>,
|
||||
tile_under_cursor: Res<TileUnderCursor>,
|
||||
mut chunk_modified: EventWriter<ChunkModifiedEvent>,
|
||||
mut tile_modified: EventWriter<TileModifiedEvent>,
|
||||
) {
|
||||
let mut multi = 0.;
|
||||
if mouse.just_pressed(MouseButton::Left) {
|
||||
@@ -35,33 +45,20 @@ fn deform(
|
||||
return;
|
||||
}
|
||||
|
||||
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 {
|
||||
if let Some(contact) = tile_under_cursor.0 {
|
||||
#[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 modified_chunks = heightmap.create_crater(&contact_coord, 5, 5. * multi);
|
||||
for c in modified_chunks {
|
||||
commands.entity(chunks.chunks[c]).insert(RebuildChunk);
|
||||
let modified_tiles = heightmap.create_crater(&contact.tile, 5, 5. * multi);
|
||||
let mut chunk_set: HashSet<usize> = HashSet::new();
|
||||
for (tile, height) in modified_tiles {
|
||||
let chunk = tile.to_chunk_index(heightmap.width);
|
||||
if !chunk_set.contains(&chunk) {
|
||||
chunk_modified.send(ChunkModifiedEvent { index: chunk });
|
||||
chunk_set.insert(chunk);
|
||||
commands.entity(chunks.chunks[chunk]).insert(RebuildChunk);
|
||||
}
|
||||
commands.entity(e).insert(RebuildChunk);
|
||||
tile_modified.send(TileModifiedEvent::HeightChanged(tile, height));
|
||||
}
|
||||
// commands.entity(e).insert(RebuildChunk);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use crate::camera_system::camera_plugin::PhosCameraPlugin;
|
||||
use crate::camera_system::components::PhosCamera;
|
||||
use crate::map_rendering::map_init::MapInitPlugin;
|
||||
use crate::utlis::render_distance_system::RenderDistancePlugin;
|
||||
use crate::map_rendering::render_distance_system::RenderDistancePlugin;
|
||||
use crate::ui::build_ui::BuildUIPlugin;
|
||||
use crate::utlis::editor_plugin::EditorPlugin;
|
||||
use crate::utlis::tile_selection_plugin::TileSelectionPlugin;
|
||||
use crate::{camera_system::camera_plugin::PhosCameraPlugin, utlis::debug_plugin::DebugPlugin};
|
||||
use bevy::{
|
||||
pbr::{wireframe::WireframeConfig, CascadeShadowConfig},
|
||||
prelude::*,
|
||||
@@ -11,9 +14,13 @@ 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 iyes_perf_ui::prelude::*;
|
||||
use shared::animation_plugin::SimpleAnimationPlugin;
|
||||
use shared::sets::GameplaySet;
|
||||
use shared::states::{GameplayState, MenuState};
|
||||
use shared::{despawn::DespawnPuglin, states::AssetLoadState};
|
||||
use units::units_plugin::UnitsPlugin;
|
||||
use world_generation::states::GeneratorState;
|
||||
|
||||
pub struct PhosGamePlugin;
|
||||
|
||||
@@ -31,10 +38,20 @@ impl Plugin for PhosGamePlugin {
|
||||
PhosCameraPlugin,
|
||||
MapInitPlugin,
|
||||
RenderDistancePlugin,
|
||||
// BuildingPugin,
|
||||
BuildingPugin,
|
||||
BuildUIPlugin,
|
||||
SimpleAnimationPlugin,
|
||||
UnitsPlugin,
|
||||
DespawnPuglin,
|
||||
TileSelectionPlugin,
|
||||
#[cfg(debug_assertions)]
|
||||
EditorPlugin,
|
||||
#[cfg(debug_assertions)]
|
||||
DebugPlugin,
|
||||
));
|
||||
|
||||
configure_gameplay_set(app);
|
||||
|
||||
//Systems - Startup
|
||||
app.add_systems(Startup, init_game);
|
||||
|
||||
@@ -44,8 +61,8 @@ impl Plugin for PhosGamePlugin {
|
||||
//Perf UI
|
||||
app.add_plugins(bevy::diagnostic::FrameTimeDiagnosticsPlugin)
|
||||
.add_plugins(bevy::diagnostic::EntityCountDiagnosticsPlugin)
|
||||
.add_plugins(bevy::diagnostic::SystemInformationDiagnosticsPlugin)
|
||||
.add_plugins(PerfUiPlugin);
|
||||
.add_plugins(bevy::diagnostic::SystemInformationDiagnosticsPlugin);
|
||||
// .add_plugins(PerfUiPlugin);
|
||||
|
||||
//Physics
|
||||
app.add_plugins(RapierPhysicsPlugin::<NoUserData>::default());
|
||||
@@ -58,27 +75,54 @@ impl Plugin for PhosGamePlugin {
|
||||
}
|
||||
}
|
||||
|
||||
fn init_game(mut commands: Commands, mut materials: ResMut<Assets<StandardMaterial>>) {
|
||||
commands.spawn((
|
||||
PerfUiRoot::default(),
|
||||
PerfUiEntryFPS::default(),
|
||||
PerfUiEntryFPSWorst::default(),
|
||||
PerfUiEntryFrameTime::default(),
|
||||
PerfUiEntryFrameTimeWorst::default(),
|
||||
));
|
||||
fn configure_gameplay_set(app: &mut App) {
|
||||
app.configure_sets(
|
||||
Update,
|
||||
GameplaySet.run_if(in_state(GeneratorState::Idle).and(in_state(MenuState::InGame))),
|
||||
);
|
||||
app.configure_sets(
|
||||
PreUpdate,
|
||||
GameplaySet.run_if(in_state(GeneratorState::Idle).and(in_state(MenuState::InGame))),
|
||||
);
|
||||
app.configure_sets(
|
||||
PostUpdate,
|
||||
GameplaySet.run_if(in_state(GeneratorState::Idle).and(in_state(MenuState::InGame))),
|
||||
);
|
||||
|
||||
commands.spawn(DirectionalLightBundle {
|
||||
directional_light: DirectionalLight {
|
||||
app.configure_sets(
|
||||
FixedUpdate,
|
||||
GameplaySet.run_if(in_state(GeneratorState::Idle).and(in_state(MenuState::InGame))),
|
||||
);
|
||||
app.configure_sets(
|
||||
FixedPreUpdate,
|
||||
GameplaySet.run_if(in_state(GeneratorState::Idle).and(in_state(MenuState::InGame))),
|
||||
);
|
||||
app.configure_sets(
|
||||
FixedPostUpdate,
|
||||
GameplaySet.run_if(in_state(GeneratorState::Idle).and(in_state(MenuState::InGame))),
|
||||
);
|
||||
}
|
||||
|
||||
fn init_game(mut commands: Commands, mut materials: ResMut<Assets<StandardMaterial>>) {
|
||||
// commands.spawn((
|
||||
// PerfUiRoot::default(),
|
||||
// PerfUiEntryFPS::default(),
|
||||
// PerfUiEntryFPSWorst::default(),
|
||||
// PerfUiEntryFrameTime::default(),
|
||||
// PerfUiEntryFrameTimeWorst::default(),
|
||||
// ));
|
||||
|
||||
commands.spawn((
|
||||
DirectionalLight {
|
||||
shadows_enabled: true,
|
||||
..default()
|
||||
},
|
||||
cascade_shadow_config: CascadeShadowConfig {
|
||||
CascadeShadowConfig {
|
||||
bounds: vec![200., 400., 600., 800.],
|
||||
..default()
|
||||
},
|
||||
transform: Transform::from_xyz(500., 260.0, 500.).looking_at(Vec3::ZERO, Vec3::Y),
|
||||
..default()
|
||||
});
|
||||
Transform::from_xyz(500., 260.0, 500.).looking_at(Vec3::ZERO, Vec3::Y),
|
||||
));
|
||||
|
||||
let sphere_mat = StandardMaterial {
|
||||
base_color: Color::srgb(1., 1., 0.),
|
||||
@@ -101,12 +145,9 @@ fn spawn_sphere(
|
||||
if keyboard_input.just_pressed(KeyCode::KeyF) {
|
||||
let cam_transform = cam.single();
|
||||
commands.spawn((
|
||||
MaterialMeshBundle {
|
||||
mesh: meshes.add(Sphere::new(0.3)),
|
||||
material: mat.0.clone(),
|
||||
transform: Transform::from_translation(cam_transform.translation),
|
||||
..default()
|
||||
},
|
||||
Mesh3d(meshes.add(Sphere::new(0.3))),
|
||||
MeshMaterial3d(mat.0.clone()),
|
||||
Transform::from_translation(cam_transform.translation),
|
||||
Collider::ball(0.3),
|
||||
RigidBody::Dynamic,
|
||||
Ccd::enabled(),
|
||||
|
||||
@@ -30,12 +30,14 @@ impl PhosChunk {
|
||||
#[derive(Resource, Default)]
|
||||
pub struct PhosChunkRegistry {
|
||||
pub chunks: Vec<Entity>,
|
||||
pub waters: Vec<Entity>,
|
||||
}
|
||||
|
||||
impl PhosChunkRegistry {
|
||||
pub fn new(size: usize) -> Self {
|
||||
return Self {
|
||||
chunks: Vec::with_capacity(size),
|
||||
waters: Vec::with_capacity(size),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use bevy::asset::{Asset, Handle};
|
||||
use bevy::pbr::MaterialExtension;
|
||||
use bevy::image::Image;
|
||||
use bevy::pbr::{Material, MaterialExtension};
|
||||
use bevy::reflect::TypePath;
|
||||
use bevy::render::mesh::{MeshVertexAttribute, MeshVertexBufferLayoutRef};
|
||||
use bevy::render::render_resource::{AsBindGroup, ShaderRef};
|
||||
use bevy::render::texture::Image;
|
||||
use world_generation::consts::{ATTRIBUTE_PACKED_VERTEX_DATA, ATTRIBUTE_VERTEX_HEIGHT};
|
||||
|
||||
#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
|
||||
pub struct ChunkMaterial {
|
||||
@@ -15,25 +17,50 @@ impl MaterialExtension for ChunkMaterial {
|
||||
fn fragment_shader() -> ShaderRef {
|
||||
"shaders/world/chunk.wgsl".into()
|
||||
}
|
||||
}
|
||||
|
||||
// fn vertex_shader() -> ShaderRef {
|
||||
#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
|
||||
pub struct PackedChunkMaterial {
|
||||
#[texture(100, dimension = "2d_array")]
|
||||
#[sampler(101)]
|
||||
pub array_texture: Handle<Image>,
|
||||
}
|
||||
|
||||
impl Material for PackedChunkMaterial {
|
||||
fn fragment_shader() -> ShaderRef {
|
||||
"shaders/world/chunk.wgsl".into()
|
||||
}
|
||||
|
||||
fn vertex_shader() -> ShaderRef {
|
||||
"shaders/world/chunk_packed.wgsl".into()
|
||||
}
|
||||
|
||||
fn prepass_vertex_shader() -> ShaderRef {
|
||||
"shaders/world/chunk_packed.wgsl".into()
|
||||
}
|
||||
|
||||
// fn deferred_vertex_shader() -> ShaderRef {
|
||||
// "shaders/world/chunk_packed.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(())
|
||||
// fn opaque_render_method(&self) -> bevy::pbr::OpaqueRendererMethod {
|
||||
// return OpaqueRendererMethod::Auto;
|
||||
// }
|
||||
|
||||
fn specialize(
|
||||
_pipeline: &bevy::pbr::MaterialPipeline<Self>,
|
||||
descriptor: &mut bevy::render::render_resource::RenderPipelineDescriptor,
|
||||
layout: &MeshVertexBufferLayoutRef,
|
||||
_key: bevy::pbr::MaterialPipelineKey<Self>,
|
||||
) -> Result<(), bevy::render::render_resource::SpecializedMeshPipelineError> {
|
||||
let vertex_layout = layout.0.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(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@ pub struct WaterMaterial {
|
||||
pub struct WaterSettings {
|
||||
pub offset: f32,
|
||||
pub scale: f32,
|
||||
pub deep_color: Vec3,
|
||||
pub f_power: f32,
|
||||
pub deep_color: LinearRgba,
|
||||
}
|
||||
|
||||
impl Default for WaterSettings {
|
||||
@@ -23,7 +24,8 @@ impl Default for WaterSettings {
|
||||
Self {
|
||||
offset: 0.0,
|
||||
scale: 1.0,
|
||||
deep_color: Vec3::ZERO,
|
||||
f_power: 2.0,
|
||||
deep_color: default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
38
game/main/src/ui/build_ui.rs
Normal file
38
game/main/src/ui/build_ui.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
use bevy::{
|
||||
prelude::*,
|
||||
render::{camera::RenderTarget, view::RenderLayers},
|
||||
};
|
||||
use shared::{states::AssetLoadState, tags::MainCamera};
|
||||
pub struct BuildUIPlugin;
|
||||
|
||||
impl Plugin for BuildUIPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(Startup, setup_cameras);
|
||||
app.add_systems(Update, spawn_ui.run_if(in_state(AssetLoadState::LoadComplete)));
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_cameras(mut commands: Commands) {
|
||||
commands.spawn((Camera2d, IsDefaultUiCamera, UiBoxShadowSamples(6)));
|
||||
}
|
||||
|
||||
fn spawn_ui(mut commands: Commands) {
|
||||
commands
|
||||
.spawn((Node {
|
||||
width: Val::Percent(100.),
|
||||
height: Val::Percent(100.),
|
||||
justify_content: JustifyContent::Center,
|
||||
align_items: AlignItems::End,
|
||||
..default()
|
||||
},))
|
||||
.insert(PickingBehavior::IGNORE)
|
||||
.with_children(|parent| {
|
||||
parent.spawn((
|
||||
Node {
|
||||
width: Val::Px(500.),
|
||||
..Default::default()
|
||||
},
|
||||
BackgroundColor(LinearRgba::GREEN.into()),
|
||||
));
|
||||
});
|
||||
}
|
||||
1
game/main/src/ui/mod.rs
Normal file
1
game/main/src/ui/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod build_ui;
|
||||
@@ -3,14 +3,18 @@ use bevy::log::*;
|
||||
use bevy::{
|
||||
asset::Assets,
|
||||
ecs::system::Res,
|
||||
math::{IVec2, Vec3},
|
||||
math::{IVec2, UVec2, 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},
|
||||
generators::{
|
||||
chunk_colliders::generate_chunk_collider,
|
||||
mesh_generator::{generate_chunk_mesh, generate_chunk_water_mesh},
|
||||
packed_mesh_generator::generate_packed_chunk_mesh,
|
||||
},
|
||||
hex_utils::offset_to_world,
|
||||
prelude::{Chunk, Map, MeshChunkData},
|
||||
tile_manager::TileAsset,
|
||||
@@ -50,16 +54,20 @@ pub fn paint_chunk(
|
||||
|
||||
pub fn prepare_chunk_mesh(
|
||||
chunk: &MeshChunkData,
|
||||
sealevel: f32,
|
||||
chunk_offset: IVec2,
|
||||
chunk_index: usize,
|
||||
) -> (Mesh, (Vec<Vec3>, Vec<[u32; 3]>), Vec3, usize) {
|
||||
map_size: UVec2,
|
||||
) -> (Mesh, 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 chunk_mesh = generate_chunk_mesh(chunk);
|
||||
let water_mesh = generate_chunk_water_mesh(chunk, sealevel, map_size.x as usize, map_size.y as usize);
|
||||
let col_data = generate_chunk_collider(chunk);
|
||||
|
||||
return (
|
||||
mesh,
|
||||
chunk_mesh,
|
||||
water_mesh,
|
||||
col_data,
|
||||
offset_to_world(chunk_offset * Chunk::SIZE as i32, 0.),
|
||||
chunk_index,
|
||||
@@ -68,15 +76,18 @@ pub fn prepare_chunk_mesh(
|
||||
|
||||
pub fn prepare_chunk_mesh_with_collider(
|
||||
chunk: &MeshChunkData,
|
||||
sealevel: f32,
|
||||
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);
|
||||
map_size: UVec2,
|
||||
) -> (Mesh, Mesh, Collider, Vec3, usize) {
|
||||
let (chunk_mesh, water_mesh, (col_verts, col_indicies), pos, index) =
|
||||
prepare_chunk_mesh(chunk, sealevel, chunk_offset, chunk_index, map_size);
|
||||
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);
|
||||
return (chunk_mesh, water_mesh, collider, pos, index);
|
||||
}
|
||||
|
||||
100
game/main/src/utlis/debug_plugin.rs
Normal file
100
game/main/src/utlis/debug_plugin.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
use bevy::{gizmos::gizmos, prelude::*};
|
||||
use shared::states::GameplayState;
|
||||
use shared::{resources::TileUnderCursor, sets::GameplaySet};
|
||||
use world_generation::{
|
||||
consts::{HEX_CORNERS, WATER_HEX_CORNERS},
|
||||
prelude::Map,
|
||||
states::GeneratorState,
|
||||
};
|
||||
|
||||
use crate::camera_system::components::{PhosCamera, PhosOrbitCamera};
|
||||
|
||||
pub struct DebugPlugin;
|
||||
|
||||
impl Plugin for DebugPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.insert_state(DebugState::Base);
|
||||
|
||||
app.add_systems(
|
||||
Update,
|
||||
show_tile_heights
|
||||
.run_if(in_state(GeneratorState::Idle))
|
||||
.run_if(not(in_state(DebugState::None))),
|
||||
);
|
||||
|
||||
app.add_systems(
|
||||
Update,
|
||||
verbose_data
|
||||
.run_if(in_state(GeneratorState::Idle))
|
||||
.run_if(in_state(DebugState::Verbose)),
|
||||
);
|
||||
|
||||
// app.add_systems(Update, camera_debug.in_set(GameplaySet));
|
||||
app.add_systems(Update, regenerate_map.run_if(in_state(GeneratorState::Idle)));
|
||||
|
||||
app.insert_resource(Shape(Polyline3d::new([
|
||||
HEX_CORNERS[0],
|
||||
HEX_CORNERS[1],
|
||||
HEX_CORNERS[2],
|
||||
HEX_CORNERS[3],
|
||||
HEX_CORNERS[4],
|
||||
HEX_CORNERS[5],
|
||||
HEX_CORNERS[0],
|
||||
])));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct Shape(pub Polyline3d<7>);
|
||||
|
||||
#[derive(States, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum DebugState {
|
||||
Base,
|
||||
None,
|
||||
Verbose,
|
||||
}
|
||||
|
||||
fn regenerate_map(
|
||||
mut generator_state: ResMut<NextState<GeneratorState>>,
|
||||
mut gameplay_state: ResMut<NextState<GameplayState>>,
|
||||
input: Res<ButtonInput<KeyCode>>,
|
||||
) {
|
||||
if input.just_pressed(KeyCode::KeyR) {
|
||||
generator_state.set(GeneratorState::Regenerate);
|
||||
gameplay_state.set(GameplayState::PlaceHQ);
|
||||
}
|
||||
}
|
||||
|
||||
fn show_tile_heights(map: Res<Map>, mut gizmos: Gizmos, shape: Res<Shape>, tile_under_cursor: Res<TileUnderCursor>) {
|
||||
if let Some(contact) = tile_under_cursor.0 {
|
||||
let height = map.sample_height(&contact.tile);
|
||||
gizmos.primitive_3d(&shape.0, contact.tile.to_world(height + 0.01), Color::WHITE);
|
||||
|
||||
gizmos.line(contact.point, contact.point + Vec3::X, LinearRgba::RED);
|
||||
gizmos.line(contact.point, contact.point + Vec3::Y, LinearRgba::GREEN);
|
||||
gizmos.line(contact.point, contact.point + Vec3::Z, LinearRgba::BLUE);
|
||||
|
||||
// show_water_corners(contact.tile.to_world(height + 1.0), &mut gizmos);
|
||||
}
|
||||
}
|
||||
|
||||
fn show_water_corners(pos: Vec3, gizmos: &mut Gizmos) {
|
||||
for i in 0..WATER_HEX_CORNERS.len() {
|
||||
let p = pos + WATER_HEX_CORNERS[i];
|
||||
let p2 = pos + WATER_HEX_CORNERS[(i + 1) % WATER_HEX_CORNERS.len()];
|
||||
|
||||
gizmos.line(p, p2, LinearRgba::RED);
|
||||
}
|
||||
}
|
||||
|
||||
fn camera_debug(mut cam_query: Query<(&PhosCamera, &PhosOrbitCamera)>, mut gizmos: Gizmos) {
|
||||
let (config, orbit) = cam_query.single();
|
||||
|
||||
gizmos.sphere(orbit.target, 0.3, LinearRgba::RED);
|
||||
let cam_proxy = orbit.target - (orbit.forward * 10.0);
|
||||
gizmos.ray(orbit.target, orbit.forward * 10.0, LinearRgba::rgb(1.0, 0.0, 1.0));
|
||||
|
||||
gizmos.circle(cam_proxy, 0.3, LinearRgba::rgb(1.0, 1.0, 0.0));
|
||||
}
|
||||
|
||||
fn verbose_data() {}
|
||||
161
game/main/src/utlis/editor_plugin.rs
Normal file
161
game/main/src/utlis/editor_plugin.rs
Normal file
@@ -0,0 +1,161 @@
|
||||
use bevy::{prelude::*, render::render_asset::RenderAssetUsages};
|
||||
use bevy_inspector_egui::bevy_egui::EguiContexts;
|
||||
use bevy_inspector_egui::egui::{self};
|
||||
use image::{ImageBuffer, Rgba};
|
||||
use world_generation::biome_asset::BiomeAsset;
|
||||
use world_generation::biome_painter::BiomePainterAsset;
|
||||
use world_generation::map::biome_map::BiomeMap;
|
||||
use world_generation::map::map_utils::{render_biome_map, render_biome_noise_map};
|
||||
use world_generation::{map::map_utils::render_map, prelude::Map, states::GeneratorState};
|
||||
|
||||
pub struct EditorPlugin;
|
||||
|
||||
impl Plugin for EditorPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<UIState>();
|
||||
|
||||
// app.add_systems(PostUpdate, prepare_image.run_if(in_state(GeneratorState::SpawnMap)));
|
||||
// app.add_systems(
|
||||
// Update,
|
||||
// (render_map_ui, update_map_render, asset_reloaded).run_if(in_state(GeneratorState::Idle)),
|
||||
// );
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct MapImage(pub Handle<Image>);
|
||||
|
||||
pub fn prepare_image(mut images: ResMut<Assets<Image>>, heightmap: Res<Map>, mut commands: Commands) {
|
||||
let image = render_map(&heightmap, 0.1);
|
||||
let handle = images.add(Image::from_dynamic(image.into(), true, RenderAssetUsages::RENDER_WORLD));
|
||||
|
||||
commands.insert_resource(MapImage(handle));
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct UIState {
|
||||
pub is_open: bool,
|
||||
pub target_map_type: MapDisplayType,
|
||||
pub cur_map_type: MapDisplayType,
|
||||
}
|
||||
|
||||
impl Default for UIState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
is_open: true,
|
||||
target_map_type: default(),
|
||||
cur_map_type: default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
|
||||
enum MapDisplayType {
|
||||
#[default]
|
||||
HeightMap,
|
||||
Biomes,
|
||||
BiomeNoise,
|
||||
BiomeNoiseTemp,
|
||||
BiomeNoiseContinent,
|
||||
BiomeNoiseMoisture,
|
||||
}
|
||||
|
||||
fn asset_reloaded(
|
||||
mut asset_events: EventReader<AssetEvent<BiomeAsset>>,
|
||||
mut biomes: ResMut<Assets<BiomeAsset>>,
|
||||
biome_painter: Res<BiomePainterAsset>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
let mut rebuild = false;
|
||||
for event in asset_events.read() {
|
||||
match event {
|
||||
AssetEvent::Modified { .. } => rebuild = true,
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
if rebuild {
|
||||
let painter = biome_painter.build(&biomes);
|
||||
commands.insert_resource(painter);
|
||||
}
|
||||
}
|
||||
|
||||
fn render_map_ui(
|
||||
image: Res<MapImage>,
|
||||
heightmap: Res<Map>,
|
||||
biome_map: Res<BiomeMap>,
|
||||
mut contexts: EguiContexts,
|
||||
mut state: ResMut<UIState>,
|
||||
) {
|
||||
let id = contexts.add_image(image.0.clone_weak());
|
||||
|
||||
let mut map_type = state.target_map_type;
|
||||
let ctx = contexts.ctx_mut();
|
||||
egui::Window::new("Map").open(&mut state.is_open).show(ctx, |ui| {
|
||||
ui.label("Map Test");
|
||||
egui::ComboBox::from_label("Display Type")
|
||||
.selected_text(format!("{:?}", map_type))
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut map_type, MapDisplayType::HeightMap, "Heightmap");
|
||||
ui.selectable_value(&mut map_type, MapDisplayType::Biomes, "Biomes");
|
||||
ui.selectable_value(&mut map_type, MapDisplayType::BiomeNoise, "Biome Noise");
|
||||
ui.selectable_value(
|
||||
&mut map_type,
|
||||
MapDisplayType::BiomeNoiseTemp,
|
||||
"Biome Noise: Tempurature",
|
||||
);
|
||||
ui.selectable_value(
|
||||
&mut map_type,
|
||||
MapDisplayType::BiomeNoiseContinent,
|
||||
"Biome Noise: Continent",
|
||||
);
|
||||
ui.selectable_value(
|
||||
&mut map_type,
|
||||
MapDisplayType::BiomeNoiseMoisture,
|
||||
"Biome Noise: Moisture",
|
||||
);
|
||||
});
|
||||
|
||||
ui.add(egui::widgets::Image::new(egui::load::SizedTexture::new(
|
||||
id,
|
||||
[512.0, 512.0],
|
||||
)));
|
||||
|
||||
if ui.button("Save Image").clicked() {
|
||||
let img = get_map_image(&heightmap, &biome_map, map_type);
|
||||
_ = img.save(format!("{:?}.png", map_type));
|
||||
}
|
||||
});
|
||||
|
||||
state.target_map_type = map_type;
|
||||
}
|
||||
|
||||
fn update_map_render(
|
||||
mut state: ResMut<UIState>,
|
||||
mut images: ResMut<Assets<Image>>,
|
||||
heightmap: Res<Map>,
|
||||
biome_map: Res<BiomeMap>,
|
||||
image: Res<MapImage>,
|
||||
) {
|
||||
if state.cur_map_type == state.target_map_type {
|
||||
return;
|
||||
}
|
||||
|
||||
let result = get_map_image(&heightmap, &biome_map, state.target_map_type);
|
||||
images.insert(
|
||||
image.0.id(),
|
||||
Image::from_dynamic(result.into(), true, RenderAssetUsages::RENDER_WORLD),
|
||||
);
|
||||
|
||||
state.cur_map_type = state.target_map_type;
|
||||
}
|
||||
|
||||
fn get_map_image(heightmap: &Map, biome_map: &BiomeMap, map_type: MapDisplayType) -> ImageBuffer<Rgba<u8>, Vec<u8>> {
|
||||
return match map_type {
|
||||
MapDisplayType::HeightMap => render_map(&heightmap, 0.1),
|
||||
MapDisplayType::Biomes => render_biome_map(&heightmap, &biome_map),
|
||||
MapDisplayType::BiomeNoise => render_biome_noise_map(&biome_map, Vec3::ONE),
|
||||
MapDisplayType::BiomeNoiseTemp => render_biome_noise_map(&biome_map, Vec3::X),
|
||||
MapDisplayType::BiomeNoiseContinent => render_biome_noise_map(&biome_map, Vec3::Y),
|
||||
MapDisplayType::BiomeNoiseMoisture => render_biome_noise_map(&biome_map, Vec3::Z),
|
||||
};
|
||||
}
|
||||
@@ -1,2 +1,4 @@
|
||||
pub mod chunk_utils;
|
||||
pub mod render_distance_system;
|
||||
pub mod debug_plugin;
|
||||
pub mod editor_plugin;
|
||||
pub mod tile_selection_plugin;
|
||||
|
||||
70
game/main/src/utlis/tile_selection_plugin.rs
Normal file
70
game/main/src/utlis/tile_selection_plugin.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
use bevy::{prelude::*, window::PrimaryWindow};
|
||||
use bevy_rapier3d::{
|
||||
plugin::{RapierContext, ReadDefaultRapierContext},
|
||||
prelude::QueryFilter,
|
||||
};
|
||||
use shared::{
|
||||
resources::{TileContact, TileUnderCursor},
|
||||
tags::MainCamera,
|
||||
};
|
||||
use world_generation::{hex_utils::HexCoord, prelude::Map, states::GeneratorState};
|
||||
pub struct TileSelectionPlugin;
|
||||
|
||||
impl Plugin for TileSelectionPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<TileUnderCursor>();
|
||||
app.add_systems(
|
||||
PreUpdate,
|
||||
update_tile_under_cursor.run_if(in_state(GeneratorState::Idle)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn update_tile_under_cursor(
|
||||
cam_query: Query<(&GlobalTransform, &Camera), With<MainCamera>>,
|
||||
window: Query<&Window, With<PrimaryWindow>>,
|
||||
rapier_context: ReadDefaultRapierContext,
|
||||
map: Res<Map>,
|
||||
mut tile_under_cursor: ResMut<TileUnderCursor>,
|
||||
) {
|
||||
let win_r = window.get_single();
|
||||
if win_r.is_err() {
|
||||
return;
|
||||
}
|
||||
let win = win_r.unwrap();
|
||||
|
||||
let (cam_transform, camera) = cam_query.single();
|
||||
let Some(cursor_pos) = win.cursor_position() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Ok(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);
|
||||
//todo: handle correct tile detection when contacting a tile from the side
|
||||
if !map.is_in_bounds(&contact_coord) {
|
||||
tile_under_cursor.0 = None;
|
||||
return;
|
||||
}
|
||||
let surface = map.sample_height(&contact_coord);
|
||||
tile_under_cursor.0 = Some(TileContact::new(
|
||||
contact_coord,
|
||||
contact_point,
|
||||
contact_coord.to_world(surface),
|
||||
));
|
||||
} else {
|
||||
tile_under_cursor.0 = None;
|
||||
}
|
||||
}
|
||||
20
game/resources/Cargo.toml
Normal file
20
game/resources/Cargo.toml
Normal file
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "resources"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
bevy = "0.15.1"
|
||||
world_generation = { path = "../../engine/world_generation" }
|
||||
shared = { path = "../shared" }
|
||||
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.22.0", features = [
|
||||
"standard_dynamic_assets",
|
||||
"3d",
|
||||
] }
|
||||
|
||||
[features]
|
||||
tracing = []
|
||||
16
game/resources/src/lib.rs
Normal file
16
game/resources/src/lib.rs
Normal file
@@ -0,0 +1,16 @@
|
||||
pub mod resource_asset;
|
||||
|
||||
pub fn add(left: usize, right: usize) -> usize {
|
||||
left + right
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let result = add(2, 2);
|
||||
assert_eq!(result, 4);
|
||||
}
|
||||
}
|
||||
49
game/resources/src/resource_asset.rs
Normal file
49
game/resources/src/resource_asset.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use asset_loader::create_asset_loader;
|
||||
use bevy::prelude::*;
|
||||
use bevy_asset_loader::asset_collection::AssetCollection;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use shared::Tier;
|
||||
|
||||
#[derive(Asset, TypePath, Debug, Serialize, Deserialize)]
|
||||
pub struct ResourceAsset {
|
||||
pub identifier: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub sprite_id: usize,
|
||||
pub tier: Tier,
|
||||
}
|
||||
|
||||
create_asset_loader!(
|
||||
ResourceAssetPlugin,
|
||||
ResourceAssetLoader,
|
||||
ResourceAsset,
|
||||
&["res", "res.ron"],
|
||||
;?
|
||||
);
|
||||
|
||||
#[derive(Resource, AssetCollection)]
|
||||
pub struct ResourceDatabase {
|
||||
#[asset(key = "resources", collection(typed))]
|
||||
pub units: Vec<Handle<ResourceAsset>>,
|
||||
}
|
||||
|
||||
impl ResourceDatabase {
|
||||
pub fn create_lookup(&self, assets: &Assets<ResourceAsset>) -> ResourceLookup {
|
||||
let mut identifiers = Vec::with_capacity(self.units.len());
|
||||
for handle in &self.units {
|
||||
if let Some(asset) = assets.get(handle.id()) {
|
||||
identifiers.push(asset.identifier.clone());
|
||||
}
|
||||
}
|
||||
return ResourceLookup {
|
||||
handles: self.units.clone(),
|
||||
identifiers,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct ResourceLookup {
|
||||
pub handles: Vec<Handle<ResourceAsset>>,
|
||||
pub identifiers: Vec<String>,
|
||||
}
|
||||
@@ -6,8 +6,9 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
bevy = "0.14.0"
|
||||
bevy = "0.15.1"
|
||||
serde = { version = "1.0.204", features = ["derive"] }
|
||||
world_generation = { path = "../../engine/world_generation" }
|
||||
|
||||
|
||||
[features]
|
||||
|
||||
18
game/shared/src/animation_plugin.rs
Normal file
18
game/shared/src/animation_plugin.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::prefab_defination::RotationAnimation;
|
||||
|
||||
pub struct SimpleAnimationPlugin;
|
||||
|
||||
impl Plugin for SimpleAnimationPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(Update, rotate);
|
||||
}
|
||||
}
|
||||
|
||||
fn rotate(mut query: Query<(&mut Transform, &RotationAnimation)>, time: Res<Time>) {
|
||||
for (mut transform, rot) in query.iter_mut() {
|
||||
let cur_rot = transform.rotation;
|
||||
transform.rotation = cur_rot * Quat::from_axis_angle(rot.axis, rot.speed.to_radians() * time.delta_secs());
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,29 @@
|
||||
use bevy::reflect::Reflect;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct BuildingIdentifier(u32);
|
||||
#[derive(Default, Reflect, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct BuildingIdentifier(pub usize);
|
||||
|
||||
impl From<i32> for BuildingIdentifier {
|
||||
fn from(value: i32) -> Self {
|
||||
return BuildingIdentifier(value as usize);
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u32> for BuildingIdentifier {
|
||||
fn from(value: u32) -> Self {
|
||||
return BuildingIdentifier(value as usize);
|
||||
}
|
||||
}
|
||||
|
||||
impl From<usize> for BuildingIdentifier {
|
||||
fn from(value: usize) -> Self {
|
||||
return BuildingIdentifier(value);
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<usize> for BuildingIdentifier {
|
||||
fn into(self) -> usize {
|
||||
return self.0;
|
||||
}
|
||||
}
|
||||
|
||||
20
game/shared/src/component_defination.rs
Normal file
20
game/shared/src/component_defination.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use bevy::{
|
||||
ecs::system::EntityCommands, math::{Quat, Vec3}, prelude::*
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::prefab_defination::AnimationComponent;
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ComponentDefination {
|
||||
pub path: String,
|
||||
pub animations: Vec<AnimationComponent>,
|
||||
}
|
||||
|
||||
|
||||
impl ComponentDefination {
|
||||
pub fn apply(&self, commands: &mut EntityCommands){
|
||||
for c in &self.animations {
|
||||
c.apply(commands);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ impl Plugin for DespawnPuglin {
|
||||
|
||||
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();
|
||||
let d = at.0 - time.elapsed_secs();
|
||||
commands
|
||||
.entity(entity)
|
||||
.insert(DespawnAfter(Timer::from_seconds(d, TimerMode::Once)));
|
||||
|
||||
13
game/shared/src/events.rs
Normal file
13
game/shared/src/events.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
use bevy::prelude::*;
|
||||
use world_generation::hex_utils::*;
|
||||
|
||||
#[derive(Event)]
|
||||
pub enum TileModifiedEvent {
|
||||
HeightChanged(HexCoord, f32),
|
||||
TypeChanged(HexCoord, usize),
|
||||
}
|
||||
|
||||
#[derive(Event)]
|
||||
pub struct ChunkModifiedEvent {
|
||||
pub index: usize,
|
||||
}
|
||||
15
game/shared/src/identifiers.rs
Normal file
15
game/shared/src/identifiers.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
use bevy::reflect::Reflect;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use world_generation::hex_utils::HexCoord;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Reflect)]
|
||||
pub struct ResourceIdentifier {
|
||||
pub id: u32,
|
||||
pub qty: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Reflect)]
|
||||
pub struct UnitIdentifier(u32);
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Reflect)]
|
||||
pub struct TileIdentifier(u32);
|
||||
@@ -1,5 +1,37 @@
|
||||
use bevy::reflect::Reflect;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub mod building;
|
||||
pub mod despawn;
|
||||
pub mod resource;
|
||||
pub mod events;
|
||||
pub mod identifiers;
|
||||
pub mod resources;
|
||||
pub mod sets;
|
||||
pub mod states;
|
||||
pub mod tags;
|
||||
pub mod prefab_defination;
|
||||
pub mod component_defination;
|
||||
pub mod animation_plugin;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum Tier {
|
||||
Zero,
|
||||
One,
|
||||
Two,
|
||||
Three,
|
||||
Superior,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Reflect)]
|
||||
pub enum StatusEffect {
|
||||
UnitRange(f32),
|
||||
UnitAttack(f32),
|
||||
UnitHealth(f32),
|
||||
StructureRange(f32),
|
||||
StructureAttack(f32),
|
||||
StructureHealth(f32),
|
||||
BuildSpeedMulti(f32),
|
||||
BuildCostMulti(f32),
|
||||
ConsumptionMulti(f32),
|
||||
ProductionMulti(f32),
|
||||
}
|
||||
|
||||
79
game/shared/src/prefab_defination.rs
Normal file
79
game/shared/src/prefab_defination.rs
Normal file
@@ -0,0 +1,79 @@
|
||||
use bevy::{
|
||||
ecs::system::{EntityCommand, EntityCommands},
|
||||
gltf::{Gltf, GltfMesh},
|
||||
math::{Quat, Vec3},
|
||||
prelude::*,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct PrefabDefination {
|
||||
pub path: String,
|
||||
pub pos: Vec3,
|
||||
pub rot: Vec3,
|
||||
pub children: Option<Vec<PrefabDefination>>,
|
||||
pub animations: Option<Vec<AnimationComponent>>,
|
||||
}
|
||||
|
||||
impl PrefabDefination {
|
||||
pub fn spawn_recursive(&self, gltf: &Gltf, commands: &mut ChildBuilder, meshes: &Assets<GltfMesh>) {
|
||||
let mesh_handle = &gltf.named_meshes[&self.path.clone().into_boxed_str()];
|
||||
if let Some(gltf_mesh) = meshes.get(mesh_handle.id()) {
|
||||
let (m, mat) = gltf_mesh.unpack();
|
||||
let mut entity = commands.spawn((
|
||||
Mesh3d(m),
|
||||
MeshMaterial3d(mat),
|
||||
Transform::from_translation(self.pos).with_rotation(Quat::from_euler(
|
||||
bevy::math::EulerRot::XYZ,
|
||||
self.rot.x,
|
||||
self.rot.y,
|
||||
self.rot.z,
|
||||
)),
|
||||
));
|
||||
if let Some(children) = &self.children {
|
||||
entity.with_children(|b| {
|
||||
for child in children {
|
||||
child.spawn_recursive(gltf, b, meshes);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait UnpackGltfMesh {
|
||||
fn unpack(&self) -> (Handle<Mesh>, Handle<StandardMaterial>);
|
||||
}
|
||||
|
||||
impl UnpackGltfMesh for GltfMesh {
|
||||
fn unpack(&self) -> (Handle<Mesh>, Handle<StandardMaterial>) {
|
||||
let p = &self.primitives[0];
|
||||
let mut mat: Handle<StandardMaterial> = default();
|
||||
if let Some(mesh_material) = &p.material {
|
||||
mat = mesh_material.clone();
|
||||
}
|
||||
return (p.mesh.clone(), mat);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub enum AnimationComponent {
|
||||
Rotation(RotationAnimation),
|
||||
Slider,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Component, Clone, Copy)]
|
||||
pub struct RotationAnimation {
|
||||
pub axis: Vec3,
|
||||
pub speed: f32,
|
||||
}
|
||||
|
||||
impl AnimationComponent {
|
||||
pub fn apply(&self, commands: &mut EntityCommands) {
|
||||
match self {
|
||||
AnimationComponent::Rotation(comp) => {
|
||||
commands.insert(comp.clone());
|
||||
}
|
||||
AnimationComponent::Slider => todo!(),
|
||||
};
|
||||
}
|
||||
}
|
||||
22
game/shared/src/resources.rs
Normal file
22
game/shared/src/resources.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use bevy::prelude::*;
|
||||
use world_generation::hex_utils::HexCoord;
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct TileUnderCursor(pub Option<TileContact>);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct TileContact {
|
||||
pub tile: HexCoord,
|
||||
pub point: Vec3,
|
||||
pub surface: Vec3,
|
||||
}
|
||||
|
||||
impl TileContact {
|
||||
pub fn new(tile: HexCoord, contact: Vec3, surface: Vec3) -> Self {
|
||||
return Self {
|
||||
tile,
|
||||
point: contact,
|
||||
surface,
|
||||
};
|
||||
}
|
||||
}
|
||||
4
game/shared/src/sets.rs
Normal file
4
game/shared/src/sets.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct GameplaySet;
|
||||
@@ -1,3 +1,9 @@
|
||||
use bevy::prelude::*;
|
||||
#[derive(Component)]
|
||||
pub struct MainCamera;
|
||||
|
||||
#[derive(Component, Clone, Copy)]
|
||||
pub enum Faction {
|
||||
Player,
|
||||
Phos,
|
||||
}
|
||||
|
||||
24
game/units/Cargo.toml
Normal file
24
game/units/Cargo.toml
Normal file
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "units"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
bevy = "0.15.1"
|
||||
world_generation = { path = "../../engine/world_generation" }
|
||||
shared = { path = "../shared" }
|
||||
bevy_rapier3d = "0.28.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.22.0", features = [
|
||||
"standard_dynamic_assets",
|
||||
"3d",
|
||||
] }
|
||||
quadtree_rs = "0.1.3"
|
||||
pathfinding = "4.11.0"
|
||||
ordered-float = "4.3.0"
|
||||
|
||||
[features]
|
||||
tracing = ["bevy/trace_tracy"]
|
||||
3
game/units/src/assets/mod.rs
Normal file
3
game/units/src/assets/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
|
||||
pub mod unit_asset;
|
||||
pub mod unit_database;
|
||||
57
game/units/src/assets/unit_asset.rs
Normal file
57
game/units/src/assets/unit_asset.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
use asset_loader::create_asset_loader;
|
||||
use bevy::{ecs::world::CommandQueue, prelude::*};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::components::{AirUnit, LandUnit, NavalUnit, Unit, UnitDomain};
|
||||
|
||||
#[derive(Asset, TypePath, Debug, Serialize, Deserialize)]
|
||||
pub struct UnitAsset {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub size: u32,
|
||||
pub prefab_path: String,
|
||||
#[serde(skip)]
|
||||
pub prefab: Handle<Scene>,
|
||||
pub unit_type: UnitType,
|
||||
pub domain: UnitDomain,
|
||||
}
|
||||
|
||||
impl UnitAsset {
|
||||
pub fn spawn(&self, transform: Transform) -> CommandQueue {
|
||||
let mut commands = CommandQueue::default();
|
||||
|
||||
let bundle = (
|
||||
PbrBundle {
|
||||
transform: transform,
|
||||
..default()
|
||||
},
|
||||
Unit,
|
||||
);
|
||||
let domain = self.domain.clone();
|
||||
commands.push(move |world: &mut World| {
|
||||
let mut e = world.spawn(bundle);
|
||||
match domain {
|
||||
UnitDomain::Land => e.insert(LandUnit),
|
||||
UnitDomain::Air => e.insert(AirUnit),
|
||||
UnitDomain::Naval => e.insert(NavalUnit),
|
||||
};
|
||||
});
|
||||
|
||||
todo!();
|
||||
}
|
||||
}
|
||||
|
||||
create_asset_loader!(
|
||||
UnitAssetPlugin,
|
||||
UnitAssetLoader,
|
||||
UnitAsset,
|
||||
&["unit", "unit.ron"],
|
||||
prefab_path -> prefab
|
||||
;?
|
||||
);
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum UnitType {
|
||||
Basic,
|
||||
Turret,
|
||||
}
|
||||
10
game/units/src/assets/unit_database.rs
Normal file
10
game/units/src/assets/unit_database.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
use bevy::prelude::*;
|
||||
use bevy_asset_loader::asset_collection::AssetCollection;
|
||||
|
||||
use super::unit_asset::UnitAsset;
|
||||
|
||||
#[derive(Resource, AssetCollection)]
|
||||
pub struct UnitDatabase {
|
||||
#[asset(key = "units", collection(typed))]
|
||||
pub units: Vec<Handle<UnitAsset>>,
|
||||
}
|
||||
31
game/units/src/components.rs
Normal file
31
game/units/src/components.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
use bevy::{ecs::world::CommandQueue, prelude::*, tasks::Task};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use world_generation::hex_utils::HexCoord;
|
||||
|
||||
#[derive(Component, Debug)]
|
||||
pub struct Unit;
|
||||
|
||||
#[derive(Component, Debug)]
|
||||
pub struct AirUnit;
|
||||
#[derive(Component, Debug)]
|
||||
pub struct LandUnit;
|
||||
#[derive(Component, Debug)]
|
||||
pub struct NavalUnit;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
|
||||
pub enum UnitDomain {
|
||||
Land,
|
||||
Air,
|
||||
Naval,
|
||||
}
|
||||
|
||||
#[derive(Component, Debug)]
|
||||
pub struct Target(pub HexCoord);
|
||||
|
||||
#[derive(Component, Debug)]
|
||||
pub struct Path(pub Vec<Vec3>, pub usize);
|
||||
|
||||
#[derive(Component, Debug)]
|
||||
pub struct PathTask(pub Task<Option<CommandQueue>>);
|
||||
#[derive(Component, Debug)]
|
||||
pub struct PathTaskPending(pub usize);
|
||||
16
game/units/src/lib.rs
Normal file
16
game/units/src/lib.rs
Normal file
@@ -0,0 +1,16 @@
|
||||
use bevy::reflect::Reflect;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub mod assets;
|
||||
pub mod components;
|
||||
pub mod nav_data;
|
||||
pub mod resources;
|
||||
#[cfg(debug_assertions)]
|
||||
pub mod units_debug_plugin;
|
||||
pub mod units_plugin;
|
||||
pub mod units_spacial_set;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum UnitType {
|
||||
Basic,
|
||||
}
|
||||
100
game/units/src/nav_data.rs
Normal file
100
game/units/src/nav_data.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
use bevy::prelude::*;
|
||||
use ordered_float::OrderedFloat;
|
||||
use world_generation::{hex_utils::HexCoord, prelude::Map};
|
||||
|
||||
#[derive(Clone, Resource)]
|
||||
pub struct NavData {
|
||||
pub tiles: Vec<NavTile>,
|
||||
pub map_height: usize,
|
||||
pub map_width: usize,
|
||||
}
|
||||
|
||||
impl NavData {
|
||||
pub fn get_neighbors(&self, coord: &HexCoord) -> Vec<(HexCoord, OrderedFloat<f32>)> {
|
||||
let mut neighbors = Vec::with_capacity(6);
|
||||
let cur_height = self.get_height(coord);
|
||||
for i in 0..6 {
|
||||
let n = coord.get_neighbor(i);
|
||||
if !self.is_in_bounds(&n) {
|
||||
continue;
|
||||
}
|
||||
let n_height = self.get_height(&n);
|
||||
neighbors.push((n, OrderedFloat((cur_height - n_height).abs().powi(2))));
|
||||
}
|
||||
return neighbors;
|
||||
}
|
||||
pub fn get(&self, coord: &HexCoord) -> &NavTile {
|
||||
return &self.tiles[coord.to_index(self.map_width)];
|
||||
}
|
||||
|
||||
pub fn get_height(&self, coord: &HexCoord) -> f32 {
|
||||
return self.tiles[coord.to_index(self.map_width)].height;
|
||||
}
|
||||
|
||||
pub fn is_in_bounds(&self, pos: &HexCoord) -> bool {
|
||||
return pos.is_in_bounds(self.map_height, self.map_width);
|
||||
}
|
||||
|
||||
pub fn build(map: &Map) -> NavData {
|
||||
#[cfg(feature = "tracing")]
|
||||
let _path_span = info_span!("Build Nav Data").entered();
|
||||
let mut tiles = Vec::with_capacity(map.get_tile_count());
|
||||
let h = map.get_tile_height();
|
||||
let w = map.get_tile_width();
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let coord = HexCoord::from_grid_pos(x, y);
|
||||
let height = map.sample_height(&coord);
|
||||
let tile = NavTile {
|
||||
coord,
|
||||
height,
|
||||
move_cost: 1.0,
|
||||
};
|
||||
tiles.push(tile);
|
||||
}
|
||||
}
|
||||
|
||||
return NavData {
|
||||
tiles,
|
||||
map_width: w,
|
||||
map_height: h,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn update(&mut self, map: &Map) {
|
||||
#[cfg(feature = "tracing")]
|
||||
let _path_span = info_span!("Update Nav Data").entered();
|
||||
let h = map.get_tile_height();
|
||||
let w = map.get_tile_width();
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let coord = HexCoord::from_grid_pos(x, y);
|
||||
let height = map.sample_height(&coord);
|
||||
let tile = NavTile {
|
||||
coord,
|
||||
height,
|
||||
move_cost: 1.0,
|
||||
};
|
||||
self.tiles[y * w + x] = tile;
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn update_tile(&mut self, coord: &HexCoord, height: f32, move_cost: f32) {
|
||||
let tile = &mut self.tiles[coord.to_index(self.map_width)];
|
||||
tile.move_cost = move_cost;
|
||||
tile.height = height;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct NavTile {
|
||||
pub height: f32,
|
||||
pub move_cost: f32,
|
||||
pub coord: HexCoord,
|
||||
}
|
||||
|
||||
impl NavTile {
|
||||
pub fn calculate_heuristic(&self, to: &HexCoord) -> OrderedFloat<f32> {
|
||||
return (self.coord.distance(to) as f32).into();
|
||||
}
|
||||
}
|
||||
4
game/units/src/resources.rs
Normal file
4
game/units/src/resources.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
#[derive(Resource, Debug, Default)]
|
||||
pub struct PathBatchId(pub usize);
|
||||
78
game/units/src/units_debug_plugin.rs
Normal file
78
game/units/src/units_debug_plugin.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
use bevy::prelude::*;
|
||||
use shared::{resources::TileUnderCursor, sets::GameplaySet, states::AssetLoadState};
|
||||
|
||||
use crate::components::{LandUnit, Path, Target, Unit};
|
||||
|
||||
pub struct UnitsDebugPlugin;
|
||||
|
||||
impl Plugin for UnitsDebugPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(Update, init.run_if(in_state(AssetLoadState::Loading)));
|
||||
|
||||
app.add_systems(Update, (spawn_test_unit, set_unit_target).in_set(GameplaySet));
|
||||
app.add_systems(FixedUpdate, (visualize_paths).in_set(GameplaySet));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct TestUnit(pub Handle<Mesh>);
|
||||
|
||||
fn init(mut meshes: ResMut<Assets<Mesh>>, mut commands: Commands) {
|
||||
let mesh_handle = meshes.add(Cuboid::from_length(1.0));
|
||||
commands.insert_resource(TestUnit(mesh_handle));
|
||||
}
|
||||
|
||||
fn spawn_test_unit(
|
||||
mut commands: Commands,
|
||||
input: Res<ButtonInput<KeyCode>>,
|
||||
tile_under_cursor: Res<TileUnderCursor>,
|
||||
unit: Res<TestUnit>,
|
||||
) {
|
||||
if !input.just_pressed(KeyCode::KeyT) {
|
||||
return;
|
||||
}
|
||||
if let Some(contact) = tile_under_cursor.0 {
|
||||
info!("Spawning Test Unit");
|
||||
commands.spawn((
|
||||
(Transform::from_translation(contact.surface), Mesh3d(unit.0.clone())),
|
||||
Unit,
|
||||
LandUnit,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn set_unit_target(
|
||||
mut commands: Commands,
|
||||
units: Query<Entity, With<Unit>>,
|
||||
input: Res<ButtonInput<MouseButton>>,
|
||||
tile_under_cursor: Res<TileUnderCursor>,
|
||||
) {
|
||||
if !input.just_pressed(MouseButton::Right) {
|
||||
return;
|
||||
}
|
||||
if let Some(contact) = tile_under_cursor.0 {
|
||||
for e in units.iter() {
|
||||
info!("Setting Target");
|
||||
let mut e = commands.entity(e);
|
||||
e.insert(Target(contact.tile));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visualize_paths(units: Query<&Path, With<Unit>>, mut gizmos: Gizmos) {
|
||||
for path in units.iter() {
|
||||
if path.1 > path.0.len() {
|
||||
continue;
|
||||
}
|
||||
for node in 1..path.0.len() {
|
||||
let from = path.0[node];
|
||||
let to = path.0[node - 1];
|
||||
let color = if node > path.1 {
|
||||
LinearRgba::rgb(1.0, 0.5, 0.0)
|
||||
} else {
|
||||
LinearRgba::rgb(1.0, 0.5, 1.5)
|
||||
};
|
||||
gizmos.line(from + Vec3::Y * 0.1, to + Vec3::Y * 0.1, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
234
game/units/src/units_plugin.rs
Normal file
234
game/units/src/units_plugin.rs
Normal file
@@ -0,0 +1,234 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use bevy::{ecs::world::CommandQueue, prelude::*, tasks::AsyncComputeTaskPool, utils::futures};
|
||||
use pathfinding::prelude::astar;
|
||||
use shared::{events::TileModifiedEvent, resources::TileUnderCursor, sets::GameplaySet};
|
||||
use world_generation::{hex_utils::HexCoord, prelude::Map, states::GeneratorState};
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
use crate::units_debug_plugin::UnitsDebugPlugin;
|
||||
use crate::{
|
||||
assets::unit_asset::UnitAssetPlugin,
|
||||
components::{Path, PathTask, PathTaskPending, Target, Unit},
|
||||
nav_data::NavData,
|
||||
resources::PathBatchId,
|
||||
};
|
||||
|
||||
pub struct UnitsPlugin;
|
||||
|
||||
impl Plugin for UnitsPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<PathBatchId>();
|
||||
app.add_plugins(UnitAssetPlugin);
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
app.add_plugins(UnitsDebugPlugin);
|
||||
|
||||
// app.configure_loading_state(LoadingStateConfig::new(AssetLoadState::Loading).load_collection::<UnitDatabase>());
|
||||
app.add_systems(PostUpdate, build_navdata.run_if(in_state(GeneratorState::SpawnMap)));
|
||||
|
||||
app.add_systems(Update, units_control.in_set(GameplaySet));
|
||||
app.add_systems(Update, (move_unit, update_navdata).in_set(GameplaySet));
|
||||
app.add_systems(
|
||||
FixedPreUpdate,
|
||||
(dispatch_path_requests, resolve_path_task).in_set(GameplaySet),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn build_navdata(mut commands: Commands, map: Res<Map>) {
|
||||
let nav_data = NavData::build(&map);
|
||||
commands.insert_resource(nav_data);
|
||||
}
|
||||
|
||||
fn update_navdata(mut tile_updates: EventReader<TileModifiedEvent>, mut nav_data: ResMut<NavData>) {
|
||||
for event in tile_updates.read() {
|
||||
match event {
|
||||
TileModifiedEvent::HeightChanged(coord, new_height) => {
|
||||
nav_data.update_tile(coord, *new_height, 1.0);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn units_control(tile_under_cursor: Res<TileUnderCursor>) {}
|
||||
|
||||
fn move_unit(
|
||||
mut units: Query<(&mut Transform, &mut Path, Entity), With<Unit>>,
|
||||
time: Res<Time>,
|
||||
map: Res<Map>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
for (mut t, mut path, entity) in units.iter_mut() {
|
||||
if path.1 >= path.0.len() {
|
||||
commands.entity(entity).remove::<Path>();
|
||||
continue;
|
||||
}
|
||||
let p = path.0[path.1];
|
||||
let d = p - t.translation;
|
||||
if d.length() < 0.1 {
|
||||
path.1 += 1;
|
||||
continue;
|
||||
}
|
||||
let vel = d.normalize() * 10.0 * time.delta_secs();
|
||||
t.translation += vel;
|
||||
let coord = HexCoord::from_world_pos(t.translation);
|
||||
if map.is_in_bounds(&coord) {
|
||||
t.translation.y = map.sample_height(&coord);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_path_requests(
|
||||
units: Query<(&Transform, &Target, Entity), With<Unit>>,
|
||||
map: Res<Map>,
|
||||
nav_data: Res<NavData>,
|
||||
mut batch_id: ResMut<PathBatchId>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
if units.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut groups: HashMap<HexCoord, Vec<PathRequest>> = HashMap::new();
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
let _group_span = info_span!("Grouping").entered();
|
||||
for (transform, target, entity) in units.iter() {
|
||||
let req = PathRequest {
|
||||
entity,
|
||||
from: HexCoord::from_world_pos(transform.translation),
|
||||
};
|
||||
if let Some(group) = groups.get_mut(&target.0) {
|
||||
group.push(req);
|
||||
} else {
|
||||
groups.insert(target.0, vec![req]);
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "tracing")]
|
||||
drop(_group_span);
|
||||
|
||||
let pool = AsyncComputeTaskPool::get();
|
||||
for (target, units) in groups {
|
||||
let id = batch_id.0;
|
||||
batch_id.0 += 1;
|
||||
|
||||
for req in &units {
|
||||
commands
|
||||
.entity(req.entity)
|
||||
.insert(PathTaskPending(id))
|
||||
.remove::<Target>();
|
||||
}
|
||||
|
||||
let destinations = get_end_points(&target, units.len(), &map);
|
||||
let req = BatchPathRequest::new(units, destinations);
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
let _clone_span = info_span!("Nav Data Clone").entered();
|
||||
let local_nav_data = nav_data.clone();
|
||||
#[cfg(feature = "tracing")]
|
||||
drop(_clone_span);
|
||||
|
||||
let batch_task = pool.spawn(async move {
|
||||
let mut i = 0;
|
||||
let mut queue = CommandQueue::default();
|
||||
for entitiy_req in req.entities {
|
||||
let dst = req.destination[i];
|
||||
i += 1;
|
||||
#[cfg(feature = "tracing")]
|
||||
let _path_span = info_span!("Path Finding").entered();
|
||||
if let Some(path) = calculate_path(&entitiy_req.from, &dst, &local_nav_data) {
|
||||
queue.push(move |world: &mut World| {
|
||||
let mut unit_e = world.entity_mut(entitiy_req.entity);
|
||||
|
||||
if let Some(pending_task) = unit_e.get::<PathTaskPending>() {
|
||||
if pending_task.0 == id {
|
||||
unit_e.insert(path);
|
||||
unit_e.remove::<PathTaskPending>();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
if queue.is_empty() {
|
||||
return None;
|
||||
}
|
||||
return Some(queue);
|
||||
});
|
||||
commands.spawn(PathTask(batch_task));
|
||||
}
|
||||
}
|
||||
|
||||
fn get_end_points(coord: &HexCoord, count: usize, map: &Map) -> Vec<HexCoord> {
|
||||
let mut result = Vec::with_capacity(count);
|
||||
if count == 1 {
|
||||
return vec![*coord];
|
||||
}
|
||||
result.push(*coord);
|
||||
let mut r = 1;
|
||||
while result.len() < count {
|
||||
let tiles = HexCoord::select_ring(coord, r);
|
||||
let needed = count - result.len();
|
||||
if needed >= tiles.len() {
|
||||
for t in tiles {
|
||||
if map.is_in_bounds(&t) {
|
||||
result.push(t);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for i in 0..needed {
|
||||
let t = tiles[i];
|
||||
if map.is_in_bounds(&t) {
|
||||
result.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
r += 1;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
fn resolve_path_task(mut tasks: Query<(&mut PathTask, Entity)>, mut commands: Commands) {
|
||||
for (mut task, entity) in tasks.iter_mut() {
|
||||
if let Some(c) = futures::check_ready(&mut task.0) {
|
||||
if let Some(mut queue) = c {
|
||||
commands.append(&mut queue);
|
||||
}
|
||||
commands.entity(entity).despawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn calculate_path(from: &HexCoord, to: &HexCoord, nav: &NavData) -> Option<Path> {
|
||||
let path = astar(
|
||||
from,
|
||||
|n| nav.get_neighbors(n),
|
||||
|n| nav.get(n).calculate_heuristic(to),
|
||||
|n| n == to,
|
||||
);
|
||||
if let Some((nodes, _cost)) = path {
|
||||
let result: Vec<_> = nodes.iter().map(|f| f.to_world(nav.get_height(f))).collect();
|
||||
return Some(Path(result, 1));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
struct PathRequest {
|
||||
pub entity: Entity,
|
||||
pub from: HexCoord,
|
||||
}
|
||||
|
||||
struct BatchPathRequest {
|
||||
pub entities: Vec<PathRequest>,
|
||||
pub destination: Vec<HexCoord>,
|
||||
}
|
||||
|
||||
impl BatchPathRequest {
|
||||
pub fn new(entities: Vec<PathRequest>, dst: Vec<HexCoord>) -> Self {
|
||||
return Self {
|
||||
destination: dst,
|
||||
entities,
|
||||
};
|
||||
}
|
||||
}
|
||||
82
game/units/src/units_spacial_set.rs
Normal file
82
game/units/src/units_spacial_set.rs
Normal file
@@ -0,0 +1,82 @@
|
||||
use bevy::prelude::*;
|
||||
use quadtree_rs::{area::AreaBuilder, point::Point, Quadtree};
|
||||
use shared::tags::Faction;
|
||||
|
||||
use crate::{components::UnitDomain, UnitType};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct UnitEntity {
|
||||
pub entity: Entity,
|
||||
pub domain: UnitDomain,
|
||||
pub unit_type: UnitType,
|
||||
pub faction: Faction,
|
||||
pub position: Vec3,
|
||||
}
|
||||
|
||||
pub struct UnitSpacialSet {
|
||||
tree: Quadtree<usize, UnitEntity>,
|
||||
}
|
||||
|
||||
impl UnitSpacialSet {
|
||||
pub fn new(map_size: f32) -> Self {
|
||||
let n = f32::log2(map_size) / f32::log2(2.0);
|
||||
return Self {
|
||||
tree: Quadtree::new(n.ceil() as usize),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn add_unit(&mut self, unit: UnitEntity, pos: Vec3) -> Option<u64> {
|
||||
return self.tree.insert_pt(convert_to_point(pos.xz()), unit);
|
||||
}
|
||||
|
||||
pub fn move_unit(&mut self, handle: u64, pos: Vec3) -> Option<u64> {
|
||||
if let Some(existing) = self.tree.get(handle) {
|
||||
if existing.anchor() == convert_to_point(pos.xz()) {
|
||||
return None;
|
||||
}
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
|
||||
if let Some(entry) = self.tree.delete_by_handle(handle) {
|
||||
let p = convert_to_point(pos.xz());
|
||||
let mut entry = *entry.value_ref();
|
||||
entry.position = pos;
|
||||
return self.tree.insert_pt(p, entry);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
pub fn get_units_in_circle(self, center: Vec3, radius: f32) -> Vec<Entity> {
|
||||
let anchor = center.xz() - Vec2::new(radius, radius);
|
||||
let d = (radius * 2.0) as usize;
|
||||
let area = AreaBuilder::default()
|
||||
.anchor(convert_to_point(anchor))
|
||||
.dimensions((d, d))
|
||||
.build()
|
||||
.unwrap();
|
||||
let query = self.tree.query(area);
|
||||
return query
|
||||
.filter(|e| e.value_ref().position.distance(center) <= radius)
|
||||
.map(|e| e.value_ref().entity)
|
||||
.collect();
|
||||
}
|
||||
|
||||
pub fn get_units_in_rect(self, anchor: Vec2, size: Vec2) -> Vec<Entity> {
|
||||
let area = AreaBuilder::default()
|
||||
.anchor(convert_to_point(anchor))
|
||||
.dimensions((size.x as usize, size.y as usize))
|
||||
.build()
|
||||
.unwrap();
|
||||
let query = self.tree.query(area);
|
||||
return query.map(|e| e.value_ref().entity).collect();
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_to_point(pos: Vec2) -> Point<usize> {
|
||||
let p = pos.as_uvec2();
|
||||
return Point {
|
||||
x: p.x as usize,
|
||||
y: p.y as usize,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user