convert core to new format, improve tower placement

This commit is contained in:
Jim 2025-08-30 23:13:23 -04:00
parent 2808f6dd2c
commit bc02db7b26
Signed by: jim
GPG key ID: 3D7D94BA53088BF4
12 changed files with 250 additions and 107 deletions

5
Cargo.lock generated
View file

@ -1657,6 +1657,7 @@ dependencies = [
"avian3d", "avian3d",
"bevy", "bevy",
"building", "building",
"input",
"physics", "physics",
] ]
@ -3034,8 +3035,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"avian3d", "avian3d",
"bevy", "bevy",
"building_core", "building",
"building_impaler",
"camera", "camera",
"combat", "combat",
"inhabitant_coranth", "inhabitant_coranth",
@ -5068,6 +5068,7 @@ dependencies = [
name = "ui_debug" name = "ui_debug"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"avian3d",
"bevy", "bevy",
"bevy-inspector-egui", "bevy-inspector-egui",
"input", "input",

View file

@ -1,8 +1,17 @@
( (
map: { map: {
MouseButton(Middle): [
CameraOrbitEnable,
],
MouseButton(Left): [
CameraPanEnable,
],
KeyCode(F1): [ KeyCode(F1): [
ToggleDebugUI, ToggleDebugUI,
], ],
MouseButton(Right): [
PlaceTower,
],
MouseScroll: [ MouseScroll: [
CameraZoom, CameraZoom,
], ],
@ -10,17 +19,11 @@
CameraYaw, CameraYaw,
CameraPanX, CameraPanX,
], ],
MouseMovementY: [
CameraPanY,
],
KeyCode(Escape): [ KeyCode(Escape): [
TogglePause, TogglePause,
], ],
MouseButton(Middle): [ MouseMovementY: [
CameraOrbitEnable, CameraPanY,
],
MouseButton(Left): [
CameraPanEnable,
], ],
}, },
) )

View file

@ -2,7 +2,7 @@
#![allow(clippy::type_complexity)] #![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)] #![allow(clippy::too_many_arguments)]
use avian3d::picking::PhysicsPickable; use avian3d::prelude::*;
use bevy::{ use bevy::{
ecs::{component::HookContext, world::DeferredWorld}, ecs::{component::HookContext, world::DeferredWorld},
platform::collections::HashMap, platform::collections::HashMap,
@ -22,10 +22,35 @@ impl Plugin for BuildingPlugin {
} }
} }
#[derive(Component, Default)] #[derive(Component)]
#[require(Health, Team::Core, PhysicsPickable)] #[require(Health, Team::Core, PhysicsPickable)]
pub struct Building { pub struct Building {
pub level: u32, pub level: u32,
pub info: Entity,
}
#[derive(Component)]
#[component(on_remove = on_building_removed)]
struct BuildingPosition(IVec3);
fn on_building_removed(mut world: DeferredWorld, context: HookContext) {
let (info, location) = world
.get_entity(context.entity)
.map(|e| {
(
e.components::<&Building>().info,
e.components::<&BuildingPosition>().0,
)
})
.unwrap();
let size = world
.get_entity(info)
.unwrap()
.components::<&BuildingInfo>()
.size;
world
.resource_mut::<PlacedBuildings>()
.remove_building(location, size);
} }
#[derive(Component, Clone)] #[derive(Component, Clone)]
@ -35,7 +60,7 @@ pub struct Building {
#[component(immutable)] #[component(immutable)]
pub struct BuildingInfo { pub struct BuildingInfo {
pub preview: Entity, pub preview: Entity,
pub size: UVec2, pub size: UVec3,
} }
#[derive(Component)] #[derive(Component)]
@ -43,8 +68,8 @@ pub struct BuildingPreview {
pub info: Entity, pub info: Entity,
} }
#[derive(Component)] #[derive(Component, Default)]
pub struct ActiveBuildingPreview; pub struct ActiveBuildingPreview(pub IVec3);
pub const PREVIEW_ALPHA: f32 = 0.5; pub const PREVIEW_ALPHA: f32 = 0.5;
@ -93,8 +118,67 @@ pub struct PlacedBuildings {
} }
impl PlacedBuildings { impl PlacedBuildings {
// todo - update these to account for building being in the center
pub fn placement_valid(&self, location: IVec3, info: &BuildingInfo) -> bool { pub fn placement_valid(&self, location: IVec3, info: &BuildingInfo) -> bool {
true for x in 0..info.size.x {
for y in 0..info.size.y {
for z in 0..info.size.z {
if self
.map
.contains_key(&(location + IVec3::new(x as i32, y as i32, z as i32)))
{
//shouldn't happen
return false;
}
}
}
}
return true;
}
fn place_building(
&mut self,
location: IVec3,
info: &BuildingInfo,
info_entity: Entity,
instance_entity: Entity,
) {
for x in 0..info.size.x {
for y in 0..info.size.y {
for z in 0..info.size.z {
if self
.map
.insert(
location + IVec3::new(x as i32, y as i32, z as i32),
PlacedBuilding {
info: info_entity,
instance: instance_entity,
},
)
.is_some()
{
//shouldn't happen
error!("placed building on old building!!! RIP");
}
}
}
}
}
fn remove_building(&mut self, location: IVec3, size: UVec3) {
for x in 0..size.x {
for y in 0..size.y {
for z in 0..size.z {
if self
.map
.remove(&(location + IVec3::new(x as i32, y as i32, z as i32)))
.is_none()
{
//shouldn't happen
error!("removed building where there wasn't one!!!! RIP");
}
}
}
}
} }
} }
@ -128,23 +212,22 @@ fn place_building(
error!("invalid building placement at {:?}, rejecting", location); error!("invalid building placement at {:?}, rejecting", location);
continue; continue;
} }
let size_v3 = info.size.as_vec3();
let instance = commands let instance = commands
.spawn(( .spawn((
Transform::from_translation(location.as_vec3()), // adjust model up slightly so base of all towers are aligned
Building::default(), Transform::from_translation(location.as_vec3() + Vec3::new(0., size_v3.y / 2., 0.)),
Building {
level: 0,
info: *info_entity,
},
BuildingPosition(*location),
Collider::cuboid(size_v3.x, size_v3.y, size_v3.z),
Mesh3d::default(),
)) ))
.id(); .id();
if let Some(old_placement) = building_map.map.insert( building_map.place_building(*location, info, *info_entity, instance);
*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); commands.trigger_targets(PopulatePlacedBuilding { info: *info_entity }, instance);
} }
} }

View file

@ -4,50 +4,86 @@
use avian3d::prelude::*; use avian3d::prelude::*;
use bevy::prelude::*; use bevy::prelude::*;
use building::Building; use building::{BuildingInfo, BuildingPreview, PREVIEW_ALPHA, PopulatePlacedBuilding};
use combat::{Defense, Health}; use combat::{Defense, Health};
use state::GameSystemSet;
pub struct BuildingCorePlugin; pub struct BuildingCorePlugin;
impl Plugin for BuildingCorePlugin { impl Plugin for BuildingCorePlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_event::<SpawnCore>() app.add_systems(Startup, register).add_observer(populate);
.add_systems(FixedUpdate, spawn_core.in_set(GameSystemSet::PostTick));
} }
} }
#[derive(Component)] #[derive(Component)]
#[require(Building)]
pub struct Core; pub struct Core;
#[derive(Event)] #[derive(Resource)]
pub struct SpawnCore { struct CoreResources {
pub transform: Transform, mesh: Handle<Mesh>,
material: Handle<StandardMaterial>,
info_entity: Entity,
} }
fn spawn_core( const SIZE: UVec3 = UVec3::new(2, 2, 2);
mut reader: EventReader<SpawnCore>,
fn register(
mut commands: Commands, mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>, mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>, mut materials: ResMut<Assets<StandardMaterial>>,
) { ) {
for SpawnCore { transform } in reader.read() { let mesh = meshes.add(Cuboid::from_length(2.0));
commands.spawn(( let base_material = StandardMaterial {
RigidBody::Static, base_color: Color::srgb_u8(166, 69, 16),
Collider::cuboid(2.0, 2.0, 2.0), metallic: 0.0,
Mesh3d(meshes.add(Cuboid::from_length(2.0))), perceptual_roughness: 0.8,
MeshMaterial3d(materials.add(StandardMaterial { ..default()
base_color: Color::srgb_u8(166, 69, 16), };
metallic: 0.0, let material = materials.add(base_material.clone());
perceptual_roughness: 0.8, let preview_material = materials.add(StandardMaterial {
..default() alpha_mode: AlphaMode::Blend,
})), base_color: base_material.base_color.with_alpha(PREVIEW_ALPHA),
Core, ..base_material
transform.clone(), });
Health::new(100.0),
Defense::new(10.0), let info = commands.spawn_empty().id();
Name::from("Core"), let preview = commands
)); .spawn((
} BuildingPreview { info },
Visibility::Hidden,
Mesh3d(mesh.clone()),
MeshMaterial3d(preview_material),
))
.id();
commands.entity(info).insert((
BuildingInfo {
preview,
size: SIZE,
},
Name::new("Core"),
));
commands.insert_resource(CoreResources {
mesh: mesh,
material: material,
info_entity: info,
});
}
fn populate(
trigger: Trigger<PopulatePlacedBuilding>,
mut commands: Commands,
res: Res<CoreResources>,
) {
if trigger.event().info != res.info_entity {
return;
}
commands.entity(trigger.target()).insert((
RigidBody::Static,
Core,
Health::new(100.0),
Defense::new(5.0),
Name::from("Core"),
Mesh3d(res.mesh.clone()),
MeshMaterial3d(res.material.clone()),
));
} }

View file

@ -5,8 +5,7 @@
use avian3d::prelude::*; use avian3d::prelude::*;
use bevy::prelude::*; use bevy::prelude::*;
use building::{ use building::{
ActiveBuildingPreview, Building, BuildingInfo, BuildingPreview, PREVIEW_ALPHA, ActiveBuildingPreview, BuildingInfo, BuildingPreview, PREVIEW_ALPHA, PopulatePlacedBuilding,
PopulatePlacedBuilding,
}; };
use combat::{Defense, Health}; use combat::{Defense, Health};
use combat_damagers::ContactDamage; use combat_damagers::ContactDamage;
@ -20,7 +19,6 @@ impl Plugin for BuildingImpalerPlugin {
} }
#[derive(Component)] #[derive(Component)]
#[require(Building)]
pub struct Impaler; pub struct Impaler;
#[derive(Resource)] #[derive(Resource)]
@ -30,6 +28,8 @@ struct ImpalerResources {
info_entity: Entity, info_entity: Entity,
} }
const SIZE: UVec3 = UVec3::ONE;
fn register( fn register(
mut commands: Commands, mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>, mut meshes: ResMut<Assets<Mesh>>,
@ -53,11 +53,7 @@ fn register(
let preview = commands let preview = commands
.spawn(( .spawn((
BuildingPreview { info }, BuildingPreview { info },
ActiveBuildingPreview, // Visibility::Hidden, ActiveBuildingPreview::default(), // Visibility::Hidden,
Mesh3d::default(),
))
.with_child((
Transform::from_xyz(0., 0.5, 0.),
Mesh3d(mesh.clone()), Mesh3d(mesh.clone()),
MeshMaterial3d(preview_material), MeshMaterial3d(preview_material),
)) ))
@ -65,7 +61,7 @@ fn register(
commands.entity(info).insert(( commands.entity(info).insert((
BuildingInfo { BuildingInfo {
preview, preview,
size: UVec2::new(1, 1), size: SIZE,
}, },
Name::new("Impaler"), Name::new("Impaler"),
)); ));
@ -84,26 +80,14 @@ fn populate(
if trigger.event().info != res.info_entity { if trigger.event().info != res.info_entity {
return; return;
} }
commands commands.entity(trigger.target()).insert((
.entity(trigger.target()) RigidBody::Static,
.insert(( Impaler,
RigidBody::Static, Health::new(20.0),
Impaler, Defense::new(5.0),
Health::new(20.0), ContactDamage { amount: 5.0 },
Defense::new(5.0), Name::from("Impaler"),
ContactDamage { amount: 5.0 }, Mesh3d(res.mesh.clone()),
Name::from("Impaler"), MeshMaterial3d(res.material.clone()),
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()),
));
} }

View file

@ -9,6 +9,7 @@ avian3d = { workspace = true }
building = { path = "../building" } building = { path = "../building" }
physics = { path = "../physics" } physics = { path = "../physics" }
input = { path = "../input" }
[lints] [lints]
workspace = true workspace = true

View file

@ -6,6 +6,7 @@ use bevy::prelude::*;
use building::{ use building::{
ActiveBuildingPreview, BuildingInfo, BuildingPreview, PlaceBuilding, PlacedBuildings, ActiveBuildingPreview, BuildingInfo, BuildingPreview, PlaceBuilding, PlacedBuildings,
}; };
use input::Inputs;
use physics::Ground; use physics::Ground;
pub struct BuildingPlacementPlugin; pub struct BuildingPlacementPlugin;
@ -30,47 +31,50 @@ fn init(mut commands: Commands, query: Single<Entity, With<Ground>>, mut setup:
fn move_preview( fn move_preview(
trigger: Trigger<Pointer<Move>>, trigger: Trigger<Pointer<Move>>,
preview: Single<(&mut Transform, &BuildingPreview), With<ActiveBuildingPreview>>, preview: Single<(&mut Transform, &mut ActiveBuildingPreview, &BuildingPreview)>,
info_query: Query<&BuildingInfo>, info_query: Query<&BuildingInfo>,
placed_buildings: Res<PlacedBuildings>, placed_buildings: Res<PlacedBuildings>,
) { ) {
let Some(dest) = trigger.event().hit.position else { let Some(dest) = trigger.event().hit.position else {
return; return;
}; };
let (mut tf, preview) = preview.into_inner(); let (mut tf, mut active, preview) = preview.into_inner();
let Ok(info) = info_query.get(preview.info) else { let Ok(info) = info_query.get(preview.info) else {
error!("building preview has no associated info!"); error!("building preview has no associated info!");
return; return;
}; };
// center mouse on building
let loc = dest.round(); let loc = dest.round();
if !placed_buildings.placement_valid(loc.as_ivec3(), info) { if !placed_buildings.placement_valid(loc.as_ivec3(), info) {
info!("invalid placement!!!!!"); info!("invalid placement!!!!!");
return; return;
} }
tf.translation = dest.round(); active.0 = loc.as_ivec3();
tf.translation = loc + Vec3::Y * info.size.y as f32 / 2.;
} }
fn place_preview( fn place_preview(
trigger: Trigger<Pointer<Click>>, _trigger: Trigger<Pointer<Click>>,
preview: Single<&BuildingPreview, With<ActiveBuildingPreview>>, inputs: Res<Inputs<Update>>,
query: Single<(&BuildingPreview, &ActiveBuildingPreview)>,
info_query: Query<&BuildingInfo>, info_query: Query<&BuildingInfo>,
placed_buildings: Res<PlacedBuildings>, placed_buildings: Res<PlacedBuildings>,
mut place_writer: EventWriter<PlaceBuilding>, mut place_writer: EventWriter<PlaceBuilding>,
) { ) {
let Some(dest) = trigger.event().hit.position else { if !inputs.pressed(input::actions::InputAction::PlaceTower) {
return; return;
}; }
let (preview, active) = query.into_inner();
let Ok(info) = info_query.get(preview.info) else { let Ok(info) = info_query.get(preview.info) else {
error!("building preview has no associated info!"); error!("building preview has no associated info!");
return; return;
}; };
let loc = dest.round(); if !placed_buildings.placement_valid(active.0, info) {
if !placed_buildings.placement_valid(loc.as_ivec3(), info) {
info!("invalid placement!!!!!"); info!("invalid placement!!!!!");
return; return;
} }
place_writer.write(PlaceBuilding { place_writer.write(PlaceBuilding {
info: preview.info, info: preview.info,
location: loc.as_ivec3(), location: active.0,
}); });
} }

View file

@ -13,6 +13,7 @@ pub enum InputAction {
CameraPanY, CameraPanY,
CameraPanEnable, CameraPanEnable,
CameraOrbitEnable, CameraOrbitEnable,
PlaceTower,
} }
impl Default for InputMap { impl Default for InputMap {
@ -38,6 +39,10 @@ impl Default for InputMap {
InputMethod::MouseButton(MouseButton::Left), InputMethod::MouseButton(MouseButton::Left),
InputAction::CameraPanEnable, InputAction::CameraPanEnable,
), ),
(
InputMethod::MouseButton(MouseButton::Right),
InputAction::PlaceTower,
),
]) ])
} }
} }

View file

@ -11,8 +11,7 @@ state = { path = "../state" }
camera = { path = "../camera" } camera = { path = "../camera" }
combat = { path = "../combat" } combat = { path = "../combat" }
physics = { path = "../physics" } physics = { path = "../physics" }
building_core = { path = "../building_core" } building = { path = "../building" }
building_impaler = { path = "../building_impaler" }
inhabitant_coranth = { path = "../inhabitant_coranth" } inhabitant_coranth = { path = "../inhabitant_coranth" }
[lints] [lints]

View file

@ -2,6 +2,8 @@
#![allow(clippy::type_complexity)] #![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)] #![allow(clippy::too_many_arguments)]
use std::time::Duration;
use avian3d::prelude::*; use avian3d::prelude::*;
use bevy::{ use bevy::{
core_pipeline::{bloom::Bloom, experimental::taa::TemporalAntiAliasing}, core_pipeline::{bloom::Bloom, experimental::taa::TemporalAntiAliasing},
@ -9,17 +11,18 @@ use bevy::{
prelude::*, prelude::*,
render::camera::Exposure, render::camera::Exposure,
}; };
use building_core::SpawnCore; use building::{BuildingTypes, PlaceBuilding};
use camera::ControlledCamera; use camera::ControlledCamera;
use inhabitant_coranth::SpawnCoranth; use inhabitant_coranth::SpawnCoranth;
use physics::Ground; use physics::Ground;
use state::AppState; use state::{AppState, GameSystemSet};
pub struct LevelPlugin; pub struct LevelPlugin;
impl Plugin for LevelPlugin { impl Plugin for LevelPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_systems(OnEnter(AppState::Game), setup); app.add_systems(OnEnter(AppState::Game), setup)
.add_systems(FixedUpdate, spawn_enemies.in_set(GameSystemSet::Execute));
} }
} }
@ -27,7 +30,8 @@ fn setup(
mut commands: Commands, mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>, mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>, mut materials: ResMut<Assets<StandardMaterial>>,
mut core_writer: EventWriter<SpawnCore>, buildings: Res<BuildingTypes>,
mut place_writer: EventWriter<PlaceBuilding>,
mut coranth_writer: EventWriter<SpawnCoranth>, mut coranth_writer: EventWriter<SpawnCoranth>,
) { ) {
let level_size = 50.0; let level_size = 50.0;
@ -51,9 +55,9 @@ fn setup(
transform: Transform::from_xyz(y as f32 * 0.25, y as f32 * 1.1, 0.0), transform: Transform::from_xyz(y as f32 * 0.25, y as f32 * 1.1, 0.0),
}); });
} }
place_writer.write(PlaceBuilding {
core_writer.write(SpawnCore { info: buildings.info.get("Core").unwrap().0,
transform: Transform::from_xyz(5.0, 1.0, 5.0), location: IVec3 { x: 5, y: 0, z: 5 },
}); });
// Light // Light
@ -85,3 +89,23 @@ fn setup(
Transform::from_xyz(-2.5, 9.5, 9.0).looking_at(Vec3::ZERO, Dir3::Y), Transform::from_xyz(-2.5, 9.5, 9.0).looking_at(Vec3::ZERO, Dir3::Y),
)); ));
} }
fn spawn_enemies(
mut writer: EventWriter<SpawnCoranth>,
time: Res<Time>,
mut setup: Local<bool>,
mut timer: Local<Timer>,
) {
if !*setup {
*timer = Timer::new(Duration::from_secs(1), TimerMode::Repeating);
*setup = true;
}
timer.tick(time.delta());
if timer.just_finished() {
for _ in 0..3 {
writer.write(SpawnCoranth {
transform: Transform::from_xyz(0.0, 2.0, 0.0),
});
}
}
}

View file

@ -6,6 +6,7 @@ edition = "2024"
[dependencies] [dependencies]
bevy = { workspace = true } bevy = { workspace = true }
bevy-inspector-egui = { workspace = true } bevy-inspector-egui = { workspace = true }
avian3d = { workspace = true }
input = { path = "../input" } input = { path = "../input" }
state = { path = "../state" } state = { path = "../state" }

View file

@ -2,6 +2,7 @@
#![allow(clippy::type_complexity)] #![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)] #![allow(clippy::too_many_arguments)]
use avian3d::prelude::*;
use bevy::prelude::*; use bevy::prelude::*;
use bevy_inspector_egui::quick::WorldInspectorPlugin; use bevy_inspector_egui::quick::WorldInspectorPlugin;
use input::{actions::InputAction, conditions::action_just_pressed}; use input::{actions::InputAction, conditions::action_just_pressed};
@ -13,6 +14,7 @@ impl Plugin for UiDebugPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.init_state::<DebugUIState>() app.init_state::<DebugUIState>()
.add_plugins(WorldInspectorPlugin::new().run_if(in_state(DebugUIState::Enabled))) .add_plugins(WorldInspectorPlugin::new().run_if(in_state(DebugUIState::Enabled)))
.add_plugins(PhysicsDebugPlugin::default())
.add_systems( .add_systems(
Update, Update,
toggle_debug_ui toggle_debug_ui