use bevy::prelude::*;
use crate::chunk::Chunk;
use crate::voxel::VoxelType;
use super::{ChunkManager, ChunkModified};
#[derive(Resource, Debug, Clone)]
pub struct PlacementConfig {
pub cooldown: f32,
}
impl Default for PlacementConfig {
fn default() -> Self {
Self { cooldown: 0.25 }
}
}
#[derive(Resource, Default, Debug)]
pub struct PlacementState {
pub cooldown_elapsed: f32,
}
impl PlacementState {
pub fn can_place(&self, config: &PlacementConfig) -> bool {
self.cooldown_elapsed >= config.cooldown
}
}
#[derive(Message, Debug, Clone)]
pub struct VoxelPlaced {
pub chunk_coord: IVec3,
pub local: (usize, usize, usize),
pub world_pos: Vec3,
pub face_normal: IVec3,
}
fn notify_border_neighbors(
chunk_coord: IVec3,
local: (usize, usize, usize),
modified: &mut MessageWriter<ChunkModified>,
) {
use crate::chunk::CHUNK_SIZE;
let (x, y, z) = local;
let offsets: [(usize, IVec3); 6] = [
(x, IVec3::NEG_X),
(CHUNK_SIZE - 1 - x, IVec3::X),
(y, IVec3::NEG_Y),
(CHUNK_SIZE - 1 - y, IVec3::Y),
(z, IVec3::NEG_Z),
(CHUNK_SIZE - 1 - z, IVec3::Z),
];
for (dist, dir) in offsets {
if dist == 0 {
modified.write(ChunkModified(chunk_coord + dir));
}
}
}
fn voxel_world_pos(chunk_coord: IVec3, local: (usize, usize, usize)) -> Vec3 {
let chunk_origin = chunk_coord.as_vec3() * crate::chunk::CHUNK_SIZE as f32;
chunk_origin
+ Vec3::new(
local.0 as f32 + 0.5,
local.1 as f32 + 0.5,
local.2 as f32 + 0.5,
)
}
#[allow(clippy::too_many_arguments)]
pub fn try_place_voxel<V: VoxelType>(
target_chunk: IVec3,
target_local: (usize, usize, usize),
voxel: V,
face_normal: IVec3,
state: &mut PlacementState,
config: &PlacementConfig,
manager: &ChunkManager,
chunks: &mut Query<&mut Chunk<V>>,
placed: &mut MessageWriter<VoxelPlaced>,
modified: &mut MessageWriter<ChunkModified>,
) -> bool {
if !state.can_place(config) {
return false;
}
let Some(entity) = manager.get_entity(target_chunk) else {
return false;
};
let Ok(mut chunk) = chunks.get_mut(entity) else {
return false;
};
let (x, y, z) = target_local;
if chunk.get(x, y, z).is_solid() {
return false;
}
chunk.set(x, y, z, voxel);
chunk.set_state(x, y, z, crate::chunk::face_to_state(face_normal));
state.cooldown_elapsed = 0.0;
let world_pos = voxel_world_pos(target_chunk, target_local);
placed.write(VoxelPlaced {
chunk_coord: target_chunk,
local: target_local,
world_pos,
face_normal,
});
modified.write(ChunkModified(target_chunk));
notify_border_neighbors(target_chunk, target_local, modified);
true
}
pub fn tick_placement(delta_secs: f32, state: &mut PlacementState, config: &PlacementConfig) {
state.cooldown_elapsed = (state.cooldown_elapsed + delta_secs).min(config.cooldown);
}
pub struct PlacementPlugin;
impl Plugin for PlacementPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<PlacementConfig>();
app.init_resource::<PlacementState>();
app.add_message::<VoxelPlaced>();
}
}
#[cfg(feature = "items")]
pub struct PlacementInputPlugin<V: VoxelType> {
_m: std::marker::PhantomData<V>,
}
#[cfg(feature = "items")]
impl<V: VoxelType> PlacementInputPlugin<V> {
pub fn new() -> Self {
Self {
_m: std::marker::PhantomData,
}
}
}
#[cfg(feature = "items")]
impl<V: VoxelType> Default for PlacementInputPlugin<V> {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "items")]
impl<V: VoxelType> Plugin for PlacementInputPlugin<V> {
fn build(&self, app: &mut App) {
app.add_systems(Update, placement_input_system::<V>);
}
}
#[cfg(feature = "items")]
pub fn placement_input_system<V: VoxelType>(
buttons: Res<ButtonInput<MouseButton>>,
camera_q: Query<&GlobalTransform, With<Camera3d>>,
manager: Res<ChunkManager>,
mut chunks: Query<&mut crate::chunk::Chunk<V>>,
mut state: ResMut<PlacementState>,
config: Res<PlacementConfig>,
hotbar: Res<crate::items::hotbar::HotbarState>,
mut placed: MessageWriter<VoxelPlaced>,
mut modified: MessageWriter<ChunkModified>,
time: Res<Time>,
) {
tick_placement(time.delta_secs(), &mut state, &config);
if !buttons.just_pressed(MouseButton::Right) {
return;
}
let Ok(cam_tf) = camera_q.single() else {
return;
};
let origin = cam_tf.translation();
let direction = cam_tf.forward().as_vec3();
let mut lens = chunks.transmute_lens::<&crate::chunk::Chunk<V>>();
let Some(hit) = super::raycast::raycast(origin, direction, 6.0, &manager, &lens.query()) else {
return;
};
let place_world = hit.position + hit.face_normal;
let place_chunk = crate::chunk::world_to_chunk_coord(place_world);
let place_local = crate::chunk::world_to_local_coord(place_world);
let voxel = V::from_byte(hotbar.selected as u8 + 1);
let face_normal = hit.face_normal.as_ivec3();
try_place_voxel(
place_chunk,
place_local,
voxel,
face_normal,
&mut state,
&config,
&manager,
&mut chunks,
&mut placed,
&mut modified,
);
}
#[cfg(test)]
mod tests {
use super::*;
fn default_config() -> PlacementConfig {
PlacementConfig { cooldown: 0.25 }
}
#[test]
fn test_can_place_when_cooldown_expired() {
let config = default_config();
let state = PlacementState {
cooldown_elapsed: 0.25,
};
assert!(state.can_place(&config));
}
#[test]
fn test_cannot_place_when_on_cooldown() {
let config = default_config();
let state = PlacementState {
cooldown_elapsed: 0.10,
};
assert!(!state.can_place(&config));
}
#[test]
fn test_tick_advances_cooldown() {
let config = default_config();
let mut state = PlacementState {
cooldown_elapsed: 0.0,
};
tick_placement(0.10, &mut state, &config);
assert!((state.cooldown_elapsed - 0.10).abs() < f32::EPSILON);
}
#[test]
fn test_tick_clamps_to_cooldown_max() {
let config = default_config();
let mut state = PlacementState {
cooldown_elapsed: 0.20,
};
tick_placement(0.20, &mut state, &config);
assert_eq!(state.cooldown_elapsed, config.cooldown);
}
use crate::chunk::CHUNK_SIZE;
use crate::test_support::world_with_chunks;
use crate::voxel::DefaultVoxel;
use bevy::ecs::message::Messages;
use bevy::ecs::system::SystemState;
use bevy::ecs::world::World;
fn placement_world(chunk: Chunk<DefaultVoxel>) -> World {
let mut world = world_with_chunks([(IVec3::ZERO, chunk)]);
world.init_resource::<Messages<VoxelPlaced>>();
world.init_resource::<Messages<ChunkModified>>();
world
}
fn ready_state() -> PlacementState {
PlacementState {
cooldown_elapsed: default_config().cooldown,
}
}
fn place(
world: &mut World,
state: &mut PlacementState,
chunk: IVec3,
local: (usize, usize, usize),
normal: IVec3,
) -> bool {
let mut system_state: SystemState<(
Res<ChunkManager>,
Query<&mut Chunk<DefaultVoxel>>,
MessageWriter<VoxelPlaced>,
MessageWriter<ChunkModified>,
)> = SystemState::new(world);
let (manager, mut chunks, mut placed, mut modified) = system_state.get_mut(world);
let ok = try_place_voxel(
chunk,
local,
DefaultVoxel::Rock,
normal,
state,
&default_config(),
&manager,
&mut chunks,
&mut placed,
&mut modified,
);
system_state.apply(world);
ok
}
fn chunk_at_origin(world: &World) -> &Chunk<DefaultVoxel> {
let entity = world
.resource::<ChunkManager>()
.get_entity(IVec3::ZERO)
.unwrap();
world.entity(entity).get::<Chunk<DefaultVoxel>>().unwrap()
}
fn modified_coords(world: &World) -> Vec<IVec3> {
world
.resource::<Messages<ChunkModified>>()
.iter_current_update_messages()
.map(|m| m.0)
.collect()
}
#[test]
fn places_voxel_records_face_state_and_emits_messages() {
let mut world = placement_world(Chunk::new());
let mut state = ready_state();
assert!(place(
&mut world,
&mut state,
IVec3::ZERO,
(8, 8, 8),
IVec3::Y
));
let chunk = chunk_at_origin(&world);
assert_eq!(chunk.get(8, 8, 8), DefaultVoxel::Rock);
assert_eq!(
chunk.get_state(8, 8, 8),
crate::chunk::face_to_state(IVec3::Y)
);
assert_eq!(
state.cooldown_elapsed, 0.0,
"a placement restarts the cooldown"
);
let placed: Vec<_> = world
.resource::<Messages<VoxelPlaced>>()
.iter_current_update_messages()
.cloned()
.collect();
assert_eq!(placed.len(), 1);
assert_eq!(placed[0].local, (8, 8, 8));
assert_eq!(placed[0].world_pos, Vec3::splat(8.5));
assert_eq!(placed[0].face_normal, IVec3::Y);
assert_eq!(modified_coords(&world), vec![IVec3::ZERO]);
}
#[test]
fn every_face_normal_maps_to_a_distinct_state() {
let normals = [
IVec3::X,
IVec3::NEG_X,
IVec3::Y,
IVec3::NEG_Y,
IVec3::Z,
IVec3::NEG_Z,
];
let mut world = placement_world(Chunk::new());
let mut states = Vec::new();
for (i, normal) in normals.into_iter().enumerate() {
let mut state = ready_state();
assert!(place(
&mut world,
&mut state,
IVec3::ZERO,
(i, 0, 0),
normal
));
states.push(chunk_at_origin(&world).get_state(i, 0, 0));
}
states.sort_unstable();
states.dedup();
assert_eq!(states.len(), 6, "each face needs its own orientation state");
}
#[test]
fn rejects_occupied_cell_without_side_effects() {
let mut chunk = Chunk::new();
chunk.set(1, 1, 1, DefaultVoxel::IronOre);
let mut world = placement_world(chunk);
let mut state = ready_state();
assert!(!place(
&mut world,
&mut state,
IVec3::ZERO,
(1, 1, 1),
IVec3::Y
));
assert_eq!(chunk_at_origin(&world).get(1, 1, 1), DefaultVoxel::IronOre);
assert_eq!(state.cooldown_elapsed, default_config().cooldown);
assert!(modified_coords(&world).is_empty());
}
#[test]
fn rejects_unloaded_chunk_and_active_cooldown() {
let mut world = placement_world(Chunk::new());
let mut state = ready_state();
assert!(!place(
&mut world,
&mut state,
IVec3::new(5, 0, 0),
(0, 0, 0),
IVec3::Y
));
let mut cooling = PlacementState {
cooldown_elapsed: 0.0,
};
assert!(!place(
&mut world,
&mut cooling,
IVec3::ZERO,
(0, 0, 0),
IVec3::Y
));
assert_eq!(chunk_at_origin(&world).get(0, 0, 0), DefaultVoxel::Air);
assert!(modified_coords(&world).is_empty());
}
#[test]
fn border_placement_marks_touching_neighbors_dirty() {
let mut world = placement_world(Chunk::new());
let max = CHUNK_SIZE - 1;
let mut state = ready_state();
assert!(place(
&mut world,
&mut state,
IVec3::ZERO,
(0, max, 0),
IVec3::Y
));
let mut coords = modified_coords(&world);
coords.sort_by_key(|c| (c.x, c.y, c.z));
assert_eq!(
coords,
vec![
IVec3::new(-1, 0, 0),
IVec3::new(0, 0, -1),
IVec3::ZERO,
IVec3::new(0, 1, 0),
]
);
}
}