voxel_framework/world/placement.rs
1//! Voxel placement (block-placing) API.
2//!
3//! # Design — pure functions, no implicit systems
4//!
5//! This module mirrors the mining module's architecture: all placement logic
6//! lives in free functions so game code retains full scheduling control.
7//! [`PlacementPlugin`] only registers the required resources and message
8//! types; it adds **no** systems of its own.
9//!
10//! # Integration pattern
11//!
12//! ```no_run
13//! # use bevy::prelude::*;
14//! # use voxel_framework::world::placement::{
15//! # PlacementPlugin, PlacementConfig, PlacementState, VoxelPlaced,
16//! # try_place_voxel, tick_placement,
17//! # };
18//! # use voxel_framework::world::{ChunkManager, ChunkModified};
19//! # use voxel_framework::chunk::Chunk;
20//! # use voxel_framework::voxel::DefaultVoxel;
21//! // 1. Add the plugin once when building the App.
22//! // App::new().add_plugins(PlacementPlugin);
23//!
24//! // 2. In your input system, call tick_placement every frame and
25//! // try_place_voxel once per button press.
26//! fn my_placement_system(
27//! mut state: ResMut<PlacementState>,
28//! config: Res<PlacementConfig>,
29//! manager: Res<ChunkManager>,
30//! mut chunks: Query<&mut Chunk<DefaultVoxel>>,
31//! mut placed: MessageWriter<VoxelPlaced>,
32//! mut modified: MessageWriter<ChunkModified>,
33//! time: Res<Time>,
34//! ) {
35//! tick_placement(time.delta_secs(), &mut state, &config);
36//!
37//! let place_pressed = true; // replace with real input
38//! if place_pressed {
39//! try_place_voxel(
40//! IVec3::ZERO, (8, 8, 8), DefaultVoxel::Rock,
41//! IVec3::Y, // face the block was placed against
42//! &mut state, &config, &manager,
43//! &mut chunks, &mut placed, &mut modified,
44//! );
45//! }
46//! }
47//! ```
48
49use bevy::prelude::*;
50
51use crate::chunk::Chunk;
52use crate::voxel::VoxelType;
53
54use super::{ChunkManager, ChunkModified};
55
56// ─── Resources ───────────────────────────────────────────────────────────────
57
58/// Configuration for the block placement system.
59///
60/// Insert this resource before adding [`PlacementPlugin`], or mutate it at
61/// runtime to change placement speed.
62#[derive(Resource, Debug, Clone)]
63pub struct PlacementConfig {
64 /// Minimum time in seconds that must elapse between two successive placements.
65 ///
66 /// Prevents click-spam from placing blocks faster than intended.
67 /// **Default: `0.25` seconds.**
68 pub cooldown: f32,
69}
70
71impl Default for PlacementConfig {
72 fn default() -> Self {
73 Self { cooldown: 0.25 }
74 }
75}
76
77/// Runtime state for the placement cooldown timer.
78///
79/// Initialised to `cooldown_elapsed = 0.0` (on cooldown) so the player
80/// cannot place a block the instant the game starts. Call
81/// [`tick_placement`] every frame to advance the timer.
82#[derive(Resource, Default, Debug)]
83pub struct PlacementState {
84 /// Seconds elapsed since the last successful placement.
85 ///
86 /// Capped at `config.cooldown`; placement is allowed when this value
87 /// equals or exceeds that threshold.
88 pub cooldown_elapsed: f32,
89}
90
91impl PlacementState {
92 /// Returns true if placement is currently allowed (cooldown expired).
93 pub fn can_place(&self, config: &PlacementConfig) -> bool {
94 self.cooldown_elapsed >= config.cooldown
95 }
96}
97
98// ─── Messages ────────────────────────────────────────────────────────────────
99
100/// Message fired once when a voxel is successfully placed.
101///
102/// Emitted by [`try_place_voxel`] on the same frame the voxel is written.
103/// Systems that react to new blocks (e.g. sound effects, achievement tracking)
104/// should read this message.
105#[derive(Message, Debug, Clone)]
106pub struct VoxelPlaced {
107 /// Chunk-grid coordinate of the chunk that received the new voxel.
108 pub chunk_coord: IVec3,
109 /// Local voxel index `(x, y, z)` within the chunk. Each component is in
110 /// `[0, CHUNK_SIZE)`.
111 pub local: (usize, usize, usize),
112 /// World-space center of the newly placed voxel.
113 pub world_pos: Vec3,
114 /// Integer face normal of the surface the block was placed against.
115 ///
116 /// Each component is `−1`, `0`, or `1`. Use [`crate::chunk::face_to_state`]
117 /// to convert this to a compact 3-bit state value.
118 pub face_normal: IVec3,
119}
120
121// ─── Free functions ───────────────────────────────────────────────────────────
122
123/// Sends [`ChunkModified`] for neighboring chunks that share the border of
124/// the voxel at `local` within `chunk_coord`.
125///
126/// Placement and mining on a chunk border also affects the adjacent chunk's
127/// mesh — its border faces need to be re-evaluated with the updated data.
128fn notify_border_neighbors(
129 chunk_coord: IVec3,
130 local: (usize, usize, usize),
131 modified: &mut MessageWriter<ChunkModified>,
132) {
133 use crate::chunk::CHUNK_SIZE;
134 let (x, y, z) = local;
135 let offsets: [(usize, IVec3); 6] = [
136 (x, IVec3::NEG_X),
137 (CHUNK_SIZE - 1 - x, IVec3::X),
138 (y, IVec3::NEG_Y),
139 (CHUNK_SIZE - 1 - y, IVec3::Y),
140 (z, IVec3::NEG_Z),
141 (CHUNK_SIZE - 1 - z, IVec3::Z),
142 ];
143 for (dist, dir) in offsets {
144 if dist == 0 {
145 modified.write(ChunkModified(chunk_coord + dir));
146 }
147 }
148}
149
150/// Compute the world-space center of a voxel given its chunk coord and local index.
151fn voxel_world_pos(chunk_coord: IVec3, local: (usize, usize, usize)) -> Vec3 {
152 let chunk_origin = chunk_coord.as_vec3() * crate::chunk::CHUNK_SIZE as f32;
153 chunk_origin
154 + Vec3::new(
155 local.0 as f32 + 0.5,
156 local.1 as f32 + 0.5,
157 local.2 as f32 + 0.5,
158 )
159}
160
161/// Attempt to place a voxel at the given chunk-local position.
162///
163/// Call this **once** on the frame the place button is pressed — not every
164/// frame.
165///
166/// The function returns `false` (and does nothing) in two cases:
167///
168/// 1. **Cooldown active** — `state.cooldown_elapsed < config.cooldown`. Call
169/// [`tick_placement`] every frame so the timer advances.
170/// 2. **Target already solid** — the destination voxel is not air; placement
171/// into occupied cells is not allowed.
172///
173/// On success the function:
174///
175/// 1. Writes `voxel` into the chunk at `(target_local.0, target_local.1,
176/// target_local.2)`.
177/// 2. Resets `state.cooldown_elapsed` to `0.0`.
178/// 3. Writes a [`VoxelPlaced`] message.
179/// 4. Writes a [`crate::world::ChunkModified`] message to trigger remeshing.
180///
181/// # Parameters
182///
183/// - `target_chunk` — Chunk-grid coordinate of the destination chunk.
184/// - `target_local` — Local `(x, y, z)` voxel index within the chunk.
185/// - `voxel` — The voxel value to write.
186/// - `state` — Mutable reference to the shared [`PlacementState`] resource.
187/// - `config` — Read-only placement configuration (cooldown).
188/// - `manager` — Chunk registry used to look up the chunk entity.
189/// - `chunks` — Mutable query used to write the new voxel.
190/// - `placed` — Message writer for [`VoxelPlaced`].
191/// - `modified` — Message writer for [`crate::world::ChunkModified`].
192///
193/// # Return value
194///
195/// `true` if the voxel was placed, `false` if placement was rejected.
196///
197/// # Examples
198///
199/// ```no_run
200/// # use bevy::prelude::*;
201/// # use voxel_framework::world::placement::{PlacementConfig, PlacementState, VoxelPlaced, try_place_voxel};
202/// # use voxel_framework::world::{ChunkManager, ChunkModified};
203/// # use voxel_framework::chunk::Chunk;
204/// # use voxel_framework::voxel::DefaultVoxel;
205/// fn on_click(
206/// mut state: ResMut<PlacementState>,
207/// config: Res<PlacementConfig>,
208/// manager: Res<ChunkManager>,
209/// mut chunks: Query<&mut Chunk<DefaultVoxel>>,
210/// mut placed: MessageWriter<VoxelPlaced>,
211/// mut modified: MessageWriter<ChunkModified>,
212/// ) {
213/// let placed_ok = try_place_voxel(
214/// IVec3::ZERO, (8, 8, 8), DefaultVoxel::Rock,
215/// IVec3::Y, // face normal: placed on top surface
216/// &mut state, &config, &manager,
217/// &mut chunks, &mut placed, &mut modified,
218/// );
219/// if !placed_ok {
220/// println!("placement rejected (cooldown or occupied)");
221/// }
222/// }
223/// ```
224#[allow(clippy::too_many_arguments)]
225pub fn try_place_voxel<V: VoxelType>(
226 target_chunk: IVec3,
227 target_local: (usize, usize, usize),
228 voxel: V,
229 face_normal: IVec3,
230 state: &mut PlacementState,
231 config: &PlacementConfig,
232 manager: &ChunkManager,
233 chunks: &mut Query<&mut Chunk<V>>,
234 placed: &mut MessageWriter<VoxelPlaced>,
235 modified: &mut MessageWriter<ChunkModified>,
236) -> bool {
237 if !state.can_place(config) {
238 return false;
239 }
240
241 let Some(entity) = manager.get_entity(target_chunk) else {
242 return false;
243 };
244
245 let Ok(mut chunk) = chunks.get_mut(entity) else {
246 return false;
247 };
248
249 let (x, y, z) = target_local;
250
251 // Only place into empty (non-solid) voxels.
252 if chunk.get(x, y, z).is_solid() {
253 return false;
254 }
255
256 chunk.set(x, y, z, voxel);
257 chunk.set_state(x, y, z, crate::chunk::face_to_state(face_normal));
258 state.cooldown_elapsed = 0.0;
259
260 let world_pos = voxel_world_pos(target_chunk, target_local);
261
262 placed.write(VoxelPlaced {
263 chunk_coord: target_chunk,
264 local: target_local,
265 world_pos,
266 face_normal,
267 });
268
269 modified.write(ChunkModified(target_chunk));
270 notify_border_neighbors(target_chunk, target_local, modified);
271
272 true
273}
274
275/// Advance the placement cooldown timer by `delta_secs`.
276///
277/// Call this **every frame** unconditionally (regardless of whether the player
278/// is pressing the place button) so the cooldown always counts down. The
279/// elapsed value is capped at `config.cooldown` to prevent unbounded growth.
280///
281/// # Examples
282///
283/// ```no_run
284/// # use bevy::prelude::*;
285/// # use voxel_framework::world::placement::{PlacementConfig, PlacementState, tick_placement};
286/// fn every_frame(
287/// mut state: ResMut<PlacementState>,
288/// config: Res<PlacementConfig>,
289/// time: Res<Time>,
290/// ) {
291/// tick_placement(time.delta_secs(), &mut state, &config);
292/// }
293/// ```
294pub fn tick_placement(delta_secs: f32, state: &mut PlacementState, config: &PlacementConfig) {
295 state.cooldown_elapsed = (state.cooldown_elapsed + delta_secs).min(config.cooldown);
296}
297
298// ─── Plugin ───────────────────────────────────────────────────────────────────
299
300/// Bevy plugin that registers the placement subsystem.
301///
302/// Adds the following to the [`bevy::prelude::App`]:
303///
304/// - [`PlacementConfig`] resource (initialised with defaults — `cooldown: 0.25 s`)
305/// - [`PlacementState`] resource (initialised at default / on cooldown)
306/// - [`VoxelPlaced`] message type
307///
308/// Does **not** add any systems. Game code is responsible for calling
309/// [`try_place_voxel`] and [`tick_placement`] from its own update systems.
310pub struct PlacementPlugin;
311
312impl Plugin for PlacementPlugin {
313 fn build(&self, app: &mut App) {
314 app.init_resource::<PlacementConfig>();
315 app.init_resource::<PlacementState>();
316 app.add_message::<VoxelPlaced>();
317 }
318}
319
320// ─── PlacementInputPlugin ─────────────────────────────────────────────────────
321
322/// Convenience plugin that wires mouse input to the placement API automatically.
323///
324/// `PlacementInputPlugin<V>` adds a single [`Update`] system that:
325///
326/// 1. Advances the placement cooldown timer every frame via [`tick_placement`].
327/// 2. Raycasts from the active [`Camera3d`] (max `6.0` world units) on a
328/// **right mouse button** press.
329/// 3. Calls [`try_place_voxel`] with the block type derived from the active
330/// [`crate::items::HotbarState`] slot: `V::from_byte(selected + 1)`.
331/// (Slot 0 → byte 1, slot 1 → byte 2, …)
332///
333/// # Prerequisites
334///
335/// [`PlacementPlugin`] must be added **before** this plugin so that the
336/// required resources ([`PlacementState`], [`PlacementConfig`]) and message
337/// channels ([`VoxelPlaced`]) are already registered.
338///
339/// [`crate::items::HotbarPlugin`] must also be added for hotbar slot selection.
340///
341/// # Example
342///
343/// ```no_run
344/// use bevy::prelude::*;
345/// use voxel_framework::{VoxelPlugin, generator::{GeneratorPlugin, GeneratorResource}};
346/// use voxel_framework::world::placement::PlacementInputPlugin;
347/// use voxel_framework::voxel::DefaultTerrainVoxel;
348///
349/// App::new()
350/// .add_plugins(DefaultPlugins)
351/// .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
352/// .add_plugins(PlacementInputPlugin::<DefaultTerrainVoxel>::new())
353/// .run();
354/// ```
355#[cfg(feature = "items")]
356pub struct PlacementInputPlugin<V: VoxelType> {
357 _m: std::marker::PhantomData<V>,
358}
359
360#[cfg(feature = "items")]
361impl<V: VoxelType> PlacementInputPlugin<V> {
362 /// Creates a new [`PlacementInputPlugin`] for voxel type `V`.
363 pub fn new() -> Self {
364 Self {
365 _m: std::marker::PhantomData,
366 }
367 }
368}
369
370#[cfg(feature = "items")]
371impl<V: VoxelType> Default for PlacementInputPlugin<V> {
372 fn default() -> Self {
373 Self::new()
374 }
375}
376
377#[cfg(feature = "items")]
378impl<V: VoxelType> Plugin for PlacementInputPlugin<V> {
379 fn build(&self, app: &mut App) {
380 app.add_systems(Update, placement_input_system::<V>);
381 }
382}
383
384/// System added by [`PlacementInputPlugin`].
385///
386/// Ticks the cooldown every frame, then raycasts and places on right-click.
387/// Added automatically — do not add this system manually when using
388/// [`PlacementInputPlugin`].
389#[cfg(feature = "items")]
390pub fn placement_input_system<V: VoxelType>(
391 buttons: Res<ButtonInput<MouseButton>>,
392 camera_q: Query<&GlobalTransform, With<Camera3d>>,
393 manager: Res<ChunkManager>,
394 mut chunks: Query<&mut crate::chunk::Chunk<V>>,
395 mut state: ResMut<PlacementState>,
396 config: Res<PlacementConfig>,
397 hotbar: Res<crate::items::hotbar::HotbarState>,
398 mut placed: MessageWriter<VoxelPlaced>,
399 mut modified: MessageWriter<ChunkModified>,
400 time: Res<Time>,
401) {
402 tick_placement(time.delta_secs(), &mut state, &config);
403
404 if !buttons.just_pressed(MouseButton::Right) {
405 return;
406 }
407
408 let Ok(cam_tf) = camera_q.single() else {
409 return;
410 };
411
412 let origin = cam_tf.translation();
413 let direction = cam_tf.forward().as_vec3();
414
415 // `transmute_lens` gives a read-only view without a second conflicting query.
416 let mut lens = chunks.transmute_lens::<&crate::chunk::Chunk<V>>();
417 let Some(hit) = super::raycast::raycast(origin, direction, 6.0, &manager, &lens.query()) else {
418 return;
419 };
420
421 // Place one step back along the face normal (adjacent air voxel).
422 let place_world = hit.position + hit.face_normal;
423 let place_chunk = crate::chunk::world_to_chunk_coord(place_world);
424 let place_local = crate::chunk::world_to_local_coord(place_world);
425
426 // Map hotbar slot to voxel type: slot 0 → byte 1, slot 1 → byte 2, etc.
427 let voxel = V::from_byte(hotbar.selected as u8 + 1);
428 let face_normal = hit.face_normal.as_ivec3();
429
430 try_place_voxel(
431 place_chunk,
432 place_local,
433 voxel,
434 face_normal,
435 &mut state,
436 &config,
437 &manager,
438 &mut chunks,
439 &mut placed,
440 &mut modified,
441 );
442}
443
444// ─── Tests ────────────────────────────────────────────────────────────────────
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449
450 fn default_config() -> PlacementConfig {
451 PlacementConfig { cooldown: 0.25 }
452 }
453
454 // ── can_place ─────────────────────────────────────────────────────────────
455
456 #[test]
457 fn test_can_place_when_cooldown_expired() {
458 let config = default_config();
459 let state = PlacementState {
460 cooldown_elapsed: 0.25,
461 };
462 assert!(state.can_place(&config));
463 }
464
465 #[test]
466 fn test_cannot_place_when_on_cooldown() {
467 let config = default_config();
468 let state = PlacementState {
469 cooldown_elapsed: 0.10,
470 };
471 assert!(!state.can_place(&config));
472 }
473
474 // ── tick_placement ────────────────────────────────────────────────────────
475
476 #[test]
477 fn test_tick_advances_cooldown() {
478 let config = default_config();
479 let mut state = PlacementState {
480 cooldown_elapsed: 0.0,
481 };
482 tick_placement(0.10, &mut state, &config);
483 assert!((state.cooldown_elapsed - 0.10).abs() < f32::EPSILON);
484 }
485
486 #[test]
487 fn test_tick_clamps_to_cooldown_max() {
488 let config = default_config();
489 let mut state = PlacementState {
490 cooldown_elapsed: 0.20,
491 };
492 // Adding 0.20 would give 0.40, but max is 0.25.
493 tick_placement(0.20, &mut state, &config);
494 assert_eq!(state.cooldown_elapsed, config.cooldown);
495 }
496}