From 2808f6dd2cfbf85e147fece9e4f08588c3c4ee18 Mon Sep 17 00:00:00 2001 From: Jim Date: Sat, 30 Aug 2025 20:41:42 -0400 Subject: [PATCH] place buildings --- Cargo.lock | 15 +++ Cargo.toml | 1 + assets/settings/input_map.ron | 6 +- crates/building/Cargo.toml | 2 + crates/building/src/lib.rs | 138 ++++++++++++++++++++++++++- crates/building_impaler/src/lib.rs | 96 +++++++++++++++---- crates/building_placement/Cargo.toml | 14 +++ crates/building_placement/src/lib.rs | 76 +++++++++++++++ crates/combat/Cargo.toml | 1 + crates/inhabitant_coranth/src/lib.rs | 3 +- crates/level/Cargo.toml | 1 + crates/level/src/lib.rs | 9 +- crates/physics/src/lib.rs | 8 +- src/main.rs | 4 +- 14 files changed, 338 insertions(+), 36 deletions(-) mode change 100755 => 100644 Cargo.toml create mode 100644 crates/building_placement/Cargo.toml create mode 100644 crates/building_placement/src/lib.rs mode change 100755 => 100644 src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 8a75a2e..e877fbd 100755 --- a/Cargo.lock +++ b/Cargo.lock @@ -1621,8 +1621,10 @@ dependencies = [ name = "building" version = "0.1.0" dependencies = [ + "avian3d", "bevy", "combat", + "state", ] [[package]] @@ -1648,6 +1650,16 @@ dependencies = [ "state", ] +[[package]] +name = "building_placement" +version = "0.1.0" +dependencies = [ + "avian3d", + "bevy", + "building", + "physics", +] + [[package]] name = "bumpalo" version = "3.19.0" @@ -1803,6 +1815,7 @@ version = "0.1.0" dependencies = [ "avian3d", "bevy", + "physics", "state", ] @@ -1961,6 +1974,7 @@ dependencies = [ "building", "building_core", "building_impaler", + "building_placement", "camera", "combat", "combat_damagers", @@ -3025,6 +3039,7 @@ dependencies = [ "camera", "combat", "inhabitant_coranth", + "physics", "state", ] diff --git a/Cargo.toml b/Cargo.toml old mode 100755 new mode 100644 index 79d35c9..3e9f279 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,4 +49,5 @@ building_impaler = { path = "crates/building_impaler" } combat_damagers = { path = "crates/combat_damagers" } inhabitant = { path = "crates/inhabitant" } inhabitant_coranth = { path = "crates/inhabitant_coranth" } +building_placement = { path = "crates/building_placement" } #new internal crates go here diff --git a/assets/settings/input_map.ron b/assets/settings/input_map.ron index 2c24da8..54be48d 100755 --- a/assets/settings/input_map.ron +++ b/assets/settings/input_map.ron @@ -16,11 +16,11 @@ KeyCode(Escape): [ TogglePause, ], - MouseButton(Left): [ - CameraPanEnable, - ], MouseButton(Middle): [ CameraOrbitEnable, ], + MouseButton(Left): [ + CameraPanEnable, + ], }, ) \ No newline at end of file diff --git a/crates/building/Cargo.toml b/crates/building/Cargo.toml index c499394..6383d03 100755 --- a/crates/building/Cargo.toml +++ b/crates/building/Cargo.toml @@ -5,7 +5,9 @@ edition = "2024" [dependencies] bevy = { workspace = true } +avian3d = { workspace = true } combat = { path = "../combat" } +state = { path = "../state" } [lints] workspace = true diff --git a/crates/building/src/lib.rs b/crates/building/src/lib.rs index f4ee401..498cbf3 100755 --- a/crates/building/src/lib.rs +++ b/crates/building/src/lib.rs @@ -2,17 +2,149 @@ #![allow(clippy::type_complexity)] #![allow(clippy::too_many_arguments)] -use bevy::prelude::*; +use avian3d::picking::PhysicsPickable; +use bevy::{ + ecs::{component::HookContext, world::DeferredWorld}, + platform::collections::HashMap, + prelude::*, +}; use combat::{Health, Team}; +use state::GameSystemSet; pub struct BuildingPlugin; impl Plugin for BuildingPlugin { - fn build(&self, _app: &mut App) {} + fn build(&self, app: &mut App) { + app.init_resource::() + .init_resource::() + .add_event::() + .add_systems(FixedUpdate, place_building.in_set(GameSystemSet::PostTick)); + } } #[derive(Component, Default)] -#[require(Health, Team::Core)] +#[require(Health, Team::Core, PhysicsPickable)] pub struct Building { pub level: u32, } + +#[derive(Component, Clone)] +#[require(Name)] +#[component(on_add = register_building_info)] +#[component(on_remove = unregister_building_info)] +#[component(immutable)] +pub struct BuildingInfo { + pub preview: Entity, + pub size: UVec2, +} + +#[derive(Component)] +pub struct BuildingPreview { + pub info: Entity, +} + +#[derive(Component)] +pub struct ActiveBuildingPreview; + +pub const PREVIEW_ALPHA: f32 = 0.5; + +fn register_building_info(mut world: DeferredWorld, context: HookContext) { + let (info, name) = world + .get_entity(context.entity) + .unwrap() + .components::<(&BuildingInfo, &Name)>(); + if name.is_empty() { + panic!("name cannot be empty when registering building"); + } + let (info, name) = (info.clone(), name.to_string()); + let mut types = world.get_resource_mut::().unwrap(); + info!("registering building {}", name); + types.info.insert(name, (context.entity, info)); +} + +fn unregister_building_info(mut world: DeferredWorld, context: HookContext) { + let name = world + .get_entity(context.entity) + .unwrap() + .components::<&Name>() + .to_string(); + if name.is_empty() { + panic!("name cannot be empty when ungregistering building"); + } + let mut types = world.get_resource_mut::().unwrap(); + info!("unregistering building {}", name); + types.info.remove(&name); +} + +#[derive(Resource, Default)] +pub struct BuildingTypes { + pub info: HashMap, +} + +#[derive(Clone)] +pub struct PlacedBuilding { + pub info: Entity, + pub instance: Entity, +} + +#[derive(Resource, Default)] +pub struct PlacedBuildings { + pub map: HashMap, +} + +impl PlacedBuildings { + pub fn placement_valid(&self, location: IVec3, info: &BuildingInfo) -> bool { + true + } +} + +#[derive(Event)] +pub struct PlaceBuilding { + pub info: Entity, + pub location: IVec3, +} + +#[derive(Event)] +pub struct PopulatePlacedBuilding { + pub info: Entity, +} + +fn place_building( + mut reader: EventReader, + mut building_map: ResMut, + mut commands: Commands, + info_query: Query<&BuildingInfo>, +) { + for PlaceBuilding { + info: info_entity, + location, + } in reader.read() + { + let Ok(info) = info_query.get(*info_entity) else { + error!("tried to place building without info!"); + continue; + }; + if !building_map.placement_valid(*location, info) { + error!("invalid building placement at {:?}, rejecting", location); + continue; + } + let instance = commands + .spawn(( + Transform::from_translation(location.as_vec3()), + Building::default(), + )) + .id(); + if let Some(old_placement) = building_map.map.insert( + *location, + PlacedBuilding { + info: *info_entity, + instance, + }, + ) { + //shouldn't happen + error!("placed building on old building, removing old building"); + commands.entity(old_placement.instance).despawn(); + } + commands.trigger_targets(PopulatePlacedBuilding { info: *info_entity }, instance); + } +} diff --git a/crates/building_impaler/src/lib.rs b/crates/building_impaler/src/lib.rs index af8eb60..74c7a3c 100755 --- a/crates/building_impaler/src/lib.rs +++ b/crates/building_impaler/src/lib.rs @@ -4,17 +4,18 @@ use avian3d::prelude::*; use bevy::prelude::*; -use building::Building; +use building::{ + ActiveBuildingPreview, Building, BuildingInfo, BuildingPreview, PREVIEW_ALPHA, + PopulatePlacedBuilding, +}; use combat::{Defense, Health}; use combat_damagers::ContactDamage; -use state::GameSystemSet; pub struct BuildingImpalerPlugin; impl Plugin for BuildingImpalerPlugin { fn build(&self, app: &mut App) { - app.add_event::() - .add_systems(FixedUpdate, spawn.in_set(GameSystemSet::PostTick)); + app.add_systems(Startup, register).add_observer(populate); } } @@ -22,34 +23,87 @@ impl Plugin for BuildingImpalerPlugin { #[require(Building)] pub struct Impaler; -#[derive(Event)] -pub struct SpawnImpaler { - pub transform: Transform, +#[derive(Resource)] +struct ImpalerResources { + mesh: Handle, + material: Handle, + info_entity: Entity, } -fn spawn( - mut reader: EventReader, +fn register( mut commands: Commands, mut meshes: ResMut>, mut materials: ResMut>, ) { - for SpawnImpaler { transform } in reader.read() { - commands.spawn(( + let mesh = meshes.add(Cuboid::from_length(1.0)); + let base_material = StandardMaterial { + base_color: Color::srgb_u8(0xd6, 0x50, 0x61), + metallic: 0.2, + perceptual_roughness: 0.6, + ..default() + }; + let material = materials.add(base_material.clone()); + let preview_material = materials.add(StandardMaterial { + alpha_mode: AlphaMode::Blend, + base_color: base_material.base_color.with_alpha(PREVIEW_ALPHA), + ..base_material + }); + + let info = commands.spawn_empty().id(); + let preview = commands + .spawn(( + BuildingPreview { info }, + ActiveBuildingPreview, // Visibility::Hidden, + Mesh3d::default(), + )) + .with_child(( + Transform::from_xyz(0., 0.5, 0.), + Mesh3d(mesh.clone()), + MeshMaterial3d(preview_material), + )) + .id(); + commands.entity(info).insert(( + BuildingInfo { + preview, + size: UVec2::new(1, 1), + }, + Name::new("Impaler"), + )); + commands.insert_resource(ImpalerResources { + mesh: mesh, + material: material, + info_entity: info, + }); +} + +fn populate( + trigger: Trigger, + mut commands: Commands, + res: Res, +) { + if trigger.event().info != res.info_entity { + return; + } + commands + .entity(trigger.target()) + .insert(( RigidBody::Static, - Collider::cuboid(1.0, 1.0, 1.0), - Mesh3d(meshes.add(Cuboid::from_length(1.0))), - MeshMaterial3d(materials.add(StandardMaterial { - base_color: Color::srgb_u8(0xd6, 0x50, 0x61), - metallic: 0.2, - perceptual_roughness: 0.6, - ..default() - })), Impaler, - transform.clone(), Health::new(20.0), Defense::new(5.0), ContactDamage { amount: 5.0 }, Name::from("Impaler"), + Mesh3d::default(), + Collider::compound(vec![( + Vec3::Y * 0.5, + Quat::IDENTITY, + Collider::cuboid(1.0, 1.0, 1.0), + )]), + )) + .with_child(( + // don't think I'll need this with actual models + Transform::from_xyz(0., 0.5, 0.), + Mesh3d(res.mesh.clone()), + MeshMaterial3d(res.material.clone()), )); - } } diff --git a/crates/building_placement/Cargo.toml b/crates/building_placement/Cargo.toml new file mode 100644 index 0000000..e7a55ae --- /dev/null +++ b/crates/building_placement/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "building_placement" +version = "0.1.0" +edition = "2024" + +[dependencies] +bevy = { workspace = true } +avian3d = { workspace = true } + +building = { path = "../building" } +physics = { path = "../physics" } + +[lints] +workspace = true diff --git a/crates/building_placement/src/lib.rs b/crates/building_placement/src/lib.rs new file mode 100644 index 0000000..c9be1ca --- /dev/null +++ b/crates/building_placement/src/lib.rs @@ -0,0 +1,76 @@ +//bevy system signatures often violate these rules +#![allow(clippy::type_complexity)] +#![allow(clippy::too_many_arguments)] + +use bevy::prelude::*; +use building::{ + ActiveBuildingPreview, BuildingInfo, BuildingPreview, PlaceBuilding, PlacedBuildings, +}; +use physics::Ground; + +pub struct BuildingPlacementPlugin; + +impl Plugin for BuildingPlacementPlugin { + fn build(&self, app: &mut App) { + app.add_systems(Update, init); + } +} + +fn init(mut commands: Commands, query: Single>, mut setup: Local) { + if *setup { + return; + } + *setup = true; + commands + .entity(*query) + .observe(move_preview) + .observe(place_preview); + info!("added building placement observers!"); +} + +fn move_preview( + trigger: Trigger>, + preview: Single<(&mut Transform, &BuildingPreview), With>, + info_query: Query<&BuildingInfo>, + placed_buildings: Res, +) { + let Some(dest) = trigger.event().hit.position else { + return; + }; + let (mut tf, preview) = preview.into_inner(); + let Ok(info) = info_query.get(preview.info) else { + error!("building preview has no associated info!"); + return; + }; + let loc = dest.round(); + if !placed_buildings.placement_valid(loc.as_ivec3(), info) { + info!("invalid placement!!!!!"); + return; + } + tf.translation = dest.round(); +} + +fn place_preview( + trigger: Trigger>, + preview: Single<&BuildingPreview, With>, + info_query: Query<&BuildingInfo>, + placed_buildings: Res, + mut place_writer: EventWriter, +) { + let Some(dest) = trigger.event().hit.position else { + return; + }; + let Ok(info) = info_query.get(preview.info) else { + error!("building preview has no associated info!"); + return; + }; + let loc = dest.round(); + if !placed_buildings.placement_valid(loc.as_ivec3(), info) { + info!("invalid placement!!!!!"); + return; + } + place_writer.write(PlaceBuilding { + info: preview.info, + location: loc.as_ivec3(), + }); +} diff --git a/crates/combat/Cargo.toml b/crates/combat/Cargo.toml index e351c43..386601e 100755 --- a/crates/combat/Cargo.toml +++ b/crates/combat/Cargo.toml @@ -8,6 +8,7 @@ bevy = { workspace = true } avian3d = { workspace = true } state = { path = "../state" } +physics = { path = "../physics"} [lints] workspace = true diff --git a/crates/inhabitant_coranth/src/lib.rs b/crates/inhabitant_coranth/src/lib.rs index a0e20e8..ba7d383 100755 --- a/crates/inhabitant_coranth/src/lib.rs +++ b/crates/inhabitant_coranth/src/lib.rs @@ -5,7 +5,7 @@ use avian3d::prelude::*; use bevy::prelude::*; use building::Building; -use combat::{GaveDamage, Health, Team}; +use combat::{GaveDamage, Health}; use combat_damagers::ContactDamage; use inhabitant::Inhabitant; use state::GameSystemSet; @@ -76,7 +76,6 @@ fn explode( // &SpatialQueryFilter::from_mask(Team::Inhabitant), &SpatialQueryFilter::default(), ) { - info!("found hit"); if let Ok((gtf, mut v)) = other_query.get_mut(e) { let delta = gtf.translation() - origin; v.0 += delta.normalize_or_zero() * 10.0; diff --git a/crates/level/Cargo.toml b/crates/level/Cargo.toml index 44fdbc9..0dae5b6 100755 --- a/crates/level/Cargo.toml +++ b/crates/level/Cargo.toml @@ -10,6 +10,7 @@ avian3d = { workspace = true } state = { path = "../state" } camera = { path = "../camera" } combat = { path = "../combat" } +physics = { path = "../physics" } building_core = { path = "../building_core" } building_impaler = { path = "../building_impaler" } inhabitant_coranth = { path = "../inhabitant_coranth" } diff --git a/crates/level/src/lib.rs b/crates/level/src/lib.rs index 8ddf9e8..afdc508 100755 --- a/crates/level/src/lib.rs +++ b/crates/level/src/lib.rs @@ -10,9 +10,9 @@ use bevy::{ render::camera::Exposure, }; use building_core::SpawnCore; -use building_impaler::SpawnImpaler; use camera::ControlledCamera; use inhabitant_coranth::SpawnCoranth; +use physics::Ground; use state::AppState; pub struct LevelPlugin; @@ -28,7 +28,6 @@ fn setup( mut meshes: ResMut>, mut materials: ResMut>, mut core_writer: EventWriter, - mut impaler_writer: EventWriter, mut coranth_writer: EventWriter, ) { let level_size = 50.0; @@ -43,6 +42,8 @@ fn setup( perceptual_roughness: 0.8, ..default() })), + PhysicsPickable, + Ground, )); for y in 5..15 { @@ -54,9 +55,6 @@ fn setup( core_writer.write(SpawnCore { transform: Transform::from_xyz(5.0, 1.0, 5.0), }); - impaler_writer.write(SpawnImpaler { - transform: Transform::from_xyz(-5.0, 0.5, 5.0), - }); // Light commands.spawn(( @@ -83,6 +81,7 @@ fn setup( Atmosphere::EARTH, Exposure::SUNLIGHT, Bloom::NATURAL, + PhysicsPickable, Transform::from_xyz(-2.5, 9.5, 9.0).looking_at(Vec3::ZERO, Dir3::Y), )); } diff --git a/crates/physics/src/lib.rs b/crates/physics/src/lib.rs index 132466a..ec68355 100755 --- a/crates/physics/src/lib.rs +++ b/crates/physics/src/lib.rs @@ -12,6 +12,12 @@ impl Plugin for PhysicsPlugin { app.add_plugins(( PhysicsPlugins::default().set(PhysicsInterpolationPlugin::interpolate_all()), PhysicsPickingPlugin, - )); + )) + .insert_resource(PhysicsPickingSettings { + require_markers: true, + }); } } + +#[derive(Component)] +pub struct Ground; diff --git a/src/main.rs b/src/main.rs old mode 100755 new mode 100644 index 70993a8..9bd3ffd --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,11 @@ -use bevy::prelude::*; +use bevy::{prelude::*, window::WindowResolution}; fn main() { let mut app = App::new(); app.add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "Coreheart".to_string(), + resolution: WindowResolution::new(1600., 900.), ..default() }), ..default() @@ -30,6 +31,7 @@ fn main() { ), inhabitant::InhabitantPlugin, inhabitant_coranth::InhabitantCoranthPlugin, + building_placement::BuildingPlacementPlugin, // new internal crates go here ));