voxel-framework 0.13.2

A reusable voxel engine framework built on Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! A spot light carried by an entity the game marks.

use bevy::prelude::*;

use super::LightingSystems;

// ─── Components ───────────────────────────────────────────────────────────────

/// A configurable spot light carried by this entity.
///
/// The framework never discovers players or cameras: the game adds this
/// component to the entity that should carry the light, usually its camera.
/// [`HeadlampPlugin`] then keeps one child entity tagged [`HeadlampLight`]
/// with a Bevy `SpotLight` that mirrors these values. The light shines along
/// the carrier's local `-Z` axis, which is where a camera looks.
///
/// The carrier needs a `Transform` and a `Visibility` so the child inherits
/// its position and visibility; a camera entity already has both.
///
/// Change any field at runtime and the light follows. `enabled` is the
/// on/off switch; [`Headlamp::toggle`] flips it. Removing the component
/// despawns the light.
///
/// The default mirrors Bevy's `SpotLight::default()`, switched on, with no
/// offset.
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::lighting::Headlamp;
///
/// let mut lamp = Headlamp {
///     color: Color::srgb(1.0, 0.95, 0.8),
///     intensity: 200_000.0,
///     range: 40.0,
///     ..default()
/// };
/// assert!(lamp.enabled);
/// assert!(!lamp.toggle());
/// assert!(!lamp.enabled);
/// ```
#[derive(Component, Debug, Clone, Copy, PartialEq)]
pub struct Headlamp {
    /// Whether the light is on. When `false` the spot light stays in the
    /// world but is hidden, so it lights nothing. **Default: `true`.**
    pub enabled: bool,
    /// Light color. **Default: `Color::WHITE`.**
    pub color: Color,
    /// Luminous power in lumens. **Default: `1_000_000.0`.**
    pub intensity: f32,
    /// Distance at which the light stops, in world units. **Default: `20.0`.**
    pub range: f32,
    /// Radius of the light source, for specular highlights. **Default: `0.0`.**
    pub radius: f32,
    /// Angle in radians inside which the light is at full intensity.
    /// **Default: `0.0`.**
    pub inner_angle: f32,
    /// Angle in radians at which the light fades out completely.
    /// **Default: `PI / 4`.**
    pub outer_angle: f32,
    /// Whether the light casts shadows. **Default: `false`.**
    pub shadows_enabled: bool,
    /// Position of the light relative to the carrier, in the carrier's local
    /// space. **Default: `Vec3::ZERO`.**
    pub offset: Vec3,
}

impl Default for Headlamp {
    fn default() -> Self {
        Self {
            enabled: true,
            color: Color::WHITE,
            intensity: 1_000_000.0,
            range: 20.0,
            radius: 0.0,
            inner_angle: 0.0,
            outer_angle: std::f32::consts::FRAC_PI_4,
            shadows_enabled: false,
            offset: Vec3::ZERO,
        }
    }
}

impl Headlamp {
    /// Flips [`Headlamp::enabled`] and returns the new value.
    pub fn toggle(&mut self) -> bool {
        self.enabled = !self.enabled;
        self.enabled
    }

    /// Copies the light values into `light`, leaving its other fields (for
    /// example shadow bias) as they are.
    fn apply(&self, light: &mut SpotLight) {
        light.color = self.color;
        light.intensity = self.intensity;
        light.range = self.range;
        light.radius = self.radius;
        light.inner_angle = self.inner_angle;
        light.outer_angle = self.outer_angle;
        light.shadows_enabled = self.shadows_enabled;
    }

    fn visibility(&self) -> Visibility {
        if self.enabled {
            Visibility::Inherited
        } else {
            Visibility::Hidden
        }
    }
}

/// Marker on the spot light entity that [`HeadlampPlugin`] creates as a child
/// of each [`Headlamp`] carrier.
#[derive(Component, Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct HeadlampLight;

// ─── Systems ──────────────────────────────────────────────────────────────────

/// Despawns the light of every carrier that lost its [`Headlamp`] component.
/// A despawned carrier takes its child with it, so nothing is left to do then.
fn remove_headlamp_lights(
    mut commands: Commands,
    mut removed: RemovedComponents<Headlamp>,
    lights: Query<(Entity, &ChildOf), With<HeadlampLight>>,
) {
    let carriers: Vec<Entity> = removed.read().collect();
    if carriers.is_empty() {
        return;
    }
    for (entity, child_of) in &lights {
        if carriers.contains(&child_of.parent()) {
            commands.entity(entity).try_despawn();
        }
    }
}

/// Creates the light of a new [`Headlamp`] and updates it when the component
/// changes.
fn sync_headlamps(
    mut commands: Commands,
    lamps: Query<(Entity, &Headlamp, Option<&Children>), Changed<Headlamp>>,
    mut lights: Query<(&mut SpotLight, &mut Transform, &mut Visibility), With<HeadlampLight>>,
) {
    for (carrier, lamp, children) in &lamps {
        let existing = children.and_then(|children| {
            let children: &[Entity] = children;
            children
                .iter()
                .copied()
                .find(|child| lights.contains(*child))
        });
        let visibility = lamp.visibility();

        let existing = match existing {
            Some(child) => lights.get_mut(child).ok(),
            None => None,
        };
        match existing {
            Some((mut light, mut transform, mut current)) => {
                lamp.apply(&mut light);
                if transform.translation != lamp.offset {
                    transform.translation = lamp.offset;
                }
                if *current != visibility {
                    *current = visibility;
                }
            }
            None => {
                let mut light = SpotLight::default();
                lamp.apply(&mut light);
                commands.entity(carrier).with_child((
                    HeadlampLight,
                    light,
                    Transform::from_translation(lamp.offset),
                    visibility,
                ));
            }
        }
    }
}

// ─── Plugin ───────────────────────────────────────────────────────────────────

/// Default Implementation plugin that gives every entity with a [`Headlamp`]
/// component a spot light.
///
/// It is explicit: no bundle adds it, and it does nothing until the game adds
/// a [`Headlamp`] to an entity. Its systems run in `Update`, in
/// [`LightingSystems::Headlamp`]. A system that changes a `Headlamp` before
/// that set sees the light change in the same frame; otherwise it changes on
/// the next one.
///
/// The plugin reads no input. The game toggles the light from its own system:
///
/// ```no_run
/// use bevy::prelude::*;
/// use voxel_framework::lighting::{Headlamp, HeadlampPlugin, LightingSystems};
///
/// fn spawn_camera(mut commands: Commands) {
///     commands.spawn((
///         Camera3d::default(),
///         Headlamp {
///             enabled: false,
///             range: 30.0,
///             ..default()
///         },
///     ));
/// }
///
/// fn toggle(keys: Res<ButtonInput<KeyCode>>, mut lamps: Query<&mut Headlamp>) {
///     if keys.just_pressed(KeyCode::KeyF) {
///         for mut lamp in &mut lamps {
///             lamp.toggle();
///         }
///     }
/// }
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugins(HeadlampPlugin)
///     .add_systems(Startup, spawn_camera)
///     .add_systems(Update, toggle.before(LightingSystems::Headlamp))
///     .run();
/// ```
pub struct HeadlampPlugin;

impl Plugin for HeadlampPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(
            Update,
            (remove_headlamp_lights, sync_headlamps)
                .chain()
                .in_set(LightingSystems::Headlamp),
        );
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn app() -> App {
        let mut app = App::new();
        app.add_plugins(HeadlampPlugin);
        app
    }

    fn spawn_carrier(app: &mut App, lamp: Headlamp) -> Entity {
        app.world_mut()
            .spawn((lamp, Transform::default(), Visibility::default()))
            .id()
    }

    /// Light entities whose parent is `carrier`.
    fn lights_of(app: &mut App, carrier: Entity) -> Vec<Entity> {
        let mut query = app
            .world_mut()
            .query_filtered::<(Entity, &ChildOf), With<HeadlampLight>>();
        query
            .iter(app.world())
            .filter(|(_, child_of)| child_of.parent() == carrier)
            .map(|(entity, _)| entity)
            .collect()
    }

    #[test]
    fn default_matches_the_engine_spot_light() {
        let lamp = Headlamp::default();
        let engine = SpotLight::default();
        assert!(lamp.enabled);
        assert_eq!(lamp.color, engine.color);
        assert_eq!(lamp.intensity, engine.intensity);
        assert_eq!(lamp.range, engine.range);
        assert_eq!(lamp.radius, engine.radius);
        assert_eq!(lamp.inner_angle, engine.inner_angle);
        assert_eq!(lamp.outer_angle, engine.outer_angle);
        assert_eq!(lamp.shadows_enabled, engine.shadows_enabled);
        assert_eq!(lamp.offset, Vec3::ZERO);
    }

    #[test]
    fn toggle_flips_enabled_and_returns_it() {
        let mut lamp = Headlamp::default();
        assert!(!lamp.toggle());
        assert!(!lamp.enabled);
        assert!(lamp.toggle());
        assert!(lamp.enabled);
    }

    #[test]
    fn marked_entity_gets_one_child_light_with_its_values() {
        let mut app = app();
        let lamp = Headlamp {
            color: Color::srgb(1.0, 0.5, 0.25),
            intensity: 1234.0,
            range: 33.0,
            radius: 0.5,
            inner_angle: 0.1,
            outer_angle: 0.6,
            shadows_enabled: true,
            offset: Vec3::new(0.0, 0.2, -0.3),
            ..default()
        };
        let carrier = spawn_carrier(&mut app, lamp);
        app.update();
        app.update();

        let lights = lights_of(&mut app, carrier);
        assert_eq!(lights.len(), 1);
        let world = app.world();
        let light = world.get::<SpotLight>(lights[0]).unwrap();
        assert_eq!(light.color, lamp.color);
        assert_eq!(light.intensity, 1234.0);
        assert_eq!(light.range, 33.0);
        assert_eq!(light.radius, 0.5);
        assert_eq!(light.inner_angle, 0.1);
        assert_eq!(light.outer_angle, 0.6);
        assert!(light.shadows_enabled);
        assert_eq!(
            world.get::<Transform>(lights[0]).unwrap().translation,
            lamp.offset
        );
        assert_eq!(
            *world.get::<Visibility>(lights[0]).unwrap(),
            Visibility::Inherited
        );
    }

    #[test]
    fn entities_without_the_component_get_no_light() {
        let mut app = app();
        let plain = app
            .world_mut()
            .spawn((Transform::default(), Visibility::default()))
            .id();
        app.update();
        assert!(lights_of(&mut app, plain).is_empty());
    }

    #[test]
    fn disabling_hides_the_same_light_and_enabling_shows_it() {
        let mut app = app();
        let carrier = spawn_carrier(&mut app, Headlamp::default());
        app.update();
        let light = lights_of(&mut app, carrier)[0];

        app.world_mut()
            .get_mut::<Headlamp>(carrier)
            .unwrap()
            .toggle();
        app.update();
        assert_eq!(lights_of(&mut app, carrier), vec![light]);
        assert_eq!(
            *app.world().get::<Visibility>(light).unwrap(),
            Visibility::Hidden
        );

        app.world_mut()
            .get_mut::<Headlamp>(carrier)
            .unwrap()
            .toggle();
        app.update();
        assert_eq!(
            *app.world().get::<Visibility>(light).unwrap(),
            Visibility::Inherited
        );
    }

    #[test]
    fn a_headlamp_spawned_disabled_starts_hidden() {
        let mut app = app();
        let carrier = spawn_carrier(
            &mut app,
            Headlamp {
                enabled: false,
                ..default()
            },
        );
        app.update();
        let light = lights_of(&mut app, carrier)[0];
        assert_eq!(
            *app.world().get::<Visibility>(light).unwrap(),
            Visibility::Hidden
        );
    }

    #[test]
    fn changed_values_reach_the_existing_light() {
        let mut app = app();
        let carrier = spawn_carrier(&mut app, Headlamp::default());
        app.update();
        let light = lights_of(&mut app, carrier)[0];

        {
            let mut lamp = app.world_mut().get_mut::<Headlamp>(carrier).unwrap();
            lamp.intensity = 5.0;
            lamp.offset = Vec3::X;
        }
        app.update();

        assert_eq!(lights_of(&mut app, carrier), vec![light]);
        assert_eq!(app.world().get::<SpotLight>(light).unwrap().intensity, 5.0);
        assert_eq!(
            app.world().get::<Transform>(light).unwrap().translation,
            Vec3::X
        );
    }

    #[test]
    fn removing_the_component_despawns_the_light() {
        let mut app = app();
        let carrier = spawn_carrier(&mut app, Headlamp::default());
        let other = spawn_carrier(&mut app, Headlamp::default());
        app.update();
        let light = lights_of(&mut app, carrier)[0];

        app.world_mut().entity_mut(carrier).remove::<Headlamp>();
        app.update();

        assert!(app.world().get_entity(light).is_err());
        assert!(lights_of(&mut app, carrier).is_empty());
        assert_eq!(lights_of(&mut app, other).len(), 1);
    }

    #[test]
    fn despawning_the_carrier_despawns_the_light() {
        let mut app = app();
        let carrier = spawn_carrier(&mut app, Headlamp::default());
        app.update();
        let light = lights_of(&mut app, carrier)[0];

        app.world_mut().entity_mut(carrier).despawn();
        app.update();

        assert!(app.world().get_entity(light).is_err());
    }
}