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

View file

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

View file

@ -2,7 +2,7 @@
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
use avian3d::picking::PhysicsPickable;
use avian3d::prelude::*;
use bevy::{
ecs::{component::HookContext, world::DeferredWorld},
platform::collections::HashMap,
@ -22,10 +22,35 @@ impl Plugin for BuildingPlugin {
}
}
#[derive(Component, Default)]
#[derive(Component)]
#[require(Health, Team::Core, PhysicsPickable)]
pub struct Building {
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)]
@ -35,7 +60,7 @@ pub struct Building {
#[component(immutable)]
pub struct BuildingInfo {
pub preview: Entity,
pub size: UVec2,
pub size: UVec3,
}
#[derive(Component)]
@ -43,8 +68,8 @@ pub struct BuildingPreview {
pub info: Entity,
}
#[derive(Component)]
pub struct ActiveBuildingPreview;
#[derive(Component, Default)]
pub struct ActiveBuildingPreview(pub IVec3);
pub const PREVIEW_ALPHA: f32 = 0.5;
@ -93,8 +118,67 @@ pub struct PlacedBuildings {
}
impl PlacedBuildings {
// todo - update these to account for building being in the center
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);
continue;
}
let size_v3 = info.size.as_vec3();
let instance = commands
.spawn((
Transform::from_translation(location.as_vec3()),
Building::default(),
// adjust model up slightly so base of all towers are aligned
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();
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();
}
building_map.place_building(*location, info, *info_entity, instance);
commands.trigger_targets(PopulatePlacedBuilding { info: *info_entity }, instance);
}
}

View file

@ -4,50 +4,86 @@
use avian3d::prelude::*;
use bevy::prelude::*;
use building::Building;
use building::{BuildingInfo, BuildingPreview, PREVIEW_ALPHA, PopulatePlacedBuilding};
use combat::{Defense, Health};
use state::GameSystemSet;
pub struct BuildingCorePlugin;
impl Plugin for BuildingCorePlugin {
fn build(&self, app: &mut App) {
app.add_event::<SpawnCore>()
.add_systems(FixedUpdate, spawn_core.in_set(GameSystemSet::PostTick));
app.add_systems(Startup, register).add_observer(populate);
}
}
#[derive(Component)]
#[require(Building)]
pub struct Core;
#[derive(Event)]
pub struct SpawnCore {
pub transform: Transform,
#[derive(Resource)]
struct CoreResources {
mesh: Handle<Mesh>,
material: Handle<StandardMaterial>,
info_entity: Entity,
}
fn spawn_core(
mut reader: EventReader<SpawnCore>,
const SIZE: UVec3 = UVec3::new(2, 2, 2);
fn register(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
for SpawnCore { transform } in reader.read() {
commands.spawn((
RigidBody::Static,
Collider::cuboid(2.0, 2.0, 2.0),
Mesh3d(meshes.add(Cuboid::from_length(2.0))),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: Color::srgb_u8(166, 69, 16),
metallic: 0.0,
perceptual_roughness: 0.8,
..default()
})),
Core,
transform.clone(),
Health::new(100.0),
Defense::new(10.0),
Name::from("Core"),
));
}
let mesh = meshes.add(Cuboid::from_length(2.0));
let base_material = StandardMaterial {
base_color: Color::srgb_u8(166, 69, 16),
metallic: 0.0,
perceptual_roughness: 0.8,
..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 },
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 bevy::prelude::*;
use building::{
ActiveBuildingPreview, Building, BuildingInfo, BuildingPreview, PREVIEW_ALPHA,
PopulatePlacedBuilding,
ActiveBuildingPreview, BuildingInfo, BuildingPreview, PREVIEW_ALPHA, PopulatePlacedBuilding,
};
use combat::{Defense, Health};
use combat_damagers::ContactDamage;
@ -20,7 +19,6 @@ impl Plugin for BuildingImpalerPlugin {
}
#[derive(Component)]
#[require(Building)]
pub struct Impaler;
#[derive(Resource)]
@ -30,6 +28,8 @@ struct ImpalerResources {
info_entity: Entity,
}
const SIZE: UVec3 = UVec3::ONE;
fn register(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
@ -53,11 +53,7 @@ fn register(
let preview = commands
.spawn((
BuildingPreview { info },
ActiveBuildingPreview, // Visibility::Hidden,
Mesh3d::default(),
))
.with_child((
Transform::from_xyz(0., 0.5, 0.),
ActiveBuildingPreview::default(), // Visibility::Hidden,
Mesh3d(mesh.clone()),
MeshMaterial3d(preview_material),
))
@ -65,7 +61,7 @@ fn register(
commands.entity(info).insert((
BuildingInfo {
preview,
size: UVec2::new(1, 1),
size: SIZE,
},
Name::new("Impaler"),
));
@ -84,26 +80,14 @@ fn populate(
if trigger.event().info != res.info_entity {
return;
}
commands
.entity(trigger.target())
.insert((
RigidBody::Static,
Impaler,
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()),
));
commands.entity(trigger.target()).insert((
RigidBody::Static,
Impaler,
Health::new(20.0),
Defense::new(5.0),
ContactDamage { amount: 5.0 },
Name::from("Impaler"),
Mesh3d(res.mesh.clone()),
MeshMaterial3d(res.material.clone()),
));
}

View file

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

View file

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

View file

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

View file

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

View file

@ -2,6 +2,8 @@
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
use std::time::Duration;
use avian3d::prelude::*;
use bevy::{
core_pipeline::{bloom::Bloom, experimental::taa::TemporalAntiAliasing},
@ -9,17 +11,18 @@ use bevy::{
prelude::*,
render::camera::Exposure,
};
use building_core::SpawnCore;
use building::{BuildingTypes, PlaceBuilding};
use camera::ControlledCamera;
use inhabitant_coranth::SpawnCoranth;
use physics::Ground;
use state::AppState;
use state::{AppState, GameSystemSet};
pub struct LevelPlugin;
impl Plugin for LevelPlugin {
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 meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut core_writer: EventWriter<SpawnCore>,
buildings: Res<BuildingTypes>,
mut place_writer: EventWriter<PlaceBuilding>,
mut coranth_writer: EventWriter<SpawnCoranth>,
) {
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),
});
}
core_writer.write(SpawnCore {
transform: Transform::from_xyz(5.0, 1.0, 5.0),
place_writer.write(PlaceBuilding {
info: buildings.info.get("Core").unwrap().0,
location: IVec3 { x: 5, y: 0, z: 5 },
});
// Light
@ -85,3 +89,23 @@ fn setup(
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]
bevy = { workspace = true }
bevy-inspector-egui = { workspace = true }
avian3d = { workspace = true }
input = { path = "../input" }
state = { path = "../state" }

View file

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