diff --git a/engine/asset_loader/src/macros.rs b/engine/asset_loader/src/macros.rs index 668cb74..a37ffdf 100644 --- a/engine/asset_loader/src/macros.rs +++ b/engine/asset_loader/src/macros.rs @@ -1,5 +1,3 @@ -use bevy::{asset::AssetLoader, reflect::TypePath}; - #[macro_export] macro_rules! create_asset_loader { ( diff --git a/engine/world_generation/src/map/map_utils.rs b/engine/world_generation/src/map/map_utils.rs index fefaeed..21c9a08 100644 --- a/engine/world_generation/src/map/map_utils.rs +++ b/engine/world_generation/src/map/map_utils.rs @@ -1,6 +1,6 @@ use std::ops::Add; -use bevy::{asset::AssetLoader, math::VectorSpace, prelude::*}; +use bevy::{math::VectorSpace, prelude::*}; use image::ImageBuffer; use rayon::prelude::*; @@ -13,7 +13,8 @@ pub fn render_image( data: &Vec, color1: LinearRgba, color2: LinearRgba, -) -> ImageBuffer, Vec> { +) -> ImageBuffer, Vec> +{ 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); @@ -26,7 +27,8 @@ pub fn update_image( color1: LinearRgba, color2: LinearRgba, image: &mut ImageBuffer, Vec>, -) { +) +{ 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); @@ -41,7 +43,8 @@ pub fn update_image( }); } -fn to_pixel(col: &LinearRgba) -> image::Rgba { +fn to_pixel(col: &LinearRgba) -> image::Rgba +{ return image::Rgba([ (col.red * 255.0) as u8, (col.green * 255.0) as u8, @@ -49,7 +52,8 @@ fn to_pixel(col: &LinearRgba) -> image::Rgba { 255, ]); } -pub fn render_map(map: &Map, smooth: f32) -> ImageBuffer, Vec> { +pub fn render_map(map: &Map, smooth: f32) -> ImageBuffer, Vec> +{ let mut image = ImageBuffer::new( map.width as u32 * Chunk::SIZE as u32, map.height as u32 * Chunk::SIZE as u32, @@ -57,18 +61,21 @@ pub fn render_map(map: &Map, smooth: f32) -> ImageBuffer, Vec, Vec>) { +pub fn update_map(map: &Map, smooth: f32, image: &mut ImageBuffer, Vec>) +{ 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 { + if height < map.sealevel + { color.hue = 217.0; } - if map.is_in_bounds(&right) { + if map.is_in_bounds(&right) + { let h2 = map.sample_height(&right); color = get_height_color_blend(color, height, h2, smooth); } @@ -77,22 +84,33 @@ pub fn update_map(map: &Map, smooth: f32, image: &mut ImageBuffer Hsla { +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 { + if smooth == 0.0 || d.abs() > smooth + { + if d > 0.0 + { color.lightness += 0.1; - } else if d < 0.0 { + } + else if d < 0.0 + { color.lightness -= 0.1; } - } else { - if d.abs() <= smooth { + } + else + { + if d.abs() <= smooth + { d /= smooth; - if d > 0.0 { + if d > 0.0 + { let c2: LinearRgba = color.with_lightness(color.lightness + 0.1).into(); color = LinearRgba::lerp(color.into(), c2, d).into(); - } else { + } + else + { let c2: LinearRgba = color.with_lightness(color.lightness - 0.1).into(); color = LinearRgba::lerp(color.into(), c2, d.abs()).into(); } @@ -102,13 +120,15 @@ fn get_height_color_blend(base_color: Hsla, height: f32, height2: f32, smooth: f return color; } -pub fn render_biome_noise_map(map: &BiomeMap, multi: Vec3) -> ImageBuffer, Vec> { +pub fn render_biome_noise_map(map: &BiomeMap, multi: Vec3) -> ImageBuffer, Vec> +{ 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, Vec>) { +pub fn update_biome_noise_map(map: &BiomeMap, multi: Vec3, image: &mut ImageBuffer, Vec>) +{ image.par_enumerate_pixels_mut().for_each(|(x, y, pixel)| { let tile = map.get_biome_data(x as usize, y as usize); @@ -121,7 +141,8 @@ pub fn update_biome_noise_map(map: &BiomeMap, multi: Vec3, image: &mut ImageBuff }); } -pub fn render_biome_map(map: &Map, biome_map: &BiomeMap) -> ImageBuffer, Vec> { +pub fn render_biome_map(map: &Map, biome_map: &BiomeMap) -> ImageBuffer, Vec> +{ let mut image = ImageBuffer::new( map.width as u32 * Chunk::SIZE as u32, map.height as u32 * Chunk::SIZE as u32, @@ -130,19 +151,22 @@ pub fn render_biome_map(map: &Map, biome_map: &BiomeMap) -> ImageBuffer, Vec>) { +pub fn update_biome_map(map: &Map, biome_map: &BiomeMap, image: &mut ImageBuffer, Vec>) +{ 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() { + 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) { + 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(); diff --git a/engine/world_generation/src/map/mesh_chunk.rs b/engine/world_generation/src/map/mesh_chunk.rs index 7b6c7f2..290f211 100644 --- a/engine/world_generation/src/map/mesh_chunk.rs +++ b/engine/world_generation/src/map/mesh_chunk.rs @@ -6,7 +6,8 @@ use crate::hex_utils::HexCoord; use super::chunk::Chunk; -pub struct MeshChunkData { +pub struct MeshChunkData +{ pub heights: [f32; Chunk::AREA], pub textures: [[u32; 2]; Chunk::AREA], pub min_height: f32, @@ -14,13 +15,17 @@ pub struct MeshChunkData { pub distance_to_land: [f32; Chunk::AREA], } -impl MeshChunkData { - pub fn get_neighbors(&self, coord: &HexCoord) -> [f32; 6] { +impl MeshChunkData +{ + pub fn get_neighbors(&self, coord: &HexCoord) -> [f32; 6] + { let mut data = [self.min_height; 6]; let n_tiles = coord.get_neighbors(); - for i in 0..6 { + for i in 0..6 + { let n = n_tiles[i]; - if !n.is_in_bounds(Chunk::SIZE, Chunk::SIZE) { + if !n.is_in_bounds(Chunk::SIZE, Chunk::SIZE) + { continue; } data[i] = self.heights[n.to_index(Chunk::SIZE)]; @@ -29,56 +34,70 @@ impl MeshChunkData { return data; } - pub fn get_neighbors_with_water_info(&self, coord: &HexCoord) -> ([(f32, Option); 6], bool) { + pub fn get_neighbors_with_water_info(&self, coord: &HexCoord) -> ([(f32, Option); 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 { + for i in 0..6 + { let n = n_tiles[i]; - if !n.is_in_bounds(Chunk::SIZE, Chunk::SIZE) { + 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 { + if data[i].0 > self.sealevel + { has_land = true; } } return (data, has_land); } - pub fn caluclate_water_distances(data: &mut Vec, height: usize, width: usize, range: usize) { + pub fn caluclate_water_distances(data: &mut Vec, 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 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 { + 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 { + if h > self.sealevel + { open.push_back((coord, h, 0)); } } } } + #[allow(dead_code)] + #[allow(unused)] fn fill_chunk_borders( &mut self, chunks: &Vec, 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") } diff --git a/game/buildings/src/assets/building_asset.rs b/game/buildings/src/assets/building_asset.rs index d772c6b..5dbbee6 100644 --- a/game/buildings/src/assets/building_asset.rs +++ b/game/buildings/src/assets/building_asset.rs @@ -12,11 +12,11 @@ use crate::{ resource_gathering::ResourceGatheringBuildingInfo, }, footprint::BuildingFootprint, - prelude::Building, }; #[derive(Asset, TypePath, Debug, Serialize, Deserialize)] -pub struct BuildingAsset { +pub struct BuildingAsset +{ pub name: String, pub description: String, pub footprint: BuildingFootprint, @@ -35,7 +35,9 @@ pub struct BuildingAsset { // pub components: Option>, } -impl BuildingAsset { +impl BuildingAsset +{ + #[allow(unused)] pub fn spawn( &self, pos: Vec3, @@ -44,7 +46,8 @@ impl BuildingAsset { commands: &mut Commands, meshes: &Assets, nodes: &Assets, - ) -> Option { + ) -> Option + { todo!("Update building spawning"); // let base_node = &gltf.named_nodes[&self.base_mesh_path.clone().into_boxed_str()]; // if let Some(node) = nodes.get(base_node.id()) { @@ -120,7 +123,8 @@ impl BuildingAsset { } #[derive(Serialize, Deserialize, Debug, TypePath)] -pub enum BuildingType { +pub enum BuildingType +{ Basic, Gathering(ResourceGatheringBuildingInfo), FactoryBuildingInfo(FactoryBuildingInfo), diff --git a/game/buildings/src/building_plugin.rs b/game/buildings/src/building_plugin.rs index 50edfca..ed704d6 100644 --- a/game/buildings/src/building_plugin.rs +++ b/game/buildings/src/building_plugin.rs @@ -1,26 +1,19 @@ -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::{parry::transformation::utils::transform, pipeline::QueryFilter, plugin::RapierContext}; use shared::{ despawn::Despawn, events::TileModifiedEvent, resources::TileUnderCursor, states::{AssetLoadState, GameplayState}, - tags::MainCamera, -}; -use world_generation::{ - heightmap, hex_utils::HexCoord, map::map::Map, prelude::GenerationConfig, states::GeneratorState, }; +use world_generation::{map::map::Map, prelude::GenerationConfig, states::GeneratorState}; use crate::{ assets::{ @@ -34,8 +27,10 @@ use crate::{ pub struct BuildingPugin; -impl Plugin for BuildingPugin { - fn build(&self, app: &mut App) { +impl Plugin for BuildingPugin +{ + fn build(&self, app: &mut App) + { app.insert_resource(BuildQueue::default()); app.add_plugins(BuildingAssetPlugin); @@ -62,12 +57,15 @@ impl Plugin for BuildingPugin { } } -fn prepare_building_map(mut commands: Commands, cfg: Res) { +fn prepare_building_map(mut commands: Commands, cfg: Res) +{ commands.insert_resource(BuildingMap::new(cfg.size)); } -fn regernerate(mut commands: Commands, buildings: Query>, cfg: Res) { - for e in buildings.iter() { +fn regernerate(mut commands: Commands, buildings: Query>, cfg: Res) +{ + for e in buildings.iter() + { commands.entity(e).despawn(); } commands.insert_resource(BuildingMap::new(cfg.size)); @@ -76,7 +74,8 @@ fn regernerate(mut commands: Commands, buildings: Query>, #[derive(Resource)] struct IndicatorCube(Handle, Handle); -fn init(mut commands: Commands, mut meshes: ResMut>, mut materials: ResMut>) { +fn init(mut commands: Commands, mut meshes: ResMut>, mut materials: ResMut>) +{ let cube = Cuboid::from_size(Vec3::splat(1.)); let mesh_handle = meshes.add(cube); let mat_handle = materials.add(Color::WHITE); @@ -91,12 +90,15 @@ fn hq_placement( indicator: Res, mut build_queue: ResMut, mut next_state: ResMut>, -) { - if let Some(contact) = tile_under_cursor.0 { +) +{ + 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) { + if mouse.just_pressed(MouseButton::Left) + { build_queue.queue.push(QueueEntry { building: 0.into(), pos: contact.tile, @@ -107,8 +109,10 @@ fn hq_placement( } } -fn show_indicators(positions: Vec, commands: &mut Commands, indicator: &IndicatorCube) { - for p in positions { +fn show_indicators(positions: Vec, commands: &mut Commands, indicator: &IndicatorCube) +{ + for p in positions + { commands.spawn(( Mesh3d(indicator.0.clone()), MeshMaterial3d(indicator.1.clone()), @@ -128,13 +132,17 @@ fn process_build_queue( gltf_nodes: Res>, mut building_map: ResMut, heightmap: Res, -) { - for item in &queue.queue { +) +{ + for item in &queue.queue + { let handle = &db.buildings[item.building.0]; - if let Some(building) = building_assets.get(handle.id()) { + 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()) { + if let Some(gltf) = gltf_assets.get(building.prefab.id()) + { let e = building.spawn( item.pos.to_world(h), Quat::IDENTITY, @@ -143,10 +151,13 @@ fn process_build_queue( &gltf_meshes, &gltf_nodes, ); - if let Some(b) = e { + if let Some(b) = e + { building_map.add_building(BuildingEntry::new(item.pos, b)); } - } else { + } + else + { warn!("Failed to spawn building"); } } @@ -158,17 +169,23 @@ fn update_building_heights( mut tile_updates: MessageReader, building_map: Res, 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) { +) +{ + 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::() { + if let Some(mut transform) = emut.get_mut::() + { transform.translation.y = h; } }); diff --git a/game/main/src/camera_system/camera_plugin.rs b/game/main/src/camera_system/camera_plugin.rs index ce4488b..424bcf8 100644 --- a/game/main/src/camera_system/camera_plugin.rs +++ b/game/main/src/camera_system/camera_plugin.rs @@ -1,4 +1,4 @@ -use bevy::anti_alias::taa::{TemporalAntiAliasPlugin, TemporalAntiAliasing}; +use bevy::anti_alias::taa::TemporalAntiAliasing; use bevy::core_pipeline::prepass::DepthPrepass; use bevy::input::mouse::{MouseMotion, MouseScrollUnit, MouseWheel}; use bevy::prelude::*; @@ -25,12 +25,10 @@ impl Plugin for PhosCameraPlugin 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 init_bounds(mut commands: Commands, mut cam: Single<(&mut Transform, Entity), With>, heightmap: Res) +fn init_bounds(mut commands: Commands, cam: Single<(&mut Transform, Entity), With>, heightmap: Res) { let (mut cam_t, cam_entity) = cam.into_inner(); cam_t.translation = heightmap.get_center(); diff --git a/game/main/src/camera_system/components.rs b/game/main/src/camera_system/components.rs index bcc81a8..56d2a6c 100644 --- a/game/main/src/camera_system/components.rs +++ b/game/main/src/camera_system/components.rs @@ -1,10 +1,11 @@ use bevy::prelude::*; use rayon::str; -use world_generation::{hex_utils::SHORT_DIAGONAL, prelude::Chunk}; +use world_generation::prelude::Chunk; #[derive(Component, Reflect)] #[reflect(Component)] -pub struct PhosCamera { +pub struct PhosCamera +{ pub min_height: f32, pub max_height: f32, pub speed: f32, @@ -14,8 +15,10 @@ pub struct PhosCamera { pub max_angle: f32, } -impl Default for PhosCamera { - fn default() -> Self { +impl Default for PhosCamera +{ + fn default() -> Self + { Self { min_height: 10., max_height: 420., @@ -28,14 +31,17 @@ impl Default for PhosCamera { } } #[derive(Component, Reflect)] -pub struct PhosOrbitCamera { +pub struct PhosOrbitCamera +{ pub target: Vec3, pub distance: f32, pub forward: Vec3, } -impl Default for PhosOrbitCamera { - fn default() -> Self { +impl Default for PhosOrbitCamera +{ + fn default() -> Self + { Self { target: Default::default(), distance: 40.0, @@ -45,13 +51,16 @@ impl Default for PhosOrbitCamera { } #[derive(Component, Default)] -pub struct CameraBounds { +pub struct CameraBounds +{ pub min: Vec2, pub max: Vec2, } -impl CameraBounds { - pub fn from_size(world_size: Vec2) -> Self { +impl CameraBounds +{ + pub fn from_size(world_size: Vec2) -> Self + { let padding = Chunk::WORLD_SIZE; return Self { min: Vec2::ZERO - padding, diff --git a/game/main/src/main.rs b/game/main/src/main.rs index f510098..05e6a3f 100644 --- a/game/main/src/main.rs +++ b/game/main/src/main.rs @@ -1,5 +1,3 @@ -use std::env; - use bevy::image::{ImageAddressMode, ImageFilterMode, ImageSamplerDescriptor}; use bevy::pbr::wireframe::WireframePlugin; use bevy::prelude::*; diff --git a/game/main/src/map_rendering/chunk_rebuild.rs b/game/main/src/map_rendering/chunk_rebuild.rs index 63a596f..8b4108d 100644 --- a/game/main/src/map_rendering/chunk_rebuild.rs +++ b/game/main/src/map_rendering/chunk_rebuild.rs @@ -9,6 +9,7 @@ use world_generation::prelude::Map; use world_generation::states::GeneratorState; use crate::prelude::RebuildChunk; +use crate::prelude::WaterMesh; use crate::{ prelude::{PhosChunk, PhosChunkRegistry}, utlis::chunk_utils::prepare_chunk_mesh, @@ -16,8 +17,10 @@ use crate::{ pub struct ChunkRebuildPlugin; -impl Plugin for ChunkRebuildPlugin { - fn build(&self, app: &mut App) { +impl Plugin for ChunkRebuildPlugin +{ + fn build(&self, app: &mut App) + { app.init_resource::(); app.add_message::(); app.add_message::(); @@ -30,11 +33,13 @@ fn chunk_rebuilder( mut commands: Commands, chunk_query: Query<(Entity, &PhosChunk), (With, Without)>, heightmap: Res, -) { +) +{ let pool = AsyncComputeTaskPool::get(); let map_size = UVec2::new(heightmap.width as u32, heightmap.height as u32); - for (chunk_entity, idx) in &chunk_query { + for (chunk_entity, idx) in &chunk_query + { #[cfg(feature = "tracing")] let _spawn_span = info_span!("Rebuild Chunk").entered(); info!("Rebuilding Chunk"); @@ -62,7 +67,7 @@ fn chunk_rebuilder( world.entity_mut(chunk_entity).insert(c).remove::(); }); - return (queue, mesh); + return (queue, mesh, water_mesh); }); commands @@ -73,19 +78,28 @@ fn chunk_rebuilder( } fn collider_task_resolver( - mut chunks: Query<(&mut ChunkRebuildTask, &Mesh3d), With>, + mut chunks: Query<(&mut ChunkRebuildTask, &Mesh3d, &WaterMesh), With>, mut commands: Commands, mut meshes: ResMut>, -) { - for (mut task, mesh_handle) in &mut chunks { - if let Some((mut c, mesh)) = futures::check_ready(&mut task.task) { +) +{ + for (mut task, mesh_handle, water_mesh_handle) in &mut chunks + { + if let Some((mut c, chunk_mesh, water_mesh)) = futures::check_ready(&mut task.task) + { commands.append(&mut c); - meshes.insert(mesh_handle.id(), mesh); + meshes + .insert(mesh_handle.id(), chunk_mesh) + .expect("Failed to update chunk mesh"); + meshes + .insert(water_mesh_handle.0, water_mesh) + .expect("Failed to update chink water mesh"); } } } #[derive(Component)] -struct ChunkRebuildTask { - pub task: Task<(CommandQueue, Mesh)>, +struct ChunkRebuildTask +{ + pub task: Task<(CommandQueue, Mesh, Mesh)>, } diff --git a/game/main/src/map_rendering/map_init.rs b/game/main/src/map_rendering/map_init.rs index cc88c83..d7dbb3a 100644 --- a/game/main/src/map_rendering/map_init.rs +++ b/game/main/src/map_rendering/map_init.rs @@ -1,11 +1,6 @@ #[cfg(feature = "tracing")] use bevy::log::*; -use bevy::{ - light::NotShadowCaster, - pbr::ExtendedMaterial, - prelude::*, - render::render_resource::{ColorTargetState, FragmentState, RenderPipelineDescriptor}, -}; +use bevy::{light::NotShadowCaster, pbr::ExtendedMaterial, prelude::*}; use bevy_asset_loader::prelude::*; use bevy_inspector_egui::quick::ResourceInspectorPlugin; @@ -23,7 +18,7 @@ use world_generation::{ }; use crate::{ - prelude::{PhosAssets, PhosChunk, PhosChunkRegistry}, + prelude::{PhosAssets, PhosChunk, PhosChunkRegistry, WaterMesh}, shader_extensions::{ chunk_material::ChunkMaterial, water_material::{WaterMaterial, WaterSettings}, @@ -258,19 +253,21 @@ fn spawn_map( for (chunk_mesh, water_mesh, collider, pos, index) in chunk_meshes { // let mesh_handle = meshes.a + let water_mesh_handle = meshes.add(water_mesh); let chunk = commands .spawn(( Mesh3d(meshes.add(chunk_mesh)), MeshMaterial3d(atlas.chunk_material_handle.clone()), Transform::from_translation(pos), PhosChunk::new(index), + WaterMesh(water_mesh_handle.id()), RenderDistanceVisibility::default().with_offset(visibility_offset), collider, )) .id(); let water = commands .spawn(( - Mesh3d(meshes.add(water_mesh)), + Mesh3d(water_mesh_handle), MeshMaterial3d(atlas.water_material.clone()), Transform::from_translation(pos), PhosChunk::new(index), diff --git a/game/main/src/map_rendering/prelude.rs b/game/main/src/map_rendering/prelude.rs index 55ebc11..8b13789 100644 --- a/game/main/src/map_rendering/prelude.rs +++ b/game/main/src/map_rendering/prelude.rs @@ -1,2 +1 @@ -use bevy::prelude::*; -use world_generation::biome_painter::BiomePainterAsset; + diff --git a/game/main/src/map_rendering/render_distance_system.rs b/game/main/src/map_rendering/render_distance_system.rs index 3f6dfe4..48c05f2 100644 --- a/game/main/src/map_rendering/render_distance_system.rs +++ b/game/main/src/map_rendering/render_distance_system.rs @@ -1,12 +1,12 @@ use bevy::prelude::*; use shared::tags::MainCamera; -use crate::camera_system::components::PhosCamera; - pub struct RenderDistancePlugin; -impl Plugin for RenderDistancePlugin { - fn build(&self, app: &mut bevy::prelude::App) { +impl Plugin for RenderDistancePlugin +{ + fn build(&self, app: &mut bevy::prelude::App) + { app.register_type::(); app.add_systems(PostUpdate, render_distance_system) .insert_resource(RenderDistanceSettings::default()); @@ -15,38 +15,48 @@ impl Plugin for RenderDistancePlugin { #[derive(Resource, Reflect)] #[reflect(Resource)] -pub struct RenderDistanceSettings { +pub struct RenderDistanceSettings +{ pub render_distance: f32, } -impl RenderDistanceSettings { - pub fn new(distance: f32) -> Self { +impl RenderDistanceSettings +{ + pub fn new(distance: f32) -> Self + { return Self { render_distance: distance, }; } } -impl Default for RenderDistanceSettings { - fn default() -> Self { +impl Default for RenderDistanceSettings +{ + fn default() -> Self + { Self::new(500.) } } #[derive(Component)] -pub struct RenderDistanceVisibility { +pub struct RenderDistanceVisibility +{ pub offset: Vec3, } -impl RenderDistanceVisibility { - pub fn with_offset(mut self, offset: Vec3) -> Self { +impl RenderDistanceVisibility +{ + pub fn with_offset(mut self, offset: Vec3) -> Self + { self.offset = offset; return self; } } -impl Default for RenderDistanceVisibility { - fn default() -> Self { +impl Default for RenderDistanceVisibility +{ + fn default() -> Self + { Self { offset: Vec3::ZERO } } } @@ -55,13 +65,18 @@ fn render_distance_system( mut objects: Query<(&Transform, &mut Visibility, &RenderDistanceVisibility)>, camera: Single<&Transform, With>, settings: Res, -) { +) +{ let cam_pos = Vec3::new(camera.translation.x, 0.0, camera.translation.z); - for (t, mut vis, r) in objects.iter_mut() { + for (t, mut vis, r) in objects.iter_mut() + { let dist = (cam_pos - (t.translation + r.offset)).length(); - if settings.render_distance < dist { + if settings.render_distance < dist + { *vis = Visibility::Hidden; - } else { + } + else + { *vis = Visibility::Visible; } } diff --git a/game/main/src/map_rendering/terraforming_test.rs b/game/main/src/map_rendering/terraforming_test.rs index eefc1a5..2bec755 100644 --- a/game/main/src/map_rendering/terraforming_test.rs +++ b/game/main/src/map_rendering/terraforming_test.rs @@ -1,21 +1,20 @@ -use bevy::{platform::collections::HashSet, prelude::*, window::PrimaryWindow}; -use bevy_rapier3d::{pipeline::QueryFilter, plugin::RapierContext}; +use bevy::{platform::collections::HashSet, prelude::*}; use shared::{ events::{ChunkModifiedEvent, TileModifiedEvent}, resources::TileUnderCursor, states::GameplayState, }; -use world_generation::{hex_utils::HexCoord, prelude::Map, states::GeneratorState}; +use world_generation::{prelude::Map, states::GeneratorState}; -use crate::{ - camera_system::components::PhosCamera, - prelude::{PhosChunkRegistry, RebuildChunk}, -}; +use crate::prelude::{PhosChunkRegistry, RebuildChunk}; +#[allow(dead_code)] pub struct TerraFormingTestPlugin; -impl Plugin for TerraFormingTestPlugin { - fn build(&self, app: &mut App) { +impl Plugin for TerraFormingTestPlugin +{ + fn build(&self, app: &mut App) + { app.add_systems( Update, deform @@ -25,6 +24,7 @@ impl Plugin for TerraFormingTestPlugin { } } +#[allow(dead_code)] fn deform( mut commands: Commands, mouse: Res>, @@ -33,26 +33,34 @@ fn deform( tile_under_cursor: Res, mut chunk_modified: MessageWriter, mut tile_modified: MessageWriter, -) { +) +{ let mut multi = 0.; - if mouse.just_pressed(MouseButton::Left) { + if mouse.just_pressed(MouseButton::Left) + { multi = 1.; - } else if mouse.just_pressed(MouseButton::Right) { + } + else if mouse.just_pressed(MouseButton::Right) + { multi = -1.; } - if multi == 0. { + if multi == 0. + { return; } - if let Some(contact) = tile_under_cursor.0 { + if let Some(contact) = tile_under_cursor.0 + { #[cfg(feature = "tracing")] let span = info_span!("Deform Mesh").entered(); let modified_tiles = heightmap.create_crater(&contact.tile, 5, 5. * multi); let mut chunk_set: HashSet = HashSet::new(); - for (tile, height) in modified_tiles { + for (tile, height) in modified_tiles + { let chunk = tile.to_chunk_index(heightmap.width); - if !chunk_set.contains(&chunk) { + if !chunk_set.contains(&chunk) + { chunk_modified.write(ChunkModifiedEvent { index: chunk }); chunk_set.insert(chunk); commands.entity(chunks.chunks[chunk]).insert(RebuildChunk); diff --git a/game/main/src/phos.rs b/game/main/src/phos.rs index db1cd1c..fbe2af1 100644 --- a/game/main/src/phos.rs +++ b/game/main/src/phos.rs @@ -1,7 +1,7 @@ use crate::camera_system::components::PhosCamera; use crate::map_rendering::map_init::MapInitPlugin; use crate::map_rendering::render_distance_system::RenderDistancePlugin; -// use crate::ui::build_ui::BuildUIPlugin; +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}; @@ -40,7 +40,7 @@ impl Plugin for PhosGamePlugin MapInitPlugin, RenderDistancePlugin, // BuildingPugin, - // BuildUIPlugin, + BuildUIPlugin, // SimpleAnimationPlugin, // UnitsPlugin, DespawnPuglin, diff --git a/game/main/src/prelude.rs b/game/main/src/prelude.rs index 6ff4870..de864a0 100644 --- a/game/main/src/prelude.rs +++ b/game/main/src/prelude.rs @@ -3,13 +3,13 @@ use bevy::pbr::ExtendedMaterial; use bevy::prelude::*; use bevy::prelude::{Component, Image, Resource}; use bevy_asset_loader::asset_collection::AssetCollection; -use world_generation::biome_painter::BiomePainterAsset; use crate::shader_extensions::chunk_material::ChunkMaterial; use crate::shader_extensions::water_material::WaterMaterial; #[derive(AssetCollection, Resource, Default)] -pub struct PhosAssets { +pub struct PhosAssets +{ #[asset(key = "chunk_atlas")] pub handle: Handle, pub chunk_material_handle: Handle>, @@ -17,24 +17,33 @@ pub struct PhosAssets { } #[derive(Component)] -pub struct PhosChunk { +pub struct PhosChunk +{ pub index: usize, } -impl PhosChunk { - pub fn new(index: usize) -> Self { +impl PhosChunk +{ + pub fn new(index: usize) -> Self + { return Self { index }; } } +#[derive(Component)] +pub struct WaterMesh(pub AssetId); + #[derive(Resource, Default)] -pub struct PhosChunkRegistry { +pub struct PhosChunkRegistry +{ pub chunks: Vec, pub waters: Vec, } -impl PhosChunkRegistry { - pub fn new(size: usize) -> Self { +impl PhosChunkRegistry +{ + pub fn new(size: usize) -> Self + { return Self { chunks: Vec::with_capacity(size), waters: Vec::with_capacity(size), diff --git a/game/main/src/shader_extensions/chunk_material.rs b/game/main/src/shader_extensions/chunk_material.rs index 5e2abaf..b84164a 100644 --- a/game/main/src/shader_extensions/chunk_material.rs +++ b/game/main/src/shader_extensions/chunk_material.rs @@ -22,6 +22,7 @@ impl MaterialExtension for ChunkMaterial } } +#[allow(dead_code)] #[derive(Asset, TypePath, AsBindGroup, Debug, Clone)] pub struct PackedChunkMaterial { @@ -56,10 +57,10 @@ impl Material for PackedChunkMaterial // } fn specialize( - pipeline: &bevy::pbr::MaterialPipeline, + _pipeline: &bevy::pbr::MaterialPipeline, descriptor: &mut bevy::render::render_resource::RenderPipelineDescriptor, layout: &bevy::mesh::MeshVertexBufferLayoutRef, - key: bevy::pbr::MaterialPipelineKey, + _key: bevy::pbr::MaterialPipelineKey, ) -> bevy::ecs::error::Result<(), bevy::render::render_resource::SpecializedMeshPipelineError> { let vertex_layout = layout.0.get_layout(&[ diff --git a/game/main/src/shader_extensions/water_material.rs b/game/main/src/shader_extensions/water_material.rs index 69317c8..63861e4 100644 --- a/game/main/src/shader_extensions/water_material.rs +++ b/game/main/src/shader_extensions/water_material.rs @@ -1,11 +1,9 @@ use bevy::asset::Asset; -use bevy::math::VectorSpace; use bevy::pbr::MaterialExtension; use bevy::prelude::*; use bevy::reflect::Reflect; use bevy::render::render_resource::{AsBindGroup, ShaderType}; use bevy::shader::ShaderRef; -use world_generation::consts::{ATTRIBUTE_PACKED_VERTEX_DATA, ATTRIBUTE_VERTEX_HEIGHT}; #[derive(Asset, Reflect, AsBindGroup, Debug, Clone, Default)] pub struct WaterMaterial diff --git a/game/main/src/ui/build_ui.rs b/game/main/src/ui/build_ui.rs index c7c2a15..17bc801 100644 --- a/game/main/src/ui/build_ui.rs +++ b/game/main/src/ui/build_ui.rs @@ -1,19 +1,23 @@ -use bevy::prelude::*; -use shared::{states::AssetLoadState, tags::MainCamera}; +use bevy::{camera::visibility::RenderLayers, prelude::*}; +use shared::states::AssetLoadState; pub struct BuildUIPlugin; -impl Plugin for BuildUIPlugin { - fn build(&self, app: &mut App) { +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)); +fn setup_cameras(mut commands: Commands) +{ + commands.spawn((Camera2d, IsDefaultUiCamera, RenderLayers::layer(2))); } -fn spawn_ui(mut commands: Commands) { +fn spawn_ui(mut commands: Commands) +{ commands .spawn((Node { width: Val::Percent(100.), diff --git a/game/main/src/utlis/chunk_utils.rs b/game/main/src/utlis/chunk_utils.rs index be40fe7..12f5746 100644 --- a/game/main/src/utlis/chunk_utils.rs +++ b/game/main/src/utlis/chunk_utils.rs @@ -13,7 +13,6 @@ use world_generation::{ 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}, @@ -26,7 +25,8 @@ pub fn paint_map( painter: &BiomePainter, tiles: &Res>, mappers: &Res>, -) { +) +{ map.chunks.par_iter_mut().for_each(|chunk: &mut Chunk| { paint_chunk(chunk, painter, tiles, mappers); }); @@ -37,9 +37,12 @@ pub fn paint_chunk( painter: &BiomePainter, tiles: &Res>, mappers: &Res>, -) { - for z in 0..Chunk::SIZE { - for x in 0..Chunk::SIZE { +) +{ + for z in 0..Chunk::SIZE + { + for x in 0..Chunk::SIZE + { let idx = x + z * Chunk::SIZE; let height = chunk.heights[idx]; let biome_id = chunk.biome_id[idx]; @@ -58,7 +61,8 @@ pub fn prepare_chunk_mesh( chunk_offset: IVec2, chunk_index: usize, map_size: UVec2, -) -> (Mesh, Mesh, (Vec, Vec<[u32; 3]>), Vec3, usize) { +) -> (Mesh, Mesh, (Vec, Vec<[u32; 3]>), Vec3, usize) +{ #[cfg(feature = "tracing")] let _gen_mesh = info_span!("Generate Chunk").entered(); let chunk_mesh = generate_chunk_mesh(chunk); @@ -80,7 +84,8 @@ pub fn prepare_chunk_mesh_with_collider( chunk_offset: IVec2, chunk_index: usize, map_size: UVec2, -) -> (Mesh, Mesh, Collider, Vec3, usize) { +) -> (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; diff --git a/game/main/src/utlis/debug_plugin.rs b/game/main/src/utlis/debug_plugin.rs index 65a28f7..9a781ac 100644 --- a/game/main/src/utlis/debug_plugin.rs +++ b/game/main/src/utlis/debug_plugin.rs @@ -1,4 +1,4 @@ -use bevy::{gizmos::gizmos, prelude::*}; +use bevy::prelude::*; use shared::states::GameplayState; use shared::{resources::TileUnderCursor, sets::GameplaySet}; use world_generation::{ @@ -11,8 +11,10 @@ use crate::camera_system::components::{PhosCamera, PhosOrbitCamera}; pub struct DebugPlugin; -impl Plugin for DebugPlugin { - fn build(&self, app: &mut App) { +impl Plugin for DebugPlugin +{ + fn build(&self, app: &mut App) + { app.insert_state(DebugState::Base); app.add_systems( @@ -29,7 +31,7 @@ impl Plugin for DebugPlugin { .run_if(in_state(DebugState::Verbose)), ); - // app.add_systems(Update, camera_debug.in_set(GameplaySet)); + 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([ @@ -48,7 +50,8 @@ impl Plugin for DebugPlugin { struct Shape(pub Polyline3d); #[derive(States, Debug, Clone, PartialEq, Eq, Hash)] -pub enum DebugState { +pub enum DebugState +{ Base, None, Verbose, @@ -58,15 +61,19 @@ fn regenerate_map( mut generator_state: ResMut>, mut gameplay_state: ResMut>, input: Res>, -) { - if input.just_pressed(KeyCode::KeyR) { +) +{ + if input.just_pressed(KeyCode::KeyR) + { generator_state.set(GeneratorState::Regenerate); gameplay_state.set(GameplayState::PlaceHQ); } } -fn show_tile_heights(map: Res, mut gizmos: Gizmos, shape: Res, tile_under_cursor: Res) { - if let Some(contact) = tile_under_cursor.0 { +fn show_tile_heights(map: Res, mut gizmos: Gizmos, shape: Res, tile_under_cursor: Res) +{ + 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); @@ -78,8 +85,11 @@ fn show_tile_heights(map: Res, mut gizmos: Gizmos, shape: Res, tile_ } } -fn show_water_corners(pos: Vec3, gizmos: &mut Gizmos) { - for i in 0..WATER_HEX_CORNERS.len() { +#[allow(dead_code)] +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()]; @@ -87,8 +97,9 @@ fn show_water_corners(pos: Vec3, gizmos: &mut Gizmos) { } } -fn camera_debug(mut cam_query: Single<(&PhosCamera, &PhosOrbitCamera)>, mut gizmos: Gizmos) { - let (config, orbit) = cam_query.into_inner(); +fn camera_debug(cam_query: Single<(&PhosCamera, &PhosOrbitCamera)>, mut gizmos: Gizmos) +{ + let (_config, orbit) = cam_query.into_inner(); gizmos.sphere(orbit.target, 0.3, LinearRgba::RED); let cam_proxy = orbit.target - (orbit.forward * 10.0); diff --git a/game/main/src/utlis/editor_plugin.rs b/game/main/src/utlis/editor_plugin.rs index 23f38e7..891450d 100644 --- a/game/main/src/utlis/editor_plugin.rs +++ b/game/main/src/utlis/editor_plugin.rs @@ -11,22 +11,25 @@ use world_generation::{map::map_utils::render_map, prelude::Map, states::Generat pub struct EditorPlugin; -impl Plugin for EditorPlugin { - fn build(&self, app: &mut App) { +impl Plugin for EditorPlugin +{ + fn build(&self, app: &mut App) + { app.init_resource::(); - // 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)), - // ); + 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); -pub fn prepare_image(mut images: ResMut>, heightmap: Res, mut commands: Commands) { +pub fn prepare_image(mut images: ResMut>, heightmap: Res, mut commands: Commands) +{ let image = render_map(&heightmap, 0.1); let handle = images.add(Image::from_dynamic(image.into(), true, RenderAssetUsages::RENDER_WORLD)); @@ -34,14 +37,17 @@ pub fn prepare_image(mut images: ResMut>, heightmap: Res, mut } #[derive(Resource)] -struct UIState { +struct UIState +{ pub is_open: bool, pub target_map_type: MapDisplayType, pub cur_map_type: MapDisplayType, } -impl Default for UIState { - fn default() -> Self { +impl Default for UIState +{ + fn default() -> Self + { Self { is_open: true, target_map_type: default(), @@ -51,7 +57,8 @@ impl Default for UIState { } #[derive(Debug, PartialEq, Eq, Clone, Copy, Default)] -enum MapDisplayType { +enum MapDisplayType +{ #[default] HeightMap, Biomes, @@ -63,72 +70,77 @@ enum MapDisplayType { fn asset_reloaded( mut asset_events: MessageReader>, - mut biomes: ResMut>, + biomes: Res>, biome_painter: Res, mut commands: Commands, -) { +) +{ let mut rebuild = false; - for event in asset_events.read() { - match event { + for event in asset_events.read() + { + match event + { AssetEvent::Modified { .. } => rebuild = true, _ => (), } } - if rebuild { + if rebuild + { let painter = biome_painter.build(&biomes); commands.insert_resource(painter); } } -// fn render_map_ui( -// image: Res, -// heightmap: Res, -// biome_map: Res, -// mut contexts: EguiContexts, -// mut state: ResMut, -// ) { -// let id = contexts.add_image(image.0.clone()); +fn render_map_ui( + // image: Res, + heightmap: Res, + biome_map: Res, + mut contexts: EguiContexts, + mut state: ResMut, +) +{ + // let id = contexts.add_image(image.0.); + let mut map_type = state.target_map_type; + let ctx = contexts.ctx_mut().expect("Failed to get egui context"); + 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", + ); + }); -// 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], + // ))); -// 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)); + } + }); -// 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; -// } + state.target_map_type = map_type; +} fn update_map_render( mut state: ResMut, @@ -136,22 +148,28 @@ fn update_map_render( heightmap: Res, biome_map: Res, image: Res, -) { - if state.cur_map_type == state.target_map_type { +) +{ + 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), - ); + images + .insert( + image.0.id(), + Image::from_dynamic(result.into(), true, RenderAssetUsages::RENDER_WORLD), + ) + .expect("Failed to update map image"); state.cur_map_type = state.target_map_type; } -fn get_map_image(heightmap: &Map, biome_map: &BiomeMap, map_type: MapDisplayType) -> ImageBuffer, Vec> { - return match map_type { +fn get_map_image(heightmap: &Map, biome_map: &BiomeMap, map_type: MapDisplayType) -> ImageBuffer, Vec> +{ + 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), diff --git a/game/main/src/utlis/tile_selection_plugin.rs b/game/main/src/utlis/tile_selection_plugin.rs index 839668c..41475ea 100644 --- a/game/main/src/utlis/tile_selection_plugin.rs +++ b/game/main/src/utlis/tile_selection_plugin.rs @@ -1,5 +1,5 @@ use bevy::{prelude::*, window::PrimaryWindow}; -use bevy_rapier3d::{plugin::RapierContext, prelude::QueryFilter}; +use bevy_rapier3d::{plugin::ReadRapierContext, prelude::QueryFilter}; use shared::{ resources::{TileContact, TileUnderCursor}, tags::MainCamera, @@ -7,8 +7,10 @@ use shared::{ use world_generation::{hex_utils::HexCoord, prelude::Map, states::GeneratorState}; pub struct TileSelectionPlugin; -impl Plugin for TileSelectionPlugin { - fn build(&self, app: &mut App) { +impl Plugin for TileSelectionPlugin +{ + fn build(&self, app: &mut App) + { app.init_resource::(); app.add_systems( PreUpdate, @@ -20,42 +22,53 @@ impl Plugin for TileSelectionPlugin { fn update_tile_under_cursor( cam_query: Single<(&GlobalTransform, &Camera), With>, window: Single<&Window, With>, - // rapier_context: RapierContext, + rapier: ReadRapierContext, map: Res, mut tile_under_cursor: ResMut, -) { +) +{ let (cam_transform, camera) = cam_query.into_inner(); - let Some(cursor_pos) = window.cursor_position() else { + let Some(cursor_pos) = window.cursor_position() + else + { return; }; - let Ok(cam_ray) = camera.viewport_to_world(cam_transform, cursor_pos) else { + 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(), - // ); + let ctx = rapier.single().expect("Failed to get rapier read context"); - // 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; - // } + let collision = ctx.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; + } } diff --git a/game/shared/src/identifiers.rs b/game/shared/src/identifiers.rs index 166f5d7..0ef6328 100644 --- a/game/shared/src/identifiers.rs +++ b/game/shared/src/identifiers.rs @@ -1,9 +1,9 @@ use bevy::reflect::Reflect; use serde::{Deserialize, Serialize}; -use world_generation::hex_utils::HexCoord; #[derive(Serialize, Deserialize, Debug, Reflect)] -pub struct ResourceIdentifier { +pub struct ResourceIdentifier +{ pub id: u32, pub qty: u32, } diff --git a/game/units/src/lib.rs b/game/units/src/lib.rs index 61e9eb8..f12fd4e 100644 --- a/game/units/src/lib.rs +++ b/game/units/src/lib.rs @@ -1,6 +1,3 @@ -use bevy::reflect::Reflect; -use serde::{Deserialize, Serialize}; - pub mod assets; pub mod components; pub mod nav_data; @@ -11,6 +8,7 @@ pub mod units_plugin; pub mod units_spacial_set; #[derive(Clone, Copy)] -pub enum UnitType { +pub enum UnitType +{ Basic, }