voxel-framework 0.13.1

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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
//! Author-defined static sky: a background color plus layers of figures.
//!
//! [`StaticSkyConfig`] describes a sky with no day cycle whose look is decided
//! entirely by the game: one background color and any number of
//! [`SkyLayer`]s, each with its own shape, count, size range, weighted colors,
//! placement and optional brightness variation. Select it with
//! [`SkyboxMode::Static`](super::SkyboxMode::Static).
//!
//! The layout is computed by pure, deterministic functions
//! ([`generate_sky_layer`], [`generate_sky_layout`]) seeded through the crate's
//! own [`hash3`], so the same configuration always produces the same sky and
//! the layout can be inspected or tested without a window.
//!
//! The framework ships no presets beyond [`StaticSkyConfig::from_starfield`],
//! which mirrors the existing starfield mode. Every color, shape, size, count
//! and timing is a value supplied by the game.

use std::f32::consts::{FRAC_PI_2, PI, TAU};

use bevy::asset::RenderAssetUsages;
use bevy::light::NotShadowCaster;
use bevy::mesh::{Indices, PrimitiveTopology};
use bevy::prelude::*;

use super::{SkyboxRoot, StarfieldConfig};
use crate::noise::hash3;
use crate::world::ViewerPosition;

// Hash channels: one independent pseudo-random stream per figure attribute.
const CHANNEL_HEIGHT: i32 = 0;
const CHANNEL_AZIMUTH: i32 = 1;
const CHANNEL_SIZE: i32 = 2;
const CHANNEL_COLOR: i32 = 3;
const CHANNEL_GROUP: i32 = 4;
const CHANNEL_PERIOD: i32 = 5;
const CHANNEL_PHASE: i32 = 6;

// ─── Configuration ────────────────────────────────────────────────────────────

/// An inclusive range of values, picked per figure or per animation group.
///
/// `min` and `max` may be given in either order. A single value converts with
/// `From<f32>`:
///
/// ```
/// use voxel_framework::skybox::SkyRange;
///
/// let fixed: SkyRange = 0.5.into();
/// assert_eq!(fixed, SkyRange::new(0.5, 0.5));
/// assert_eq!(SkyRange::new(1.0, 3.0).sample(0.5), 2.0);
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SkyRange {
    /// One end of the range.
    pub min: f32,
    /// The other end of the range.
    pub max: f32,
}

impl SkyRange {
    /// Creates a range between two values.
    pub const fn new(min: f32, max: f32) -> Self {
        Self { min, max }
    }

    /// Creates a range that always yields `value`.
    pub const fn fixed(value: f32) -> Self {
        Self {
            min: value,
            max: value,
        }
    }

    /// Returns the value at fraction `t` of the range; `t` is clamped to
    /// `[0.0, 1.0]`.
    pub fn sample(&self, t: f32) -> f32 {
        self.min + (self.max - self.min) * t.clamp(0.0, 1.0)
    }
}

impl From<f32> for SkyRange {
    fn from(value: f32) -> Self {
        Self::fixed(value)
    }
}

/// The figure drawn for every element of a [`SkyLayer`].
///
/// Built-in shapes are unit-sized meshes scaled by the figure size. A custom
/// mesh is scaled the same way, so author it at unit size.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum SkyShape {
    /// A cube. The figure size is its side length.
    #[default]
    Cube,
    /// A flat square whose front face points along local `+Z`. Combine it with
    /// [`SkyOrientation::FaceCenter`] so it faces a viewer at the sky center;
    /// its back face is not drawn.
    Quad,
    /// An octahedron (a three-dimensional diamond). The figure size is the
    /// distance between opposite tips.
    Diamond,
    /// A mesh supplied by the game.
    Mesh(Handle<Mesh>),
}

/// How the figures of a [`SkyLayer`] are distributed inside its
/// [`SkyRegion`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SkyPlacement {
    /// Even coverage using a golden-angle spiral. Over the full sphere this is
    /// the same distribution the starfield mode uses. It ignores the seed.
    #[default]
    Even,
    /// Seeded irregular coverage: uniform by area, different for every seed
    /// and every layer.
    Scattered,
}

/// The part of the sky sphere a [`SkyLayer`] may occupy.
///
/// A region is the set of directions whose elevation above the plane
/// perpendicular to `axis` lies between `min_elevation` and `max_elevation`
/// (radians, `-Ï€/2` to `Ï€/2`). With the default `+Y` axis that is a horizontal
/// band; with another axis and a `max_elevation` of `Ï€/2` it is a circular
/// patch around that direction.
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::skybox::SkyRegion;
///
/// // Everything above the horizon.
/// let upper = SkyRegion::band(0.0, std::f32::consts::FRAC_PI_2);
/// // A patch of 10 degrees around a direction.
/// let patch = SkyRegion::cap(Vec3::new(1.0, 1.0, 0.0), 10.0_f32.to_radians());
/// assert_ne!(upper, patch);
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SkyRegion {
    /// Direction the elevations are measured from. It does not need to be
    /// normalized; a zero or non-finite axis falls back to `+Y`.
    pub axis: Vec3,
    /// Lowest elevation in radians. Default: `-Ï€/2`.
    pub min_elevation: f32,
    /// Highest elevation in radians. Default: `Ï€/2`.
    pub max_elevation: f32,
}

impl SkyRegion {
    /// The whole sky sphere.
    pub const fn full() -> Self {
        Self {
            axis: Vec3::Y,
            min_elevation: -FRAC_PI_2,
            max_elevation: FRAC_PI_2,
        }
    }

    /// A band around the `+Y` axis between two elevations in radians.
    pub const fn band(min_elevation: f32, max_elevation: f32) -> Self {
        Self {
            axis: Vec3::Y,
            min_elevation,
            max_elevation,
        }
    }

    /// A circular patch centered on `center` with the given angular radius in
    /// radians.
    pub fn cap(center: Vec3, half_angle: f32) -> Self {
        Self {
            axis: center,
            min_elevation: FRAC_PI_2 - half_angle.clamp(0.0, PI),
            max_elevation: FRAC_PI_2,
        }
    }

    /// Returns `(top, bottom)`: the highest and lowest height along the axis,
    /// each in `[-1.0, 1.0]`.
    fn height_range(&self) -> (f32, f32) {
        let height = |elevation: f32| {
            if elevation.is_nan() {
                0.0
            } else if elevation >= FRAC_PI_2 {
                1.0
            } else if elevation <= -FRAC_PI_2 {
                -1.0
            } else {
                elevation.sin()
            }
        };
        let a = height(self.min_elevation);
        let b = height(self.max_elevation);
        (a.max(b), a.min(b))
    }

    /// Rotation taking `+Y` to the region axis, or `None` when the axis is
    /// `+Y` (or unusable) and no rotation is needed.
    fn rotation(&self) -> Option<Quat> {
        let axis = self.axis.try_normalize()?;
        if !axis.is_finite() || axis == Vec3::Y {
            return None;
        }
        Some(Quat::from_rotation_arc(Vec3::Y, axis))
    }
}

impl Default for SkyRegion {
    fn default() -> Self {
        Self::full()
    }
}

/// How each figure of a [`SkyLayer`] is rotated.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SkyOrientation {
    /// Local `+Z` points at the center of the sky sphere, so flat shapes face
    /// a viewer placed there.
    #[default]
    FaceCenter,
    /// No rotation: figures keep the world axes, as starfield cubes do.
    WorldAligned,
}

/// A slow brightness variation for the figures of a [`SkyLayer`].
///
/// Brightness moves between `1.0 - amplitude` and `1.0` following a cosine.
/// Figures are split into `groups`; every group has its own period, picked
/// from `period`, and its own phase, so the layer does not pulse in unison.
/// Each group of each color uses one material, which keeps the number of
/// materials at `colors × groups` whatever the figure count.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SkyTwinkle {
    /// Fraction of brightness removed at the dimmest point, clamped to
    /// `[0.0, 1.0]`.
    pub amplitude: f32,
    /// Length of one full cycle in seconds, picked per group. A group whose
    /// period is not positive does not vary.
    pub period: SkyRange,
    /// Number of independent groups; values below one count as one.
    pub groups: u32,
}

/// One set of figures in a static sky.
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::skybox::{SkyLayer, SkyPlacement, SkyRange, SkyShape};
///
/// let layer = SkyLayer {
///     shape: SkyShape::Quad,
///     count: 300,
///     size: SkyRange::new(1.0, 4.0),
///     colors: vec![(Color::WHITE, 3.0), (Color::srgb(1.0, 0.8, 0.6), 1.0)],
///     placement: SkyPlacement::Scattered,
///     ..default()
/// };
/// assert_eq!(layer.count, 300);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct SkyLayer {
    /// The figure drawn. Default: [`SkyShape::Cube`].
    pub shape: SkyShape,
    /// Number of figures. Default: `0`.
    pub count: u32,
    /// Figure size in world units, picked per figure. Default: `1.0`.
    pub size: SkyRange,
    /// Colors with their relative weights; one is picked per figure. Weights
    /// that are negative or not finite count as zero, and if every weight is
    /// zero the first color is used. An empty list means white. Default:
    /// empty.
    pub colors: Vec<(Color, f32)>,
    /// Distribution inside the region. Default: [`SkyPlacement::Even`].
    pub placement: SkyPlacement,
    /// Part of the sky the layer occupies. Default: the whole sphere.
    pub region: SkyRegion,
    /// Figure rotation. Default: [`SkyOrientation::FaceCenter`].
    pub orientation: SkyOrientation,
    /// Optional brightness variation. Default: `None`.
    pub animation: Option<SkyTwinkle>,
}

impl Default for SkyLayer {
    fn default() -> Self {
        Self {
            shape: SkyShape::default(),
            count: 0,
            size: SkyRange::fixed(1.0),
            colors: Vec::new(),
            placement: SkyPlacement::default(),
            region: SkyRegion::default(),
            orientation: SkyOrientation::default(),
            animation: None,
        }
    }
}

impl SkyLayer {
    /// Number of animation groups: the configured count, at least one, or one
    /// when the layer has no animation.
    pub fn group_count(&self) -> u32 {
        self.animation.map_or(1, |twinkle| twinkle.groups.max(1))
    }

    /// Number of distinct colors figures can take; an empty list counts as one
    /// (white).
    pub fn color_count(&self) -> usize {
        self.colors.len().max(1)
    }
}

/// Description of a static sky: a background color and layers of figures.
///
/// Use it through [`SkyboxMode::Static`](super::SkyboxMode::Static). An empty
/// `layers` list is a plain colored sky.
///
/// ```no_run
/// use bevy::prelude::*;
/// use voxel_framework::skybox::{
///     SkyLayer, SkyPlacement, SkyRange, SkyShape, SkyboxConfig, SkyboxMode, SkyboxPlugin,
///     StaticSkyConfig,
/// };
///
/// App::new()
///     .insert_resource(SkyboxConfig {
///         mode: SkyboxMode::Static(StaticSkyConfig {
///             background: Color::srgb(0.02, 0.02, 0.05),
///             seed: 7,
///             layers: vec![SkyLayer {
///                 shape: SkyShape::Quad,
///                 count: 500,
///                 size: SkyRange::new(1.0, 3.0),
///                 colors: vec![(Color::WHITE, 1.0)],
///                 placement: SkyPlacement::Scattered,
///                 ..default()
///             }],
///             ..default()
///         }),
///     })
///     .add_plugins(SkyboxPlugin)
///     .run();
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct StaticSkyConfig {
    /// Color written to `ClearColor`. Default: black.
    pub background: Color,
    /// Distance from the sky center to every figure, in world units. Keep it
    /// below the far clipping plane of the camera. Default: `900.0`.
    pub radius: f32,
    /// Seed for [`SkyPlacement::Scattered`], sizes, colors and animation
    /// groups. Default: `0`.
    pub seed: u32,
    /// When `true`, the sky center follows
    /// [`ViewerPosition`](crate::world::ViewerPosition) so figures stay at a
    /// fixed distance from the viewer. When `false`, or when that resource
    /// does not exist, the sky stays centered on the world origin. Default:
    /// `true`.
    pub follow_viewer: bool,
    /// The sets of figures, spawned in order. Default: empty.
    pub layers: Vec<SkyLayer>,
}

impl Default for StaticSkyConfig {
    fn default() -> Self {
        Self {
            background: Color::BLACK,
            radius: 900.0,
            seed: 0,
            follow_viewer: true,
            layers: Vec::new(),
        }
    }
}

impl StaticSkyConfig {
    /// A sky with a background color and no figures.
    pub fn color(background: Color) -> Self {
        Self {
            background,
            ..Self::default()
        }
    }

    /// Builds the static-sky equivalent of a starfield: a black background and
    /// one layer of evenly placed, world-aligned cubes of one size and color,
    /// centered on the world origin.
    ///
    /// Figure positions equal the ones
    /// [`SkyboxMode::Starfield`](super::SkyboxMode::Starfield) spawns. Use it
    /// as a starting point to extend the starfield with more layers.
    ///
    /// ```
    /// use voxel_framework::skybox::{StarfieldConfig, StaticSkyConfig};
    ///
    /// let sky = StaticSkyConfig::from_starfield(&StarfieldConfig::default());
    /// assert_eq!(sky.layers.len(), 1);
    /// assert_eq!(sky.layers[0].count, 800);
    /// ```
    pub fn from_starfield(starfield: &StarfieldConfig) -> Self {
        Self {
            background: Color::BLACK,
            radius: starfield.radius,
            seed: 0,
            follow_viewer: false,
            layers: vec![SkyLayer {
                shape: SkyShape::Cube,
                count: starfield.count,
                size: SkyRange::fixed(starfield.star_size),
                colors: vec![(starfield.color, 1.0)],
                placement: SkyPlacement::Even,
                region: SkyRegion::full(),
                orientation: SkyOrientation::WorldAligned,
                animation: None,
            }],
        }
    }
}

// ─── Pure layout ──────────────────────────────────────────────────────────────

/// One generated figure of a sky layer.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SkyFigure {
    /// Position relative to the sky center, at the configured radius.
    pub position: Vec3,
    /// Rotation of the figure.
    pub rotation: Quat,
    /// Size in world units (uniform scale of the unit mesh).
    pub size: f32,
    /// Index into the layer's `colors` (`0` when the list is empty).
    pub color_index: usize,
    /// Animation group, below [`SkyLayer::group_count`].
    pub group: u32,
}

/// Picks an index from relative `weights` using `u` in `[0.0, 1.0]`.
///
/// Negative and non-finite weights count as zero. Returns `0` when the slice
/// is empty or every weight is zero.
///
/// ```
/// use voxel_framework::skybox::pick_weighted_index;
///
/// assert_eq!(pick_weighted_index(&[1.0, 3.0], 0.1), 0);
/// assert_eq!(pick_weighted_index(&[1.0, 3.0], 0.5), 1);
/// ```
pub fn pick_weighted_index(weights: &[f32], u: f32) -> usize {
    let usable = |weight: f32| {
        if weight.is_finite() && weight > 0.0 {
            weight
        } else {
            0.0
        }
    };
    let total: f32 = weights.iter().copied().map(usable).sum();
    if !total.is_finite() || total <= 0.0 {
        return 0;
    }
    let target = u.clamp(0.0, 1.0) * total;
    let mut accumulated = 0.0;
    let mut last_usable = 0;
    for (index, weight) in weights.iter().copied().map(usable).enumerate() {
        if weight <= 0.0 {
            continue;
        }
        accumulated += weight;
        last_usable = index;
        if target < accumulated {
            return index;
        }
    }
    last_usable
}

/// Generates the figures of one layer.
///
/// Pure and deterministic: the same `layer`, `layer_index`, `seed` and
/// `radius` always give the same figures, in the same order. `layer_index`
/// separates the random streams of layers that share a seed.
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::skybox::{generate_sky_layer, SkyLayer, SkyPlacement};
///
/// let layer = SkyLayer {
///     count: 50,
///     placement: SkyPlacement::Scattered,
///     ..default()
/// };
/// let figures = generate_sky_layer(&layer, 0, 42, 900.0);
/// assert_eq!(figures.len(), 50);
/// assert_eq!(figures, generate_sky_layer(&layer, 0, 42, 900.0));
/// ```
pub fn generate_sky_layer(
    layer: &SkyLayer,
    layer_index: u32,
    seed: u32,
    radius: f32,
) -> Vec<SkyFigure> {
    let golden_angle: f32 = PI * (3.0 - 5.0_f32.sqrt());
    let (top, bottom) = layer.region.height_range();
    let region_rotation = layer.region.rotation();
    let weights: Vec<f32> = layer.colors.iter().map(|(_, weight)| *weight).collect();
    let groups = layer.group_count();
    let stream = layer_index as i32;

    let mut figures = Vec::with_capacity(layer.count as usize);
    for i in 0..layer.count {
        let index = i as i32;
        let (height_fraction, phi) = match layer.placement {
            SkyPlacement::Even => (i as f32 / layer.count as f32, golden_angle * i as f32),
            SkyPlacement::Scattered => (
                hash3(index, stream, CHANNEL_HEIGHT, seed),
                TAU * hash3(index, stream, CHANNEL_AZIMUTH, seed),
            ),
        };

        // Height along the axis is linear in the fraction, which keeps the
        // density uniform by area (Archimedes' hat-box theorem).
        let cos_theta = top - (top - bottom) * height_fraction;
        let sin_theta = (1.0 - cos_theta * cos_theta).max(0.0).sqrt();

        let mut position = Vec3::new(
            radius * sin_theta * phi.cos(),
            radius * cos_theta,
            radius * sin_theta * phi.sin(),
        );
        if let Some(rotation) = region_rotation {
            position = rotation * position;
        }

        let rotation = match layer.orientation {
            SkyOrientation::WorldAligned => Quat::IDENTITY,
            SkyOrientation::FaceCenter => match (-position).try_normalize() {
                Some(toward_center) => Quat::from_rotation_arc(Vec3::Z, toward_center),
                None => Quat::IDENTITY,
            },
        };

        let size = layer.size.sample(hash3(index, stream, CHANNEL_SIZE, seed));
        let color_index = pick_weighted_index(&weights, hash3(index, stream, CHANNEL_COLOR, seed));
        let group = if groups > 1 {
            let scaled = hash3(index, stream, CHANNEL_GROUP, seed) * groups as f32;
            (scaled as u32).min(groups - 1)
        } else {
            0
        };

        figures.push(SkyFigure {
            position,
            rotation,
            size,
            color_index,
            group,
        });
    }
    figures
}

/// Generates the figures of every layer of `config`, one `Vec` per layer in
/// layer order.
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::skybox::{generate_sky_layout, SkyLayer, StaticSkyConfig};
///
/// let config = StaticSkyConfig {
///     layers: vec![
///         SkyLayer { count: 10, ..default() },
///         SkyLayer { count: 20, ..default() },
///     ],
///     ..default()
/// };
/// let layout = generate_sky_layout(&config);
/// assert_eq!(layout[0].len(), 10);
/// assert_eq!(layout[1].len(), 20);
/// ```
pub fn generate_sky_layout(config: &StaticSkyConfig) -> Vec<Vec<SkyFigure>> {
    config
        .layers
        .iter()
        .enumerate()
        .map(|(index, layer)| generate_sky_layer(layer, index as u32, config.seed, config.radius))
        .collect()
}

/// Returns `(period_seconds, phase)` for one animation group of a layer;
/// `phase` is a fraction of a cycle in `[0.0, 1.0]`.
///
/// Deterministic for a given `twinkle`, `layer_index`, `group` and `seed`.
pub fn sky_twinkle_timing(
    twinkle: &SkyTwinkle,
    layer_index: u32,
    group: u32,
    seed: u32,
) -> (f32, f32) {
    let stream = layer_index as i32;
    let period = twinkle
        .period
        .sample(hash3(group as i32, stream, CHANNEL_PERIOD, seed));
    let phase = hash3(group as i32, stream, CHANNEL_PHASE, seed);
    (period, phase)
}

/// Brightness multiplier of a twinkling group at `elapsed_seconds`.
///
/// Follows a cosine between `1.0 - amplitude` and `1.0`; `amplitude` is
/// clamped to `[0.0, 1.0]`. `phase` is a fraction of a cycle. Returns `1.0`
/// when `period_seconds` is not a positive finite number.
///
/// ```
/// use voxel_framework::skybox::sky_brightness;
///
/// assert!((sky_brightness(0.4, 10.0, 0.0, 0.0) - 1.0).abs() < 1e-5);
/// assert!((sky_brightness(0.4, 10.0, 0.0, 5.0) - 0.6).abs() < 1e-5);
/// ```
pub fn sky_brightness(
    amplitude: f32,
    period_seconds: f32,
    phase: f32,
    elapsed_seconds: f64,
) -> f32 {
    if !period_seconds.is_finite() || period_seconds <= 0.0 || amplitude.is_nan() {
        return 1.0;
    }
    let amplitude = amplitude.clamp(0.0, 1.0);
    let cycle = (elapsed_seconds / period_seconds as f64 + phase as f64).fract() as f32;
    1.0 - amplitude * 0.5 * (1.0 - (TAU * cycle).cos())
}

// ─── Meshes ───────────────────────────────────────────────────────────────────

/// Builds the unit octahedron used by [`SkyShape::Diamond`]: tips at `±0.5`
/// on every axis, flat-shaded, counter-clockwise winding.
pub fn sky_diamond_mesh() -> Mesh {
    let mut positions: Vec<[f32; 3]> = Vec::with_capacity(24);
    let mut normals: Vec<[f32; 3]> = Vec::with_capacity(24);
    let mut uvs: Vec<[f32; 2]> = Vec::with_capacity(24);
    let mut indices: Vec<u32> = Vec::with_capacity(24);

    let inv_sqrt3 = 1.0 / 3.0_f32.sqrt();
    for sx in [1.0_f32, -1.0] {
        for sy in [1.0_f32, -1.0] {
            for sz in [1.0_f32, -1.0] {
                let a = [0.5 * sx, 0.0, 0.0];
                let b = [0.0, 0.5 * sy, 0.0];
                let c = [0.0, 0.0, 0.5 * sz];
                let normal = [sx * inv_sqrt3, sy * inv_sqrt3, sz * inv_sqrt3];
                let base = positions.len() as u32;
                // a → b → c is counter-clockwise seen from outside when the
                // octant has an even number of negative signs.
                if sx * sy * sz > 0.0 {
                    positions.extend([a, b, c]);
                } else {
                    positions.extend([a, c, b]);
                }
                normals.extend([normal; 3]);
                uvs.extend([[0.0, 0.0], [1.0, 0.0], [0.5, 1.0]]);
                indices.extend([base, base + 1, base + 2]);
            }
        }
    }

    Mesh::new(
        PrimitiveTopology::TriangleList,
        RenderAssetUsages::default(),
    )
    .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
    .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
    .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
    .with_inserted_indices(Indices::U32(indices))
}

// ─── Runtime ──────────────────────────────────────────────────────────────────

/// Marker on a [`SkyboxRoot`] whose translation follows
/// [`ViewerPosition`](crate::world::ViewerPosition).
///
/// Added by the static sky when [`StaticSkyConfig::follow_viewer`] is `true`.
/// Remove it to stop following, or add it to your own sky root.
#[derive(Component, Debug, Clone, Copy, Default)]
pub struct SkyFollowViewer;

/// One material whose brightness varies over time.
#[derive(Debug, Clone)]
struct SkyTwinkleMaterial {
    handle: Handle<StandardMaterial>,
    base: LinearRgba,
    amplitude: f32,
    period: f32,
    phase: f32,
}

/// Materials animated by [`animate_static_sky_system`]. Inserted only when a
/// static sky has at least one animated layer.
#[derive(Resource, Debug, Clone, Default)]
pub(super) struct SkyTwinkleMaterials(Vec<SkyTwinkleMaterial>);

/// Scales a color's linear RGB by `brightness`, keeping alpha.
fn scaled_color(base: LinearRgba, brightness: f32) -> Color {
    Color::LinearRgba(LinearRgba::new(
        base.red * brightness,
        base.green * brightness,
        base.blue * brightness,
        base.alpha,
    ))
}

/// Spawns the figures of a static sky under one [`SkyboxRoot`] entity and
/// records the animated materials.
pub(super) fn spawn_static_sky(
    commands: &mut Commands,
    meshes: &mut Assets<Mesh>,
    materials: &mut Assets<StandardMaterial>,
    config: &StaticSkyConfig,
) {
    let mut cube_mesh: Option<Handle<Mesh>> = None;
    let mut quad_mesh: Option<Handle<Mesh>> = None;
    let mut diamond_mesh: Option<Handle<Mesh>> = None;
    let mut animated: Vec<SkyTwinkleMaterial> = Vec::new();
    let mut children: Vec<Entity> = Vec::new();

    for (layer_index, layer) in config.layers.iter().enumerate() {
        if layer.count == 0 {
            continue;
        }
        let layer_index = layer_index as u32;

        let mesh = match &layer.shape {
            SkyShape::Cube => cube_mesh
                .get_or_insert_with(|| meshes.add(Cuboid::new(1.0, 1.0, 1.0)))
                .clone(),
            SkyShape::Quad => quad_mesh
                .get_or_insert_with(|| meshes.add(Rectangle::new(1.0, 1.0)))
                .clone(),
            SkyShape::Diamond => diamond_mesh
                .get_or_insert_with(|| meshes.add(sky_diamond_mesh()))
                .clone(),
            SkyShape::Mesh(handle) => handle.clone(),
        };

        // One material per (color, group). Without animation there is a
        // single group, so a layer uses one material per color.
        let groups = layer.group_count();
        let colors: Vec<Color> = if layer.colors.is_empty() {
            vec![Color::WHITE]
        } else {
            layer.colors.iter().map(|(color, _)| *color).collect()
        };
        let mut layer_materials: Vec<Vec<Handle<StandardMaterial>>> =
            Vec::with_capacity(colors.len());
        for color in &colors {
            let base = color.to_linear();
            let alpha_mode = if base.alpha < 1.0 {
                AlphaMode::Blend
            } else {
                AlphaMode::Opaque
            };
            let mut per_group = Vec::with_capacity(groups as usize);
            for group in 0..groups {
                let handle = materials.add(StandardMaterial {
                    base_color: *color,
                    unlit: true,
                    alpha_mode,
                    ..default()
                });
                if let Some(twinkle) = &layer.animation {
                    let (period, phase) =
                        sky_twinkle_timing(twinkle, layer_index, group, config.seed);
                    animated.push(SkyTwinkleMaterial {
                        handle: handle.clone(),
                        base,
                        amplitude: twinkle.amplitude,
                        period,
                        phase,
                    });
                }
                per_group.push(handle);
            }
            layer_materials.push(per_group);
        }

        for figure in generate_sky_layer(layer, layer_index, config.seed, config.radius) {
            let color_index = figure.color_index.min(colors.len() - 1);
            let group = figure.group.min(groups - 1) as usize;
            let material = layer_materials[color_index][group].clone();
            let child = commands
                .spawn((
                    Mesh3d(mesh.clone()),
                    MeshMaterial3d(material),
                    Transform {
                        translation: figure.position,
                        rotation: figure.rotation,
                        scale: Vec3::splat(figure.size),
                    },
                    NotShadowCaster,
                ))
                .id();
            children.push(child);
        }
    }

    let mut root = commands.spawn((SkyboxRoot, Transform::default(), Visibility::default()));
    if config.follow_viewer {
        root.insert(SkyFollowViewer);
    }
    root.add_children(&children);

    if !animated.is_empty() {
        commands.insert_resource(SkyTwinkleMaterials(animated));
    }
}

/// Keeps every [`SkyFollowViewer`] root centered on the viewer.
pub(super) fn follow_viewer_system(
    viewer: Option<Res<ViewerPosition>>,
    mut roots: Query<&mut Transform, With<SkyFollowViewer>>,
) {
    let Some(viewer) = viewer else {
        return;
    };
    for mut transform in &mut roots {
        if transform.translation != viewer.position {
            transform.translation = viewer.position;
        }
    }
}

/// Applies the brightness variation to the animated sky materials.
pub(super) fn animate_static_sky_system(
    time: Res<Time>,
    animated: Res<SkyTwinkleMaterials>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    let elapsed = time.elapsed_secs_f64();
    for entry in &animated.0 {
        let brightness = sky_brightness(entry.amplitude, entry.period, entry.phase, elapsed);
        if let Some(material) = materials.get_mut(&entry.handle) {
            material.base_color = scaled_color(entry.base, brightness);
        }
    }
}

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

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

    fn scattered(count: u32) -> SkyLayer {
        SkyLayer {
            count,
            placement: SkyPlacement::Scattered,
            ..default()
        }
    }

    #[test]
    fn static_sky_defaults() {
        let config = StaticSkyConfig::default();
        assert_eq!(config.background, Color::BLACK);
        assert_eq!(config.radius, 900.0);
        assert_eq!(config.seed, 0);
        assert!(config.follow_viewer);
        assert!(config.layers.is_empty());
        assert!(generate_sky_layout(&config).is_empty());

        let layer = SkyLayer::default();
        assert_eq!(layer.shape, SkyShape::Cube);
        assert_eq!(layer.count, 0);
        assert_eq!(layer.size, SkyRange::fixed(1.0));
        assert!(layer.colors.is_empty());
        assert_eq!(layer.placement, SkyPlacement::Even);
        assert_eq!(layer.region, SkyRegion::full());
        assert_eq!(layer.orientation, SkyOrientation::FaceCenter);
        assert!(layer.animation.is_none());
    }

    #[test]
    fn color_constructor_has_no_layers() {
        let color = Color::srgb(0.2, 0.4, 0.6);
        let config = StaticSkyConfig::color(color);
        assert_eq!(config.background, color);
        assert!(config.layers.is_empty());
    }

    #[test]
    fn layer_has_requested_count_on_the_sphere() {
        for placement in [SkyPlacement::Even, SkyPlacement::Scattered] {
            let layer = SkyLayer {
                count: 200,
                placement,
                ..default()
            };
            let figures = generate_sky_layer(&layer, 0, 3, 500.0);
            assert_eq!(figures.len(), 200);
            for figure in &figures {
                assert!((figure.position.length() - 500.0).abs() < 0.05);
            }
        }
    }

    #[test]
    fn layout_is_deterministic() {
        let config = StaticSkyConfig {
            seed: 11,
            layers: vec![scattered(64), scattered(32)],
            ..default()
        };
        assert_eq!(generate_sky_layout(&config), generate_sky_layout(&config));
    }

    #[test]
    fn seed_and_layer_index_change_scattered_layout() {
        let layer = scattered(32);
        let a = generate_sky_layer(&layer, 0, 1, 900.0);
        let other_seed = generate_sky_layer(&layer, 0, 2, 900.0);
        let other_layer = generate_sky_layer(&layer, 1, 1, 900.0);
        assert_ne!(a, other_seed);
        assert_ne!(a, other_layer);
    }

    #[test]
    fn even_placement_ignores_seed() {
        let layer = SkyLayer {
            count: 40,
            orientation: SkyOrientation::WorldAligned,
            ..default()
        };
        let a = generate_sky_layer(&layer, 0, 1, 900.0);
        let b = generate_sky_layer(&layer, 0, 99, 900.0);
        for (x, y) in a.iter().zip(&b) {
            assert_eq!(x.position, y.position);
        }
    }

    #[test]
    fn starfield_preset_matches_starfield_positions() {
        let starfield = StarfieldConfig {
            count: 100,
            ..StarfieldConfig::default()
        };
        let config = StaticSkyConfig::from_starfield(&starfield);
        assert_eq!(config.background, Color::BLACK);
        assert!(!config.follow_viewer);
        let figures = &generate_sky_layout(&config)[0];
        assert_eq!(figures.len(), 100);

        // Same formula as `spawn_starfield`.
        let golden_angle: f32 = PI * (3.0 - 5.0_f32.sqrt());
        for (i, figure) in figures.iter().enumerate() {
            let t = i as f32 / starfield.count as f32;
            let cos_theta = 1.0 - 2.0 * t;
            let sin_theta = (1.0 - cos_theta * cos_theta).max(0.0).sqrt();
            let phi = golden_angle * i as f32;
            let expected = Vec3::new(
                starfield.radius * sin_theta * phi.cos(),
                starfield.radius * cos_theta,
                starfield.radius * sin_theta * phi.sin(),
            );
            assert!(figure.position.distance(expected) < 1e-3);
            assert_eq!(figure.rotation, Quat::IDENTITY);
            assert_eq!(figure.size, starfield.star_size);
            assert_eq!(figure.color_index, 0);
            assert_eq!(figure.group, 0);
        }
    }

    #[test]
    fn band_limits_elevation() {
        let min = 10.0_f32.to_radians();
        let max = 30.0_f32.to_radians();
        for placement in [SkyPlacement::Even, SkyPlacement::Scattered] {
            let layer = SkyLayer {
                count: 300,
                placement,
                region: SkyRegion::band(min, max),
                ..default()
            };
            for figure in generate_sky_layer(&layer, 0, 5, 100.0) {
                let elevation = (figure.position.y / 100.0).clamp(-1.0, 1.0).asin();
                assert!(elevation >= min - 1e-3 && elevation <= max + 1e-3);
            }
        }
    }

    #[test]
    fn band_accepts_swapped_limits() {
        let layer = SkyLayer {
            count: 50,
            placement: SkyPlacement::Scattered,
            region: SkyRegion::band(0.5, -0.5),
            ..default()
        };
        for figure in generate_sky_layer(&layer, 0, 5, 1.0) {
            assert!(figure.position.y.abs() <= 0.5_f32.sin() + 1e-4);
        }
    }

    #[test]
    fn cap_stays_within_angle_of_center() {
        let center = Vec3::new(1.0, 0.5, -2.0);
        let half_angle = 15.0_f32.to_radians();
        let layer = SkyLayer {
            count: 300,
            placement: SkyPlacement::Scattered,
            region: SkyRegion::cap(center, half_angle),
            ..default()
        };
        let direction = center.normalize();
        for figure in generate_sky_layer(&layer, 2, 8, 50.0) {
            let angle = figure.position.normalize().angle_between(direction);
            assert!(angle <= half_angle + 1e-2, "angle {angle}");
        }
    }

    #[test]
    fn unusable_axis_falls_back_to_y() {
        let zero_axis = SkyRegion {
            axis: Vec3::ZERO,
            ..SkyRegion::full()
        };
        let a = generate_sky_layer(
            &SkyLayer {
                count: 20,
                region: zero_axis,
                ..default()
            },
            0,
            0,
            10.0,
        );
        let b = generate_sky_layer(
            &SkyLayer {
                count: 20,
                ..default()
            },
            0,
            0,
            10.0,
        );
        assert_eq!(a, b);
    }

    #[test]
    fn face_center_points_local_z_at_center() {
        let figures = generate_sky_layer(&scattered(100), 0, 4, 300.0);
        for figure in figures {
            let forward = figure.rotation * Vec3::Z;
            let toward_center = -figure.position.normalize();
            assert!(forward.dot(toward_center) > 0.999);
        }
    }

    #[test]
    fn sizes_stay_in_range_and_vary() {
        let layer = SkyLayer {
            size: SkyRange::new(4.0, 2.0),
            ..scattered(200)
        };
        let figures = generate_sky_layer(&layer, 0, 9, 900.0);
        assert!(figures.iter().all(|f| f.size >= 2.0 && f.size <= 4.0));
        let first = figures[0].size;
        assert!(figures.iter().any(|f| (f.size - first).abs() > 1e-3));
    }

    #[test]
    fn weighted_pick_edges() {
        assert_eq!(pick_weighted_index(&[], 0.5), 0);
        assert_eq!(pick_weighted_index(&[0.0, 0.0], 0.9), 0);
        assert_eq!(pick_weighted_index(&[1.0, 1.0], 0.0), 0);
        assert_eq!(pick_weighted_index(&[1.0, 1.0], 1.0), 1);
        assert_eq!(pick_weighted_index(&[0.0, 2.0, 0.0], 0.0), 1);
        assert_eq!(pick_weighted_index(&[0.0, 2.0, 0.0], 1.0), 1);
        assert_eq!(pick_weighted_index(&[-5.0, f32::NAN, 1.0], 0.3), 2);
        assert_eq!(pick_weighted_index(&[1.0, 3.0], 0.2), 0);
        assert_eq!(pick_weighted_index(&[1.0, 3.0], 0.3), 1);
    }

    #[test]
    fn colors_follow_weights() {
        let layer = SkyLayer {
            colors: vec![
                (Color::WHITE, 0.0),
                (Color::BLACK, 3.0),
                (Color::srgb(1.0, 0.0, 0.0), 1.0),
            ],
            ..scattered(2000)
        };
        let figures = generate_sky_layer(&layer, 0, 21, 900.0);
        let count = |index: usize| figures.iter().filter(|f| f.color_index == index).count();
        assert_eq!(count(0), 0);
        assert!(count(1) > count(2));
        assert!(count(2) > 0);
        assert_eq!(count(1) + count(2), 2000);
    }

    #[test]
    fn empty_colors_use_index_zero() {
        let figures = generate_sky_layer(&scattered(30), 0, 1, 900.0);
        assert!(figures.iter().all(|f| f.color_index == 0));
        assert_eq!(scattered(30).color_count(), 1);
    }

    #[test]
    fn groups_stay_below_group_count() {
        let layer = SkyLayer {
            animation: Some(SkyTwinkle {
                amplitude: 0.5,
                period: SkyRange::new(2.0, 6.0),
                groups: 4,
            }),
            ..scattered(500)
        };
        assert_eq!(layer.group_count(), 4);
        let figures = generate_sky_layer(&layer, 0, 13, 900.0);
        assert!(figures.iter().all(|f| f.group < 4));
        for group in 0..4 {
            assert!(figures.iter().any(|f| f.group == group));
        }

        let no_animation = generate_sky_layer(&scattered(50), 0, 13, 900.0);
        assert!(no_animation.iter().all(|f| f.group == 0));
    }

    #[test]
    fn zero_groups_count_as_one() {
        let layer = SkyLayer {
            animation: Some(SkyTwinkle {
                amplitude: 0.5,
                period: SkyRange::fixed(3.0),
                groups: 0,
            }),
            ..scattered(10)
        };
        assert_eq!(layer.group_count(), 1);
        assert!(
            generate_sky_layer(&layer, 0, 0, 900.0)
                .iter()
                .all(|f| f.group == 0)
        );
    }

    #[test]
    fn twinkle_timing_is_deterministic_and_in_range() {
        let twinkle = SkyTwinkle {
            amplitude: 0.3,
            period: SkyRange::new(4.0, 12.0),
            groups: 8,
        };
        for group in 0..8 {
            let (period, phase) = sky_twinkle_timing(&twinkle, 1, group, 77);
            assert!((4.0..=12.0).contains(&period));
            assert!((0.0..=1.0).contains(&phase));
            assert_eq!((period, phase), sky_twinkle_timing(&twinkle, 1, group, 77));
        }
    }

    #[test]
    fn brightness_stays_between_floor_and_one() {
        for step in 0..200 {
            let elapsed = step as f64 * 0.37;
            let value = sky_brightness(0.4, 7.0, 0.25, elapsed);
            assert!(value >= 0.6 - 1e-5 && value <= 1.0 + 1e-5);
        }
        assert!((sky_brightness(0.4, 10.0, 0.0, 0.0) - 1.0).abs() < 1e-5);
        assert!((sky_brightness(0.4, 10.0, 0.0, 5.0) - 0.6).abs() < 1e-5);
        assert!((sky_brightness(0.4, 10.0, 0.5, 0.0) - 0.6).abs() < 1e-5);
        // Periodic.
        let a = sky_brightness(0.4, 10.0, 0.1, 3.0);
        let b = sky_brightness(0.4, 10.0, 0.1, 13.0);
        assert!((a - b).abs() < 1e-4);
    }

    #[test]
    fn brightness_handles_degenerate_input() {
        assert_eq!(sky_brightness(0.5, 0.0, 0.0, 3.0), 1.0);
        assert_eq!(sky_brightness(0.5, -2.0, 0.0, 3.0), 1.0);
        assert_eq!(sky_brightness(0.5, f32::NAN, 0.0, 3.0), 1.0);
        assert_eq!(sky_brightness(f32::NAN, 2.0, 0.0, 3.0), 1.0);
        // Amplitude above one is clamped: never negative.
        assert!(sky_brightness(5.0, 2.0, 0.0, 1.0) >= 0.0);
    }

    #[test]
    fn diamond_mesh_has_eight_outward_triangles() {
        let mesh = sky_diamond_mesh();
        assert_eq!(mesh.count_vertices(), 24);
        let Some(bevy::mesh::VertexAttributeValues::Float32x3(positions)) =
            mesh.attribute(Mesh::ATTRIBUTE_POSITION)
        else {
            panic!("positions missing");
        };
        let Some(bevy::mesh::VertexAttributeValues::Float32x3(normals)) =
            mesh.attribute(Mesh::ATTRIBUTE_NORMAL)
        else {
            panic!("normals missing");
        };
        for triangle in 0..8 {
            let a = Vec3::from(positions[triangle * 3]);
            let b = Vec3::from(positions[triangle * 3 + 1]);
            let c = Vec3::from(positions[triangle * 3 + 2]);
            let face_normal = (b - a).cross(c - a).normalize();
            let stored = Vec3::from(normals[triangle * 3]);
            assert!(face_normal.dot(stored) > 0.99);
            assert!(face_normal.dot(a + b + c) > 0.0);
        }
    }

    #[test]
    fn scaled_color_keeps_alpha() {
        let base = LinearRgba::new(0.8, 0.4, 0.2, 0.5);
        let scaled = scaled_color(base, 0.5).to_linear();
        assert!((scaled.red - 0.4).abs() < 1e-6);
        assert!((scaled.green - 0.2).abs() < 1e-6);
        assert!((scaled.blue - 0.1).abs() < 1e-6);
        assert_eq!(scaled.alpha, 0.5);
    }

    #[test]
    fn follow_system_moves_only_marked_roots() {
        let mut app = App::new();
        app.insert_resource(ViewerPosition {
            position: Vec3::new(5.0, -2.0, 9.0),
        });
        app.add_systems(Update, follow_viewer_system);
        let following = app
            .world_mut()
            .spawn((SkyboxRoot, SkyFollowViewer, Transform::default()))
            .id();
        let fixed = app
            .world_mut()
            .spawn((SkyboxRoot, Transform::default()))
            .id();
        app.update();
        assert_eq!(
            app.world().get::<Transform>(following).unwrap().translation,
            Vec3::new(5.0, -2.0, 9.0)
        );
        assert_eq!(
            app.world().get::<Transform>(fixed).unwrap().translation,
            Vec3::ZERO
        );
    }
}