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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Fixed scene lighting: a sun, a fill light and the global ambient light.

use bevy::ecs::query::QueryFilter;
use bevy::light::GlobalAmbientLight;
use bevy::prelude::*;

use super::LightingSystems;

// ─── Config ───────────────────────────────────────────────────────────────────

/// A fixed directional sun for [`SceneLightingConfig::sun`].
///
/// The default mirrors Bevy's `DirectionalLight::default()` (white,
/// 10 000 lux, no shadows) shining straight down.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SunConfig {
    /// Light color. **Default: `Color::WHITE`.**
    pub color: Color,
    /// Illuminance in lux. **Default: `10_000.0`.**
    pub illuminance: f32,
    /// Direction the light travels, in world space. It does not need to be
    /// normalized. A zero or non-finite vector counts as straight down.
    ///
    /// **Default: `Vec3::NEG_Y`.**
    pub direction: Vec3,
    /// Whether the sun casts shadows. **Default: `false`.**
    pub shadows_enabled: bool,
}

impl Default for SunConfig {
    fn default() -> Self {
        Self {
            color: Color::WHITE,
            illuminance: 10_000.0,
            direction: Vec3::NEG_Y,
            shadows_enabled: false,
        }
    }
}

/// A shadowless directional fill light for [`SceneLightingConfig::fill`].
///
/// A fill light brightens the faces the sun does not reach. It never casts
/// shadows.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FillLightConfig {
    /// Light color. **Default: `Color::WHITE`.**
    pub color: Color,
    /// Illuminance in lux. **Default: `1_000.0`.**
    pub illuminance: f32,
    /// Direction the light travels, in world space. `None` (or a zero or
    /// non-finite vector) means the opposite of the sun's direction, or
    /// straight up when [`SceneLightingConfig::sun`] is `None`.
    ///
    /// **Default: `None`.**
    pub direction: Option<Vec3>,
}

impl Default for FillLightConfig {
    fn default() -> Self {
        Self {
            color: Color::WHITE,
            illuminance: 1_000.0,
            direction: None,
        }
    }
}

/// Global ambient light values for [`SceneLightingConfig::ambient`].
///
/// The default mirrors Bevy's `GlobalAmbientLight::default()`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AmbientConfig {
    /// Ambient color. **Default: `Color::WHITE`.**
    pub color: Color,
    /// Ambient brightness. **Default: `80.0`.**
    pub brightness: f32,
}

impl Default for AmbientConfig {
    fn default() -> Self {
        Self {
            color: Color::WHITE,
            brightness: 80.0,
        }
    }
}

/// What [`SceneLightingPlugin`] keeps in the scene.
///
/// Every part is optional and the default is all `None`: the plugin then
/// creates nothing and leaves the global ambient light alone. Insert the
/// resource before or after adding the plugin, and change it at any time; the
/// lights follow on the next frame the plugin's system runs.
///
/// Setting a part back to `None` despawns its light. Setting `ambient` back to
/// `None` stops writing the ambient light but does not restore an earlier
/// value.
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::lighting::{FillLightConfig, SceneLightingConfig, SunConfig};
///
/// let config = SceneLightingConfig {
///     sun: Some(SunConfig {
///         direction: Vec3::new(1.0, -1.0, 0.0),
///         ..default()
///     }),
///     fill: Some(FillLightConfig {
///         color: Color::srgb(0.6, 0.7, 1.0),
///         illuminance: 400.0,
///         direction: None,
///     }),
///     ambient: None,
/// };
/// // With no explicit direction the fill light opposes the sun.
/// let fill = config.fill_direction().unwrap();
/// assert!(fill.x < 0.0 && fill.y > 0.0);
/// ```
#[derive(Resource, Debug, Clone, Copy, PartialEq, Default)]
pub struct SceneLightingConfig {
    /// The fixed sun, tagged [`SceneSunLight`]. **Default: `None`.**
    pub sun: Option<SunConfig>,
    /// The fill light, tagged [`SceneFillLight`]. **Default: `None`.**
    pub fill: Option<FillLightConfig>,
    /// Values written to Bevy's `GlobalAmbientLight` resource. `None` leaves
    /// the resource untouched. **Default: `None`.**
    pub ambient: Option<AmbientConfig>,
}

impl SceneLightingConfig {
    /// Normalized direction the sun travels, or `None` without a sun.
    pub fn sun_direction(&self) -> Option<Vec3> {
        self.sun.map(|sun| normalize_or_down(sun.direction))
    }

    /// Normalized direction the fill light travels, or `None` without a fill
    /// light.
    ///
    /// An explicit valid [`FillLightConfig::direction`] wins. Otherwise it is
    /// the opposite of the sun's direction, or straight up without a sun.
    pub fn fill_direction(&self) -> Option<Vec3> {
        let fill = self.fill?;
        let explicit = fill.direction.and_then(Vec3::try_normalize);
        Some(explicit.unwrap_or_else(|| -self.sun_direction().unwrap_or(Vec3::NEG_Y)))
    }
}

fn normalize_or_down(direction: Vec3) -> Vec3 {
    direction.try_normalize().unwrap_or(Vec3::NEG_Y)
}

/// Rotation that makes a light shine along `direction`.
///
/// Bevy's directional and spot lights shine along their local `-Z` axis. A
/// zero or non-finite `direction` counts as straight down.
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::lighting::light_rotation;
///
/// let rotation = light_rotation(Vec3::new(0.0, -2.0, 0.0));
/// assert!((rotation * Vec3::NEG_Z).abs_diff_eq(Vec3::NEG_Y, 1e-5));
/// ```
pub fn light_rotation(direction: Vec3) -> Quat {
    Quat::from_rotation_arc(Vec3::NEG_Z, normalize_or_down(direction))
}

// ─── Markers ──────────────────────────────────────────────────────────────────

/// Marker on the directional light created from [`SceneLightingConfig::sun`].
///
/// It is a different component from the day cycle's
/// [`SunLight`](crate::world::SunLight), so the two plugins do not edit each
/// other's lights.
#[derive(Component, Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct SceneSunLight;

/// Marker on the directional light created from [`SceneLightingConfig::fill`].
#[derive(Component, Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct SceneFillLight;

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

/// Values one managed directional light should have.
#[derive(Clone, Copy)]
struct DirectionalSpec {
    color: Color,
    illuminance: f32,
    shadows_enabled: bool,
    rotation: Quat,
}

/// Makes the lights matched by `query` equal to `desired`: updates the first
/// one, despawns extras, spawns one tagged `marker` when none exists, and
/// despawns all of them when `desired` is `None`.
fn sync_directional<M: Component, F: QueryFilter>(
    commands: &mut Commands,
    query: &mut Query<(Entity, &mut DirectionalLight, &mut Transform), F>,
    marker: M,
    desired: Option<DirectionalSpec>,
) {
    let mut kept = false;
    for (entity, mut light, mut transform) in query.iter_mut() {
        match desired {
            Some(spec) if !kept => {
                kept = true;
                light.color = spec.color;
                light.illuminance = spec.illuminance;
                light.shadows_enabled = spec.shadows_enabled;
                transform.rotation = spec.rotation;
            }
            _ => commands.entity(entity).try_despawn(),
        }
    }
    if let (false, Some(spec)) = (kept, desired) {
        commands.spawn((
            marker,
            DirectionalLight {
                color: spec.color,
                illuminance: spec.illuminance,
                shadows_enabled: spec.shadows_enabled,
                ..default()
            },
            Transform::from_rotation(spec.rotation),
        ));
    }
}

type SunQuery<'w, 's> = Query<
    'w,
    's,
    (
        Entity,
        &'static mut DirectionalLight,
        &'static mut Transform,
    ),
    (With<SceneSunLight>, Without<SceneFillLight>),
>;
type FillQuery<'w, 's> = Query<
    'w,
    's,
    (
        Entity,
        &'static mut DirectionalLight,
        &'static mut Transform,
    ),
    (With<SceneFillLight>, Without<SceneSunLight>),
>;

fn sync_scene_lighting(
    mut commands: Commands,
    config: Res<SceneLightingConfig>,
    mut suns: SunQuery,
    mut fills: FillQuery,
    ambient: Option<ResMut<GlobalAmbientLight>>,
) {
    if !config.is_changed() {
        return;
    }

    let sun = config.sun.map(|sun| DirectionalSpec {
        color: sun.color,
        illuminance: sun.illuminance,
        shadows_enabled: sun.shadows_enabled,
        rotation: light_rotation(sun.direction),
    });
    sync_directional(&mut commands, &mut suns, SceneSunLight, sun);

    let fill = config
        .fill
        .zip(config.fill_direction())
        .map(|(fill, direction)| DirectionalSpec {
            color: fill.color,
            illuminance: fill.illuminance,
            shadows_enabled: false,
            rotation: light_rotation(direction),
        });
    sync_directional(&mut commands, &mut fills, SceneFillLight, fill);

    if let Some(values) = config.ambient {
        match ambient {
            Some(mut ambient) => {
                ambient.color = values.color;
                ambient.brightness = values.brightness;
            }
            None => commands.insert_resource(GlobalAmbientLight {
                color: values.color,
                brightness: values.brightness,
                ..default()
            }),
        }
    }
}

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

/// Default Implementation plugin that keeps a fixed sun, a fill light and the
/// global ambient light in sync with [`SceneLightingConfig`].
///
/// It is explicit: no bundle adds it. With the default config (all `None`) it
/// creates nothing, so adding it does not change a scene until the game sets
/// a part of the config. The system runs in `Update`, in
/// [`LightingSystems::Scene`], and only does work when the resource changed.
///
/// The sun is an entity tagged [`SceneSunLight`] and the fill light one tagged
/// [`SceneFillLight`]. The plugin writes their color, illuminance, shadow flag
/// and rotation; other fields (for example shadow bias) keep whatever the game
/// set on the entity.
///
/// ```no_run
/// use bevy::prelude::*;
/// use voxel_framework::lighting::{
///     AmbientConfig, FillLightConfig, SceneLightingConfig, SceneLightingPlugin, SunConfig,
/// };
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .insert_resource(SceneLightingConfig {
///         sun: Some(SunConfig {
///             illuminance: 15_000.0,
///             direction: Vec3::new(-1.0, -2.0, -1.0),
///             shadows_enabled: true,
///             ..default()
///         }),
///         fill: Some(FillLightConfig {
///             color: Color::srgb(0.5, 0.6, 1.0),
///             illuminance: 300.0,
///             direction: None,
///         }),
///         ambient: Some(AmbientConfig {
///             brightness: 40.0,
///             ..default()
///         }),
///     })
///     .add_plugins(SceneLightingPlugin)
///     .run();
/// ```
pub struct SceneLightingPlugin;

impl Plugin for SceneLightingPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<SceneLightingConfig>();
        app.add_systems(Update, sync_scene_lighting.in_set(LightingSystems::Scene));
    }
}

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

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

    fn app_with(config: SceneLightingConfig) -> App {
        let mut app = App::new();
        app.insert_resource(config);
        app.add_plugins(SceneLightingPlugin);
        app
    }

    fn suns(app: &mut App) -> Vec<(DirectionalLight, Transform)> {
        let mut query = app
            .world_mut()
            .query_filtered::<(&DirectionalLight, &Transform), With<SceneSunLight>>();
        query
            .iter(app.world())
            .map(|(light, transform)| (*light, *transform))
            .collect()
    }

    fn fills(app: &mut App) -> Vec<(DirectionalLight, Transform)> {
        let mut query = app
            .world_mut()
            .query_filtered::<(&DirectionalLight, &Transform), With<SceneFillLight>>();
        query
            .iter(app.world())
            .map(|(light, transform)| (*light, *transform))
            .collect()
    }

    #[test]
    fn default_config_is_empty() {
        let config = SceneLightingConfig::default();
        assert_eq!(config.sun, None);
        assert_eq!(config.fill, None);
        assert_eq!(config.ambient, None);
        assert_eq!(config.sun_direction(), None);
        assert_eq!(config.fill_direction(), None);
    }

    #[test]
    fn rotation_points_local_forward_along_direction() {
        for direction in [
            Vec3::NEG_Y,
            Vec3::Y,
            Vec3::X,
            Vec3::Z,
            Vec3::NEG_Z,
            Vec3::new(-0.4, -1.0, 0.3),
        ] {
            let forward = light_rotation(direction * 3.0) * Vec3::NEG_Z;
            assert!(
                forward.abs_diff_eq(direction.normalize(), 1e-5),
                "{direction}: {forward}"
            );
        }
    }

    #[test]
    fn invalid_direction_points_down() {
        for direction in [
            Vec3::ZERO,
            Vec3::splat(f32::NAN),
            Vec3::splat(f32::INFINITY),
        ] {
            let forward = light_rotation(direction) * Vec3::NEG_Z;
            assert!(forward.abs_diff_eq(Vec3::NEG_Y, 1e-5), "{direction}");
        }
    }

    #[test]
    fn fill_opposes_the_sun_unless_given_a_direction() {
        let mut config = SceneLightingConfig {
            sun: Some(SunConfig {
                direction: Vec3::new(0.0, -5.0, 0.0),
                ..default()
            }),
            fill: Some(FillLightConfig::default()),
            ambient: None,
        };
        assert!(config.fill_direction().unwrap().abs_diff_eq(Vec3::Y, 1e-6));

        config.fill = Some(FillLightConfig {
            direction: Some(Vec3::new(2.0, 0.0, 0.0)),
            ..default()
        });
        assert!(config.fill_direction().unwrap().abs_diff_eq(Vec3::X, 1e-6));

        // An unusable explicit direction falls back to opposing the sun.
        config.fill = Some(FillLightConfig {
            direction: Some(Vec3::ZERO),
            ..default()
        });
        assert!(config.fill_direction().unwrap().abs_diff_eq(Vec3::Y, 1e-6));

        // Without a sun the fill light shines straight up.
        config.sun = None;
        assert!(config.fill_direction().unwrap().abs_diff_eq(Vec3::Y, 1e-6));
    }

    #[test]
    fn default_config_spawns_nothing_and_leaves_ambient_alone() {
        let mut app = app_with(SceneLightingConfig::default());
        app.insert_resource(GlobalAmbientLight {
            brightness: 123.0,
            ..default()
        });
        app.update();
        app.update();

        assert!(suns(&mut app).is_empty());
        assert!(fills(&mut app).is_empty());
        assert_eq!(
            app.world().resource::<GlobalAmbientLight>().brightness,
            123.0
        );
    }

    #[test]
    fn config_spawns_one_sun_and_one_fill() {
        let mut app = app_with(SceneLightingConfig {
            sun: Some(SunConfig {
                color: Color::srgb(1.0, 0.9, 0.8),
                illuminance: 5_000.0,
                direction: Vec3::NEG_Y,
                shadows_enabled: true,
            }),
            fill: Some(FillLightConfig {
                color: Color::srgb(0.2, 0.3, 0.9),
                illuminance: 250.0,
                direction: None,
            }),
            ambient: None,
        });
        app.update();
        app.update();

        let suns = suns(&mut app);
        assert_eq!(suns.len(), 1);
        let (sun, sun_transform) = suns[0];
        assert_eq!(sun.color, Color::srgb(1.0, 0.9, 0.8));
        assert_eq!(sun.illuminance, 5_000.0);
        assert!(sun.shadows_enabled);
        assert!((sun_transform.rotation * Vec3::NEG_Z).abs_diff_eq(Vec3::NEG_Y, 1e-5));

        let fills = fills(&mut app);
        assert_eq!(fills.len(), 1);
        let (fill, fill_transform) = fills[0];
        assert_eq!(fill.color, Color::srgb(0.2, 0.3, 0.9));
        assert_eq!(fill.illuminance, 250.0);
        assert!(!fill.shadows_enabled);
        assert!((fill_transform.rotation * Vec3::NEG_Z).abs_diff_eq(Vec3::Y, 1e-5));
    }

    #[test]
    fn config_change_updates_the_same_light_and_none_despawns_it() {
        let mut app = app_with(SceneLightingConfig {
            sun: Some(SunConfig::default()),
            fill: Some(FillLightConfig::default()),
            ambient: None,
        });
        app.update();
        let mut query = app
            .world_mut()
            .query_filtered::<Entity, With<SceneSunLight>>();
        let first = query.single(app.world()).expect("one sun");

        app.world_mut()
            .resource_mut::<SceneLightingConfig>()
            .sun
            .as_mut()
            .unwrap()
            .illuminance = 42.0;
        app.update();
        let second = query.single(app.world()).expect("still one sun");
        assert_eq!(first, second);
        assert_eq!(suns(&mut app)[0].0.illuminance, 42.0);

        *app.world_mut().resource_mut::<SceneLightingConfig>() = SceneLightingConfig::default();
        app.update();
        assert!(suns(&mut app).is_empty());
        assert!(fills(&mut app).is_empty());
    }

    #[test]
    fn ambient_is_written_or_inserted() {
        let ambient = AmbientConfig {
            color: Color::srgb(0.1, 0.2, 0.3),
            brightness: 12.0,
        };
        let config = SceneLightingConfig {
            ambient: Some(ambient),
            ..default()
        };

        // Existing resource: overwritten.
        let mut app = app_with(config);
        app.insert_resource(GlobalAmbientLight::default());
        app.update();
        let res = app.world().resource::<GlobalAmbientLight>();
        assert_eq!(res.color, ambient.color);
        assert_eq!(res.brightness, 12.0);

        // Missing resource: inserted.
        let mut app = app_with(config);
        app.update();
        let res = app.world().resource::<GlobalAmbientLight>();
        assert_eq!(res.color, ambient.color);
        assert_eq!(res.brightness, 12.0);
    }

    #[test]
    fn day_cycle_sun_is_not_touched() {
        use crate::world::SunLight;

        let mut app = app_with(SceneLightingConfig {
            sun: Some(SunConfig {
                illuminance: 7.0,
                ..default()
            }),
            ..default()
        });
        let other = app
            .world_mut()
            .spawn((
                SunLight,
                DirectionalLight {
                    illuminance: 999.0,
                    ..default()
                },
            ))
            .id();
        app.update();

        assert_eq!(
            app.world()
                .get::<DirectionalLight>(other)
                .unwrap()
                .illuminance,
            999.0
        );
        assert_eq!(suns(&mut app).len(), 1);
    }
}