bevy_elements 0.7.6

Living environments for Bevy: sun, moon and stars, climate-driven weather, GPU wind, volumetric clouds, rain, snow and fog, lightning, terrain with hydraulic and thermal erosion, flooding, snow cover, wetness and dust — simulated in compute shaders.
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
1246
//! Volumetric clouds: a weather-driven cloud layer ray-marched in compute, accumulated over a few
//! frames, composited after the transparent pass, plus a cloud shadow map for the sun's light.
//! See `docs/research/clouds.md`.

mod gpu;
#[cfg(test)]
mod gpu_tests;
#[cfg(test)]
mod model;

use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};

use bevy::asset::{RenderAssetUsages, embedded_asset};
use bevy::camera::Exposure;
use bevy::image::{ImageAddressMode, ImageFilterMode, ImageSampler, ImageSamplerDescriptor};
use bevy::light::light_consts::lux;
use bevy::light::{Atmosphere, GeneratedEnvironmentMapLight};
use bevy::math::DVec2;
use bevy::pbr::{DistanceFog, FogFalloff};
use bevy::prelude::*;
use bevy::render::RenderApp;
use bevy::render::extract_component::ExtractComponent;
use bevy::render::render_resource::{
    Extent3d, ShaderType, TextureDimension, TextureFormat, TextureUsages, TextureViewDescriptor,
    TextureViewDimension,
};
use bevy::render::storage::ShaderBuffer;
use bevy::shader::load_shader_library;

use crate::celestial::{
    CelestialFrame, CelestialSettings, CloudLight, MOON_TINT, NIGHT_SKY_LUMINANCE, Sun, SunState,
    beam_transmittance, cloud_ambient, scene_illuminance, sky_clear_gain, sky_gain,
};
use crate::climate::Weather;
use crate::flash::LightningFlash;
use crate::fog::{HORIZON_RING, HorizonRing};
use crate::gpu::grid::storage_buffer;
use crate::gpu::readback::{Readbacks, decode};
use crate::plugin::{
    ElementsQuality, ElementsSystems, ElementsUnits, ElementsView, ensure_gpu_core,
    needs_depth_prepass,
};
use crate::query::EnvironmentSnapshot;
use crate::terrain::TerrainGrid;

/// Smoothstep, `S(a, b, x)` of the research note.
fn smoothstep(a: f32, b: f32, x: f32) -> f32 {
    let t = ((x - a) / (b - a)).clamp(0.0, 1.0);
    t * t * (3.0 - 2.0 * t)
}

/// Where the cloud layer is: a spherical shell whose base and top are altitudes above the
/// planet surface (`y = 0`).
///
/// Derived from [`Weather`] every frame ([`CloudLayer::from_weather`]); the lightning plugin
/// reads it to put a bolt's top at the cloud base. Read-only for everyone else.
#[derive(Resource, Clone, Copy, Debug, PartialEq, Reflect)]
pub struct CloudLayer {
    /// Altitude of the cloud base, m above `y = 0`. 600–1500.
    pub base_m: f32,
    /// Altitude of the cloud top, m above `y = 0`. 1400–9500.
    pub top_m: f32,
}

impl Default for CloudLayer {
    fn default() -> Self {
        Self {
            base_m: 1500.0,
            top_m: 3300.0,
        }
    }
}

impl CloudLayer {
    /// The layer for a weather state: base 1500 m, lowered toward 600 m in fog and drizzle;
    /// thickness 800 m (stratus), 1800 m (cumulus) or 8000 m (cumulonimbus) by
    /// [`kind_from_weather`](Self::kind_from_weather).
    pub fn from_weather(weather: &Weather) -> Self {
        let rh = weather.relative_humidity;
        let rain = weather.precipitation_mm_h;
        let low = (smoothstep(0.9, 0.98, rh) * (1.0 - smoothstep(0.1, 0.5, rain)))
            .max(smoothstep(0.1, 0.3, rain) * (1.0 - smoothstep(0.8, 1.5, rain)));
        let base_m = 1500.0 + (600.0 - 1500.0) * low;
        let kind = Self::kind_from_weather(weather);
        let thickness = if kind <= 0.5 {
            800.0 + 1000.0 * (kind / 0.5).min(1.0)
        } else {
            1800.0 + 6200.0 * (kind - 0.5) / 0.5
        };
        Self {
            base_m,
            top_m: base_m + thickness,
        }
    }

    /// The cloud type of a weather state, the weather map's blue channel: 0 stratus, 0.5
    /// cumulus, 1 cumulonimbus, continuous in every [`Weather`] field.
    pub fn kind_from_weather(weather: &Weather) -> f32 {
        let c = weather.cloud_cover;
        let stratus = smoothstep(0.5, 0.9, c).max(smoothstep(0.9, 0.98, weather.relative_humidity));
        let towering = (weather.storminess / 6.0)
            .clamp(0.0, 1.0)
            .max(smoothstep(12.0, 16.0, weather.wind_speed_ms) * smoothstep(0.9, 1.0, c));
        0.5 * (1.0 - stratus) * (1.0 - towering) + towering
    }

    /// Precipitation darkening `min(R / 25, 1)` of a weather state (the weather map's green
    /// channel before it is masked by coverage).
    pub fn precipitation_from_weather(weather: &Weather) -> f32 {
        (weather.precipitation_mm_h / 25.0).clamp(0.0, 1.0)
    }
}

/// The 512² `rgba8unorm` weather map the clouds are built from, covering 32 km around the
/// camera: R coverage, G precipitation (never above `precipitation_mm_h / 25`, zero where there
/// is no cloud), B cloud type. Sample it with a bilinear, repeating sampler at
/// `uv = (p.xz − origin) / extent`, `p` a world position in the metre frame (world ÷
/// [`crate::ElementsUnits::units_per_metre`]; the same as world for the default 1.0).
#[derive(Resource, Clone, Debug)]
pub struct CloudWeatherMap {
    /// The map texture; written by a compute kernel every frame.
    pub map: Handle<Image>,
    /// Metre-frame XZ of the map's minimum corner, m (snapped to a whole texel).
    pub origin: Vec2,
    /// Side length of the map, m.
    pub extent: f32,
}

/// The cloud shadow map: sun (or moon) transmittance through the clouds for the plane `y = 0`,
/// 1024² `rgba16float` over an 8 km square centred on the camera. R is the direct transmittance
/// `T`, G the optical depth (clamped to 60), B the precipitation darkening of the weather map.
///
/// A consumer at metre-frame position `P` (world ÷ `ElementsUnits::units_per_metre`) samples with
/// `uv = (P.xz − light_direction.xz · P.y / light_direction.y − origin) / extent` and `Clamp`
/// addressing; outside the map `T = 1`.
#[derive(Resource, Clone, Debug)]
pub struct CloudShadows {
    /// The map texture.
    pub map: Handle<Image>,
    /// Metre-frame XZ of the map's minimum corner, m (snapped to a whole texel).
    pub origin: Vec2,
    /// Side length of the map, m.
    pub extent: f32,
    /// Unit vector toward the light the map was generated for: the sun by day, the moon when
    /// the sun is lower than −4°.
    pub light_direction: Vec3,
    /// Mean direct transmittance over the whole map (the 8 km around the camera), 0–1,
    /// smoothed over 1 s of real time: the share of the clear-sky beam the landscape gets on
    /// average. Before the first GPU readback it is `1 − cover^3.4`, the cover-only estimate
    /// of the weather. The sun's and moon's `DirectionalLight` carry `T̄` of their clear-sky
    /// illuminance (and so do Bevy's sky, aerial perspective and environment map, which they
    /// light) and the camera's `AmbientLight` the diffuse remainder `0.25 · (1 − T̄)`; a
    /// surface that samples the map takes its own shadow relative to it,
    /// `(0.25 + 0.75 T) / (0.25 + 0.75 T̄)` (`docs/research/broken-cloud-light.md`).
    pub mean_transmittance: f32,
}

/// Lowest sine of the light's elevation the shadow map is generated for: arcsin 0.1 = 5.74°. A
/// lower sun would put the cloud layer beyond the weather map; it is dim and red anyway.
pub(crate) const SHADOW_MIN_LIGHT_SINE: f32 = 0.1;

impl CloudShadows {
    /// The unit direction toward the light the map was actually generated for: `light_direction`
    /// with its elevation raised to 5.74° when lower.
    pub fn generation_direction(&self) -> Vec3 {
        let l = self.light_direction;
        if l.y >= SHADOW_MIN_LIGHT_SINE {
            return l;
        }
        let flat = l.xz().normalize_or(Vec2::X);
        let c = (1.0 - SHADOW_MIN_LIGHT_SINE * SHADOW_MIN_LIGHT_SINE).sqrt();
        Vec3::new(flat.x * c, SHADOW_MIN_LIGHT_SINE, flat.y * c)
    }

    /// Texture coordinate (0–1 over the map) of the shadow cast on metre-frame position `position`
    /// (world ÷ `ElementsUnits::units_per_metre`; `Environment::cloud_shadow_at` converts):
    /// `(P.xz − l.xz · P.y / l.y − origin) / extent`, the point where the ray from `P` toward
    /// the light would cross the plane `y = 0` the map is generated for. Sample with `Clamp`
    /// addressing; a coordinate outside 0–1 is outside the map and unshadowed (`T = 1`).
    pub fn uv(&self, position: Vec3) -> Vec2 {
        let l = self.generation_direction();
        (position.xz() - l.xz() * (position.y / l.y) - self.origin) / self.extent
    }
}

/// Cloud rendering cost per [`ElementsQuality`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CloudQuality {
    /// Edge, in pixels, of the block one march texel stands for: 4 (a quarter of the resolution
    /// per axis) on Low and Medium, 2 on High and Ultra.
    pub block: u32,
    /// Primary ray-march steps.
    pub steps: u32,
    /// Samples along the path to the light.
    pub light_samples: u32,
    /// Frames until every pixel has been marched once (`block²`).
    pub window: u32,
    /// Texels per face edge of the sky probe (`docs/research/sky-light.md`) marched each frame:
    /// one texel of every `k × k` block, `k = cube edge / probe_edge` clamped to 1–4. 32 on Low,
    /// Medium and High, 64 on Ultra (`k` = 4, 4, 4, 2 for Bevy's default 128² cube).
    pub probe_edge: u32,
}

impl CloudQuality {
    /// The settings of a quality level.
    pub fn of(quality: ElementsQuality) -> Self {
        let (block, steps, probe_edge) = match quality {
            ElementsQuality::Low => (4, 32, 32),
            ElementsQuality::Medium => (4, 48, 32),
            ElementsQuality::High => (2, 64, 32),
            ElementsQuality::Ultra => (2, 96, 64),
        };
        Self {
            block,
            steps,
            light_samples: 6,
            window: block * block,
            probe_edge,
        }
    }

    /// The sky probe's slot block edge `k` for a cube of `size` texels per face edge.
    pub(crate) fn probe_block(&self, size: u32) -> u32 {
        (size / self.probe_edge.max(1))
            .clamp(1, 4)
            .next_power_of_two()
            .min(4)
    }
}

/// Texels per side of the weather map and the world size it covers, m.
pub(crate) const WEATHER_TEXELS: u32 = 512;
pub(crate) const WEATHER_EXTENT_M: f32 = 32_000.0;
/// Texels per side of the shadow map and the world size it covers, m.
pub(crate) const SHADOW_TEXELS: u32 = 1024;
pub(crate) const SHADOW_EXTENT_M: f32 = 8_000.0;
/// Shadow-map texels per cell edge of the gameplay query grid ([`CloudShadowSnapshot`]).
pub(crate) const SHADOW_COARSE_STRIDE: u32 = 4;
/// Cells per side of the gameplay query grid.
pub(crate) const SHADOW_COARSE_CELLS: u32 = SHADOW_TEXELS / SHADOW_COARSE_STRIDE;
/// Texels per side of the base and detail noise volumes.
pub(crate) const NOISE_BASE_TEXELS: u32 = 128;
pub(crate) const NOISE_DETAIL_TEXELS: u32 = 32;
/// World size of the noise tiles, m (`common.wesl`; cumulus-shape.md); the cloud drift is
/// wrapped to each so f32 keeps its precision. The weather field is periodic in its 32 km
/// extent.
const BASE_TILE_M: f64 = 4096.0;
const DETAIL_TILE_M: f64 = 640.0;
/// The drift accumulates in f64 modulo a common multiple of the three periods (2²² · 5³).
const DRIFT_WRAP_M: f64 = 524_288_000.0;
/// Cloud drift is this multiple of the 10 m wind: the wind at cloud height (log-law 1.86 at
/// 1.5 km, 1.94 at the layer top) rounded up as the plan says.
const DRIFT_WIND_FACTOR: f64 = 2.0;
/// Sun altitude, degrees, below which the clouds are lit by the moon; the sun's light fades
/// out over the degree above it (the layer keeps the sun to −3.1° at 9.5 km, the dip).
const SUN_HANDOVER_DEG: f32 = -4.0;
/// Albedo of the ground the diffuse light reflects up into the air, for the in-scatter source.
const GROUND_ALBEDO: f32 = 0.3;
/// In-scatter source of the air per unit radiance of the ambient sky: isotropic scattering lights
/// the air with the scalar irradiance over 4π, `E (1 + ρ) / 4π` for the downward irradiance
/// `E = π L` of the sky and the ground albedo `ρ`, which is `L (1 + ρ) / 4`.
const AIRLIGHT_PER_SKY_RADIANCE: f32 = (1.0 + GROUND_ALBEDO) / 4.0;
/// Smoothing time of the mean transmittance, s of real time.
const MEAN_TRANSMITTANCE_TAU_S: f32 = 1.0;

/// Uniform of every cloud kernel (`common.wesl`, `CloudParams`).
#[derive(Clone, Copy, Debug, Default, ShaderType)]
pub(crate) struct CloudParams {
    /// xyz: camera, m. w: planet radius, m.
    pub camera: Vec4,
    /// x: atmosphere outer radius, m. y: aerial LUT range, m. z: aerial LUT slices. w: the night
    /// sky's background radiance behind the atmosphere (`celestial::NIGHT_SKY_LUMINANCE`), cd/m².
    pub atmo: Vec4,
    /// x: gain on the sky pixels of the composite (`celestial::sky_gain`). yzw: radiance of the
    /// air lit by the cloud-scattered diffuse light (`celestial::cloud_ambient`), cd/m².
    pub sky: Vec4,
    /// x: base altitude, m. y: top altitude, m. z: cloud type. w: cover.
    pub layer: Vec4,
    /// xyz: unit direction toward the light.
    pub light: Vec4,
    /// xyz: light illuminance outside the atmosphere, lx. w: ambient source, cd/m².
    pub light_e: Vec4,
    /// xy: drift of the weather field, m. zw: of the base noise, m.
    pub drift: Vec4,
    /// xy: drift of the detail noise, m. zw: unit wind direction.
    pub drift_detail: Vec4,
    /// xy: weather map origin. z: extent, m. w: precipitation darkening.
    pub weather: Vec4,
    /// xy: shadow map origin. z: extent, m.
    pub shadow: Vec4,
    /// xyz: flash position, m. w: intensity, cd.
    pub flash: Vec4,
    /// x: frame. y: steps. z: block edge. w: light samples.
    pub counts: UVec4,
    /// xy: full resolution. zw: march resolution.
    pub sizes: UVec4,
    /// x: previous/current exposure. y: debug mode. z: debug extinction. w: history reset.
    pub misc: Vec4,
    /// x: first noise slice of this frame.
    pub tail: UVec4,
    /// xyz: the camera's `DistanceFog` colour (linear, after exposure). w: its extinction, m⁻¹
    /// (0 without distance fog).
    pub haze: Vec4,
    /// x: extinction of the weather's air above clear air, m⁻¹ (`fog::sky_air_extinction`).
    /// The composite fogs sky pixels with it, so the sky converges on `haze.xyz` as distant
    /// ground does; 0 leaves the sky to the atmosphere alone. `clouds.md` Deviation 29. y: the
    /// gain that undoes the cloud dimming of the environment map the ambient reads
    /// (`celestial::sky_clear_gain`), so it holds the clear sky above the layer.
    pub air: Vec4,
    /// x: world units per metre ([`crate::ElementsUnits`]). Every other field is in metres;
    /// Bevy's view matrices and depth are in world units, which the shaders convert with it.
    pub units: Vec4,
    /// The sky probe (`docs/research/sky-light.md`): x the followed camera's exposure (the
    /// display-referred `haze.xyz` over it is the fog's luminance), y the slot block edge `k`,
    /// z texels per face edge, w the weight a marched texel takes in its history (1 while the
    /// history is invalid).
    pub probe: Vec4,
    /// The still sea (`StillWater`): x its level, m; y 1 while one is set.
    pub sea: Vec4,
    /// xy: the minimum corner, zw: the maximum corner, of the region (world XZ, m) the sea and
    /// its skirt cover. The composite leaves the pixels whose ray meets the sea there to the water.
    pub sea_box: Vec4,
}

/// The per-view images: this frame's march result and the two history textures.
#[derive(Clone, Debug)]
pub(crate) struct CloudViewImages {
    pub size: UVec2,
    pub march: Handle<Image>,
    pub history: [Handle<Image>; 2],
}

/// Everything the render world needs, extracted every frame.
#[derive(Resource, Clone)]
pub(crate) struct CloudGpu {
    pub base: Handle<Image>,
    pub detail: Handle<Image>,
    pub weather: Handle<Image>,
    pub shadow: Handle<Image>,
    pub histogram: Handle<ShaderBuffer>,
    pub threshold: Handle<ShaderBuffer>,
    /// Every fourth shadow-map texel's transmittance, `SHADOW_COARSE_CELLS²` row-major.
    pub shadow_coarse: Handle<ShaderBuffer>,
    /// The sky's radiance at the horizon in `HORIZON_RING` azimuths, `vec4` each with `w` 1 once
    /// the probe pass has written it (`docs/research/fog-colour.md`).
    pub horizon: Handle<ShaderBuffer>,
    /// The cube the clouds' skylight is read from: the followed camera's atmosphere environment
    /// map (Bevy's clear sky, [`SkyProbe::atmosphere`] once the probe has taken the environment
    /// map over), or `neutral_sky`.
    pub sky_probe: Handle<Image>,
    /// A 1×1 white cube: the neutral ambient of a camera with no environment map.
    pub neutral_sky: Handle<Image>,
    pub view: Option<CloudViewImages>,
    /// The sky probe's images, while the followed camera has an atmosphere environment map.
    pub probe: Option<SkyProbeImages>,
    /// Frames the render world has composed the current probe images on: the probe is handed to
    /// the environment map once every texel has been marched (`k²` frames).
    pub probe_frames: Arc<AtomicU32>,
    pub params: CloudParams,
    /// Followed camera present: the weather and shadow kernels run.
    pub active: bool,
    /// Set by the render world after the weather and shadow kernels first ran.
    pub live: Arc<AtomicBool>,
}

/// The sky probe's textures (`docs/research/sky-light.md`): two cloud states the kernel
/// ping-pongs between and the composed cube, all of the atmosphere cube's size.
#[derive(Clone, Debug)]
pub(crate) struct SkyProbeImages {
    /// Texels per face edge.
    pub size: u32,
    /// Slot block edge `k`: one texel of every `k × k` block is marched each frame.
    pub block: u32,
    /// Bevy's atmosphere cube, which the probe composes the clouds over.
    pub atmosphere: Handle<Image>,
    /// Premultiplied cloud luminance and transmittance per texel, `[even frame, odd frame]`.
    pub state: [Handle<Image>; 2],
    /// The composed sky the environment map is filtered from.
    pub composed: Handle<Image>,
}

/// On the followed camera: the clouds composed into its environment map
/// (`docs/research/sky-light.md`). Its `GeneratedEnvironmentMapLight` is filtered from
/// `composed` once `lit`, and the camera's `AmbientLight` then no longer carries the
/// cloud-scattered light, which the cube does.
#[derive(Component, Clone, Debug)]
pub(crate) struct SkyProbe {
    /// Bevy's atmosphere cube (the clear sky): the clouds' own skylight source, and what the
    /// environment map is given back when the probe ends.
    pub atmosphere: Handle<Image>,
    /// The composed cube.
    pub composed: Handle<Image>,
    /// The environment map is filtered from `composed`.
    pub lit: bool,
}

/// Marks the camera the clouds are drawn for; extracted to the render world.
#[derive(Component, Clone, Copy, Debug, Default, ExtractComponent)]
#[extract_app(RenderApp)]
pub(crate) struct CloudView;

/// The system that moves [`CloudWeatherMap`] and [`CloudShadows`] and fills the GPU uniforms;
/// consumers of the maps' origins order themselves after it.
#[derive(SystemSet, Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct CloudGpuUpdate;

/// Main-world state of the cloud simulation.
#[derive(Resource, Default)]
struct CloudRuntime {
    /// Cloud drift, m, wrapped at `DRIFT_WRAP_M`.
    drift: DVec2,
    frame: u32,
    quality: Option<ElementsQuality>,
    /// Frames left on which the history is flagged invalid.
    reset_frames: u32,
    exposure: f32,
}

/// Test-only overrides of the kernels' inputs.
#[cfg(test)]
#[derive(Resource, Clone, Debug, Default)]
pub(crate) struct CloudDebug {
    /// 1: uniform slab of extinction `sigma`; 2: output the light transmittance at the entry.
    pub mode: f32,
    pub sigma: f32,
    pub layer: Option<(f32, f32)>,
    pub light: Option<Vec3>,
    pub light_e: Option<Vec3>,
    pub kind: Option<f32>,
    pub cover: Option<f32>,
    pub drift: Option<Vec2>,
    /// The weather's air extinction, m⁻¹: 0 is clear air and leaves the sky to the atmosphere.
    pub air: Option<f32>,
}

/// Volumetric clouds.
///
/// Creates the noise volumes, the weather map and the shadow map; each frame it derives the
/// [`CloudLayer`] from the weather, marches the clouds for the followed
/// [`ElementsCamera`](crate::ElementsCamera) and composites them after the transparent pass, and keeps
/// [`CloudShadows`] current. It dims the sun and moon lights by the mean cloud transmittance over
/// the shadow map's 8 km, so a cloud's shadow over the camera darkens the surfaces in it and not
/// the sky. Needs `DepthPrepass`, `Msaa::Off` and an HDR target, which `ElementsCamera` sets up.
pub struct CloudPlugin;

impl Plugin for CloudPlugin {
    fn build(&self, app: &mut App) {
        ensure_gpu_core(app);
        needs_depth_prepass(app);
        load_shader_library!(app, "common.wesl");
        embedded_asset!(app, "generate.wesl");
        embedded_asset!(app, "weather.wesl");
        embedded_asset!(app, "shadow.wesl");
        embedded_asset!(app, "march.wesl");
        embedded_asset!(app, "resolve.wesl");
        embedded_asset!(app, "composite.wesl");
        app.init_resource::<LightningFlash>()
            .init_resource::<CloudLayer>()
            .init_resource::<CloudRuntime>()
            .init_resource::<CelestialFrame>()
            .add_systems(Startup, create_resources)
            .add_systems(
                Update,
                (
                    smooth_mean_transmittance
                        .in_set(ElementsSystems::Celestial)
                        .before(crate::celestial::update_sky),
                    (
                        mark_view,
                        update_layer,
                        advance_drift,
                        update_views,
                        update_sky_probe,
                        // The march reads this frame's `LightningFlash`.
                        update_gpu
                            .after(crate::lightning::write_flash)
                            .in_set(CloudGpuUpdate),
                    )
                        .chain()
                        .in_set(ElementsSystems::Simulation),
                    read_shadows.in_set(ElementsSystems::Readback),
                    read_horizon.in_set(ElementsSystems::Readback),
                ),
            );
        #[cfg(test)]
        app.add_systems(
            Update,
            apply_debug
                .in_set(ElementsSystems::Simulation)
                .after(update_gpu),
        );
        gpu::plugin(app);
    }
}

/// A storage texture the kernels write and shaders sample with a linear sampler.
fn texture(
    images: &mut Assets<Image>,
    size: Extent3d,
    dimension: TextureDimension,
    format: TextureFormat,
    pixel: &[u8],
    address: ImageAddressMode,
) -> Handle<Image> {
    let mut image = Image::new_fill(
        size,
        dimension,
        pixel,
        format,
        RenderAssetUsages::RENDER_WORLD,
    );
    // COPY_SRC lets the tests read any of them back.
    image.texture_descriptor.usage = TextureUsages::STORAGE_BINDING
        | TextureUsages::TEXTURE_BINDING
        | TextureUsages::COPY_SRC
        | TextureUsages::COPY_DST;
    image.sampler = ImageSampler::Descriptor(ImageSamplerDescriptor {
        address_mode_u: address,
        address_mode_v: address,
        address_mode_w: address,
        mag_filter: ImageFilterMode::Linear,
        min_filter: ImageFilterMode::Linear,
        mipmap_filter: ImageFilterMode::Linear,
        ..default()
    });
    images.add(image)
}

/// Half-precision 1.0, little-endian.
const HALF_ONE: [u8; 2] = [0x00, 0x3C];

/// A 1×1 white cube: what the ambient's colour is read from when the camera has no atmosphere
/// environment map.
fn neutral_sky_cube(images: &mut Assets<Image>) -> Handle<Image> {
    let texel = [HALF_ONE[0], HALF_ONE[1]].repeat(4);
    let mut image = Image::new_fill(
        Extent3d {
            width: 1,
            height: 1,
            depth_or_array_layers: 6,
        },
        TextureDimension::D2,
        &texel,
        TextureFormat::Rgba16Float,
        RenderAssetUsages::RENDER_WORLD,
    );
    image.texture_view_descriptor = Some(TextureViewDescriptor {
        dimension: Some(TextureViewDimension::Cube),
        ..default()
    });
    images.add(image)
}

fn create_resources(
    mut commands: Commands,
    mut images: ResMut<Assets<Image>>,
    mut buffers: ResMut<Assets<ShaderBuffer>>,
) {
    let volume = |n: u32| Extent3d {
        width: n,
        height: n,
        depth_or_array_layers: n,
    };
    let plane = |n: u32| Extent3d {
        width: n,
        height: n,
        depth_or_array_layers: 1,
    };
    let base = texture(
        &mut images,
        volume(NOISE_BASE_TEXELS),
        TextureDimension::D3,
        TextureFormat::Rgba8Unorm,
        &[0; 4],
        ImageAddressMode::Repeat,
    );
    let detail = texture(
        &mut images,
        volume(NOISE_DETAIL_TEXELS),
        TextureDimension::D3,
        TextureFormat::Rgba8Unorm,
        &[0; 4],
        ImageAddressMode::Repeat,
    );
    let weather = texture(
        &mut images,
        plane(WEATHER_TEXELS),
        TextureDimension::D2,
        TextureFormat::Rgba8Unorm,
        &[0; 4],
        ImageAddressMode::Repeat,
    );
    // Nothing shadowed until the first dispatch: T = 1.
    let shadow = texture(
        &mut images,
        plane(SHADOW_TEXELS),
        TextureDimension::D2,
        TextureFormat::Rgba16Float,
        &[HALF_ONE[0], HALF_ONE[1], 0, 0, 0, 0, 0, 0],
        ImageAddressMode::ClampToEdge,
    );
    let neutral_sky = neutral_sky_cube(&mut images);
    commands.insert_resource(CloudWeatherMap {
        map: weather.clone(),
        origin: Vec2::ZERO,
        extent: WEATHER_EXTENT_M,
    });
    commands.insert_resource(CloudShadows {
        map: shadow.clone(),
        origin: Vec2::ZERO,
        extent: SHADOW_EXTENT_M,
        light_direction: Vec3::Y,
        mean_transmittance: 1.0,
    });
    commands.insert_resource(CloudGpu {
        base,
        detail,
        weather,
        shadow,
        histogram: storage_buffer(&mut buffers, "elements_clouds_histogram", vec![0u32; 256]),
        threshold: storage_buffer(&mut buffers, "elements_clouds_threshold", vec![0f32; 4]),
        // Nothing shadowed until the first dispatch: T = 1.
        shadow_coarse: storage_buffer(
            &mut buffers,
            "elements_clouds_shadow_coarse",
            vec![1f32; (SHADOW_COARSE_CELLS * SHADOW_COARSE_CELLS) as usize],
        ),
        horizon: storage_buffer(
            &mut buffers,
            "elements_clouds_horizon",
            vec![[0f32; 4]; HORIZON_RING],
        ),
        sky_probe: neutral_sky.clone(),
        neutral_sky,
        view: None,
        probe: None,
        probe_frames: Arc::new(AtomicU32::new(0)),
        params: CloudParams::default(),
        active: false,
        live: Arc::new(AtomicBool::new(false)),
    });
}

/// `CloudView` on the followed camera and no other.
fn mark_view(
    mut commands: Commands,
    view: Res<ElementsView>,
    marked: Query<Entity, With<CloudView>>,
) {
    for entity in &marked {
        if Some(entity) != view.entity {
            commands.entity(entity).remove::<CloudView>();
        }
    }
    if let Some(entity) = view.entity
        && !marked.contains(entity)
    {
        commands.entity(entity).insert(CloudView);
    }
}

fn update_layer(weather: Res<Weather>, mut layer: ResMut<CloudLayer>) {
    let next = CloudLayer::from_weather(&weather);
    if *layer != next {
        *layer = next;
    }
}

/// The clouds drift with the wind at cloud height, `2 · u₁₀` (`Time<Virtual>`, like wind and
/// fog, so the world clock's time scale does not move them).
fn advance_drift(
    time: Res<Time<Virtual>>,
    weather: Res<Weather>,
    mut runtime: ResMut<CloudRuntime>,
) {
    let wind = weather.wind_direction.as_dvec2() * f64::from(weather.wind_speed_ms);
    let next = runtime.drift + wind * DRIFT_WIND_FACTOR * time.delta_secs_f64();
    runtime.drift = next.rem_euclid(DVec2::splat(DRIFT_WRAP_M));
}

/// March, history and result textures sized for the followed camera and the quality; rebuilt
/// when either changes (the weather map, shadow map and noise are kept).
fn update_views(
    view: Res<ElementsView>,
    quality: Res<ElementsQuality>,
    cameras: Query<&Camera>,
    mut images: ResMut<Assets<Image>>,
    mut gpu: ResMut<CloudGpu>,
    mut runtime: ResMut<CloudRuntime>,
) {
    let size = view
        .entity
        .and_then(|e| cameras.get(e).ok())
        .and_then(Camera::physical_target_size)
        .filter(|s| s.x > 0 && s.y > 0);
    let Some(size) = size else {
        if gpu.view.is_some() {
            gpu.view = None;
        }
        return;
    };
    let up_to_date =
        gpu.view.as_ref().is_some_and(|v| v.size == size) && runtime.quality == Some(*quality);
    if up_to_date {
        return;
    }
    let block = CloudQuality::of(*quality).block;
    let low = (size + UVec2::splat(block - 1)) / block;
    let plane = |s: UVec2| Extent3d {
        width: s.x,
        height: s.y,
        depth_or_array_layers: 1,
    };
    // Clear sky (no radiance, full transmittance) until the first resolve.
    let clear = [0, 0, 0, 0, 0, 0, HALF_ONE[0], HALF_ONE[1]];
    let mut make = |s: UVec2| {
        texture(
            &mut images,
            plane(s),
            TextureDimension::D2,
            TextureFormat::Rgba16Float,
            &clear,
            ImageAddressMode::ClampToEdge,
        )
    };
    gpu.view = Some(CloudViewImages {
        size,
        march: make(low),
        history: [make(size), make(size)],
    });
    runtime.quality = Some(*quality);
    runtime.reset_frames = 2;
}

/// Weight a re-marched sky-probe texel takes in its history (`docs/research/sky-light.md`,
/// Parameters): the march's per-texel jitter averaged over about seven marches.
const PROBE_HISTORY_WEIGHT: f32 = 0.25;

/// The followed camera's sky probe (`docs/research/sky-light.md`, Model 5–7): images of the size
/// of its atmosphere cube, and the environment map handed over to the composed cube once every
/// texel has been marched. A camera that stops being followed, or whose atmosphere cube is
/// replaced, gets the atmosphere cube back until a new probe is composed.
fn update_sky_probe(
    mut commands: Commands,
    view: Res<ElementsView>,
    quality: Res<ElementsQuality>,
    mut images: ResMut<Assets<Image>>,
    mut gpu: ResMut<CloudGpu>,
    mut cameras: Query<(
        Entity,
        &mut GeneratedEnvironmentMapLight,
        Option<&mut SkyProbe>,
    )>,
    orphans: Query<Entity, (With<SkyProbe>, Without<GeneratedEnvironmentMapLight>)>,
) {
    for entity in &orphans {
        commands.entity(entity).remove::<SkyProbe>();
    }
    for (entity, mut light, probe) in &mut cameras {
        if Some(entity) == view.entity {
            continue;
        }
        if let Some(probe) = probe {
            if light.environment_map == probe.composed {
                light.environment_map = probe.atmosphere.clone();
            }
            commands.entity(entity).remove::<SkyProbe>();
        }
    }
    let Some((entity, mut light, probe)) = view.entity.and_then(|e| cameras.get_mut(e).ok()) else {
        gpu.probe = None;
        return;
    };
    // The environment map's source is Bevy's atmosphere cube unless it is the composed one.
    let atmosphere = match probe.as_deref() {
        Some(p) if light.environment_map == p.composed => p.atmosphere.clone(),
        _ => light.environment_map.clone(),
    };
    let Some(size) = images
        .get(&atmosphere)
        .map(|image| image.texture_descriptor.size.width)
    else {
        gpu.probe = None;
        return;
    };
    let block = CloudQuality::of(*quality).probe_block(size);
    let current = gpu
        .probe
        .as_ref()
        .is_some_and(|p| p.atmosphere == atmosphere && p.size == size && p.block == block);
    if !current {
        let fresh = sky_probe_images(&mut images, atmosphere.clone(), size, block);
        gpu.probe_frames.store(0, Ordering::Relaxed);
        if light.environment_map != atmosphere {
            light.environment_map = atmosphere.clone();
        }
        commands.entity(entity).insert(SkyProbe {
            atmosphere,
            composed: fresh.composed.clone(),
            lit: false,
        });
        gpu.probe = Some(fresh);
        return;
    }
    if let Some(mut probe) = probe
        && !probe.lit
        && gpu.probe_frames.load(Ordering::Relaxed) >= block * block
    {
        light.environment_map = probe.composed.clone();
        probe.lit = true;
    }
}

/// The sky probe's two cloud states (no cloud: no luminance, full transmittance) and its composed
/// cube, `size²` per face, written by the render world only.
fn sky_probe_images(
    images: &mut Assets<Image>,
    atmosphere: Handle<Image>,
    size: u32,
    block: u32,
) -> SkyProbeImages {
    let mut cube = |pixel: &[u8], dimension: TextureViewDimension| {
        let mut image = Image::new_fill(
            Extent3d {
                width: size,
                height: size,
                depth_or_array_layers: 6,
            },
            TextureDimension::D2,
            pixel,
            TextureFormat::Rgba16Float,
            RenderAssetUsages::RENDER_WORLD,
        );
        // COPY_SRC lets the tests read them back.
        image.texture_descriptor.usage = TextureUsages::STORAGE_BINDING
            | TextureUsages::TEXTURE_BINDING
            | TextureUsages::COPY_SRC;
        image.texture_view_descriptor = Some(TextureViewDescriptor {
            dimension: Some(dimension),
            ..default()
        });
        images.add(image)
    };
    let clear = [0, 0, 0, 0, 0, 0, HALF_ONE[0], HALF_ONE[1]];
    let state = [
        cube(&clear, TextureViewDimension::D2Array),
        cube(&clear, TextureViewDimension::D2Array),
    ];
    let composed = cube(&[0; 8], TextureViewDimension::Cube);
    SkyProbeImages {
        size,
        block,
        atmosphere,
        state,
        composed,
    }
}

/// The light the clouds are lit by: the sun, fading out over the degree above the handover
/// altitude, and below it the moon.
fn pick_light(sun: &SunState, frame: &CelestialFrame) -> (Vec3, Vec3) {
    if sun.altitude_deg > SUN_HANDOVER_DEG {
        let weight = smoothstep(SUN_HANDOVER_DEG, SUN_HANDOVER_DEG + 1.0, sun.altitude_deg);
        (sun.direction, Vec3::splat(lux::RAW_SUNLIGHT * weight))
    } else {
        (sun.moon_direction, MOON_TINT * frame.moon_lux)
    }
}

/// Round `value` to a whole multiple of `step`.
fn snap(value: Vec2, step: f32) -> Vec2 {
    (value / step).round() * step
}

/// The still sea and the terrain whose grid it covers (`CloudParams::sea`).
type SeaInputs<'w> = (
    Option<Res<'w, crate::StillWater>>,
    Option<Res<'w, crate::TerrainState>>,
);

#[allow(clippy::too_many_arguments)]
fn update_gpu(
    view: Res<ElementsView>,
    weather: Res<Weather>,
    sun: Res<SunState>,
    frame: Res<CelestialFrame>,
    (flash, units, sea): (Res<LightningFlash>, Res<ElementsUnits>, SeaInputs<'_>),
    quality: Res<ElementsQuality>,
    layer: Res<CloudLayer>,
    atmospheres: Query<&Atmosphere>,
    exposures: Query<&Exposure>,
    fogs: Query<&DistanceFog>,
    probes: Query<&GeneratedEnvironmentMapLight>,
    mut runtime: ResMut<CloudRuntime>,
    mut gpu: ResMut<CloudGpu>,
    mut map: ResMut<CloudWeatherMap>,
    mut shadows: ResMut<CloudShadows>,
    own_sun: (
        Option<Res<CelestialSettings>>,
        Query<&GlobalTransform, With<Sun>>,
    ),
) {
    let Some(entity) = view.entity else {
        gpu.active = false;
        return;
    };
    let camera = view.position;
    let (inner, outer) = atmospheres
        .iter()
        .next()
        .map_or((6_360_000.0, 6_460_000.0), |a| {
            (a.inner_radius, a.outer_radius)
        });
    let (mut light_dir, light_e) = pick_light(&sun, &frame);
    // A game that lights its scene itself (`CelestialSettings::lights` off) and marks its key
    // light `Sun` gets the cloud shadows cast along that light, as its buildings' shadows fall
    // (`docs/research/integration.md` Deviation 2).
    let (celestial, suns) = &own_sun;
    if celestial.as_ref().is_some_and(|c| !c.lights)
        && let Some(own) = suns.iter().next()
    {
        light_dir = *own.back();
    }
    // Diffuse sky light: the metered illuminance before cloud dimming, all of it diffuse in
    // twilight and 15 % of it at high sun.
    let sky_share = 1.0 + (0.15 - 1.0) * smoothstep(-2.0, 10.0, sun.altitude_deg);
    let ambient = sky_share * scene_illuminance(&sun, frame.moon_lux, CloudLight::CLEAR)
        / (2.0 * std::f32::consts::PI);

    let weather_texel = WEATHER_EXTENT_M / WEATHER_TEXELS as f32;
    let shadow_texel = SHADOW_EXTENT_M / SHADOW_TEXELS as f32;
    map.origin = snap(
        camera.xz() - Vec2::splat(WEATHER_EXTENT_M * 0.5),
        weather_texel,
    );
    shadows.origin = snap(
        camera.xz() - Vec2::splat(SHADOW_EXTENT_M * 0.5),
        shadow_texel,
    );
    shadows.light_direction = light_dir;

    let exposure = exposures.get(entity).map_or(1.0, Exposure::exposure);
    let exposure_ratio = if runtime.exposure > 0.0 && exposure > 0.0 {
        runtime.exposure / exposure
    } else {
        1.0
    };
    runtime.exposure = exposure;
    runtime.frame = runtime.frame.wrapping_add(1);
    let reset = runtime.reset_frames > 0;
    runtime.reset_frames = runtime.reset_frames.saturating_sub(1);

    let q = CloudQuality::of(*quality);
    let size = gpu.view.as_ref().map_or(UVec2::ONE, |v| v.size);
    let low = (size + UVec2::splat(q.block - 1)) / q.block;
    let drift = runtime.drift;
    let wrap = |period: f64| {
        Vec2::new(
            drift.x.rem_euclid(period) as f32,
            drift.y.rem_euclid(period) as f32,
        )
    };
    let field = wrap(f64::from(WEATHER_EXTENT_M));
    let base = wrap(BASE_TILE_M);
    let detail = wrap(DETAIL_TILE_M);
    let wind = weather.wind_direction.normalize_or(Vec2::X);

    gpu.active = true;
    // The clouds' skylight is the clear sky's: the atmosphere cube of the followed camera (the
    // one the sky probe composes over, which the environment map no longer shows once the probe
    // is lit), or the neutral cube without one (Deviation 30).
    gpu.sky_probe = match &gpu.probe {
        Some(probe) => probe.atmosphere.clone(),
        None => probes
            .get(entity)
            .map_or_else(|_| gpu.neutral_sky.clone(), |p| p.environment_map.clone()),
    };
    // A marched probe texel replaces its history until every texel has been marched once.
    let probe = gpu.probe.as_ref().map_or(Vec4::ZERO, |p| {
        let fresh = gpu.probe_frames.load(Ordering::Relaxed) < p.block * p.block;
        Vec4::new(
            exposure,
            p.block as f32,
            p.size as f32,
            if fresh { 1.0 } else { PROBE_HISTORY_WEIGHT },
        )
    });
    let cloud = CloudLight::from_beam(shadows.mean_transmittance);
    let (diffuse_colour, diffuse_brightness) = cloud_ambient(&sun, frame.moon_lux, cloud);
    let airlight = diffuse_colour * (diffuse_brightness * AIRLIGHT_PER_SKY_RADIANCE);
    // The still sea: its level and the box of ground and skirt the water draws.
    let (sea, sea_box) = match (&sea.0, &sea.1) {
        (Some(still), Some(terrain)) => {
            let reach = crate::hydrology::WATER_SKIRT_REACH_M;
            let lo = terrain.grid.origin - Vec2::splat(reach);
            let hi = terrain.grid.origin + terrain.grid.extent() + Vec2::splat(reach);
            (
                Vec4::new(
                    terrain.grid.y0 + still.level / units.per_metre(),
                    1.0,
                    0.0,
                    0.0,
                ),
                Vec4::new(lo.x, lo.y, hi.x, hi.y),
            )
        }
        _ => (Vec4::ZERO, Vec4::ZERO),
    };
    gpu.params = CloudParams {
        camera: camera.extend(inner),
        atmo: Vec4::new(outer, 32_000.0, 32.0, NIGHT_SKY_LUMINANCE),
        sky: Vec4::new(sky_gain(&sun, cloud), airlight.x, airlight.y, airlight.z),
        layer: Vec4::new(
            layer.base_m,
            layer.top_m,
            CloudLayer::kind_from_weather(&weather),
            weather.cloud_cover.clamp(0.0, 1.0),
        ),
        light: light_dir.extend(0.0),
        light_e: light_e.extend(ambient),
        drift: Vec4::new(field.x, field.y, base.x, base.y),
        drift_detail: Vec4::new(detail.x, detail.y, wind.x, wind.y),
        weather: Vec4::new(
            map.origin.x,
            map.origin.y,
            WEATHER_EXTENT_M,
            CloudLayer::precipitation_from_weather(&weather),
        ),
        shadow: Vec4::new(shadows.origin.x, shadows.origin.y, SHADOW_EXTENT_M, 0.0),
        flash: units
            .point_to_metres(flash.position)
            .extend(flash.intensity_cd.max(0.0)),
        counts: UVec4::new(runtime.frame, q.steps, q.block, q.light_samples),
        sizes: UVec4::new(size.x, size.y, low.x, low.y),
        misc: Vec4::new(exposure_ratio, 0.0, 0.0, if reset { 1.0 } else { 0.0 }),
        tail: UVec4::ZERO,
        haze: fogs
            .get(entity)
            .map_or(Vec4::ZERO, |fog| haze(fog, units.per_metre())),
        // The sky's air comes from the camera's own `DistanceFog`, so the sky and the meshes
        // cannot disagree about the fog even if a game replaces it.
        air: Vec4::new(
            fogs.get(entity).map_or(0.0, |fog| {
                crate::fog::sky_air_extinction(fog_extinction(fog, units.per_metre()))
            }),
            sky_clear_gain(&sun, cloud),
            0.0,
            0.0,
        ),
        units: Vec4::new(units.per_metre(), 0.0, 0.0, 0.0),
        probe,
        sea,
        sea_box,
    };
}

/// The distance fog as the clouds' ground haze: its linear colour and its grey extinction in
/// m⁻¹ (`fog::distance_fog_falloff` sets extinction and in-scattering equal).
fn haze(fog: &DistanceFog, units: f32) -> Vec4 {
    let c = fog.color.to_linear();
    Vec4::new(c.red, c.green, c.blue, fog_extinction(fog, units))
}

/// Extinction of a camera's distance fog, m⁻¹ (Bevy's is per world unit, `units` of them to the
/// metre); 0 for a falloff this crate never writes (`FogFalloff::Linear` or
/// `ExponentialSquared`, which a game that replaces the component may).
fn fog_extinction(fog: &DistanceFog, units: f32) -> f32 {
    let per_world_unit = match fog.falloff {
        FogFalloff::Atmospheric { extinction, .. } => extinction.x,
        FogFalloff::Exponential { density } => density,
        FogFalloff::ExponentialSquared { .. } | FogFalloff::Linear { .. } => 0.0,
    };
    per_world_unit * units
}

#[cfg(test)]
fn apply_debug(debug: Option<Res<CloudDebug>>, mut gpu: ResMut<CloudGpu>) {
    let Some(debug) = debug else {
        return;
    };
    let p = &mut gpu.params;
    p.misc.y = debug.mode;
    p.misc.z = debug.sigma;
    if let Some((base, top)) = debug.layer {
        p.layer.x = base;
        p.layer.y = top;
    }
    if let Some(kind) = debug.kind {
        p.layer.z = kind;
    }
    if let Some(cover) = debug.cover {
        p.layer.w = cover;
    }
    if let Some(air) = debug.air {
        p.air.x = air;
    }
    if let Some(light) = debug.light {
        p.light = light.extend(0.0);
    }
    if let Some(e) = debug.light_e {
        p.light_e = e.extend(p.light_e.w);
    }
    if let Some(drift) = debug.drift {
        p.drift.x = drift.x.rem_euclid(WEATHER_EXTENT_M);
        p.drift.y = drift.y.rem_euclid(WEATHER_EXTENT_M);
        p.drift.z = drift.x.rem_euclid(BASE_TILE_M as f32);
        p.drift.w = drift.y.rem_euclid(BASE_TILE_M as f32);
        p.drift_detail.x = drift.x.rem_euclid(DETAIL_TILE_M as f32);
        p.drift_detail.y = drift.y.rem_euclid(DETAIL_TILE_M as f32);
    }
}

/// The mean transmittance the lights are dimmed by: the readback grid's mean, smoothed over a
/// second; until the first readback `1 − cover^3.4`, the cover-only beam.
fn smooth_mean_transmittance(
    time: Res<Time<Real>>,
    weather: Res<Weather>,
    snapshot: Res<EnvironmentSnapshot>,
    shadows: Option<ResMut<CloudShadows>>,
) {
    let Some(mut shadows) = shadows else {
        return;
    };
    match &snapshot.cloud_shadow {
        None => {
            shadows.mean_transmittance = beam_transmittance(weather.cloud_cover);
        }
        Some(measured) => {
            let k = 1.0 - (-time.delta_secs() / MEAN_TRANSMITTANCE_TAU_S).exp();
            let now = shadows.mean_transmittance;
            shadows.mean_transmittance = now + (measured.mean - now) * k;
        }
    }
}

fn read_shadows(
    gpu: Option<Res<CloudGpu>>,
    shadows: Option<Res<CloudShadows>>,
    mut readbacks: Readbacks,
) {
    let (Some(gpu), Some(shadows)) = (gpu, shadows) else {
        return;
    };
    if !gpu.active || !gpu.live.load(Ordering::Relaxed) {
        return;
    }
    let grid = CloudShadowSnapshot::grid(shadows.origin);
    let light = shadows.generation_direction();
    readbacks.request(
        "cloud_shadow",
        gpu.shadow_coarse.clone(),
        move |bytes, snapshot| {
            let cells = (SHADOW_COARSE_CELLS * SHADOW_COARSE_CELLS) as usize;
            if let Some(values) = decode::<f32>(bytes)
                && values.len() >= cells
            {
                let values = &values[..cells];
                // The mean over the finite cells: the share of the clear beam the 8 km get.
                let (sum, count) = values
                    .iter()
                    .filter(|t| t.is_finite())
                    .fold((0.0f64, 0u32), |(s, n), &t| {
                        (s + f64::from(t.clamp(0.0, 1.0)), n + 1)
                    });
                snapshot.cloud_shadow = Some(CloudShadowSnapshot {
                    grid,
                    light,
                    transmittance: values.into(),
                    mean: if count > 0 {
                        (sum / f64::from(count)) as f32
                    } else {
                        1.0
                    },
                });
            }
        },
    );
}

/// The sky's horizon radiance, read back for the distance fog (`docs/research/fog-colour.md`).
/// Until the probe pass has written the ring (no probe, or the first frames) nothing is stored
/// and the fog keeps its analytic colour.
fn read_horizon(gpu: Option<Res<CloudGpu>>, mut readbacks: Readbacks) {
    let Some(gpu) = gpu else {
        return;
    };
    if !gpu.active || !gpu.live.load(Ordering::Relaxed) {
        return;
    }
    readbacks.request(
        "cloud_horizon",
        gpu.horizon.clone(),
        move |bytes, snapshot| {
            if let Some(values) = decode::<[f32; 4]>(bytes)
                && values.len() >= HORIZON_RING
                && values[..HORIZON_RING].iter().all(|v| v[3] > 0.5)
            {
                let mut ring = [Vec3::ZERO; HORIZON_RING];
                for (slot, v) in ring.iter_mut().zip(&values) {
                    *slot = Vec3::new(v[0], v[1], v[2]);
                }
                snapshot.horizon = Some(HorizonRing(ring));
            }
        },
    );
}

/// CPU copy of the cloud shadow map's query grid: the direct transmittance toward the light
/// every 31.25 m over the map's 8 km square (`docs/research/cloud-shadow-query.md`).
#[derive(Clone, Debug)]
pub(crate) struct CloudShadowSnapshot {
    /// The query grid: cell `k` is centred on shadow-map texel `4k + 2`.
    pub grid: TerrainGrid,
    /// Unit direction toward the light the map was generated for (elevation ≥ 5.74°).
    pub light: Vec3,
    /// Row-major transmittance, 0–1.
    pub transmittance: Arc<[f32]>,
    /// Mean of `transmittance`: the beam the lights carry (`CloudShadows::mean_transmittance`
    /// before its smoothing).
    pub mean: f32,
}

impl CloudShadowSnapshot {
    /// The query grid of a shadow map whose minimum corner is `origin`.
    pub(crate) fn grid(origin: Vec2) -> TerrainGrid {
        let texel = SHADOW_EXTENT_M / SHADOW_TEXELS as f32;
        TerrainGrid {
            // Cell k's centre, origin + (k + 0.5)·4t, is texel 4k + 2's centre, origin + (4k + 2.5)·t.
            origin: origin + Vec2::splat(0.5 * texel),
            cell_m: texel * SHADOW_COARSE_STRIDE as f32,
            size: UVec2::splat(SHADOW_COARSE_CELLS),
            y0: 0.0,
        }
    }

    /// Direct transmittance toward the light at a world position: the position projected along
    /// the light onto the map's plane `y = 0`, bilinear; 1 outside the map.
    pub(crate) fn transmittance_at(&self, position: Vec3) -> f32 {
        let q = position.xz() - self.light.xz() * (position.y / self.light.y);
        if !self.grid.contains(q) {
            return 1.0;
        }
        self.grid.sample(&self.transmittance, q).clamp(0.0, 1.0)
    }
}