Merge branch 'master' into avian
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
use asset_loader::create_asset_loader;
|
||||
use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use shared::resource::ResourceIdentifier;
|
||||
use shared::identifiers::ResourceIdentifier;
|
||||
|
||||
use crate::footprint::BuildingFootprint;
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::path::Display;
|
||||
|
||||
use bevy::prelude::Resource;
|
||||
use shared::building::BuildingIdentifier;
|
||||
use world_generation::hex_utils::HexCoord;
|
||||
|
||||
@@ -1,19 +1,30 @@
|
||||
use bevy::{prelude::*, window::PrimaryWindow};
|
||||
use std::f32::consts::E;
|
||||
|
||||
use bevy::{ecs::world::CommandQueue, 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 +38,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 +79,23 @@ 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);
|
||||
@@ -104,4 +117,57 @@ fn show_indicators(positions: Vec<Vec3>, commands: &mut Commands, indicator: &In
|
||||
}
|
||||
}
|
||||
|
||||
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>>,
|
||||
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);
|
||||
let e = commands.spawn((
|
||||
SceneBundle {
|
||||
scene: building.prefab.clone(),
|
||||
transform: Transform::from_translation(item.pos.to_world(h)),
|
||||
..Default::default()
|
||||
},
|
||||
Building,
|
||||
));
|
||||
|
||||
building_map.add_building(BuildingEntry::new(item.pos, e.id()));
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,5 @@ pub mod build_queue;
|
||||
pub mod building_plugin;
|
||||
pub mod buildings_map;
|
||||
pub mod footprint;
|
||||
pub mod prelude;
|
||||
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,13 +7,14 @@ 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 = { version = "0.14.0", features = ["file_watcher"] }
|
||||
bevy-inspector-egui = "0.25.0"
|
||||
iyes_perf_ui = "0.3.0"
|
||||
noise = "0.8.2"
|
||||
world_generation = { path = "../../engine/world_generation" }
|
||||
rayon = "1.10.0"
|
||||
buildings = { path = "../buildings" }
|
||||
units = { path = "../units" }
|
||||
shared = { path = "../shared" }
|
||||
bevy_asset_loader = { version = "0.21.0", features = [
|
||||
"standard_dynamic_assets",
|
||||
@@ -21,6 +22,7 @@ bevy_asset_loader = { version = "0.21.0", features = [
|
||||
] }
|
||||
ron = "0.8.1"
|
||||
avian3d = { version = "0.1.1" }
|
||||
image = "0.25.2"
|
||||
|
||||
[features]
|
||||
tracing = ["bevy/trace_tracy", "world_generation/tracing", "buildings/tracing"]
|
||||
|
||||
Submodule game/main/assets updated: 3bb0aaab5b...d9e7ec8297
@@ -31,7 +31,7 @@ fn setup(mut commands: Commands, mut msaa: ResMut<Msaa>) {
|
||||
commands
|
||||
.spawn((
|
||||
Camera3dBundle {
|
||||
transform: Transform::from_xyz(0., 30., 0.).looking_to(Vec3::Z, Vec3::Y),
|
||||
transform: Transform::from_xyz(0., 30., 0.).looking_to(Vec3::NEG_Z, Vec3::Y),
|
||||
..default()
|
||||
},
|
||||
PhosCamera::default(),
|
||||
@@ -138,15 +138,15 @@ fn rts_camera_system(
|
||||
let mut cam_pos = cam.translation;
|
||||
|
||||
if key.pressed(KeyCode::KeyA) {
|
||||
cam_move.x = 1.;
|
||||
} else if key.pressed(KeyCode::KeyD) {
|
||||
cam_move.x = -1.;
|
||||
} else if key.pressed(KeyCode::KeyD) {
|
||||
cam_move.x = 1.;
|
||||
}
|
||||
|
||||
if key.pressed(KeyCode::KeyW) {
|
||||
cam_move.z = 1.;
|
||||
} else if key.pressed(KeyCode::KeyS) {
|
||||
cam_move.z = -1.;
|
||||
} else if key.pressed(KeyCode::KeyS) {
|
||||
cam_move.z = 1.;
|
||||
}
|
||||
|
||||
let move_speed = if key.pressed(KeyCode::ShiftLeft) {
|
||||
@@ -156,7 +156,7 @@ fn rts_camera_system(
|
||||
};
|
||||
|
||||
cam_move = cam_move.normalize_or_zero() * move_speed * time.delta_seconds();
|
||||
cam_pos -= cam_move;
|
||||
cam_pos += cam_move;
|
||||
|
||||
let mut scroll = 0.0;
|
||||
for e in wheel.read() {
|
||||
@@ -209,8 +209,11 @@ fn rts_camera_system(
|
||||
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;
|
||||
let mut rot = cam.rotation.to_euler(EulerRot::XYZ);
|
||||
rot.0 = -angle;
|
||||
cam.rotation = Quat::from_euler(EulerRot::XYZ, rot.0, rot.1, rot.2);
|
||||
// let rot = Quat::from_axis_angle(Vec3::X, -angle);
|
||||
// cam.rotation = rot;
|
||||
|
||||
cam.translation = cam_pos;
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ impl Default for PhosCameraTargets {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
height: Default::default(),
|
||||
forward: Vec3::Z,
|
||||
forward: Vec3::NEG_Z,
|
||||
last_height: Default::default(),
|
||||
anim_time: Default::default(),
|
||||
rotate_time: Default::default(),
|
||||
|
||||
@@ -36,6 +36,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,
|
||||
|
||||
@@ -3,6 +3,10 @@ use bevy::ecs::world::CommandQueue;
|
||||
use bevy::prelude::*;
|
||||
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,7 +21,9 @@ pub struct ChunkRebuildPlugin;
|
||||
impl Plugin for ChunkRebuildPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -32,7 +38,7 @@ fn chunk_rebuilder(
|
||||
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;
|
||||
|
||||
@@ -3,10 +3,12 @@ use bevy::log::*;
|
||||
use bevy::{
|
||||
pbr::{ExtendedMaterial, NotShadowCaster},
|
||||
prelude::*,
|
||||
render::texture::ImageFormat,
|
||||
};
|
||||
use bevy_asset_loader::prelude::*;
|
||||
|
||||
use bevy_inspector_egui::quick::ResourceInspectorPlugin;
|
||||
use image::DynamicImage;
|
||||
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
|
||||
use shared::states::{AssetLoadState, GameplayState, MenuState};
|
||||
use world_generation::{
|
||||
@@ -14,6 +16,10 @@ use world_generation::{
|
||||
biome_painter::*,
|
||||
heightmap::generate_heightmap,
|
||||
hex_utils::{offset_to_index, SHORT_DIAGONAL},
|
||||
map::{
|
||||
biome_map::{self, BiomeMap},
|
||||
map_utils::{render_biome_noise_map, render_map},
|
||||
},
|
||||
prelude::*,
|
||||
tile_manager::*,
|
||||
tile_mapper::*,
|
||||
@@ -52,7 +58,7 @@ impl Plugin for MapInitPlugin {
|
||||
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,
|
||||
@@ -81,9 +87,7 @@ impl Plugin for MapInitPlugin {
|
||||
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());
|
||||
@@ -101,14 +105,16 @@ fn setup_materials(
|
||||
) {
|
||||
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()
|
||||
@@ -124,8 +130,8 @@ 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);
|
||||
}
|
||||
|
||||
@@ -158,10 +164,10 @@ fn create_heightmap(
|
||||
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,
|
||||
@@ -172,11 +178,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,
|
||||
@@ -187,11 +192,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,
|
||||
@@ -202,7 +206,6 @@ fn create_heightmap(
|
||||
weight: 0.,
|
||||
weight_multi: 0.,
|
||||
layers: 1,
|
||||
first_layer_mask: false,
|
||||
}],
|
||||
},
|
||||
sea_level: 8.5,
|
||||
@@ -210,13 +213,14 @@ 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);
|
||||
}
|
||||
@@ -296,6 +300,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>>,
|
||||
@@ -305,6 +310,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);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
use avian3d::prelude::*;
|
||||
use bevy::{prelude::*, window::PrimaryWindow};
|
||||
use bevy::{prelude::*, utils::hashbrown::HashSet, window::PrimaryWindow};
|
||||
use shared::{
|
||||
events::{ChunkModifiedEvent, TileModifiedEvent},
|
||||
resources::TileUnderCursor,
|
||||
states::GameplayState,
|
||||
};
|
||||
use world_generation::{hex_utils::HexCoord, prelude::Map, states::GeneratorState};
|
||||
|
||||
use crate::{
|
||||
@@ -11,18 +16,24 @@ 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>>,
|
||||
spatial_query: SpatialQuery,
|
||||
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,36 +46,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 = spatial_query.cast_ray(
|
||||
cam_ray.origin,
|
||||
cam_ray.direction.into(),
|
||||
500.,
|
||||
true,
|
||||
SpatialQueryFilter::default(),
|
||||
);
|
||||
|
||||
if let Some(hit) = collision {
|
||||
if let Some(contact) = tile_under_cursor.0 {
|
||||
#[cfg(feature = "tracing")]
|
||||
let span = info_span!("Deform Mesh").entered();
|
||||
|
||||
let e = hit.entity;
|
||||
let dist = hit.time_of_impact;
|
||||
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);
|
||||
}
|
||||
tile_modified.send(TileModifiedEvent::HeightChanged(tile, height));
|
||||
}
|
||||
commands.entity(e).insert(RebuildChunk);
|
||||
// commands.entity(e).insert(RebuildChunk);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,24 @@
|
||||
use crate::camera_system::camera_plugin::PhosCameraPlugin;
|
||||
use crate::camera_system::components::PhosCamera;
|
||||
use crate::map_rendering::map_init::MapInitPlugin;
|
||||
use crate::utlis::editor_plugin::EditorPlugin;
|
||||
use crate::utlis::render_distance_system::RenderDistancePlugin;
|
||||
use avian3d::prelude::*;
|
||||
use avian3d::PhysicsPlugins;
|
||||
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::*,
|
||||
};
|
||||
use bevy_asset_loader::prelude::*;
|
||||
use bevy_rapier3d::dynamics::{Ccd, RigidBody, Velocity};
|
||||
use bevy_rapier3d::geometry::Collider;
|
||||
use bevy_rapier3d::plugin::{NoUserData, RapierPhysicsPlugin};
|
||||
use buildings::BuildingPugin;
|
||||
use iyes_perf_ui::prelude::*;
|
||||
use 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;
|
||||
|
||||
@@ -30,10 +36,18 @@ impl Plugin for PhosGamePlugin {
|
||||
PhosCameraPlugin,
|
||||
MapInitPlugin,
|
||||
RenderDistancePlugin,
|
||||
//BuildingPugin,
|
||||
BuildingPugin,
|
||||
UnitsPlugin,
|
||||
DespawnPuglin,
|
||||
TileSelectionPlugin,
|
||||
#[cfg(debug_assertions)]
|
||||
EditorPlugin,
|
||||
#[cfg(debug_assertions)]
|
||||
DebugPlugin,
|
||||
));
|
||||
|
||||
configure_gameplay_set(app);
|
||||
|
||||
//Systems - Startup
|
||||
app.add_systems(Startup, init_game);
|
||||
|
||||
@@ -47,7 +61,7 @@ impl Plugin for PhosGamePlugin {
|
||||
.add_plugins(PerfUiPlugin);
|
||||
|
||||
//Physics
|
||||
app.add_plugins(PhysicsPlugins::default());
|
||||
app.add_plugins(RapierPhysicsPlugin::<NoUserData>::default());
|
||||
// app.add_plugins(RapierDebugRenderPlugin::default());
|
||||
|
||||
app.insert_resource(WireframeConfig {
|
||||
@@ -57,6 +71,34 @@ impl Plugin for PhosGamePlugin {
|
||||
}
|
||||
}
|
||||
|
||||
fn configure_gameplay_set(app: &mut App) {
|
||||
app.configure_sets(
|
||||
Update,
|
||||
GameplaySet.run_if(in_state(GeneratorState::Idle).and_then(in_state(MenuState::InGame))),
|
||||
);
|
||||
app.configure_sets(
|
||||
PreUpdate,
|
||||
GameplaySet.run_if(in_state(GeneratorState::Idle).and_then(in_state(MenuState::InGame))),
|
||||
);
|
||||
app.configure_sets(
|
||||
PostUpdate,
|
||||
GameplaySet.run_if(in_state(GeneratorState::Idle).and_then(in_state(MenuState::InGame))),
|
||||
);
|
||||
|
||||
app.configure_sets(
|
||||
FixedUpdate,
|
||||
GameplaySet.run_if(in_state(GeneratorState::Idle).and_then(in_state(MenuState::InGame))),
|
||||
);
|
||||
app.configure_sets(
|
||||
FixedPreUpdate,
|
||||
GameplaySet.run_if(in_state(GeneratorState::Idle).and_then(in_state(MenuState::InGame))),
|
||||
);
|
||||
app.configure_sets(
|
||||
FixedPostUpdate,
|
||||
GameplaySet.run_if(in_state(GeneratorState::Idle).and_then(in_state(MenuState::InGame))),
|
||||
);
|
||||
}
|
||||
|
||||
fn init_game(mut commands: Commands, mut materials: ResMut<Assets<StandardMaterial>>) {
|
||||
commands.spawn((
|
||||
PerfUiRoot::default(),
|
||||
@@ -106,9 +148,10 @@ fn spawn_sphere(
|
||||
transform: Transform::from_translation(cam_transform.translation),
|
||||
..default()
|
||||
},
|
||||
Collider::sphere(0.3),
|
||||
Collider::ball(0.3),
|
||||
RigidBody::Dynamic,
|
||||
LinearVelocity(cam_transform.forward() * 50.),
|
||||
Ccd::enabled(),
|
||||
Velocity::linear(cam_transform.forward() * 50.),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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::{prelude::*, window::PrimaryWindow};
|
||||
use bevy_inspector_egui::bevy_egui::{systems::InputEvents, EguiContexts};
|
||||
use bevy_inspector_egui::egui;
|
||||
use bevy_rapier3d::prelude::*;
|
||||
use shared::resources::TileUnderCursor;
|
||||
use shared::states::GameplayState;
|
||||
use shared::tags::MainCamera;
|
||||
use world_generation::{
|
||||
consts::HEX_CORNERS,
|
||||
hex_utils::{HexCoord, INNER_RADIUS},
|
||||
prelude::Map,
|
||||
states::GeneratorState,
|
||||
};
|
||||
|
||||
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, 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),
|
||||
Quat::IDENTITY,
|
||||
Color::WHITE,
|
||||
);
|
||||
let nbors = map.get_neighbors(&contact.tile);
|
||||
let contact_tile_pos = contact.tile.to_world(map.sample_height(&contact.tile));
|
||||
|
||||
// for i in 0..6 {
|
||||
// if let Some(s) = nbors[i] {
|
||||
// let coord = contact.tile.get_neighbor(i);
|
||||
// let p = coord.to_world(s);
|
||||
// gizmos.arrow(p, p + Vec3::Y * (i as f32 + 1.0), Color::WHITE);
|
||||
// }
|
||||
|
||||
// let p = HEX_CORNERS[i] + contact_tile_pos;
|
||||
// gizmos.arrow(p, p + Vec3::Y * (i as f32 + 1.0), LinearRgba::rgb(1.0, 0.0, 0.5));
|
||||
// }
|
||||
|
||||
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);
|
||||
//gizmos.sphere(contact_point, Quat::IDENTITY, 0.1, LinearRgba::rgb(1., 0., 0.5));
|
||||
}
|
||||
}
|
||||
|
||||
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,5 @@
|
||||
pub mod chunk_utils;
|
||||
pub mod render_distance_system;
|
||||
pub mod debug_plugin;
|
||||
pub mod editor_plugin;
|
||||
pub mod tile_selection_plugin;
|
||||
|
||||
@@ -9,6 +9,9 @@ impl Plugin for RenderDistancePlugin {
|
||||
app.register_type::<RenderDistanceSettings>();
|
||||
app.add_systems(PostUpdate, render_distance_system)
|
||||
.insert_resource(RenderDistanceSettings::default());
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
app.insert_resource(RenderDistanceSettings::new(f32::MAX));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,8 +59,9 @@ fn render_distance_system(
|
||||
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 {
|
||||
|
||||
62
game/main/src/utlis/tile_selection_plugin.rs
Normal file
62
game/main/src/utlis/tile_selection_plugin.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
use bevy::{prelude::*, window::PrimaryWindow};
|
||||
use bevy_rapier3d::{plugin::RapierContext, 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: Res<RapierContext>,
|
||||
map: Res<Map>,
|
||||
mut tile_under_cursor: ResMut<TileUnderCursor>,
|
||||
) {
|
||||
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);
|
||||
//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;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ edition = "2021"
|
||||
[dependencies]
|
||||
bevy = "0.14.0"
|
||||
serde = { version = "1.0.204", features = ["derive"] }
|
||||
world_generation = { path = "../../engine/world_generation" }
|
||||
|
||||
|
||||
[features]
|
||||
|
||||
@@ -1,10 +1,28 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct BuildingIdentifier(u32);
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
use bevy::prelude::Resource;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use world_generation::hex_utils::HexCoord;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ResourceIdentifier {
|
||||
@@ -1,5 +1,8 @@
|
||||
pub mod building;
|
||||
pub mod despawn;
|
||||
pub mod resource;
|
||||
pub mod identifiers;
|
||||
pub mod states;
|
||||
pub mod tags;
|
||||
pub mod events;
|
||||
pub mod sets;
|
||||
pub mod resources;
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
22
game/units/Cargo.toml
Normal file
22
game/units/Cargo.toml
Normal file
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "units"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
bevy = "0.14.0"
|
||||
world_generation = { path = "../../engine/world_generation" }
|
||||
shared = { path = "../shared" }
|
||||
bevy_rapier3d = "0.27.0"
|
||||
serde = { version = "1.0.204", features = ["derive"] }
|
||||
asset_loader = { path = "../../engine/asset_loader" }
|
||||
serde_json = "1.0.120"
|
||||
ron = "0.8.1"
|
||||
bevy_asset_loader = { version = "0.21.0", features = [
|
||||
"standard_dynamic_assets",
|
||||
"3d",
|
||||
] }
|
||||
quadtree_rs = "0.1.3"
|
||||
|
||||
[features]
|
||||
tracing = []
|
||||
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>>,
|
||||
}
|
||||
28
game/units/src/components.rs
Normal file
28
game/units/src/components.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
use bevy::{ecs::world::CommandQueue, prelude::*, tasks::Task};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[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 Vec3);
|
||||
|
||||
#[derive(Component, Debug)]
|
||||
pub struct Path(pub Vec<Vec3>, pub usize);
|
||||
|
||||
#[derive(Component, Debug)]
|
||||
pub struct PathTask(pub Task<CommandQueue>);
|
||||
11
game/units/src/lib.rs
Normal file
11
game/units/src/lib.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
pub mod assets;
|
||||
pub mod components;
|
||||
#[cfg(debug_assertions)]
|
||||
pub mod units_debug_plugin;
|
||||
pub mod units_plugin;
|
||||
pub mod units_spacial_set;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum UnitType {
|
||||
Basic,
|
||||
}
|
||||
66
game/units/src/units_debug_plugin.rs
Normal file
66
game/units/src/units_debug_plugin.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
use std::f32::consts::E;
|
||||
|
||||
use bevy::prelude::*;
|
||||
use shared::{resources::TileUnderCursor, sets::GameplaySet, states::AssetLoadState};
|
||||
use world_generation::{heightmap, prelude::Map};
|
||||
|
||||
use crate::components::{LandUnit, 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));
|
||||
}
|
||||
}
|
||||
|
||||
#[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((
|
||||
PbrBundle {
|
||||
transform: Transform::from_translation(contact.surface),
|
||||
mesh: unit.0.clone(),
|
||||
..default()
|
||||
},
|
||||
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.surface));
|
||||
}
|
||||
}
|
||||
}
|
||||
94
game/units/src/units_plugin.rs
Normal file
94
game/units/src/units_plugin.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
use bevy::{
|
||||
ecs::world::CommandQueue, prelude::*, tasks::AsyncComputeTaskPool, transform::commands, utils::futures,
|
||||
window::PrimaryWindow,
|
||||
};
|
||||
use bevy_asset_loader::loading_state::{
|
||||
config::{ConfigureLoadingState, LoadingStateConfig},
|
||||
LoadingStateAppExt,
|
||||
};
|
||||
use shared::{resources::TileUnderCursor, sets::GameplaySet, states::AssetLoadState};
|
||||
use world_generation::{hex_utils::HexCoord, prelude::Map};
|
||||
|
||||
use crate::{
|
||||
assets::{unit_asset::UnitAssetPlugin, unit_database::UnitDatabase},
|
||||
components::{Path, PathTask, Target, Unit},
|
||||
units_debug_plugin::UnitsDebugPlugin,
|
||||
};
|
||||
|
||||
pub struct UnitsPlugin;
|
||||
|
||||
impl Plugin for UnitsPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
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(Update, units_control.in_set(GameplaySet));
|
||||
app.add_systems(Update, move_unit.in_set(GameplaySet));
|
||||
app.add_systems(FixedPreUpdate, (calculate_path, resolve_path_task).in_set(GameplaySet));
|
||||
}
|
||||
}
|
||||
|
||||
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_seconds();
|
||||
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 calculate_path(
|
||||
units: Query<(&Transform, &Target, Entity), (With<Unit>, Without<PathTask>)>,
|
||||
map: Res<Map>,
|
||||
mut commands: Commands,
|
||||
) {
|
||||
let pool = AsyncComputeTaskPool::get();
|
||||
for (transform, target, entity) in units.iter() {
|
||||
let from = transform.translation;
|
||||
let to = target.0;
|
||||
|
||||
let task = pool.spawn(async move {
|
||||
let mut queue = CommandQueue::default();
|
||||
|
||||
queue.push(move |world: &mut World| {
|
||||
//todo: calculate path
|
||||
world.entity_mut(entity).insert(Path(vec![from, to], 0));
|
||||
});
|
||||
return queue;
|
||||
});
|
||||
|
||||
commands.entity(entity).insert(PathTask(task)).remove::<Target>();
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_path_task(mut tasks: Query<(&mut PathTask, Entity), With<Unit>>, mut commands: Commands) {
|
||||
for (mut task, entity) in tasks.iter_mut() {
|
||||
if let Some(mut c) = futures::check_ready(&mut task.0) {
|
||||
commands.append(&mut c);
|
||||
commands.entity(entity).remove::<PathTask>();
|
||||
}
|
||||
}
|
||||
}
|
||||
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