Skip to main content

strata_render/
gpu_wgpu.rs

1//! Hardware-accelerated `wgpu` 3D renderer with double-single RTE precision and
2//! single-draw-call programmable vertex pulling for planetary/terrain tile pyramids.
3
4use crate::scene3d::{
5    Background3D, Camera3D, Geometry3D, Light3D, Material3D, Mesh3D, RetainedCameraUniforms,
6    RetainedDynamicMesh, RetainedEnvironmentAssets, RetainedOceanSurface,
7    RetainedParticleBillboard, RetainedParticleLayer, RetainedParticleSprite, RetainedStar,
8    RetainedTerrainFrame, RetainedTileMesh, RetainedTileTexture, RteTileVertex, Scene3D, TileKeyId,
9};
10use bytemuck::{Pod, Zeroable};
11use std::collections::{BTreeMap, HashMap, HashSet};
12use std::sync::Arc;
13
14#[inline]
15fn gpu_perf_logging_enabled() -> bool {
16    static PERF_ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
17    *PERF_ENABLED.get_or_init(|| std::env::var_os("STRATA_PERF_LOG").is_some())
18}
19
20/// Default maximum new tile textures uploaded to the GPU atlas per frame during continuous flight.
21pub const DEFAULT_TEXTURE_UPLOAD_BUDGET: usize = 512;
22/// Default maximum new tile meshes copied to the GPU storage slab per frame.
23pub const DEFAULT_MESH_UPLOAD_BUDGET: usize = 512;
24/// Standard terrain imagery tile dimension in the GPU `Texture2DArray` atlas.
25pub const ATLAS_TILE_SIZE: u32 = 256;
26/// Maximum imagery layers pre-allocated in the GPU `Texture2DArray` atlas.
27pub const MAX_ATLAS_LAYERS: u32 = 1024;
28
29/// Splits a 64-bit float into `(hi, lo)` 32-bit floats for GPU double-single emulation.
30#[inline]
31pub fn split_f64_to_f32(v: f64) -> (f32, f32) {
32    let hi = v as f32;
33    let lo = (v - hi as f64) as f32;
34    (hi, lo)
35}
36
37fn transpose_mat4(m: [[f32; 4]; 4]) -> [[f32; 4]; 4] {
38    [
39        [m[0][0], m[1][0], m[2][0], m[3][0]],
40        [m[0][1], m[1][1], m[2][1], m[3][1]],
41        [m[0][2], m[1][2], m[2][2], m[3][2]],
42        [m[0][3], m[1][3], m[2][3], m[3][3]],
43    ]
44}
45
46fn invert_mat4(m: [[f32; 4]; 4]) -> [[f32; 4]; 4] {
47    let a = [
48        m[0][0] as f64,
49        m[0][1] as f64,
50        m[0][2] as f64,
51        m[0][3] as f64,
52        m[1][0] as f64,
53        m[1][1] as f64,
54        m[1][2] as f64,
55        m[1][3] as f64,
56        m[2][0] as f64,
57        m[2][1] as f64,
58        m[2][2] as f64,
59        m[2][3] as f64,
60        m[3][0] as f64,
61        m[3][1] as f64,
62        m[3][2] as f64,
63        m[3][3] as f64,
64    ];
65    let mut inv = [0.0f64; 16];
66    inv[0] = a[5] * a[10] * a[15] - a[5] * a[11] * a[14] - a[9] * a[6] * a[15]
67        + a[9] * a[7] * a[14]
68        + a[13] * a[6] * a[11]
69        - a[13] * a[7] * a[10];
70    inv[4] = -a[4] * a[10] * a[15] + a[4] * a[11] * a[14] + a[8] * a[6] * a[15]
71        - a[8] * a[7] * a[14]
72        - a[12] * a[6] * a[11]
73        + a[12] * a[7] * a[10];
74    inv[8] = a[4] * a[9] * a[15] - a[4] * a[11] * a[13] - a[8] * a[5] * a[15]
75        + a[8] * a[7] * a[13]
76        + a[12] * a[5] * a[11]
77        - a[12] * a[7] * a[9];
78    inv[12] = -a[4] * a[9] * a[14] + a[4] * a[10] * a[13] + a[8] * a[5] * a[14]
79        - a[8] * a[6] * a[13]
80        - a[12] * a[5] * a[10]
81        + a[12] * a[6] * a[9];
82    inv[1] = -a[1] * a[10] * a[15] + a[1] * a[11] * a[14] + a[9] * a[2] * a[15]
83        - a[9] * a[3] * a[14]
84        - a[13] * a[2] * a[11]
85        + a[13] * a[3] * a[10];
86    inv[5] = a[0] * a[10] * a[15] - a[0] * a[11] * a[14] - a[8] * a[2] * a[15]
87        + a[8] * a[3] * a[14]
88        + a[12] * a[2] * a[11]
89        - a[12] * a[3] * a[10];
90    inv[9] = -a[0] * a[9] * a[15] + a[0] * a[11] * a[13] + a[8] * a[1] * a[15]
91        - a[8] * a[3] * a[13]
92        - a[12] * a[1] * a[11]
93        + a[12] * a[3] * a[9];
94    inv[13] = a[0] * a[9] * a[14] - a[0] * a[10] * a[13] - a[8] * a[1] * a[14]
95        + a[8] * a[2] * a[13]
96        + a[12] * a[1] * a[10]
97        - a[12] * a[2] * a[9];
98    inv[2] = a[1] * a[6] * a[15] - a[1] * a[7] * a[14] - a[5] * a[2] * a[15]
99        + a[5] * a[3] * a[14]
100        + a[13] * a[2] * a[7]
101        - a[13] * a[3] * a[6];
102    inv[6] = -a[0] * a[6] * a[15] + a[0] * a[7] * a[14] + a[4] * a[2] * a[15]
103        - a[4] * a[3] * a[14]
104        - a[12] * a[2] * a[7]
105        + a[12] * a[3] * a[6];
106    inv[10] = a[0] * a[5] * a[15] - a[0] * a[7] * a[13] - a[4] * a[1] * a[15]
107        + a[4] * a[3] * a[13]
108        + a[12] * a[1] * a[7]
109        - a[12] * a[3] * a[5];
110    inv[14] = -a[0] * a[5] * a[14] + a[0] * a[6] * a[13] + a[4] * a[1] * a[14]
111        - a[4] * a[2] * a[13]
112        - a[12] * a[1] * a[6]
113        + a[12] * a[2] * a[5];
114    inv[3] = -a[1] * a[6] * a[11] + a[1] * a[7] * a[10] + a[5] * a[2] * a[11]
115        - a[5] * a[3] * a[10]
116        - a[9] * a[2] * a[7]
117        + a[9] * a[3] * a[6];
118    inv[7] = a[0] * a[6] * a[11] - a[0] * a[7] * a[10] - a[4] * a[2] * a[11]
119        + a[4] * a[3] * a[10]
120        + a[8] * a[2] * a[7]
121        - a[8] * a[3] * a[6];
122    inv[11] = -a[0] * a[5] * a[11] + a[0] * a[7] * a[9] + a[4] * a[1] * a[11]
123        - a[4] * a[3] * a[9]
124        - a[8] * a[1] * a[7]
125        + a[8] * a[3] * a[5];
126    inv[15] = a[0] * a[5] * a[10] - a[0] * a[6] * a[9] - a[4] * a[1] * a[10]
127        + a[4] * a[2] * a[9]
128        + a[8] * a[1] * a[6]
129        - a[8] * a[2] * a[5];
130
131    let det = a[0] * inv[0] + a[1] * inv[4] + a[2] * inv[8] + a[3] * inv[12];
132    if det.abs() < 1e-24 {
133        return [
134            [1.0, 0.0, 0.0, 0.0],
135            [0.0, 1.0, 0.0, 0.0],
136            [0.0, 0.0, 1.0, 0.0],
137            [0.0, 0.0, 0.0, 1.0],
138        ];
139    }
140    let inv_det = 1.0 / det;
141    let mut out = [[0.0f32; 4]; 4];
142    for c in 0..4 {
143        for r in 0..4 {
144            out[c][r] = (inv[c * 4 + r] * inv_det) as f32;
145        }
146    }
147    out
148}
149
150#[repr(C)]
151#[derive(Clone, Copy, Pod, Zeroable)]
152struct GpuCameraUniforms {
153    view_proj_rte: [[f32; 4]; 4],
154    inv_view_proj_rte: [[f32; 4]; 4],
155    ecef_from_icrf: [[f32; 4]; 4],
156    icrf_from_ecef: [[f32; 4]; 4],
157    light_view_proj_rte: [[f32; 4]; 4],
158    eye_high: [f32; 4],
159    eye_low: [f32; 4],
160    sun_dir: [f32; 4],            // xyz = sun dir, w = sun_visible (0/1)
161    sun_color: [f32; 4],          // rgb = color, w = sun_angular_radius_rad
162    ambient_color: [f32; 4],      // rgb = ambient, w = stars_intensity (0 when off)
163    sky_top: [f32; 4],
164    sky_bottom: [f32; 4],
165    moon_dir: [f32; 4],           // xyz = moon dir, w = moon_visible (0/1)
166    env_params: [f32; 4],         // x = day_night_strength, y = city_lights_intensity, z = local_25d_blend, w = moon_angular_radius_rad
167    cloud_params: [f32; 4],       // x = cloud_layer_opacity, y = cloud_lon_offset_rad, z = time_s, w = space_sky_enabled (0/1)
168    viewport_wh: [f32; 4],        // x = w, y = h, z = skybox_intensity, w = local_cloud_opacity
169    atmo_25d_params: [f32; 4],    // x = realistic_25d_sky, y = night_stars_25d, z = terrain_25d_lighting, w = terrain_25d_shadows
170    weather_opt_params: [f32; 4], // x = weather_darkness, y = weather_cloud_cover, z = weather_haze, w = shadow_radius_m
171    cloud_tint_params: [f32; 4],  // xyz = cloud_tint_rgb, w = cloud_25d_cover_boost
172    view_flags: [f32; 4],         // x = map_2d_morph (0..1), yzw = reserved
173}
174
175fn dot3_f64(a: [f64; 3], b: [f64; 3]) -> f64 {
176    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
177}
178
179fn cross3_f64(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
180    [
181        a[1] * b[2] - a[2] * b[1],
182        a[2] * b[0] - a[0] * b[2],
183        a[0] * b[1] - a[1] * b[0],
184    ]
185}
186
187fn norm3_f64(a: [f64; 3], fallback: [f64; 3]) -> [f64; 3] {
188    let l = dot3_f64(a, a).sqrt();
189    if l > 1e-9 {
190        [a[0] / l, a[1] / l, a[2] / l]
191    } else {
192        fallback
193    }
194}
195
196/// Computes a texel-snapped RTE orthographic directional shadow matrix (`light_view_proj_rte`)
197/// framing visible mountains and 3D objects around the camera. Returns `(matrix, shadow_radius_m, active)`.
198fn compute_shadow_light_vp_rte(
199    cam: &RetainedCameraUniforms,
200    shadow_map_size: u32,
201) -> ([[f32; 4]; 4], f32, bool) {
202    let ident = [
203        [1.0, 0.0, 0.0, 0.0],
204        [0.0, 1.0, 0.0, 0.0],
205        [0.0, 0.0, 1.0, 0.0],
206        [0.0, 0.0, 0.0, 1.0],
207    ];
208    if cam.terrain_25d_shadows <= 0.001 || cam.local_25d_blend <= 0.02 {
209        return (ident, 0.0, false);
210    }
211
212    let sun = norm3_f64(
213        [cam.sun_dir[0] as f64, cam.sun_dir[1] as f64, cam.sun_dir[2] as f64],
214        [0.0, 0.0, 1.0],
215    );
216    let eye = cam.eye_ecef;
217    let eye_r = dot3_f64(eye, eye).sqrt();
218    let (eye_up, eye_alt, is_planet) = if eye_r > 1_000_000.0 {
219        (
220            [eye[0] / eye_r, eye[1] / eye_r, eye[2] / eye_r],
221            (eye_r - 6_378_137.0).max(30.0),
222            true,
223        )
224    } else {
225        ([0.0, 1.0, 0.0], eye[1].abs().max(eye_r * 0.5).max(15.0), false)
226    };
227
228    let sun_elev = dot3_f64(sun, eye_up);
229    if sun_elev <= 0.025 {
230        return (ident, 0.0, false);
231    }
232
233    // Clamp grazing light angle slightly when constructing the shadow ortho box so distant peaks still fit cleanly.
234    let radius = if is_planet {
235        (eye_alt * 3.8).clamp(380.0, 28_000.0)
236    } else {
237        (eye_alt * 3.0).clamp(40.0, 1_000.0)
238    };
239    let depth_half = (radius * 2.4).max(if is_planet { 14_000.0 } else { 200.0 });
240
241    // Camera forward vector in world space is `-row2(view_rot)` (column-major: row 2 = [view_rot[0][2], view_rot[1][2], view_rot[2][2]]).
242    let cam_fwd = norm3_f64(
243        [
244            -(cam.view_rot[0][2] as f64),
245            -(cam.view_rot[1][2] as f64),
246            -(cam.view_rot[2][2] as f64),
247        ],
248        [0.0, 0.0, -1.0],
249    );
250    let fwd_dot_up = dot3_f64(cam_fwd, eye_up);
251    let fwd_horiz = norm3_f64(
252        [
253            cam_fwd[0] - eye_up[0] * fwd_dot_up,
254            cam_fwd[1] - eye_up[1] * fwd_dot_up,
255            cam_fwd[2] - eye_up[2] * fwd_dot_up,
256        ],
257        [1.0, 0.0, 0.0],
258    );
259
260    // Center shadow frustum slightly ahead of camera and down toward ground relief.
261    let fwd_shift = radius * 0.36;
262    let down_shift = if is_planet {
263        eye_alt.min(radius * 0.65)
264    } else {
265        eye_alt * 0.5
266    };
267    let center_rel = [
268        fwd_horiz[0] * fwd_shift - eye_up[0] * down_shift,
269        fwd_horiz[1] * fwd_shift - eye_up[1] * down_shift,
270        fwd_horiz[2] * fwd_shift - eye_up[2] * down_shift,
271    ];
272
273    // Orthonormal light basis: l_right, l_up perpendicular to sun direction.
274    let ref_up = if dot3_f64(sun, eye_up).abs() > 0.96 {
275        fwd_horiz
276    } else {
277        eye_up
278    };
279    let l_right = norm3_f64(cross3_f64(ref_up, sun), [1.0, 0.0, 0.0]);
280    let l_up = norm3_f64(cross3_f64(sun, l_right), [0.0, 1.0, 0.0]);
281
282    // Snap world shadow center in light space to texel increments to prevent shimmer while panning.
283    let world_center = [
284        eye[0] + center_rel[0],
285        eye[1] + center_rel[1],
286        eye[2] + center_rel[2],
287    ];
288    let texel_size = (2.0 * radius) / (shadow_map_size.clamp(512, 4096) as f64);
289    let cx_l = (dot3_f64(world_center, l_right) / texel_size).floor() * texel_size;
290    let cy_l = (dot3_f64(world_center, l_up) / texel_size).floor() * texel_size;
291    let cz_l = dot3_f64(world_center, sun);
292
293    let eye_x_l = dot3_f64(eye, l_right);
294    let eye_y_l = dot3_f64(eye, l_up);
295    let eye_z_l = dot3_f64(eye, sun);
296
297    let dx = eye_x_l - cx_l;
298    let dy = eye_y_l - cy_l;
299    let dz = eye_z_l - cz_l;
300
301    // Map world_rel -> light NDC:
302    // ndc_x = (dot(world_rel, l_right) + dx) / radius
303    // ndc_y = (dot(world_rel, l_up) + dy) / radius
304    // ndc_z = 0.5 - (dot(world_rel, sun) + dz) / (2 * depth_half)  (closer to sun = smaller depth in [0, 1])
305    let sx = 1.0 / radius;
306    let sy = 1.0 / radius;
307    let sz = -0.5 / depth_half;
308
309    let mat = [
310        [
311            (l_right[0] * sx) as f32,
312            (l_up[0] * sy) as f32,
313            (sun[0] * sz) as f32,
314            0.0,
315        ],
316        [
317            (l_right[1] * sx) as f32,
318            (l_up[1] * sy) as f32,
319            (sun[1] * sz) as f32,
320            0.0,
321        ],
322        [
323            (l_right[2] * sx) as f32,
324            (l_up[2] * sy) as f32,
325            (sun[2] * sz) as f32,
326            0.0,
327        ],
328        [
329            (dx * sx) as f32,
330            (dy * sy) as f32,
331            (0.5 + dz * sz) as f32,
332            1.0,
333        ],
334    ];
335    (mat, radius as f32, true)
336}
337
338impl GpuCameraUniforms {
339    fn from_retained(
340        cam: &RetainedCameraUniforms,
341        viewport_w: f32,
342        viewport_h: f32,
343        light_view_proj_rte: [[f32; 4]; 4],
344        shadow_radius_m: f32,
345        shadows_active: bool,
346    ) -> Self {
347        let (ex_hi, ex_lo) = split_f64_to_f32(cam.eye_ecef[0]);
348        let (ey_hi, ey_lo) = split_f64_to_f32(cam.eye_ecef[1]);
349        let (ez_hi, ez_lo) = split_f64_to_f32(cam.eye_ecef[2]);
350        let (sky_top, sky_bottom) = match cam.background {
351            Background3D::Transparent => ([0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]),
352            Background3D::Solid(c) => {
353                let rgba = [c.r(), c.g(), c.b(), c.a()];
354                (rgba, rgba)
355            }
356            Background3D::VerticalGradient { top, bottom } => (
357                [top.r(), top.g(), top.b(), top.a()],
358                [bottom.r(), bottom.g(), bottom.b(), bottom.a()],
359            ),
360        };
361        let inv_vp = invert_mat4(cam.view_proj_rte);
362        let icrf_from_ecef = transpose_mat4(cam.ecef_from_icrf);
363        let space_sky = if cam.stars_visible
364            || cam.sun_visible
365            || cam.moon_visible
366            || cam.realistic_25d_sky > 0.001
367            || (cam.map_2d_morph > 0.001 && !matches!(cam.background, Background3D::Solid(_)))
368        {
369            1.0
370        } else if matches!(cam.background, Background3D::Solid(_)) {
371            2.0
372        } else {
373            0.0
374        };
375        let stars_eff = if cam.stars_visible {
376            cam.stars_intensity.max(0.0)
377        } else {
378            0.0
379        };
380        let shadow_strength = if shadows_active {
381            cam.terrain_25d_shadows.clamp(0.0, 1.0)
382        } else {
383            0.0
384        };
385        Self {
386            view_proj_rte: cam.view_proj_rte,
387            inv_view_proj_rte: inv_vp,
388            ecef_from_icrf: cam.ecef_from_icrf,
389            icrf_from_ecef,
390            light_view_proj_rte,
391            eye_high: [ex_hi, ey_hi, ez_hi, 0.0],
392            eye_low: [ex_lo, ey_lo, ez_lo, 0.0],
393            sun_dir: [
394                cam.sun_dir[0],
395                cam.sun_dir[1],
396                cam.sun_dir[2],
397                if cam.sun_visible { 1.0 } else { 0.0 },
398            ],
399            sun_color: [
400                cam.sun_color[0],
401                cam.sun_color[1],
402                cam.sun_color[2],
403                cam.sun_angular_radius_rad,
404            ],
405            ambient_color: [
406                cam.ambient_color[0],
407                cam.ambient_color[1],
408                cam.ambient_color[2],
409                stars_eff,
410            ],
411            sky_top,
412            sky_bottom,
413            moon_dir: [
414                cam.moon_dir[0],
415                cam.moon_dir[1],
416                cam.moon_dir[2],
417                if cam.moon_visible { 1.0 } else { 0.0 },
418            ],
419            env_params: [
420                cam.day_night_strength,
421                cam.city_lights_intensity,
422                cam.local_25d_blend,
423                cam.moon_angular_radius_rad,
424            ],
425            cloud_params: [
426                cam.cloud_layer_opacity,
427                cam.cloud_lon_offset_rad,
428                cam.time_s,
429                space_sky,
430            ],
431            viewport_wh: [
432                viewport_w.max(1.0),
433                viewport_h.max(1.0),
434                cam.skybox_intensity.max(0.0),
435                cam.local_cloud_opacity.max(0.0),
436            ],
437            atmo_25d_params: [
438                cam.realistic_25d_sky.clamp(0.0, 1.0),
439                cam.night_stars_25d.clamp(0.0, 1.0),
440                cam.terrain_25d_lighting.clamp(0.0, 1.0),
441                shadow_strength,
442            ],
443            weather_opt_params: [
444                cam.weather_darkness.clamp(0.0, 1.0),
445                cam.weather_cloud_cover.clamp(0.0, 1.0),
446                cam.weather_haze.clamp(0.0, 1.0),
447                shadow_radius_m.max(0.0),
448            ],
449            cloud_tint_params: [
450                cam.cloud_tint_rgb[0].clamp(0.0, 2.0),
451                cam.cloud_tint_rgb[1].clamp(0.0, 2.0),
452                cam.cloud_tint_rgb[2].clamp(0.0, 2.0),
453                cam.cloud_25d_cover_boost.clamp(0.0, 1.0),
454            ],
455            view_flags: [cam.map_2d_morph.clamp(0.0, 1.0), 0.0, 0.0, 0.0],
456        }
457    }
458}
459
460const OCEAN_WORLD_NOISE_PERIOD_M: f64 = 32_768.0;
461const OCEAN_OCTAVE_ANGS: [f64; 8] = [0.04, -0.26, 0.42, -0.58, 0.77, -0.86, 0.21, -0.41];
462const OCEAN_OCTAVE_WLS: [f64; 8] = [151.0, 97.0, 61.0, 38.0, 23.5, 13.7, 7.9, 4.3];
463const OCEAN_OCTAVE_PHASES: [f64; 8] = [0.37, 2.18, 4.91, 1.09, 3.64, 5.47, 2.71, 0.83];
464
465#[repr(C)]
466#[derive(Clone, Copy, Pod, Zeroable)]
467struct GpuOceanUniforms {
468    origin_high: [f32; 4],     // xyz = split high f32 of ocean origin_ecef, w = enabled (0/1)
469    origin_low: [f32; 4],      // xyz = split low f32 of ocean origin_ecef, w = alt_fade
470    basis_east: [f32; 4],      // xyz = local ENU east, w = wave_strength
471    basis_north: [f32; 4],     // xyz = local ENU north, w = wave_scale
472    basis_up: [f32; 4],        // xyz = local ENU up, w = glint_intensity
473    train_a: [f32; 4],         // x = dir_e, y = dir_n, z = wind_speed_mps, w = phase_time_s
474    train_b: [f32; 4],         // x = dir_e, y = dir_n, z = wind_speed_mps, w = phase_time_s
475    blend_params: [f32; 4],    // x = weight_a, y = weight_b, z = opacity, w = coastal_shoaling (0/1)
476    coastal_params: [f32; 4],  // x = shoaling_range_m, y = sdf_half_span_m, z = sdf_center_e, w = sdf_center_n
477    world_meta: [f32; 4],      // x = wx mod P, y = wy mod P, z = origin_lat_rad, w = east_scale_25d (<0 => disabled)
478    train_a_phases0: [f32; 4], // f64-reduced base phases for train_a octaves 0..4 in [0, TAU)
479    train_a_phases1: [f32; 4], // f64-reduced base phases for train_a octaves 4..8 in [0, TAU)
480    train_b_phases0: [f32; 4], // f64-reduced base phases for train_b octaves 0..4 in [0, TAU)
481    train_b_phases1: [f32; 4], // f64-reduced base phases for train_b octaves 4..8 in [0, TAU)
482}
483
484impl GpuOceanUniforms {
485    fn compute_train_base_phases(
486        dir_en: [f64; 2],
487        wind_speed_mps: f64,
488        phase_time_s: f64,
489        wave_scale: f64,
490        world_origin_merc_m: [f64; 2],
491    ) -> ([f32; 4], [f32; 4]) {
492        let len_wind = 0.48 + (1.72 - 0.48) * (wind_speed_mps / 18.0).clamp(0.0, 1.3);
493        let ws = wave_scale.max(0.15);
494        let perp0 = [-dir_en[1], dir_en[0]];
495        let wx = world_origin_merc_m[0];
496        let wy = world_origin_merc_m[1];
497        let mut p = [0.0f32; 8];
498        for i in 0..8 {
499            let wl = ((OCEAN_OCTAVE_WLS[i] * len_wind) / ws).max(1.4);
500            let k = std::f64::consts::TAU / wl;
501            let omega = (9.81 * k).sqrt();
502            let (sa, ca) = OCEAN_OCTAVE_ANGS[i].sin_cos();
503            let dx = dir_en[0] * ca + perp0[0] * sa;
504            let dy = dir_en[1] * ca + perp0[1] * sa;
505            let base = (dx * wx + dy * wy) * k - omega * phase_time_s + OCEAN_OCTAVE_PHASES[i];
506            p[i] = base.rem_euclid(std::f64::consts::TAU) as f32;
507        }
508        ([p[0], p[1], p[2], p[3]], [p[4], p[5], p[6], p[7]])
509    }
510
511    fn disabled() -> Self {
512        Self {
513            origin_high: [0.0; 4],
514            origin_low: [0.0; 4],
515            basis_east: [1.0, 0.0, 0.0, 0.0],
516            basis_north: [0.0, 1.0, 0.0, 1.0],
517            basis_up: [0.0, 0.0, 1.0, 1.0],
518            train_a: [1.0, 0.0, 8.0, 0.0],
519            train_b: [1.0, 0.0, 8.0, 0.0],
520            blend_params: [1.0, 0.0, 0.0, 0.0],
521            coastal_params: [360.0, 1_500.0, 0.0, 0.0],
522            world_meta: [0.0, 0.0, 0.0, -1.0],
523            train_a_phases0: [0.0; 4],
524            train_a_phases1: [0.0; 4],
525            train_b_phases0: [0.0; 4],
526            train_b_phases1: [0.0; 4],
527        }
528    }
529
530    fn from_retained(ocean: &RetainedOceanSurface, has_sdf_tex: bool) -> Self {
531        if !ocean.enabled || ocean.alt_fade <= 0.002 || ocean.opacity <= 0.002 {
532            return Self::disabled();
533        }
534        let (ox_hi, ox_lo) = split_f64_to_f32(ocean.origin_ecef[0]);
535        let (oy_hi, oy_lo) = split_f64_to_f32(ocean.origin_ecef[1]);
536        let (oz_hi, oz_lo) = split_f64_to_f32(ocean.origin_ecef[2]);
537        let norm2_f64 = |v: [f32; 2]| -> [f64; 2] {
538            let vx = v[0] as f64;
539            let vy = v[1] as f64;
540            let l = (vx * vx + vy * vy).sqrt();
541            if l > 1e-6 {
542                [vx / l, vy / l]
543            } else {
544                [1.0, 0.0]
545            }
546        };
547        let da64 = norm2_f64(ocean.train_a.dir_en);
548        let db64 = norm2_f64(ocean.train_b.dir_en);
549        let da = [da64[0] as f32, da64[1] as f32];
550        let db = [db64[0] as f32, db64[1] as f32];
551        let wave_scale = ocean.wave_scale.clamp(0.15, 6.0);
552        let speed_a = ocean.train_a.wind_speed_mps.clamp(0.2, 60.0);
553        let speed_b = ocean.train_b.wind_speed_mps.clamp(0.2, 60.0);
554
555        let has_world = ocean.world_origin_merc_m[0].abs() > 1e-3
556            || ocean.world_origin_merc_m[1].abs() > 1e-3
557            || ocean.origin_lat_rad.abs() > 1e-5
558            || ocean.origin_ecef.iter().any(|v| v.abs() > 100.0);
559        let wx_mod = ocean.world_origin_merc_m[0].rem_euclid(OCEAN_WORLD_NOISE_PERIOD_M) as f32;
560        let wy_mod = ocean.world_origin_merc_m[1].rem_euclid(OCEAN_WORLD_NOISE_PERIOD_M) as f32;
561        let east_scale_meta = if has_world {
562            ocean.east_scale.clamp(0.15, 1.0)
563        } else {
564            -1.0
565        };
566        let (ta_p0, ta_p1) = Self::compute_train_base_phases(
567            da64,
568            speed_a as f64,
569            ocean.train_a.phase_time_s as f64,
570            wave_scale as f64,
571            ocean.world_origin_merc_m,
572        );
573        let (tb_p0, tb_p1) = Self::compute_train_base_phases(
574            db64,
575            speed_b as f64,
576            ocean.train_b.phase_time_s as f64,
577            wave_scale as f64,
578            ocean.world_origin_merc_m,
579        );
580
581        Self {
582            origin_high: [ox_hi, oy_hi, oz_hi, 1.0],
583            origin_low: [ox_lo, oy_lo, oz_lo, ocean.alt_fade.clamp(0.0, 1.0)],
584            basis_east: [
585                ocean.basis_east[0],
586                ocean.basis_east[1],
587                ocean.basis_east[2],
588                ocean.wave_strength.clamp(0.0, 4.0),
589            ],
590            basis_north: [
591                ocean.basis_north[0],
592                ocean.basis_north[1],
593                ocean.basis_north[2],
594                wave_scale,
595            ],
596            basis_up: [
597                ocean.basis_up[0],
598                ocean.basis_up[1],
599                ocean.basis_up[2],
600                ocean.glint_intensity.clamp(0.0, 4.0),
601            ],
602            train_a: [da[0], da[1], speed_a, ocean.train_a.phase_time_s],
603            train_b: [db[0], db[1], speed_b, ocean.train_b.phase_time_s],
604            blend_params: [
605                ocean.train_a.weight.clamp(0.0, 1.0),
606                ocean.train_b.weight.clamp(0.0, 1.0),
607                ocean.opacity.clamp(0.0, 1.0),
608                if ocean.coastal_shoaling && has_sdf_tex {
609                    1.0
610                } else {
611                    0.0
612                },
613            ],
614            coastal_params: [
615                ocean.shoaling_range_m.max(20.0),
616                ocean.sdf_half_span_m.max(50.0),
617                ocean.sdf_center_en_m[0],
618                ocean.sdf_center_en_m[1],
619            ],
620            world_meta: [wx_mod, wy_mod, ocean.origin_lat_rad, east_scale_meta],
621            train_a_phases0: ta_p0,
622            train_a_phases1: ta_p1,
623            train_b_phases0: tb_p0,
624            train_b_phases1: tb_p1,
625        }
626    }
627}
628
629#[repr(C)]
630#[derive(Clone, Copy, Pod, Zeroable)]
631struct GpuStar {
632    icrf_dir_mag: [f32; 4], // xyz = J2000 ICRF unit dir, w = vmag
633    color: [f32; 4],        // rgba
634}
635
636#[repr(C)]
637#[derive(Clone, Copy, Pod, Zeroable)]
638struct GpuTileInstance {
639    center_high: [f32; 4],
640    center_low: [f32; 4],
641    uv_rect: [f32; 4],
642    night_uv_rect: [f32; 4],
643    tint: [f32; 4],
644    tile_meta: [u32; 4], // x = base_vertex, y = atlas_layer, z = unlit (0/1), w = night_atlas_layer
645}
646
647#[repr(C)]
648#[derive(Clone, Copy, Pod, Zeroable)]
649struct GpuDynamicUniforms {
650    anchor_high: [f32; 4],
651    anchor_low: [f32; 4],
652    color: [f32; 4],
653    dyn_meta: [u32; 4], // x = unlit, y = use_vertex_color, z = use_texture, w = atlas_layer
654}
655
656#[repr(C)]
657#[derive(Clone, Copy, Pod, Zeroable)]
658struct GpuGeoInstance {
659    anchor_high: [f32; 4], // xyz = split high f32 of anchor_ecef
660    anchor_low: [f32; 4],  // xyz = split low f32 of anchor_ecef
661    col0: [f32; 4],        // xyz = model col 0 (+X East -> world m), w = roughness
662    col1: [f32; 4],        // xyz = model col 1 (+Y North -> world m), w = metalness
663    col2: [f32; 4],        // xyz = model col 2 (+Z Up -> world m), w = unlit (1.0 or 0.0)
664    base_color: [f32; 4],  // rgba
665    emissive: [f32; 4],    // xyz = emissive rgb, w = accent_mix
666}
667
668#[repr(C)]
669#[derive(Clone, Copy, Pod, Zeroable)]
670struct GpuParticleLayerUniforms {
671    basis_east: [f32; 4],      // xyz = local ENU east, w = wrapped_phase.x
672    basis_north: [f32; 4],     // xyz = local ENU north, w = wrapped_phase.y
673    basis_up: [f32; 4],        // xyz = local ENU up, w = wrapped_phase.z
674    forward_bias: [f32; 4],    // xyz = world-space forward cone center offset, w = 0.0
675    cam_right_mpx: [f32; 4],   // xyz = camera right world vec, w = meters_per_px_at_1m
676    cam_up_pad: [f32; 4],      // xyz = camera up world vec, w = 0.0
677    altitude_bounds: [f32; 4], // x = eye_alt_msl, y = ground_alt_msl, z = ceiling_alt_msl, w = ceiling_fade_m
678    volume_params: [f32; 4],   // x = extent_xy, y = extent_z, z = edge_fade_frac, w = near_fade_m
679    motion_params: [f32; 4],   // x = fall_speed_mps, y = wind_e, z = wind_n, w = wrapped_time_s
680    size_params: [f32; 4],     // x = width_m, y = height_m, z = velocity_stretch, w = spin_rad_s
681    flutter_clamp: [f32; 4],   // x = flutter_amp_m, y = flutter_freq_hz, z = min_px, w = max_px
682    color: [f32; 4],           // rgba
683    meta: [u32; 4],            // x = sprite_mode, y = billboard_mode, z = seed, w = particle_count
684}
685
686/// Builds a shared triangle index buffer for a terrain grid `(grid_res x grid_res)` with optional skirts.
687pub fn build_terrain_grid_indices(grid_res: u32, has_skirts: bool) -> Vec<u32> {
688    let n = grid_res.max(2);
689    let cells = n - 1;
690    let skirt_quads = if has_skirts { cells * 4 } else { 0 };
691    let mut indices = Vec::with_capacity(((cells * cells + skirt_quads) * 6) as usize);
692
693    for r in 0..cells {
694        for c in 0..cells {
695            let i00 = r * n + c;
696            let i10 = i00 + 1;
697            let i01 = (r + 1) * n + c;
698            let i11 = i01 + 1;
699            indices.extend_from_slice(&[i00, i10, i11, i00, i11, i01]);
700        }
701    }
702
703    if has_skirts {
704        let base = n * n;
705        // South edge (row = 0, facing -North): s1 -> s0 -> k0 -> k1
706        for c in 0..cells {
707            let s0 = c;
708            let s1 = c + 1;
709            let k0 = base + c;
710            let k1 = base + c + 1;
711            indices.extend_from_slice(&[s1, s0, k0, s1, k0, k1]);
712        }
713        // East edge (col = n-1, facing +East): s1 -> s0 -> k0 -> k1
714        let r_base = base + n;
715        for r in 0..cells {
716            let s0 = r * n + (n - 1);
717            let s1 = (r + 1) * n + (n - 1);
718            let k0 = r_base + r;
719            let k1 = r_base + r + 1;
720            indices.extend_from_slice(&[s1, s0, k0, s1, k0, k1]);
721        }
722        // North edge (row = n-1, facing +North): s0 -> s1 -> k1 -> k0
723        let b_base = base + n * 2;
724        for c in 0..cells {
725            let s0 = (n - 1) * n + c;
726            let s1 = s0 + 1;
727            let k0 = b_base + c;
728            let k1 = b_base + c + 1;
729            indices.extend_from_slice(&[s0, s1, k1, s0, k1, k0]);
730        }
731        // West edge (col = 0, facing -East): s0 -> s1 -> k1 -> k0
732        let l_base = base + n * 3;
733        for r in 0..cells {
734            let s0 = r * n;
735            let s1 = (r + 1) * n;
736            let k0 = l_base + r;
737            let k1 = l_base + r + 1;
738            indices.extend_from_slice(&[s0, s1, k1, s0, k1, k0]);
739        }
740    }
741
742    indices
743}
744
745const SKY_WGSL: &str = r#"
746struct GpuCameraUniforms {
747    view_proj_rte: mat4x4<f32>,
748    inv_view_proj_rte: mat4x4<f32>,
749    ecef_from_icrf: mat4x4<f32>,
750    icrf_from_ecef: mat4x4<f32>,
751    light_view_proj_rte: mat4x4<f32>,
752    eye_high: vec4<f32>,
753    eye_low: vec4<f32>,
754    sun_dir: vec4<f32>,
755    sun_color: vec4<f32>,
756    ambient_color: vec4<f32>,
757    sky_top: vec4<f32>,
758    sky_bottom: vec4<f32>,
759    moon_dir: vec4<f32>,
760    env_params: vec4<f32>,
761    cloud_params: vec4<f32>,
762    viewport_wh: vec4<f32>,
763    atmo_25d_params: vec4<f32>,
764    weather_opt_params: vec4<f32>,
765    cloud_tint_params: vec4<f32>,
766    view_flags: vec4<f32>,
767}
768
769@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
770@group(0) @binding(1) var moon_tex: texture_2d<f32>;
771@group(0) @binding(2) var env_sampler: sampler;
772@group(0) @binding(3) var skybox_cube: texture_cube<f32>;
773
774struct SkyOut {
775    @builtin(position) pos: vec4<f32>,
776    @location(0) uv_y: f32,
777    @location(1) ndc: vec2<f32>,
778    @location(2) ray_dir: vec3<f32>,
779}
780
781@vertex
782fn vs_sky(@builtin(vertex_index) vid: u32) -> SkyOut {
783    var positions = array<vec2<f32>, 3>(
784        vec2<f32>(-1.0, -3.0),
785        vec2<f32>(3.0, 1.0),
786        vec2<f32>(-1.0, 1.0),
787    );
788    let p = positions[vid];
789    let p4 = cam.inv_view_proj_rte * vec4<f32>(p, 0.5, 1.0);
790    let w_safe = select(p4.w, select(-1e-6, 1e-6, p4.w >= 0.0), abs(p4.w) < 1e-6);
791    var out: SkyOut;
792    out.pos = vec4<f32>(p, 0.9999, 1.0);
793    out.uv_y = clamp((1.0 - p.y) * 0.5, 0.0, 1.0);
794    out.ndc = p;
795    out.ray_dir = p4.xyz / w_safe;
796    return out;
797}
798
799fn hash31(p: vec3<f32>) -> f32 {
800    let q = fract(p * 0.1031);
801    let r = q + vec3<f32>(dot(q, q.yzx + vec3<f32>(33.33)));
802    return fract((r.x + r.y) * r.z);
803}
804
805fn noise3(p: vec3<f32>) -> f32 {
806    let i = floor(p);
807    let f = fract(p);
808    let u = f * f * (vec3<f32>(3.0) - 2.0 * f);
809    let a = hash31(i);
810    let b = hash31(i + vec3<f32>(1.0, 0.0, 0.0));
811    let c = hash31(i + vec3<f32>(0.0, 1.0, 0.0));
812    let d = hash31(i + vec3<f32>(1.0, 1.0, 0.0));
813    let e = hash31(i + vec3<f32>(0.0, 0.0, 1.0));
814    let f1 = hash31(i + vec3<f32>(1.0, 0.0, 1.0));
815    let g = hash31(i + vec3<f32>(0.0, 1.0, 1.0));
816    let h = hash31(i + vec3<f32>(1.0, 1.0, 1.0));
817    return mix(
818        mix(mix(a, b, u.x), mix(c, d, u.x), u.y),
819        mix(mix(e, f1, u.x), mix(g, h, u.x), u.y),
820        u.z,
821    );
822}
823
824fn eval_physical_sky_25d(
825    rd: vec3<f32>,
826    eye_up: vec3<f32>,
827    horiz_sin: f32,
828    sun_dir: vec3<f32>,
829    weather_dark: f32,
830    cloud_cov: f32,
831    haze: f32,
832) -> vec3<f32> {
833    let mu = dot(rd, eye_up);
834    let elev = mu - horiz_sin;
835    let h_elev = clamp(max(elev, 0.0), 0.0, 1.0);
836    let sun_elev = dot(sun_dir, eye_up);
837
838    // Kasten-Young optical air mass approximation for solar transmittance & Rayleigh scattering.
839    let sun_deg = max(sun_elev * 57.29578, -2.0);
840    let m_sun = 1.0 / (max(sun_elev, 0.008) + 0.15 * pow(max(sun_deg + 3.885, 0.45), -1.253));
841    let sun_trans = exp(-vec3<f32>(0.085, 0.195, 0.46) * clamp(m_sun * 0.48, 0.0, 18.0));
842
843    let day_t = smoothstep(-0.08, 0.24, sun_elev);
844    let twilight_t = smoothstep(-0.22, -0.02, sun_elev) * (1.0 - smoothstep(0.02, 0.22, sun_elev));
845    let golden_t = exp(-pow((sun_elev - 0.03) * 7.8, 2.0));
846
847    // Noon zenith/mid/horizon -> Golden sunset/sunrise -> Twilight -> Deep midnight indigo.
848    let noon_zenith = vec3<f32>(0.08, 0.23, 0.56);
849    let noon_mid = vec3<f32>(0.24, 0.50, 0.86);
850    let noon_horiz = vec3<f32>(0.72, 0.85, 0.96);
851
852    let sunset_zenith = vec3<f32>(0.09, 0.13, 0.30);
853    let sunset_mid = vec3<f32>(0.36, 0.26, 0.36);
854    let sunset_horiz = vec3<f32>(0.96, 0.48, 0.19);
855
856    let night_zenith = vec3<f32>(0.006, 0.011, 0.026);
857    let night_mid = vec3<f32>(0.012, 0.020, 0.044);
858    let night_horiz = vec3<f32>(0.024, 0.038, 0.068);
859
860    let day_zen = mix(sunset_zenith, noon_zenith, smoothstep(0.02, 0.35, sun_elev));
861    let day_mid_c = mix(sunset_mid, noon_mid, smoothstep(0.02, 0.35, sun_elev));
862    let day_hor = mix(sunset_horiz, noon_horiz, smoothstep(0.02, 0.32, sun_elev));
863
864    let zenith_c = mix(night_zenith, day_zen, day_t) + vec3<f32>(0.03, 0.04, 0.09) * twilight_t;
865    let mid_c = mix(night_mid, day_mid_c, day_t) + vec3<f32>(0.10, 0.07, 0.12) * twilight_t;
866    let horiz_c = mix(night_horiz, day_hor, day_t) + vec3<f32>(0.34, 0.16, 0.10) * twilight_t;
867
868    let zenith_t = pow(clamp(h_elev * 1.85, 0.0, 1.0), 0.58);
869    let dome = mix(mid_c, zenith_c, zenith_t);
870    let optical_haze = exp(-h_elev * mix(10.0, 5.2, clamp(haze * 0.7 + weather_dark * 0.4, 0.0, 1.0)));
871
872    // Henyey-Greenstein forward Mie scattering around the sun direction.
873    let cos_theta = clamp(dot(rd, sun_dir), -1.0, 1.0);
874    let g_mie = 0.76;
875    let hg = (1.0 - g_mie * g_mie) / pow(max(1.0 + g_mie * g_mie - 2.0 * g_mie * cos_theta, 0.04), 1.5);
876    let sun_above = smoothstep(-0.08, 0.06, sun_elev);
877    let cloud_atten = 1.0 - clamp(weather_dark * 0.78 + cloud_cov * 0.35, 0.0, 0.92);
878    let mie_glow = (vec3<f32>(0.98, 0.84, 0.62) * sun_trans + vec3<f32>(0.55, 0.24, 0.06) * golden_t)
879        * clamp(hg * 0.048, 0.0, 1.35)
880        * sun_above
881        * cloud_atten
882        * (0.35 + 0.65 * exp(-h_elev * 2.2));
883
884    // Anti-solar / azimuth sunset band along the horizon toward the sun.
885    let sun_az_glow = pow(max(cos_theta, 0.0), 3.0) * (golden_t * 0.75 + twilight_t * 0.55)
886        * exp(-h_elev * 4.5) * cloud_atten;
887    let sunset_band = vec3<f32>(1.0, 0.46, 0.16) * sun_az_glow * 0.65;
888
889    var sky = mix(dome, horiz_c, clamp(optical_haze * 0.92, 0.0, 1.0)) + mie_glow + sunset_band;
890
891    // Weather / overcast cloud darkening & slate desaturation.
892    let storm_w = clamp(weather_dark * 0.82 + cloud_cov * 0.22, 0.0, 0.92);
893    if (storm_w > 0.002) {
894        let luma = dot(sky, vec3<f32>(0.299, 0.587, 0.114));
895        let overcast_day = mix(vec3<f32>(0.20, 0.24, 0.29), vec3<f32>(0.42, 0.47, 0.54), optical_haze);
896        let overcast_night = vec3<f32>(0.015, 0.020, 0.030);
897        let overcast_col = mix(overcast_night, overcast_day, clamp(day_t + twilight_t * 0.35, 0.0, 1.0));
898        let desaturated = mix(sky, vec3<f32>(luma) * vec3<f32>(0.88, 0.94, 1.02), storm_w * 0.65);
899        sky = mix(desaturated, overcast_col, storm_w * 0.68);
900    }
901
902    let below_t = smoothstep(0.0, 0.06, -elev);
903    let ground_mist = mix(
904        mix(night_horiz, horiz_c * 0.88, clamp(day_t + twilight_t * 0.5, 0.0, 1.0)),
905        vec3<f32>(0.26, 0.30, 0.36) * max(day_t, 0.08),
906        storm_w * 0.70,
907    );
908    return mix(sky, ground_mist, below_t);
909}
910
911@fragment
912fn fs_sky(in: SkyOut) -> @location(0) vec4<f32> {
913    let rd = normalize(in.ray_dir);
914    let rd_icrf = normalize((cam.icrf_from_ecef * vec4<f32>(rd, 0.0)).xyz);
915    // Derivatives must remain in uniform control flow for WGSL validation.
916    let dx_icrf = dpdx(rd_icrf);
917    let dy_icrf = dpdy(rd_icrf);
918    if (cam.cloud_params.w > 1.5) {
919        return cam.sky_top;
920    }
921
922    let space_t = 1.0 - smoothstep(0.0, 0.85, cam.env_params.z);
923    let map_2d = clamp(cam.view_flags.x, 0.0, 1.0);
924    let morph_clear = 1.0 - smoothstep(0.0, 0.85, map_2d);
925    let sun_dir = normalize(cam.sun_dir.xyz);
926    let real_sky_w = clamp(cam.atmo_25d_params.x, 0.0, 1.0);
927    let night_star_w = clamp(cam.atmo_25d_params.y, 0.0, 1.0);
928    let weather_dark = clamp(cam.weather_opt_params.x, 0.0, 1.0);
929    let cloud_cov = clamp(cam.weather_opt_params.y, 0.0, 1.0);
930    let weather_haze = clamp(cam.weather_opt_params.z, 0.0, 1.0);
931
932    let eye_pos = cam.eye_high.xyz + cam.eye_low.xyz;
933    let eye_r = length(eye_pos);
934    let eye_up = select(vec3<f32>(0.0, 1.0, 0.0), eye_pos / max(eye_r, 1.0), eye_r > 1000000.0);
935    let r_earth = 6378137.0;
936    let horiz_sin = select(
937        0.0,
938        -sqrt(max(eye_r * eye_r - r_earth * r_earth, 0.0)) / max(eye_r, r_earth),
939        eye_r > 1000000.0,
940    );
941    let elev = dot(rd, eye_up) - horiz_sin;
942    let sun_elev = dot(sun_dir, eye_up);
943
944    var atmo_sky = vec3<f32>(0.0);
945    if (cam.cloud_params.w < 0.5 || space_t < 0.999) {
946        let sky_grad_2d = mix(cam.sky_top, cam.sky_bottom, clamp(in.uv_y, 0.0, 1.0));
947        var classic_sky = sky_grad_2d.rgb;
948        if (eye_r > 1000000.0) {
949            let h_elev = clamp(max(elev, 0.0), 0.0, 1.0);
950            let day_scale = clamp(max(cam.sky_bottom.b, max(cam.sky_bottom.r, cam.sky_bottom.g)), 0.0, 1.0);
951            let zenith_col = vec3<f32>(0.10, 0.25, 0.55) * day_scale;
952            let mid_col = vec3<f32>(0.27, 0.53, 0.86) * day_scale;
953            let horizon_mist = vec3<f32>(0.75, 0.86, 0.96) * day_scale;
954
955            let zenith_t = pow(clamp(h_elev * 1.85, 0.0, 1.0), 0.58);
956            let base_dome = mix(mid_col, zenith_col, zenith_t);
957            let optical_haze = exp(-h_elev * 10.5);
958            let mie_sun = pow(max(dot(rd, sun_dir), 0.0), 5.0) * (1.0 - smoothstep(0.0, 0.45, h_elev));
959            let warm_mist = horizon_mist + vec3<f32>(0.12, 0.09, 0.04) * mie_sun * day_scale;
960            let above_sky = mix(base_dome, warm_mist, clamp(optical_haze * 0.90, 0.0, 1.0));
961            let below_t = smoothstep(0.0, 0.06, -elev);
962            let ground_mist = vec3<f32>(0.64, 0.77, 0.90) * day_scale;
963            classic_sky = mix(above_sky, ground_mist, below_t);
964        }
965        // Subtle weather darkening even in classic mode if base weather API explicitly supplies storm_darkness.
966        if (weather_dark > 0.002 && real_sky_w < 0.999) {
967            let classic_storm = vec3<f32>(0.24, 0.29, 0.36);
968            classic_sky = mix(classic_sky, classic_storm, weather_dark * 0.62);
969        }
970        if (real_sky_w > 0.001) {
971            let phys_sky = eval_physical_sky_25d(rd, eye_up, horiz_sin, sun_dir, weather_dark, cloud_cov, weather_haze);
972            atmo_sky = mix(classic_sky, phys_sky, real_sky_w);
973        } else {
974            atmo_sky = classic_sky;
975        }
976        atmo_sky = mix(sky_grad_2d.rgb, atmo_sky, morph_clear);
977        if (cam.cloud_params.w < 0.5 && map_2d <= 0.001) {
978            return vec4<f32>(atmo_sky, sky_grad_2d.a);
979        }
980    }
981
982    // Effective skybox visibility: full in orbital space, plus smooth night-sky emergence in 2.5D when synced!
983    let sky_clear_factor = 1.0 - clamp(cloud_cov * 0.85 + weather_dark * 0.55, 0.0, 0.98);
984    let night_sun_t = 1.0 - smoothstep(-0.14, 0.04, sun_elev);
985    let night_vis_25d = night_sun_t
986        * night_star_w
987        * sky_clear_factor
988        * smoothstep(-0.005, 0.08, elev);
989    let skybox_vis = max(space_t, night_vis_25d * (1.0 - space_t)) * morph_clear;
990
991    // 1. Pitch-black deep space + J2000 ICRF telescope skybox cubemap (or procedural Milky Way fallback)
992    var space_col = vec3<f32>(0.0);
993    if (cam.ambient_color.w > 0.001 && skybox_vis > 0.001) {
994        let cube_dim = max(f32(textureDimensions(skybox_cube, 0).x), 1.0);
995        let texel_sq = (cube_dim * cube_dim * 0.25) * max(dot(dx_icrf, dx_icrf), dot(dy_icrf, dy_icrf));
996        let sky_lod = max(0.5 * log2(max(texel_sq, 1.0)), 0.0);
997        let cube_s = textureSampleLevel(skybox_cube, env_sampler, rd_icrf, sky_lod);
998        let sky_gain = cam.viewport_wh.z;
999        if (cube_s.a > 0.01 && sky_gain > 0.001) {
1000            space_col += cube_s.rgb * sky_gain * skybox_vis;
1001        } else {
1002            let gnp = vec3<f32>(-0.867666, -0.198076, 0.455984);
1003            let sin_b = dot(rd_icrf, gnp);
1004            if (abs(sin_b) < 0.35) {
1005                let gc = vec3<f32>(-0.054876, -0.873437, -0.483835);
1006                let core_w = 0.35 + 0.65 * max(dot(rd_icrf, gc), 0.0);
1007                let dust_n = noise3(rd_icrf * 7.5) * 0.65 + noise3(rd_icrf * 17.0) * 0.35;
1008                let rift = smoothstep(0.015, 0.14, abs(sin_b) + (dust_n - 0.5) * 0.09);
1009                let mw = exp(-pow(abs(sin_b) * 8.0, 1.5)) * core_w * (0.45 + 0.55 * dust_n) * mix(0.45, 1.0, rift);
1010                space_col += vec3<f32>(0.075, 0.095, 0.165) * mw * min(cam.ambient_color.w, 1.8) * skybox_vis;
1011            }
1012        }
1013    }
1014
1015    // Blend pitch-black space to 3D horizon-anchored atmospheric sky when morphing down into 2.5D,
1016    // keeping night Milky Way cubemap cleanly additive over the dark 2.5D night sky!
1017    var col = space_col;
1018    if (space_t < 0.999) {
1019        col = mix(atmo_sky + space_col * 1.15, space_col, space_t);
1020    }
1021
1022    // 2. Realistic Sun (photosphere limb darkening + solar corona + atmospheric aureole in 2.5D)
1023    if (cam.sun_dir.w > 0.5) {
1024        let sun_cos = clamp(dot(rd, sun_dir), -1.0, 1.0);
1025        if (sun_cos > 0.80) {
1026            let sun_ang = acos(sun_cos);
1027            let r_sun = max(cam.sun_color.w, 0.004);
1028            let above_horiz = mix(smoothstep(-0.025, 0.015, elev), 1.0, space_t);
1029            let atmo_sun_atten = mix(1.0 - clamp(weather_dark * 0.82 + cloud_cov * 0.45, 0.0, 0.95), 1.0, space_t);
1030            let sunset_warm = mix(
1031                mix(vec3<f32>(1.0, 0.56, 0.24), vec3<f32>(1.0, 0.98, 0.92), smoothstep(-0.02, 0.28, sun_elev)),
1032                vec3<f32>(1.0, 0.98, 0.95),
1033                space_t,
1034            );
1035            let sun_vis = above_horiz * atmo_sun_atten;
1036            if (sun_vis > 0.002) {
1037                if (sun_ang < r_sun * 1.08) {
1038                    let mu_s = sqrt(max(1.0 - (sun_ang / r_sun) * (sun_ang / r_sun), 0.0));
1039                    let aa = (1.0 - smoothstep(r_sun * 0.94, r_sun * 1.06, sun_ang)) * sun_vis;
1040                    let limb = mix(0.48, 1.0, pow(mu_s, 0.45));
1041                    col = mix(col, cam.sun_color.rgb * sunset_warm * (3.6 * limb), aa);
1042                }
1043                let corona = exp(-sun_ang / (r_sun * 2.4)) * 0.85 + exp(-sun_ang / (r_sun * 12.0)) * 0.14;
1044                col += cam.sun_color.rgb * sunset_warm * corona * mix(0.62, 1.0, space_t) * sun_vis;
1045            }
1046        }
1047    }
1048
1049    // 3. Realistic Moon (NASA LRO albedo + Lommel-Seeliger phase from Sun vector + Earthshine)
1050    if (cam.moon_dir.w > 0.5) {
1051        let m_dir = normalize(cam.moon_dir.xyz);
1052        let b_cos = dot(rd, m_dir);
1053        let r_moon = max(cam.env_params.w, 0.004);
1054        let above_horiz_m = mix(smoothstep(-0.02, 0.02, elev), 1.0, space_t);
1055        if (above_horiz_m > 0.005 && b_cos > 1.0 - 0.501 * r_moon * r_moon) {
1056            let sin_r = sin(r_moon);
1057            let r2 = sin_r * sin_r;
1058            let d2 = max(1.0 - b_cos * b_cos, 0.0);
1059            if (d2 < r2) {
1060                let z_m = sqrt(max(r2 - d2, 0.0));
1061                let n_perp = rd - m_dir * b_cos;
1062                let n_moon = normalize(n_perp / sin_r - m_dir * (z_m / sin_r));
1063
1064                let up_icrf = normalize((cam.ecef_from_icrf * vec4<f32>(0.0, 0.0, 1.0, 0.0)).xyz);
1065                let ref_up = select(vec3<f32>(0.0, 1.0, 0.0), up_icrf, abs(dot(up_icrf, m_dir)) < 0.98);
1066                let m_right = normalize(cross(m_dir, ref_up));
1067                let m_up = normalize(cross(m_right, m_dir));
1068                let lx = dot(n_moon, m_right);
1069                let ly = dot(n_moon, m_up);
1070                let lz = dot(n_moon, -m_dir);
1071                let u = atan2(lx, lz) / 6.28318530718 + 0.5;
1072                let v = clamp(0.5 - asin(clamp(ly, -1.0, 1.0)) / 3.14159265359, 0.001, 0.999);
1073                let albedo = textureSampleLevel(moon_tex, env_sampler, vec2<f32>(u, v), 0.0).rgb;
1074
1075                let ndotl_m = max(dot(n_moon, sun_dir), 0.0);
1076                let ndotv_m = max(dot(n_moon, -rd), 0.02);
1077                let lommel = ndotl_m / (ndotl_m + 0.36 * ndotv_m + 0.06);
1078                let earthshine = vec3<f32>(0.024, 0.032, 0.048);
1079                let lit_moon = albedo * (cam.sun_color.rgb * lommel * 1.45 + earthshine);
1080                let aa_m = (1.0 - smoothstep(r2 * 0.90, r2, d2)) * above_horiz_m;
1081                let moon_night_t = 1.0 - smoothstep(-0.10, 0.10, sun_elev);
1082                let moon_25d_vis = mix(0.32, 0.98, moon_night_t) * sky_clear_factor;
1083                col = mix(col, max(col, lit_moon), aa_m * mix(moon_25d_vis, 1.0, space_t));
1084            }
1085        }
1086    }
1087
1088    return vec4<f32>(col, 1.0);
1089}
1090"#;
1091
1092const STARS_WGSL: &str = r#"
1093struct GpuCameraUniforms {
1094    view_proj_rte: mat4x4<f32>,
1095    inv_view_proj_rte: mat4x4<f32>,
1096    ecef_from_icrf: mat4x4<f32>,
1097    icrf_from_ecef: mat4x4<f32>,
1098    light_view_proj_rte: mat4x4<f32>,
1099    eye_high: vec4<f32>,
1100    eye_low: vec4<f32>,
1101    sun_dir: vec4<f32>,
1102    sun_color: vec4<f32>,
1103    ambient_color: vec4<f32>,
1104    sky_top: vec4<f32>,
1105    sky_bottom: vec4<f32>,
1106    moon_dir: vec4<f32>,
1107    env_params: vec4<f32>,
1108    cloud_params: vec4<f32>,
1109    viewport_wh: vec4<f32>,
1110    atmo_25d_params: vec4<f32>,
1111    weather_opt_params: vec4<f32>,
1112    cloud_tint_params: vec4<f32>,
1113    view_flags: vec4<f32>,
1114}
1115
1116struct GpuStar {
1117    icrf_dir_mag: vec4<f32>,
1118    color: vec4<f32>,
1119}
1120
1121@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
1122@group(0) @binding(1) var<storage, read> stars: array<GpuStar>;
1123
1124struct StarVsOut {
1125    @builtin(position) clip_pos: vec4<f32>,
1126    @location(0) local_uv: vec2<f32>,
1127    @location(1) color_flux: vec4<f32>,
1128}
1129
1130@vertex
1131fn vs_star(
1132    @builtin(vertex_index) vid: u32,
1133    @builtin(instance_index) inst_id: u32,
1134) -> StarVsOut {
1135    var offsets = array<vec2<f32>, 6>(
1136        vec2<f32>(-1.0, -1.0),
1137        vec2<f32>(1.0, -1.0),
1138        vec2<f32>(1.0, 1.0),
1139        vec2<f32>(-1.0, -1.0),
1140        vec2<f32>(1.0, 1.0),
1141        vec2<f32>(-1.0, 1.0),
1142    );
1143    let q = offsets[vid];
1144    let s = stars[inst_id];
1145    let dir_ecef = normalize((cam.ecef_from_icrf * vec4<f32>(s.icrf_dir_mag.xyz, 0.0)).xyz);
1146    var clip = cam.view_proj_rte * vec4<f32>(dir_ecef, 0.0);
1147
1148    var out: StarVsOut;
1149    out.local_uv = q;
1150    let space_t = 1.0 - smoothstep(0.0, 0.80, cam.env_params.z);
1151
1152    let eye_pos = cam.eye_high.xyz + cam.eye_low.xyz;
1153    let eye_r = length(eye_pos);
1154    let eye_up = select(vec3<f32>(0.0, 1.0, 0.0), eye_pos / max(eye_r, 1.0), eye_r > 1000000.0);
1155    let r_earth = 6378137.0;
1156    let horiz_sin = select(
1157        0.0,
1158        -sqrt(max(eye_r * eye_r - r_earth * r_earth, 0.0)) / max(eye_r, r_earth),
1159        eye_r > 1000000.0,
1160    );
1161    let sun_elev = dot(normalize(cam.sun_dir.xyz), eye_up);
1162    let star_elev = dot(dir_ecef, eye_up) - horiz_sin;
1163    let sky_clear = 1.0 - clamp(cam.weather_opt_params.y * 0.85 + cam.weather_opt_params.x * 0.55, 0.0, 0.98);
1164    let night_sun_t = 1.0 - smoothstep(-0.14, 0.04, sun_elev);
1165    let night_vis_25d = night_sun_t
1166        * clamp(cam.atmo_25d_params.y, 0.0, 1.0)
1167        * sky_clear
1168        * smoothstep(0.002, 0.045, star_elev);
1169    let eff_vis = max(space_t, night_vis_25d * (1.0 - space_t));
1170
1171    if (clip.w <= 0.001 || eff_vis <= 0.005 || cam.ambient_color.w <= 0.001) {
1172        out.clip_pos = vec4<f32>(2.0, 2.0, 2.0, 1.0);
1173        out.color_flux = vec4<f32>(0.0);
1174        return out;
1175    }
1176
1177    let vmag = s.icrf_dir_mag.w;
1178    let boost_25d = mix(2.35, 1.0, space_t);
1179    let flux = clamp(pow(10.0, -0.32 * (vmag - 2.6)), 0.18, 3.6) * cam.ambient_color.w * eff_vis * boost_25d;
1180    let size_px = clamp(mix(1.85, 1.55, space_t) + (5.0 - vmag) * 0.58, 1.5, 4.8);
1181    clip.z = clip.w * 0.99985;
1182    let px_ndc = (q * size_px / max(cam.viewport_wh.xy, vec2<f32>(1.0, 1.0))) * 2.0;
1183    clip.x += px_ndc.x * clip.w;
1184    clip.y += px_ndc.y * clip.w;
1185
1186    out.clip_pos = clip;
1187    out.color_flux = vec4<f32>(s.color.rgb, flux);
1188    return out;
1189}
1190
1191@fragment
1192fn fs_star(in: StarVsOut) -> @location(0) vec4<f32> {
1193    let r2 = dot(in.local_uv, in.local_uv);
1194    if (r2 > 1.0) {
1195        return vec4<f32>(0.0);
1196    }
1197    let airy = exp(-r2 * 4.8);
1198    return vec4<f32>(in.color_flux.rgb * (in.color_flux.a * airy), airy);
1199}
1200"#;
1201
1202const TERRAIN_PULL_WGSL: &str = r#"
1203struct GpuCameraUniforms {
1204    view_proj_rte: mat4x4<f32>,
1205    inv_view_proj_rte: mat4x4<f32>,
1206    ecef_from_icrf: mat4x4<f32>,
1207    icrf_from_ecef: mat4x4<f32>,
1208    light_view_proj_rte: mat4x4<f32>,
1209    eye_high: vec4<f32>,
1210    eye_low: vec4<f32>,
1211    sun_dir: vec4<f32>,
1212    sun_color: vec4<f32>,
1213    ambient_color: vec4<f32>,
1214    sky_top: vec4<f32>,
1215    sky_bottom: vec4<f32>,
1216    moon_dir: vec4<f32>,
1217    env_params: vec4<f32>,
1218    cloud_params: vec4<f32>,
1219    viewport_wh: vec4<f32>,
1220    atmo_25d_params: vec4<f32>,
1221    weather_opt_params: vec4<f32>,
1222    cloud_tint_params: vec4<f32>,
1223    view_flags: vec4<f32>,
1224}
1225
1226struct GpuOceanUniforms {
1227    origin_high: vec4<f32>,
1228    origin_low: vec4<f32>,
1229    basis_east: vec4<f32>,
1230    basis_north: vec4<f32>,
1231    basis_up: vec4<f32>,
1232    train_a: vec4<f32>,
1233    train_b: vec4<f32>,
1234    blend_params: vec4<f32>,
1235    coastal_params: vec4<f32>,
1236    world_meta: vec4<f32>,
1237    train_a_phases0: vec4<f32>,
1238    train_a_phases1: vec4<f32>,
1239    train_b_phases0: vec4<f32>,
1240    train_b_phases1: vec4<f32>,
1241}
1242
1243struct GpuTileVertex {
1244    pos_u: vec4<f32>,
1245    norm_v: vec4<f32>,
1246}
1247
1248struct GpuTileInstance {
1249    center_high: vec4<f32>,
1250    center_low: vec4<f32>,
1251    uv_rect: vec4<f32>,
1252    night_uv_rect: vec4<f32>,
1253    tint: vec4<f32>,
1254    tile_meta: vec4<u32>,
1255}
1256
1257@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
1258@group(0) @binding(1) var<storage, read> vertices: array<GpuTileVertex>;
1259@group(0) @binding(2) var<storage, read> instances: array<GpuTileInstance>;
1260@group(0) @binding(3) var terrain_atlas: texture_2d_array<f32>;
1261@group(0) @binding(4) var terrain_sampler: sampler;
1262@group(0) @binding(5) var land_mask_tex: texture_2d<f32>;
1263@group(0) @binding(6) var env_wrap_sampler: sampler;
1264
1265@group(1) @binding(0) var shadow_map: texture_depth_2d;
1266@group(1) @binding(1) var shadow_sampler: sampler_comparison;
1267@group(1) @binding(2) var<uniform> ocean: GpuOceanUniforms;
1268@group(1) @binding(3) var coastal_sdf_tex: texture_2d<f32>;
1269@group(1) @binding(4) var coastal_sdf_sampler: sampler;
1270
1271fn dir_to_equirect_uv(d: vec3<f32>) -> vec2<f32> {
1272    let xy_len_sq = dot(d.xy, d.xy);
1273    let az = select(0.0, atan2(d.y, d.x), xy_len_sq > 1e-10);
1274    return vec2<f32>(
1275        fract(az * 0.15915494309 + 0.5),
1276        clamp(0.5 - asin(clamp(d.z, -1.0, 1.0)) * 0.31830988618, 0.001, 0.999),
1277    );
1278}
1279
1280struct TerrainVsOut {
1281    @builtin(position) clip_pos: vec4<f32>,
1282    @location(0) normal: vec3<f32>,
1283    @location(1) uv: vec2<f32>,
1284    @location(2) tint: vec4<f32>,
1285    @location(3) @interpolate(flat) tex_layer: u32,
1286    @location(4) @interpolate(flat) unlit: u32,
1287    @location(5) ecef_pos: vec3<f32>,
1288    @location(6) view_rel: vec3<f32>,
1289    @location(7) night_uv: vec2<f32>,
1290    @location(8) @interpolate(flat) night_layer: u32,
1291    @location(9) land_uv_approx: vec2<f32>,
1292    @location(10) world_mod_256: vec3<f32>,
1293}
1294
1295fn hash21(p: vec2<f32>) -> f32 {
1296    var q = fract(p * vec2<f32>(0.1031, 0.1030));
1297    q += dot(q, q.yx + 33.33);
1298    return fract((q.x + q.y) * q.x);
1299}
1300
1301fn vnoise2(x: vec2<f32>) -> f32 {
1302    let i = floor(x);
1303    let f = fract(x);
1304    let u = f * f * (3.0 - 2.0 * f);
1305    let n00 = hash21(i);
1306    let n10 = hash21(i + vec2<f32>(1.0, 0.0));
1307    let n01 = hash21(i + vec2<f32>(0.0, 1.0));
1308    let n11 = hash21(i + vec2<f32>(1.0, 1.0));
1309    return mix(mix(n00, n10, u.x), mix(n01, n11, u.x), u.y);
1310}
1311
1312// Wraps global Mercator noise offset seamlessly into [0, 32768) m for bit-exact pan/zoom stability.
1313fn ocean_noise_wrap(p_m: vec2<f32>) -> vec2<f32> {
1314    return fract(p_m * (1.0 / 32768.0)) * 32768.0;
1315}
1316
1317// Maps local ENU metres near `ocean.origin` to invariant global Mercator delta metres
1318// so crossing quantized origin cells or 3D<->2.5D morph bands produces zero wave phase jumps.
1319fn ocean_merc_from_en(pos_en: vec2<f32>, blend_25d: f32) -> vec2<f32> {
1320    if (ocean.world_meta.w < 0.0) {
1321        return pos_en;
1322    }
1323    let orig_lat_rad = ocean.world_meta.z;
1324    let east_scale_25d = ocean.world_meta.w;
1325    let dlat_est = clamp(pos_en.y * (1.0 / 6378137.0), -0.4, 0.4);
1326    let cos_curved = max(cos(clamp(orig_lat_rad + dlat_est, -1.483, 1.483)), 0.15);
1327    let cos_eff_e = max(mix(cos_curved, east_scale_25d, blend_25d), 0.15);
1328    let cos_eff_n = max(cos(clamp(orig_lat_rad + 0.5 * dlat_est, -1.483, 1.483)), 0.15);
1329    return vec2<f32>(pos_en.x / cos_eff_e, pos_en.y / cos_eff_n);
1330}
1331
1332// C2 quintic periodic 2D Perlin gradient noise rotated by integer Pythagorean matrix `rot = (rx, ry)`
1333// where `32768.0 * inv_cell == period` (exact integer wrapping across the 32768 m world tile boundary).
1334// `seed` decorrelates independent octaves after modulo wrapping without breaking periodicity.
1335// Returns vec3(value in [0,1], grad_x, grad_y) with normalized dimensionless gradient.
1336fn wrap_period2(i_raw: vec2<f32>, period: f32) -> vec2<f32> {
1337    let w = i_raw - floor(i_raw * (1.0 / period)) * period;
1338    let w_pos = select(w, w + vec2<f32>(period), w < vec2<f32>(0.0));
1339    return select(w_pos, w_pos - vec2<f32>(period), w_pos >= vec2<f32>(period));
1340}
1341
1342fn pgrad2_periodic_rot(
1343    p_mod: vec2<f32>,
1344    inv_cell: f32,
1345    period: f32,
1346    rot: vec2<f32>,
1347    seed: vec2<f32>,
1348) -> vec3<f32> {
1349    let q = p_mod * inv_cell;
1350    let x = vec2<f32>(rot.x * q.x - rot.y * q.y, rot.y * q.x + rot.x * q.y);
1351    let i0_raw = floor(x);
1352    let f = fract(x);
1353    let u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
1354    let one_minus_f = 1.0 - f;
1355    let du = 30.0 * f * f * one_minus_f * one_minus_f;
1356
1357    let a = wrap_period2(i0_raw, period);
1358    let b = wrap_period2(a + vec2<f32>(1.0), period);
1359
1360    let ang00 = 6.2831853 * hash21(vec2<f32>(a.x, a.y) + seed);
1361    let ang10 = 6.2831853 * hash21(vec2<f32>(b.x, a.y) + seed);
1362    let ang01 = 6.2831853 * hash21(vec2<f32>(a.x, b.y) + seed);
1363    let ang11 = 6.2831853 * hash21(vec2<f32>(b.x, b.y) + seed);
1364
1365    let g00 = vec2<f32>(cos(ang00), sin(ang00));
1366    let g10 = vec2<f32>(cos(ang10), sin(ang10));
1367    let g01 = vec2<f32>(cos(ang01), sin(ang01));
1368    let g11 = vec2<f32>(cos(ang11), sin(ang11));
1369
1370    let v00 = dot(g00, f);
1371    let v10 = dot(g10, f - vec2<f32>(1.0, 0.0));
1372    let v01 = dot(g01, f - vec2<f32>(0.0, 1.0));
1373    let v11 = dot(g11, f - vec2<f32>(1.0, 1.0));
1374
1375    let k1 = v10 - v00;
1376    let k2 = v01 - v00;
1377    let k3 = v00 - v10 - v01 + v11;
1378    let h = v00 + k1 * u.x + k2 * u.y + k3 * u.x * u.y;
1379    let val01 = clamp(h * 0.70 + 0.5, 0.0, 1.0);
1380
1381    let gx_u = mix(mix(g00.x, g10.x, u.x), mix(g01.x, g11.x, u.x), u.y);
1382    let gy_u = mix(mix(g00.y, g10.y, u.x), mix(g01.y, g11.y, u.x), u.y);
1383    let dh_dx = gx_u + du.x * (k1 + k3 * u.y);
1384    let dh_dy = gy_u + du.y * (k2 + k3 * u.x);
1385
1386    let inv_rlen = 1.0 / max(length(rot), 1.0);
1387    let grad_norm = vec2<f32>(rot.x * dh_dx + rot.y * dh_dy, -rot.y * dh_dx + rot.x * dh_dy) * inv_rlen;
1388    return vec3<f32>(val01, grad_norm.x, grad_norm.y);
1389}
1390
1391// Returns Gerstner trochoidal wave displacement vec3(disp_east_m, disp_north_m, disp_up_m)
1392// for the 4 primary macro swells using world-locked phases and short-crested wave-group envelopes.
1393fn eval_ocean_vertex_train(
1394    d_merc: vec2<f32>,
1395    p_noise_base: vec2<f32>,
1396    wind_dir: vec2<f32>,
1397    wind_speed: f32,
1398    t: f32,
1399    wave_scale: f32,
1400    sample_scale_m: f32,
1401    sea_exposure: f32,
1402    phases0: vec4<f32>,
1403) -> vec3<f32> {
1404    let dir0 = normalize(wind_dir);
1405    let perp0 = vec2<f32>(-dir0.y, dir0.x);
1406
1407    let drift_m = ocean_noise_wrap(p_noise_base - dir0 * (t * 0.42));
1408    let n_warp1 = pgrad2_periodic_rot(drift_m, 1.0 / 512.0, 64.0, vec2<f32>(3.0, 4.0), vec2<f32>(11.3, 27.9)).x;
1409    let n_warp2 = pgrad2_periodic_rot(drift_m, 1.0 / 512.0, 64.0, vec2<f32>(8.0, 15.0), vec2<f32>(53.1, 19.7)).x;
1410    let warp_vec = vec2<f32>(n_warp1 - 0.5, n_warp2 - 0.5);
1411    let group_macro = 0.52 + 0.88 * (0.62 * n_warp1 + 0.38 * n_warp2);
1412
1413    // Physical Beaufort saturation curve: calm light air -> smooth ~1.38 asymptote at strong wind.
1414    let beaufort = clamp(1.38 * (1.0 - exp(-max(wind_speed, 0.3) / 10.5)), 0.10, 1.38);
1415    let len_wind = mix(0.48, 1.72, clamp(wind_speed / 18.0, 0.0, 1.3));
1416
1417    var angs = array<f32, 4>(0.04, -0.26, 0.42, -0.58);
1418    var wls = array<f32, 4>(151.0, 97.0, 61.0, 38.0);
1419    var amps = array<f32, 4>(0.025, 0.023, 0.020, 0.017);
1420    var base_ph = array<f32, 4>(phases0.x, phases0.y, phases0.z, phases0.w);
1421
1422    var disp = vec3<f32>(0.0);
1423    for (var i: u32 = 0u; i < 4u; i = i + 1u) {
1424        let wl = max((wls[i] * len_wind) / max(wave_scale, 0.15), 4.0);
1425        let aa_vs = 1.0 - smoothstep(wl * 0.32, wl * 1.05, sample_scale_m);
1426        if (aa_vs > 0.008) {
1427            let ca = cos(angs[i]);
1428            let sa = sin(angs[i]);
1429            let d = dir0 * ca + perp0 * sa;
1430            let k = 6.2831853 / wl;
1431            let p_eff = d_merc + warp_vec * min(wl * 0.48, 52.0);
1432            let ph = base_ph[i] + dot(d, p_eff) * k;
1433            let env_shift = mix(group_macro, 0.52 + 0.88 * n_warp2, select(0.18, 0.55, (i & 1u) == 1u));
1434            let steep = amps[i] * beaufort * sea_exposure * aa_vs * env_shift;
1435            let amp_m = (steep / k) * 0.56;
1436            let q_m = amp_m * 0.48;
1437            disp.x += d.x * (cos(ph) * q_m);
1438            disp.y += d.y * (cos(ph) * q_m);
1439            disp.z += sin(ph) * amp_m;
1440        }
1441    }
1442    return disp;
1443}
1444
1445@vertex
1446fn vs_terrain(
1447    @builtin(vertex_index) local_v: u32,
1448    @builtin(instance_index) inst_id: u32,
1449) -> TerrainVsOut {
1450    let inst = instances[inst_id];
1451    let v = vertices[inst.tile_meta.x + local_v];
1452    let center_rel = (inst.center_high.xyz - cam.eye_high.xyz)
1453                   + (inst.center_low.xyz - cam.eye_low.xyz);
1454    var world_rel = center_rel + v.pos_u.xyz;
1455    let raw_uv = vec2<f32>(v.pos_u.w, v.norm_v.w);
1456    var ecef_p = (inst.center_high.xyz + inst.center_low.xyz) + v.pos_u.xyz;
1457    let dv = normalize(ecef_p);
1458    let land_uv = dir_to_equirect_uv(dv);
1459
1460    let map_2d = clamp(cam.view_flags.x, 0.0, 1.0);
1461    let ocean_on = ocean.origin_high.w * ocean.origin_low.w * (1.0 - map_2d);
1462    if (ocean_on > 0.002 && inst.tile_meta.z == 0u) {
1463        let cam_minus_orig = (cam.eye_high.xyz - ocean.origin_high.xyz)
1464                           + (cam.eye_low.xyz - ocean.origin_low.xyz);
1465        let p_rel_orig = world_rel + cam_minus_orig;
1466        let east_v = ocean.basis_east.xyz;
1467        let north_v = ocean.basis_north.xyz;
1468        let up_v = ocean.basis_up.xyz;
1469        let pos_en = vec2<f32>(dot(p_rel_orig, east_v), dot(p_rel_orig, north_v));
1470        let rel_h = dot(p_rel_orig, up_v);
1471        let eye_pos = cam.eye_high.xyz + cam.eye_low.xyz;
1472        let eye_r = length(eye_pos);
1473        let blend_25d = clamp(cam.env_params.z, 0.0, 1.0) * (1.0 - map_2d);
1474        let curve_sag = select(0.0, 1.0, eye_r > 1000000.0)
1475            * (1.0 - blend_25d)
1476            * dot(pos_en, pos_en)
1477            / (2.0 * 6378137.0);
1478        let sea_elev = rel_h + curve_sag;
1479        let elev_water = 1.0 - smoothstep(-0.25, 2.2, sea_elev);
1480        let env_mask_vs = textureSampleLevel(land_mask_tex, env_wrap_sampler, land_uv, 0.0).r;
1481        let open_ocean_vs = 1.0 - smoothstep(0.04, 0.52, env_mask_vs);
1482
1483        let half_span = max(ocean.coastal_params.y, 50.0);
1484        let sdf_uv = (pos_en - ocean.coastal_params.zw) / (2.0 * half_span) + vec2<f32>(0.5);
1485        let in_sdf = smoothstep(0.01, 0.09, sdf_uv.x) * (1.0 - smoothstep(0.91, 0.99, sdf_uv.x))
1486                   * smoothstep(0.01, 0.09, sdf_uv.y) * (1.0 - smoothstep(0.91, 0.99, sdf_uv.y));
1487        let sdf_s = textureSampleLevel(
1488            coastal_sdf_tex,
1489            coastal_sdf_sampler,
1490            clamp(sdf_uv, vec2<f32>(0.002), vec2<f32>(0.998)),
1491            0.0,
1492        );
1493        let use_sdf = ocean.blend_params.w * in_sdf;
1494        let shore_dist_norm = mix(1.0, sdf_s.g, use_sdf);
1495        let shore_taper = mix(1.0, smoothstep(0.02, 0.16, shore_dist_norm), use_sdf);
1496        let near_exp_vs = mix(0.32, 0.78, smoothstep(0.06, 0.88, shore_dist_norm));
1497        let open_exp_vs = mix(0.38, 1.0, smoothstep(0.05, 0.92, open_ocean_vs));
1498        let sea_exposure_vs = mix(
1499            1.0,
1500            max(near_exp_vs, open_exp_vs),
1501            clamp(use_sdf + (1.0 - open_ocean_vs) * 0.65, 0.0, 1.0),
1502        );
1503        let water_vs = clamp(mix(open_ocean_vs, sdf_s.r, use_sdf) * elev_water * shore_taper, 0.0, 1.0);
1504
1505        if (water_vs > 0.005) {
1506            let view_dist = length(world_rel);
1507            let sample_scale_m = max(view_dist * 0.032, 4.0);
1508            let wave_strength = ocean.basis_east.w;
1509            let wave_scale = ocean.basis_north.w;
1510            let d_merc = ocean_merc_from_en(pos_en, blend_25d);
1511            let p_noise_base = ocean_noise_wrap(ocean.world_meta.xy + d_merc);
1512            let wa = ocean.blend_params.x;
1513            let wb = ocean.blend_params.y;
1514            let w_sum = max(wa + wb, 1e-4);
1515            var disp_enu = vec3<f32>(0.0);
1516            if (wa > 0.002) {
1517                disp_enu += eval_ocean_vertex_train(
1518                    d_merc,
1519                    p_noise_base,
1520                    ocean.train_a.xy,
1521                    ocean.train_a.z,
1522                    ocean.train_a.w,
1523                    wave_scale,
1524                    sample_scale_m,
1525                    sea_exposure_vs,
1526                    ocean.train_a_phases0,
1527                ) * wa;
1528            }
1529            if (wb > 0.002) {
1530                disp_enu += eval_ocean_vertex_train(
1531                    d_merc,
1532                    p_noise_base,
1533                    ocean.train_b.xy,
1534                    ocean.train_b.z,
1535                    ocean.train_b.w,
1536                    wave_scale,
1537                    sample_scale_m,
1538                    sea_exposure_vs,
1539                    ocean.train_b_phases0,
1540                ) * wb;
1541            }
1542            disp_enu = (disp_enu / w_sum) * wave_strength * water_vs * ocean_on * ocean.blend_params.z;
1543            let disp_world = east_v * disp_enu.x + north_v * disp_enu.y + up_v * disp_enu.z;
1544            world_rel += disp_world;
1545            ecef_p += disp_world;
1546        }
1547    }
1548
1549    let mod_base = floor(inst.center_high.xyz * (1.0 / 256.0)) * 256.0;
1550    var out: TerrainVsOut;
1551    out.clip_pos = cam.view_proj_rte * vec4<f32>(world_rel, 1.0);
1552    out.normal = normalize(v.norm_v.xyz);
1553    out.uv = mix(inst.uv_rect.xy, inst.uv_rect.zw, raw_uv);
1554    out.tint = inst.tint;
1555    out.tex_layer = inst.tile_meta.y;
1556    out.unlit = inst.tile_meta.z;
1557    out.ecef_pos = ecef_p;
1558    out.view_rel = world_rel;
1559    out.night_uv = mix(inst.night_uv_rect.xy, inst.night_uv_rect.zw, raw_uv);
1560    out.night_layer = inst.tile_meta.w;
1561    out.land_uv_approx = land_uv;
1562    out.world_mod_256 = (inst.center_high.xyz - mod_base) + inst.center_low.xyz + v.pos_u.xyz;
1563    return out;
1564}
1565
1566fn sample_shadow_pcf(world_rel: vec3<f32>, n_mesh: vec3<f32>, sun_dir: vec3<f32>, shadow_radius: f32) -> f32 {
1567    let ndotl = max(dot(n_mesh, sun_dir), 0.0);
1568    let normal_bias = max(shadow_radius * 0.0016, 0.45) * (1.25 - 0.75 * ndotl);
1569    let biased_rel = world_rel + n_mesh * normal_bias;
1570    let lclip = cam.light_view_proj_rte * vec4<f32>(biased_rel, 1.0);
1571    let ndc = lclip.xyz / max(lclip.w, 1e-5);
1572    let uv = vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
1573    let depth_ref = clamp(ndc.z - 0.00055, 0.0, 0.9999);
1574
1575    let dims = max(vec2<f32>(textureDimensions(shadow_map)), vec2<f32>(1.0));
1576    let texel = 1.0 / dims;
1577    var acc = 0.0;
1578    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(-texel.x, -texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1579    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(0.0, -texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1580    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(texel.x, -texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1581    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(-texel.x, 0.0), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1582    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv, vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1583    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(texel.x, 0.0), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1584    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(-texel.x, texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1585    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(0.0, texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1586    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(texel.x, texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
1587    let pcf = acc * (1.0 / 9.0);
1588
1589    // Smooth edge fade near the border of the orthographic shadow frustum so shadows never clip abruptly.
1590    let border = max(abs(ndc.x), abs(ndc.y));
1591    let in_bounds = (1.0 - smoothstep(0.84, 0.99, border)) * step(0.0, ndc.z) * step(ndc.z, 1.0);
1592    return mix(1.0, pcf, in_bounds);
1593}
1594
1595fn eval_sky_reflection(
1596    rd: vec3<f32>,
1597    eye_up: vec3<f32>,
1598    sun_dir: vec3<f32>,
1599    real_sky_w: f32,
1600    weather_dark: f32,
1601    cloud_cov: f32,
1602) -> vec3<f32> {
1603    let h = clamp(max(dot(rd, eye_up), 0.0), 0.0, 1.0);
1604    let sun_elev = dot(sun_dir, eye_up);
1605    let day_t = smoothstep(-0.08, 0.24, sun_elev);
1606    let twilight_t = smoothstep(-0.22, -0.02, sun_elev) * (1.0 - smoothstep(0.02, 0.22, sun_elev));
1607    let golden_t = exp(-pow((sun_elev - 0.03) * 7.5, 2.0));
1608
1609    let day_zen = mix(vec3<f32>(0.09, 0.14, 0.32), vec3<f32>(0.08, 0.24, 0.56), smoothstep(0.02, 0.35, sun_elev));
1610    let day_hor = mix(vec3<f32>(0.95, 0.48, 0.20), vec3<f32>(0.72, 0.85, 0.96), smoothstep(0.02, 0.32, sun_elev));
1611    let night_zen = vec3<f32>(0.009, 0.016, 0.036);
1612    let night_hor = vec3<f32>(0.026, 0.042, 0.075);
1613
1614    let zen = mix(night_zen, day_zen, day_t) + vec3<f32>(0.04, 0.04, 0.10) * twilight_t;
1615    let hor = mix(night_hor, day_hor, day_t) + vec3<f32>(0.32, 0.15, 0.09) * twilight_t;
1616    var phys = mix(hor, zen, pow(h, 0.55));
1617    let sun_cos = max(dot(rd, sun_dir), 0.0);
1618    let cloud_atten = 1.0 - clamp(weather_dark * 0.78 + cloud_cov * 0.35, 0.0, 0.92);
1619    phys += vec3<f32>(1.0, 0.58, 0.26) * pow(sun_cos, 6.0) * (golden_t * 0.55 + day_t * 0.18) * cloud_atten;
1620
1621    let storm_w = clamp(weather_dark * 0.82 + cloud_cov * 0.22, 0.0, 0.92);
1622    let overcast = mix(vec3<f32>(0.02, 0.025, 0.038), vec3<f32>(0.32, 0.37, 0.44), clamp(day_t + twilight_t * 0.35, 0.0, 1.0));
1623    phys = mix(phys, overcast, storm_w * 0.72);
1624
1625    let classic = mix(vec3<f32>(0.68, 0.82, 0.95), vec3<f32>(0.14, 0.34, 0.66), pow(h, 0.55));
1626    return mix(classic, phys, real_sky_w);
1627}
1628
1629// Evaluates 8 directional anti-aliased short-crested Gerstner swells plus 6 octaves of
1630// Pythagorean-rotated C2 periodic Perlin gradient-noise wavelets & capillary slopes.
1631// Uses world-fixed Mercator deltas (`d_merc`) and pre-reduced CPU f64 base phases (`phases0/1`) so
1632// ocean waves never jump or alter pattern across camera pan, zoom, or 3D<->2.5D morph transitions.
1633// Returns vec4(slope_east, slope_north, crest_steepness, subpixel_aa_roughness).
1634fn eval_ocean_train(
1635    d_merc: vec2<f32>,
1636    p_noise_base: vec2<f32>,
1637    wind_dir: vec2<f32>,
1638    wind_speed: f32,
1639    t: f32,
1640    wave_scale: f32,
1641    px_m: f32,
1642    sea_exposure: f32,
1643    phases0: vec4<f32>,
1644    phases1: vec4<f32>,
1645) -> vec4<f32> {
1646    let dir0 = normalize(wind_dir);
1647    let perp0 = vec2<f32>(-dir0.y, dir0.x);
1648
1649    // Multi-scale advected Perlin gradient noise drives smooth wave packets ("sets"), domain warp, and gusts.
1650    let drift_macro = ocean_noise_wrap(p_noise_base - dir0 * (t * 0.42));
1651    let drift_cross = ocean_noise_wrap(p_noise_base - dir0 * (t * 0.65) + perp0 * (t * 0.22));
1652    let gw1 = pgrad2_periodic_rot(drift_macro, 1.0 / 512.0, 64.0, vec2<f32>(3.0, 4.0), vec2<f32>(11.3, 27.9));
1653    let gw2 = pgrad2_periodic_rot(drift_cross, 1.0 / 512.0, 64.0, vec2<f32>(8.0, 15.0), vec2<f32>(53.1, 19.7));
1654    let n_warp1 = gw1.x;
1655    let n_warp2 = gw2.x;
1656    let warp_vec = vec2<f32>(n_warp1 - 0.5, n_warp2 - 0.5);
1657    let group_macro = 0.48 + 0.96 * (0.60 * n_warp1 + 0.40 * n_warp2);
1658
1659    let drift_mid = ocean_noise_wrap(p_noise_base - dir0 * (t * 0.85) - perp0 * (t * 0.18));
1660    let gc = pgrad2_periodic_rot(drift_mid, 1.0 / 256.0, 128.0, vec2<f32>(5.0, 12.0), vec2<f32>(103.5, 41.2));
1661    let drift_b = ocean_noise_wrap(p_noise_base - dir0 * (t * 1.15) + perp0 * (t * 0.31) + vec2<f32>(317.0, 911.0));
1662    let gd = pgrad2_periodic_rot(drift_b, 1.0 / 128.0, 256.0, vec2<f32>(15.0, 8.0), vec2<f32>(19.7, 131.3));
1663    let n_gust = 0.58 * gc.x + 0.42 * n_warp2;
1664    let group_chop = 0.42 + 1.12 * (0.55 * gc.x + 0.45 * gd.x);
1665
1666    // Physical Beaufort asymptote: calm light ripples at 2 m/s, rolling swells at 7-12 m/s,
1667    // smoothly saturating toward 1.38 in gale winds instead of scaling linearly to extremes.
1668    let beaufort = clamp(1.38 * (1.0 - exp(-max(wind_speed, 0.3) / 10.5)), 0.10, 1.38);
1669    let len_wind = mix(0.48, 1.72, clamp(wind_speed / 18.0, 0.0, 1.3));
1670
1671    // 8 incommensurable directional swells localized into short-crested wave packets so no grid stripes form.
1672    var angs = array<f32, 8>(0.04, -0.26, 0.42, -0.58, 0.77, -0.86, 0.21, -0.41);
1673    var wls = array<f32, 8>(151.0, 97.0, 61.0, 38.0, 23.5, 13.7, 7.9, 4.3);
1674    var amps = array<f32, 8>(0.025, 0.023, 0.020, 0.017, 0.014, 0.011, 0.0085, 0.006);
1675    var base_ph = array<f32, 8>(
1676        phases0.x, phases0.y, phases0.z, phases0.w,
1677        phases1.x, phases1.y, phases1.z, phases1.w,
1678    );
1679
1680    var slope = vec2<f32>(0.0);
1681    var crest_acc = 0.0;
1682    let warp_mid = vec2<f32>(gc.x - 0.5, gd.x - 0.5);
1683
1684    for (var i: u32 = 0u; i < 8u; i = i + 1u) {
1685        let wl = max((wls[i] * len_wind) / max(wave_scale, 0.15), 1.4);
1686        let aa_w = 1.0 - smoothstep(wl * 0.22, wl * 0.58, px_m);
1687        if (aa_w > 0.008) {
1688            let ca = cos(angs[i]);
1689            let sa = sin(angs[i]);
1690            let d = dir0 * ca + perp0 * sa;
1691            let k = 6.2831853 / wl;
1692            let w_m = select(min(wl * 0.28, 7.5), min(wl * 0.48, 52.0), i < 4u);
1693            let p_eff = d_merc + warp_vec * w_m + warp_mid * min(wl * 0.22, 11.0);
1694            let ph = base_ph[i] + dot(d, p_eff) * k;
1695            let s = sin(ph);
1696            let c = cos(ph);
1697            let sharp = 0.5 + 0.5 * s;
1698            let env_alt = 0.45 + 1.05 * select(gd.x, n_warp2, (i & 1u) == 1u);
1699            let env_base = select(group_chop, group_macro, i < 4u);
1700            let env = mix(env_base, env_alt, 0.35);
1701            let steep = amps[i] * beaufort * sea_exposure * aa_w * env;
1702            let d_wave = c * (0.72 + 0.56 * sharp);
1703            slope += d * (d_wave * steep);
1704            crest_acc += pow(sharp, 2.4) * steep * 4.2;
1705        }
1706    }
1707
1708    // 6 isotropic periodic Perlin gradient wavelets (~102m down to ~0.94m) provide rich organic
1709    // ocean texture with zero square-cell artifacts and preserve distant roughness via AA deficit.
1710    var noise_slope = vec2<f32>(0.0);
1711    var aa_rough = 0.0;
1712    let noise_strength = beaufort * sea_exposure * (0.62 + 0.72 * n_gust);
1713
1714    let cell_a = (512.0 / 5.0) / max(wave_scale, 0.25);
1715    let aa_a = 1.0 - smoothstep(cell_a * 0.25, cell_a * 0.85, px_m);
1716    if (aa_a > 0.008) {
1717        noise_slope += gw1.yz * (0.018 * noise_strength * aa_a);
1718    }
1719
1720    let cell_b = (512.0 / 17.0) / max(wave_scale, 0.25);
1721    let aa_b = 1.0 - smoothstep(cell_b * 0.25, cell_b * 0.85, px_m);
1722    if (aa_b > 0.008) {
1723        noise_slope += gw2.yz * (0.021 * noise_strength * aa_b);
1724    }
1725
1726    let cell_c = (256.0 / 13.0) / max(wave_scale, 0.25);
1727    let aa_c = 1.0 - smoothstep(cell_c * 0.25, cell_c * 0.85, px_m);
1728    if (aa_c > 0.008) {
1729        noise_slope += gc.yz * (0.022 * noise_strength * aa_c);
1730    }
1731
1732    let cell_d = (128.0 / 17.0) / max(wave_scale, 0.25);
1733    let aa_d = 1.0 - smoothstep(cell_d * 0.25, cell_d * 0.85, px_m);
1734    if (aa_d > 0.008) {
1735        noise_slope += gd.yz * (0.020 * noise_strength * aa_d);
1736    }
1737    aa_rough += (1.0 - aa_d) * 0.028;
1738
1739    let cell_e = (32.0 / 13.0) / max(wave_scale, 0.25);
1740    let aa_e = 1.0 - smoothstep(cell_e * 0.25, cell_e * 0.85, px_m);
1741    if (aa_e > 0.008) {
1742        let ge = pgrad2_periodic_rot(drift_mid, 1.0 / 32.0, 1024.0, vec2<f32>(12.0, 5.0), vec2<f32>(61.9, 97.1)).yz;
1743        noise_slope += ge * (0.017 * noise_strength * aa_e);
1744    }
1745    aa_rough += (1.0 - aa_e) * 0.042;
1746
1747    let cell_f = (16.0 / 17.0) / max(wave_scale, 0.25);
1748    let aa_f = 1.0 - smoothstep(cell_f * 0.25, cell_f * 0.85, px_m);
1749    if (aa_f > 0.008) {
1750        let gf = pgrad2_periodic_rot(drift_b, 1.0 / 16.0, 2048.0, vec2<f32>(8.0, 15.0), vec2<f32>(149.1, 33.7)).yz;
1751        noise_slope += gf * (0.013 * noise_strength * aa_f);
1752    }
1753    aa_rough += (1.0 - aa_f) * 0.036;
1754
1755    slope += noise_slope;
1756    crest_acc += clamp(length(noise_slope) * 1.45, 0.0, 0.36);
1757    return vec4<f32>(slope.x, slope.y, crest_acc, aa_rough * clamp(sea_exposure * beaufort, 0.15, 1.2));
1758}
1759
1760fn hash31(p: vec3<f32>) -> f32 {
1761    var q = fract(p * vec3<f32>(0.1031, 0.1030, 0.0973));
1762    q += dot(q, q.yxz + 33.33);
1763    return fract((q.x + q.y) * q.z);
1764}
1765
1766fn vnoise3_periodic(p_mod_256: vec3<f32>, period: f32) -> f32 {
1767    let x = p_mod_256 * (period * (1.0 / 256.0));
1768    let i0 = floor(x);
1769    let f = fract(x);
1770    let u = f * f * (3.0 - 2.0 * f);
1771    let a = i0 - floor(i0 / period) * period;
1772    let i1_raw = i0 + vec3<f32>(1.0);
1773    let b = i1_raw - floor(i1_raw / period) * period;
1774
1775    let c000 = hash31(vec3<f32>(a.x, a.y, a.z));
1776    let c100 = hash31(vec3<f32>(b.x, a.y, a.z));
1777    let c010 = hash31(vec3<f32>(a.x, b.y, a.z));
1778    let c110 = hash31(vec3<f32>(b.x, b.y, a.z));
1779    let c001 = hash31(vec3<f32>(a.x, a.y, b.z));
1780    let c101 = hash31(vec3<f32>(b.x, a.y, b.z));
1781    let c011 = hash31(vec3<f32>(a.x, b.y, b.z));
1782    let c111 = hash31(vec3<f32>(b.x, b.y, b.z));
1783
1784    let x00 = mix(c000, c100, u.x);
1785    let x10 = mix(c010, c110, u.x);
1786    let x01 = mix(c001, c101, u.x);
1787    let x11 = mix(c011, c111, u.x);
1788    return mix(mix(x00, x10, u.y), mix(x01, x11, u.y), u.z);
1789}
1790
1791fn eval_micro_height(p_mod_256: vec3<f32>, raw_px_m: f32) -> f32 {
1792    let w8 = 1.0 - smoothstep(1.2, 4.0, raw_px_m);
1793    let w2 = 1.0 - smoothstep(0.32, 1.0, raw_px_m);
1794    let w05 = 1.0 - smoothstep(0.08, 0.30, raw_px_m);
1795    let w01 = 1.0 - smoothstep(0.02, 0.08, raw_px_m);
1796    var h = (vnoise3_periodic(p_mod_256, 32.0) - 0.5) * 0.44 * w8;
1797    h += (vnoise3_periodic(p_mod_256, 128.0) - 0.5) * 0.30 * w2;
1798    if (w05 > 0.01) {
1799        h += (vnoise3_periodic(p_mod_256, 512.0) - 0.5) * 0.18 * w05;
1800    }
1801    if (w01 > 0.01) {
1802        h += (vnoise3_periodic(p_mod_256, 2048.0) - 0.5) * 0.10 * w01;
1803    }
1804    return h;
1805}
1806
1807fn shade_terrain(in: TerrainVsOut, base: vec4<f32>) -> vec4<f32> {
1808    let map_2d = clamp(cam.view_flags.x, 0.0, 1.0);
1809    if (in.unlit != 0u || map_2d >= 0.99) {
1810        return base;
1811    }
1812
1813    let n_mesh = normalize(in.normal);
1814    let sun_dir = normalize(cam.sun_dir.xyz);
1815    let view_dir = normalize(-in.view_rel);
1816
1817    let dn_strength = clamp(cam.env_params.x, 0.0, 1.0);
1818    let city_strength = max(cam.env_params.y, 0.0);
1819    let blend_25d = clamp(cam.env_params.z, 0.0, 1.0) * (1.0 - map_2d);
1820    let real_sky_w = clamp(cam.atmo_25d_params.x, 0.0, 1.0);
1821    let night_star_w = clamp(cam.atmo_25d_params.y, 0.0, 1.0);
1822    let lit_25d_w = clamp(cam.atmo_25d_params.z, 0.0, 1.0);
1823    let shadow_w = clamp(cam.atmo_25d_params.w, 0.0, 1.0);
1824    let weather_dark = clamp(cam.weather_opt_params.x, 0.0, 1.0);
1825    let cloud_cov = clamp(cam.weather_opt_params.y, 0.0, 1.0);
1826    let weather_haze = clamp(cam.weather_opt_params.z, 0.0, 1.0);
1827
1828    let d = normalize(in.ecef_pos);
1829    let eye_pos = cam.eye_high.xyz + cam.eye_low.xyz;
1830    let eye_r = length(eye_pos);
1831    let local_up = select(vec3<f32>(0.0, 1.0, 0.0), d, eye_r > 1000000.0);
1832    let ndotl = dot(local_up, sun_dir);
1833
1834    // Keep derivatives & texture lookups in uniform control flow for WGSL validation.
1835    let raw_px_m = length(fwidth(in.view_rel));
1836    let px_m = max(raw_px_m, 0.15);
1837    let env_uv = dir_to_equirect_uv(d);
1838    let env_lod = clamp(log2(max(px_m * 0.0001022, 1.0)), 0.0, 5.0);
1839    let env_mask = textureSampleLevel(land_mask_tex, env_wrap_sampler, env_uv, env_lod);
1840    let on_land = smoothstep(0.18, 0.55, env_mask.r);
1841
1842    // Close-ground (< ~50-80m) procedural micro-albedo grain & micro-normal bump on land surfaces.
1843    let is_water_est = clamp(
1844        (1.0 - smoothstep(0.08, 0.42, env_mask.r))
1845            + select(0.0, 0.85, (base.b - base.r > 0.015) && env_mask.r < 0.65),
1846        0.0,
1847        1.0,
1848    );
1849    let micro_w = (1.0 - smoothstep(0.05, 0.80, raw_px_m)) * (1.0 - is_water_est) * (1.0 - map_2d);
1850    var n_lit = n_mesh;
1851    var base_micro_rgb = base.rgb;
1852    if (micro_w > 0.005) {
1853        let up_ref = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(n_mesh.y) > 0.9);
1854        let t_e = normalize(cross(up_ref, n_mesh));
1855        let t_n = cross(n_mesh, t_e);
1856        let h0 = eval_micro_height(in.world_mod_256, raw_px_m);
1857        let eps = max(raw_px_m * 0.75, 0.06);
1858        let he = eval_micro_height(in.world_mod_256 + t_e * eps, raw_px_m);
1859        let hn = eval_micro_height(in.world_mod_256 + t_n * eps, raw_px_m);
1860        let slope_e = ((he - h0) / eps) * 0.16 * micro_w;
1861        let slope_n = ((hn - h0) / eps) * 0.16 * micro_w;
1862        n_lit = normalize(n_mesh - t_e * slope_e - t_n * slope_n);
1863        let albedo_mod = 1.0 + h0 * (0.24 * micro_w);
1864        base_micro_rgb = clamp(base.rgb * albedo_mod, vec3<f32>(0.0), vec3<f32>(1.0));
1865    }
1866    let slope_ndotl = max(dot(n_lit, sun_dir), 0.0);
1867
1868    // Hardware 9-tap PCF directional shadow sampling (uniform control flow).
1869    var shadow_factor = 1.0;
1870    if (shadow_w > 0.001) {
1871        let pcf = sample_shadow_pcf(in.view_rel, n_mesh, sun_dir, max(cam.weather_opt_params.w, 10.0));
1872        shadow_factor = mix(1.0, pcf, shadow_w * (1.0 - weather_dark * 0.58));
1873    }
1874
1875    // --- Orbital 3D lighting ---
1876    let slope_shade = clamp(1.0 + (dot(n_lit, sun_dir) - ndotl) * 0.35 * blend_25d, 0.82, 1.18);
1877    let terminator = smoothstep(-0.14, 0.16, ndotl);
1878    let tn = ndotl * 7.5;
1879    let twilight = exp(-tn * tn) * vec3<f32>(0.42, 0.18, 0.06);
1880    let f1 = 1.0 - max(dot(local_up, view_dir), 0.0);
1881    let fresnel = f1 * f1 * f1;
1882    let atmo_rim = vec3<f32>(0.28, 0.56, 1.0)
1883        * fresnel
1884        * smoothstep(-0.18, 0.32, ndotl)
1885        * 0.45
1886        * (1.0 - blend_25d)
1887        * (1.0 - smoothstep(0.0, 0.55, map_2d));
1888    let ocean_night = vec3<f32>(0.048, 0.068, 0.108);
1889    let land_night = vec3<f32>(0.095, 0.120, 0.174);
1890    let night_fill = mix(ocean_night, land_night, on_land);
1891    let day_lit_3d = (night_fill + cam.sun_color.rgb * terminator + twilight) * slope_shade;
1892    let flat_lit = vec3<f32>(0.98);
1893    var lit = mix(flat_lit, day_lit_3d, dn_strength);
1894
1895    // --- Opt-in Realistic 2.5D Mountain Lighting & Cast Shadows ---
1896    let local_lit_blend = lit_25d_w * blend_25d;
1897    if (local_lit_blend > 0.001) {
1898        let sun_elev = dot(local_up, sun_dir);
1899        let day_t = smoothstep(-0.08, 0.24, sun_elev);
1900        let golden_t = exp(-pow((sun_elev - 0.04) * 7.2, 2.0));
1901        let sun_tint = mix(vec3<f32>(1.0, 0.56, 0.26), vec3<f32>(1.02, 0.99, 0.94), smoothstep(0.01, 0.30, sun_elev));
1902        let weather_sun_atten = 1.0 - clamp(weather_dark * 0.70 + cloud_cov * 0.22, 0.0, 0.85);
1903        // Normalize diffuse relative to typical overhead imagery luminance so sunlit slopes look crisp,
1904        // shaded valley/mountain backs drop dramatically into cool blue ambient shadow!
1905        let direct_intensity = smoothstep(-0.04, 0.12, sun_elev) * weather_sun_atten;
1906        let slope_term = clamp(slope_ndotl / max(sun_elev, 0.28), 0.0, 1.38);
1907        let direct_sun = sun_tint * (0.76 * slope_term * direct_intensity * shadow_factor);
1908
1909        let sky_hemi = 0.5 + 0.5 * dot(n_lit, local_up);
1910        let day_amb = mix(vec3<f32>(0.22, 0.28, 0.40), vec3<f32>(0.34, 0.42, 0.54), sky_hemi)
1911            * mix(1.0, 0.72, weather_dark);
1912        let sunset_amb = vec3<f32>(0.30, 0.22, 0.26) * golden_t * 0.55;
1913        let night_amb = mix(vec3<f32>(0.055, 0.075, 0.125), vec3<f32>(0.095, 0.120, 0.180), on_land)
1914            * (0.75 + 0.25 * sky_hemi);
1915        let ambient_25d = mix(night_amb, day_amb, day_t) + sunset_amb;
1916        let lit_25d = ambient_25d + direct_sun;
1917        lit = mix(lit, lit_25d, local_lit_blend);
1918    }
1919
1920    var rgb = base_micro_rgb * lit + atmo_rim * dn_strength;
1921
1922    // --- GPU-Native Directional Ocean Waves + Optional Coastal Periodic Surf ---
1923    let ocean_on = ocean.origin_high.w * ocean.origin_low.w * (1.0 - map_2d);
1924    if (ocean_on > 0.002) {
1925        // Compute high-precision RTE local tangent coordinates relative to ocean origin.
1926        let cam_minus_orig = (cam.eye_high.xyz - ocean.origin_high.xyz)
1927                           + (cam.eye_low.xyz - ocean.origin_low.xyz);
1928        let p_rel_orig = in.view_rel + cam_minus_orig;
1929        let east_v = ocean.basis_east.xyz;
1930        let north_v = ocean.basis_north.xyz;
1931        let up_v = ocean.basis_up.xyz;
1932        let pos_en = vec2<f32>(dot(p_rel_orig, east_v), dot(p_rel_orig, north_v));
1933        let rel_h = dot(p_rel_orig, up_v);
1934
1935        // 5-tap C1-smooth coastal SDF sample eliminates 128x128 u8 bilinear facets along coastlines.
1936        let half_span = max(ocean.coastal_params.y, 50.0);
1937        let sdf_uv = (pos_en - ocean.coastal_params.zw) / (2.0 * half_span) + vec2<f32>(0.5);
1938        let in_sdf = smoothstep(0.01, 0.09, sdf_uv.x) * (1.0 - smoothstep(0.91, 0.99, sdf_uv.x))
1939                   * smoothstep(0.01, 0.09, sdf_uv.y) * (1.0 - smoothstep(0.91, 0.99, sdf_uv.y));
1940        let sdf_texel = 1.0 / max(vec2<f32>(textureDimensions(coastal_sdf_tex)), vec2<f32>(8.0));
1941        let sdf_d = sdf_texel * 0.70;
1942        let uv_c = clamp(sdf_uv, vec2<f32>(0.002), vec2<f32>(0.998));
1943        let sdf_c0 = textureSampleLevel(coastal_sdf_tex, coastal_sdf_sampler, uv_c, 0.0);
1944        let sdf_c1 = textureSampleLevel(coastal_sdf_tex, coastal_sdf_sampler, clamp(uv_c + vec2<f32>(sdf_d.x, sdf_d.y), vec2<f32>(0.002), vec2<f32>(0.998)), 0.0);
1945        let sdf_c2 = textureSampleLevel(coastal_sdf_tex, coastal_sdf_sampler, clamp(uv_c + vec2<f32>(-sdf_d.x, sdf_d.y), vec2<f32>(0.002), vec2<f32>(0.998)), 0.0);
1946        let sdf_c3 = textureSampleLevel(coastal_sdf_tex, coastal_sdf_sampler, clamp(uv_c + vec2<f32>(sdf_d.x, -sdf_d.y), vec2<f32>(0.002), vec2<f32>(0.998)), 0.0);
1947        let sdf_c4 = textureSampleLevel(coastal_sdf_tex, coastal_sdf_sampler, clamp(uv_c + vec2<f32>(-sdf_d.x, -sdf_d.y), vec2<f32>(0.002), vec2<f32>(0.998)), 0.0);
1948        let sdf_s = sdf_c0 * 0.50 + (sdf_c1 + sdf_c2 + sdf_c3 + sdf_c4) * 0.125;
1949
1950        let use_sdf = ocean.blend_params.w * in_sdf;
1951        let curve_sag = select(0.0, 1.0, eye_r > 1000000.0)
1952            * (1.0 - blend_25d)
1953            * dot(pos_en, pos_en)
1954            / (2.0 * 6378137.0);
1955        let sea_elev = rel_h + curve_sag;
1956        let elev_water = 1.0 - smoothstep(0.6, 5.5, sea_elev);
1957
1958        // Pixel-sharp water classification from satellite imagery & elevation; SDF fills bright foam holes only.
1959        let max_c = max(base.r, max(base.g, base.b));
1960        let min_c = min(base.r, min(base.g, base.b));
1961        let cool_px = select(0.0, 1.0, (base.b >= base.r - 0.010) && (base.b + 0.030 >= base.g) && ((base.b - base.r >= 0.012) || max_c < 0.42));
1962        let emerald_px = select(0.0, 1.0, (base.b >= base.r + 0.014) && (base.g >= base.r + 0.016) && base.r < 0.46);
1963        let surf_foam_px = select(0.0, 1.0, (min_c > 0.56) && (base.b >= base.r - 0.012) && (sea_elev < 0.90) && (env_mask.r < 0.72));
1964        let warm_land = select(0.0, 1.0, (base.r - base.b >= 0.022) || ((min_c > 0.64) && (base.r > base.b + 0.008)));
1965        let img_water = clamp((cool_px + emerald_px + surf_foam_px) * (1.0 - warm_land), 0.0, 1.0);
1966
1967        let open_ocean_mask = 1.0 - smoothstep(0.04, 0.52, env_mask.r);
1968        let gpu_water = clamp(mix(img_water, 1.0, open_ocean_mask) * (1.0 - smoothstep(0.75, 0.96, env_mask.r) * (1.0 - img_water)) * elev_water, 0.0, 1.0);
1969        let sdf_surf_fill = clamp((sdf_s.r - 0.55) * 2.2, 0.0, 1.0)
1970                          * (1.0 - smoothstep(0.3, 2.0, sea_elev))
1971                          * (1.0 - warm_land);
1972        let water_mask = clamp(max(gpu_water, sdf_surf_fill * use_sdf), 0.0, 1.0);
1973
1974        let swash_margin = use_sdf * (1.0 - smoothstep(36.0, 58.0, sdf_s.g * ocean.coastal_params.x))
1975                         * (1.0 - smoothstep(0.20, 1.55, sea_elev));
1976
1977        if (water_mask > 0.01 || swash_margin > 0.01) {
1978            let shore_dist_norm = mix(1.0, sdf_s.g, use_sdf);
1979            let raw_sdir = sdf_s.ba * 2.0 - vec2<f32>(1.0);
1980            let sdir_len = length(raw_sdir);
1981            let shore_dir = select(vec2<f32>(1.0, 0.0), raw_sdir / max(sdir_len, 1e-4), sdir_len > 0.05);
1982
1983            let shoal_boost = use_sdf * (1.0 - smoothstep(0.04, 0.45, shore_dist_norm));
1984
1985            let wave_strength = ocean.basis_east.w;
1986            let wave_scale = ocean.basis_north.w;
1987            let glint_scale = ocean.basis_up.w;
1988            let d_merc = ocean_merc_from_en(pos_en, blend_25d);
1989            let p_noise_base = ocean_noise_wrap(ocean.world_meta.xy + d_merc);
1990
1991            // Smooth noise-warped open-ocean fetch: calm in sheltered coves (~0.34x), gradually building
1992            // seaward to full capped open-sea swells (~1.0x) without shoreline-parallel contour bands.
1993            let d_m_raw = shore_dist_norm * ocean.coastal_params.x;
1994            let n_cw1 = pgrad2_periodic_rot(p_noise_base, 1.0 / 512.0, 64.0, vec2<f32>(3.0, 4.0), vec2<f32>(71.3, 13.9)).x;
1995            let n_cw2 = pgrad2_periodic_rot(p_noise_base, 1.0 / 256.0, 128.0, vec2<f32>(5.0, 12.0), vec2<f32>(29.1, 87.7)).x;
1996            let warp_fetch = (n_cw1 - 0.5) * 110.0 + (n_cw2 - 0.5) * 42.0;
1997            let d_fetch = max(d_m_raw + warp_fetch, 0.0);
1998            let open_fetch = 1.0 - smoothstep(0.02, 0.54, clamp(env_mask.r + (n_cw1 - 0.5) * 0.18, 0.0, 1.0));
1999            let near_fetch = mix(0.32, 0.78, smoothstep(24.0, 320.0, d_fetch));
2000            let far_fetch = mix(0.38, 1.0, smoothstep(0.05, 0.92, open_fetch));
2001            let sea_exposure = mix(1.0, max(near_fetch, far_fetch), clamp(use_sdf + (1.0 - open_ocean_mask) * 0.65, 0.0, 1.0));
2002
2003            // Dual-state smooth wind cross-fade (zero phase-spin glitch on wind angle/speed change!).
2004            let wa = ocean.blend_params.x;
2005            let wb = ocean.blend_params.y;
2006            let w_sum = max(wa + wb, 1e-4);
2007            var wave_res = vec4<f32>(0.0);
2008            if (wa > 0.002) {
2009                wave_res += eval_ocean_train(
2010                    d_merc,
2011                    p_noise_base,
2012                    ocean.train_a.xy,
2013                    ocean.train_a.z,
2014                    ocean.train_a.w,
2015                    wave_scale,
2016                    px_m,
2017                    sea_exposure,
2018                    ocean.train_a_phases0,
2019                    ocean.train_a_phases1,
2020                ) * (wa / w_sum);
2021            }
2022            if (wb > 0.002) {
2023                wave_res += eval_ocean_train(
2024                    d_merc,
2025                    p_noise_base,
2026                    ocean.train_b.xy,
2027                    ocean.train_b.z,
2028                    ocean.train_b.w,
2029                    wave_scale,
2030                    px_m,
2031                    sea_exposure,
2032                    ocean.train_b_phases0,
2033                    ocean.train_b_phases1,
2034                ) * (wb / w_sum);
2035            }
2036
2037            let eff_wind_speed = (ocean.train_a.z * wa + ocean.train_b.z * wb) / w_sum;
2038            let eff_t = (ocean.train_a.w * wa + ocean.train_b.w * wb) / w_sum;
2039
2040            // Optional Coastal Refracted Breaking Surf & Rhythmic Come-and-Go Beach Swash!
2041            var coastal_foam = 0.0;
2042            var surf_slope = vec2<f32>(0.0);
2043            var swash_cov = 0.0;
2044            var wet_darken = 0.0;
2045            if (use_sdf > 0.01 && shore_dist_norm < 0.96) {
2046                let warp_surf = (n_cw1 - 0.5) * 58.0 + (n_cw2 - 0.5) * 24.0;
2047                let d_eff = max(d_m_raw + warp_surf, 0.0);
2048                let surf_wl = clamp(mix(28.0, 48.0, clamp(eff_wind_speed / 16.0, 0.0, 1.0)), 24.0, 52.0);
2049                let k_surf = 6.2831853 / surf_wl;
2050                // Period ~8-11 s real ocean surf period; +omega*t moves crests INWARD toward the beach.
2051                let omega_surf = sqrt(9.81 * k_surf) * 0.58;
2052
2053                // Blend wave propagation direction toward shoreline only close inside <125m (Snell refraction)
2054                let refract_w = 1.0 - smoothstep(15.0, 125.0, d_eff);
2055                let inc_dir = normalize((ocean.train_a.xy * wa + ocean.train_b.xy * wb) / w_sum + vec2<f32>(1e-4, 0.0));
2056                let prop_to_shore = normalize(mix(inc_dir, shore_dir, clamp(0.35 + 0.65 * refract_w, 0.0, 1.0)));
2057
2058                // Along-shore broken wave-packet envelope breaks continuous rings into organic surf arcs.
2059                let p_along = ocean_noise_wrap(p_noise_base - prop_to_shore * (eff_t * 1.4));
2060                let n_along = pgrad2_periodic_rot(p_along, 1.0 / 256.0, 128.0, vec2<f32>(15.0, 8.0), vec2<f32>(83.1, 47.3)).x;
2061                let crest_patch = smoothstep(0.24, 0.76, n_along);
2062                let set_group = (0.55 + 0.45 * sin(0.22 * k_surf * d_eff + 0.18 * omega_surf * eff_t + n_cw1 * 3.1))
2063                              * (0.45 + 0.90 * crest_patch);
2064                let phase_var = k_surf * d_eff + omega_surf * eff_t + (n_cw1 - 0.5) * 2.4;
2065                let surf_aa = 1.0 - smoothstep(surf_wl * 0.16, surf_wl * 0.55, px_m);
2066
2067                // Subtle refracting shoaling swells & broken whitewater crests inside [10m .. 125m] (no 320m rings).
2068                let shoal_swell_zone = smoothstep(8.0, 24.0, d_m_raw) * (1.0 - smoothstep(65.0, 130.0, d_m_raw));
2069                let breaker_zone = smoothstep(10.0, 26.0, d_m_raw) * (1.0 - smoothstep(55.0, 115.0, d_m_raw));
2070                let s_wave = 0.5 + 0.5 * sin(phase_var);
2071                let crest_line = pow(s_wave, 5.2) * breaker_zone * set_group * surf_aa;
2072                let n_foam = pgrad2_periodic_rot(
2073                    ocean_noise_wrap(p_noise_base + prop_to_shore * (eff_t * 1.1)),
2074                    1.0 / 32.0,
2075                    1024.0,
2076                    vec2<f32>(12.0, 5.0),
2077                    vec2<f32>(119.3, 61.7),
2078                ).x;
2079                let foam_noise = 0.42 + 0.58 * n_foam;
2080                let wake_trail = pow(0.5 + 0.5 * sin(phase_var - 0.70), 2.8) * breaker_zone * set_group * 0.24 * surf_aa;
2081                coastal_foam += (crest_line * 0.72 + wake_trail) * foam_noise * use_sdf * water_mask;
2082                surf_slope += prop_to_shore * (cos(phase_var) * shoal_swell_zone * set_group * 0.042 * surf_aa * use_sdf);
2083
2084                // Rhythmic Come-and-Go Shoreline Swash: washes UP onto wet beach margin (-8.5m) and slides BACK (+34m).
2085                if (swash_margin > 0.01) {
2086                    let swash_ph = omega_surf * 0.76 * eff_t + (n_cw1 - 0.5) * 4.8 + (n_along - 0.5) * 2.6;
2087                    let rush_raw = 0.5 + 0.5 * sin(swash_ph);
2088                    let surge = pow(rush_raw, 0.72);
2089                    let surge_vel = cos(swash_ph);
2090                    let beach_s = d_m_raw - max(sea_elev, -0.25) * 10.0;
2091                    let front_s = mix(34.0, -8.5, surge * clamp(0.68 + 0.52 * n_along, 0.48, 1.22));
2092                    let swash_sheet = smoothstep(front_s - 2.5, front_s + 8.5, beach_s)
2093                                    * (1.0 - smoothstep(34.0, 54.0, d_m_raw))
2094                                    * swash_margin;
2095                    let swash_lip = exp(-pow((beach_s - front_s) / 4.2, 2.0))
2096                                  * (0.58 + 0.42 * max(surge_vel, 0.0))
2097                                  * swash_margin;
2098                    let n_lace = pgrad2_periodic_rot(
2099                        ocean_noise_wrap(p_noise_base - shore_dir * (eff_t * 0.75)),
2100                        1.0 / 16.0,
2101                        2048.0,
2102                        vec2<f32>(8.0, 15.0),
2103                        vec2<f32>(137.5, 91.1),
2104                    ).x;
2105                    let lace = smoothstep(0.26, 0.74, n_lace);
2106                    let foam_amt = (swash_sheet * 0.44 * lace + swash_lip * 0.84) * surf_aa * use_sdf;
2107                    coastal_foam += foam_amt;
2108                    let wet_zone = (1.0 - smoothstep(-8.0, 6.0, -beach_s)) * (1.0 - smoothstep(14.0, 34.0, d_m_raw));
2109                    wet_darken = wet_zone * swash_margin * 0.24 * use_sdf;
2110                    swash_cov = clamp(swash_sheet * 0.62 + swash_lip * 0.90, 0.0, 0.94) * use_sdf;
2111                }
2112            }
2113
2114            let cov_eff = clamp(max(water_mask, swash_cov), 0.0, 1.0);
2115            var raw_slope = (wave_res.xy * wave_strength + surf_slope) * cov_eff;
2116            // Miche breaking-steepness soft limiter caps surface slope cleanly at ~0.40 without flat clipping.
2117            let slope_len = length(raw_slope);
2118            if (slope_len > 0.16) {
2119                let over = slope_len - 0.16;
2120                let capped = 0.16 + 0.24 * (over / (0.24 + over));
2121                raw_slope *= capped / slope_len;
2122            }
2123            let n_water = normalize(up_v - east_v * raw_slope.x - north_v * raw_slope.y);
2124
2125            // Physically based Fresnel sky reflection + deep pelagic water absorption.
2126            let ndotv = max(dot(n_water, view_dir), 0.04);
2127            let f_schlick = 0.02 + 0.98 * pow(1.0 - ndotv, 5.0);
2128            var refl_dir = reflect(-view_dir, n_water);
2129            let refl_up = dot(refl_dir, local_up);
2130            if (refl_up < 0.045) {
2131                refl_dir = normalize(refl_dir + local_up * (0.045 - refl_up));
2132            }
2133            let sky_refl = eval_sky_reflection(refl_dir, local_up, sun_dir, real_sky_w, weather_dark, cloud_cov);
2134
2135            let sun_elev = dot(local_up, sun_dir);
2136            let day_t = smoothstep(-0.08, 0.24, sun_elev);
2137            let water_albedo = mix(
2138                base.rgb * lit * (1.0 - wet_darken),
2139                mix(vec3<f32>(0.014, 0.052, 0.095), vec3<f32>(0.028, 0.135, 0.205), shoal_boost) * max(lit, vec3<f32>(0.12)),
2140                mix(0.28, 0.44, water_mask),
2141            );
2142
2143            // Subsurface turquoise glow through sunlit wave crests & shallow coastal water.
2144            let sss = pow(clamp(wave_res.z * 0.72, 0.0, 1.0), 1.4) * smoothstep(-0.04, 0.30, sun_elev)
2145                    * (0.35 + 0.65 * shoal_boost) * shadow_factor * (1.0 - weather_dark * 0.72);
2146            let sss_col = vec3<f32>(0.04, 0.32, 0.36) * sss * 0.38;
2147
2148            // Crisp GGX-like solar specular glitter path widened softly by distant AA roughness + silver moon glitter.
2149            let half_s = normalize(sun_dir + view_dir);
2150            let ndoth_s = max(dot(n_water, half_s), 0.0);
2151            let rough = clamp(mix(0.06, 0.20, clamp(eff_wind_speed / 22.0, 0.0, 1.0)) + wave_res.w, 0.05, 0.34);
2152            let spec_exp = mix(420.0, 32.0, min(rough * 2.9, 1.0));
2153            let sun_vis_w = smoothstep(-0.03, 0.12, sun_elev) * (1.0 - clamp(weather_dark * 0.85 + cloud_cov * 0.45, 0.0, 0.96));
2154            let sun_spec_col = mix(vec3<f32>(1.0, 0.56, 0.22), vec3<f32>(1.0, 0.97, 0.90), smoothstep(0.0, 0.28, sun_elev));
2155            let sun_glint = sun_spec_col * (pow(ndoth_s, spec_exp) * 2.3 + pow(ndoth_s, 22.0) * 0.15)
2156                          * sun_vis_w * shadow_factor * glint_scale * cov_eff;
2157
2158            var moon_glint = vec3<f32>(0.0);
2159            if (cam.moon_dir.w > 0.5 && sun_elev < 0.02) {
2160                let m_dir = normalize(cam.moon_dir.xyz);
2161                let m_elev = dot(local_up, m_dir);
2162                if (m_elev > 0.02) {
2163                    let half_m = normalize(m_dir + view_dir);
2164                    let ndoth_m = max(dot(n_water, half_m), 0.0);
2165                    let night_w = (1.0 - smoothstep(-0.10, 0.02, sun_elev)) * (1.0 - cloud_cov * 0.75);
2166                    moon_glint = vec3<f32>(0.62, 0.74, 0.92) * pow(ndoth_m, 96.0) * 0.45 * night_w * glint_scale * cov_eff;
2167                }
2168            }
2169
2170            // Open-sea whitecap foam gated by fetch & capped Beaufort curve + coastal surf foam.
2171            let wind_foam_thresh = clamp((eff_wind_speed - 8.0) / 13.0, 0.0, 0.85) * smoothstep(0.25, 0.85, sea_exposure);
2172            let chop_noise = pgrad2_periodic_rot(
2173                ocean_noise_wrap(p_noise_base - ocean.train_a.xy * (eff_t * 1.1)),
2174                1.0 / 32.0,
2175                1024.0,
2176                vec2<f32>(5.0, 12.0),
2177                vec2<f32>(173.1, 23.9),
2178            ).x;
2179            let whitecap = smoothstep(0.62, 1.12, wave_res.z * wave_strength * (0.72 + 0.56 * chop_noise))
2180                         * wind_foam_thresh * 0.52 * water_mask;
2181            let total_foam = clamp(whitecap + coastal_foam, 0.0, 0.86);
2182            let foam_sun_tint = mix(vec3<f32>(0.98, 0.78, 0.62), vec3<f32>(0.94, 0.97, 1.0), smoothstep(0.02, 0.28, sun_elev));
2183            let foam_col = mix(vec3<f32>(0.16, 0.20, 0.28), foam_sun_tint, clamp(day_t * 0.9 + 0.12, 0.12, 1.0))
2184                         * mix(1.0, 0.68, weather_dark);
2185
2186            var ocean_rgb = mix(water_albedo + sss_col, sky_refl, clamp(f_schlick * 0.86 + 0.08, 0.0, 0.90))
2187                          + sun_glint + moon_glint;
2188            ocean_rgb = mix(ocean_rgb, foam_col, total_foam);
2189
2190            let dry_wet_rgb = mix(rgb, rgb * (1.0 - wet_darken), step(0.001, wet_darken));
2191            let ocean_blend = clamp(cov_eff * ocean.blend_params.z * ocean_on, 0.0, 1.0);
2192            rgb = mix(dry_wet_rgb, ocean_rgb, ocean_blend);
2193        }
2194    }
2195
2196    // --- Night City Lights (orbital 3D Black Marble + crisp close-2.5D street illumination) ---
2197    let eff_night_city = max(dn_strength * city_strength, local_lit_blend * night_star_w * city_strength);
2198    if (eff_night_city > 0.001 && on_land > 0.001 && ndotl < 0.06) {
2199        let night_mask = (1.0 - smoothstep(-0.14, 0.06, ndotl)) * eff_night_city * on_land;
2200        if (night_mask > 0.001) {
2201            let eg = env_mask.g;
2202            let base_lin = select(
2203                0.0,
2204                max(eg * eg * (0.75 + 0.25 * eg) - 0.022, 0.0) * 1.0225,
2205                eg > 0.175,
2206            );
2207            var black_marble = base_lin;
2208            let detail_night_w = 1.0 - smoothstep(350.0, 1100.0, px_m);
2209            if (in.night_layer != 0u && detail_night_w > 0.005) {
2210                let nl = i32(in.night_layer);
2211                let luma_w = vec3<f32>(0.299, 0.587, 0.114);
2212                let c0 = dot(textureSampleLevel(terrain_atlas, terrain_sampler, in.night_uv, nl, 0.0).rgb, luma_w);
2213                var raw_tile = c0;
2214                if (c0 > 0.015) {
2215                    let hduv = 0.5 / 256.0;
2216                    let c1 = dot(textureSampleLevel(terrain_atlas, terrain_sampler, clamp(in.night_uv + vec2<f32>(hduv, hduv), vec2<f32>(0.0), vec2<f32>(1.0)), nl, 0.0).rgb, luma_w);
2217                    let c2 = dot(textureSampleLevel(terrain_atlas, terrain_sampler, clamp(in.night_uv - vec2<f32>(hduv, hduv), vec2<f32>(0.0), vec2<f32>(1.0)), nl, 0.0).rgb, luma_w);
2218                    raw_tile = c0 * 0.5 + (c1 + c2) * 0.25;
2219                }
2220                let tile_lin = max(raw_tile - 0.022, 0.0) * 1.0225;
2221                black_marble = mix(base_lin, tile_lin, detail_night_w);
2222            }
2223            if (black_marble > 0.00018) {
2224                let bm_srgb = sqrt(clamp(black_marble, 0.0, 1.0));
2225                let city_core = smoothstep(0.08, 0.48, bm_srgb);
2226                let corridor = smoothstep(0.02, 0.22, bm_srgb) * 0.22;
2227                let orbital_city_w = 1.0 - smoothstep(0.08, 0.82, blend_25d);
2228                let local_city_w = smoothstep(0.12, 0.85, blend_25d);
2229                var pinpoint = 0.86;
2230                var corridor_mod = 0.825;
2231                if (orbital_city_w > 0.01 && px_m < 4500.0) {
2232                    let p2 = vec2<f32>(d.x - d.z * 0.618034, d.y + d.z * 0.618034);
2233                    let med_w = 1.0 - smoothstep(1400.0, 4500.0, px_m);
2234                    let n_block = vnoise2(p2 * 2800.0);
2235                    let n_street = vnoise2(p2 * 10500.0);
2236                    let fine_w = 1.0 - smoothstep(160.0, 1200.0, px_m);
2237                    var sub_grid = 1.0;
2238                    if (fine_w > 0.02) {
2239                        let arterial = smoothstep(0.30, 0.88, vnoise2(p2 * 68000.0));
2240                        let fine_mask = 0.24 + 1.12 * arterial;
2241                        sub_grid = mix(1.0, fine_mask, fine_w);
2242                    }
2243                    let street_grid = smoothstep(0.24, 0.86, n_block * 0.55 + n_street * 0.45);
2244                    let detail_pin = mix(0.62, 1.38, street_grid * (0.62 + 0.38 * n_street)) * sub_grid;
2245                    pinpoint = mix(0.86, detail_pin, med_w);
2246                    corridor_mod = mix(0.825, (0.65 + 0.35 * n_block) * sub_grid, med_w);
2247                }
2248                let orbital_luma = (city_core * pinpoint + corridor * corridor_mod) * night_mask * orbital_city_w * 0.92;
2249                let base_luma = dot(base.rgb, vec3<f32>(0.299, 0.587, 0.114));
2250                let urban_mat = smoothstep(0.18, 0.52, base_luma)
2251                    * (1.0 - smoothstep(0.03, 0.10, base.g - max(base.r, base.b)))
2252                    * (1.0 - smoothstep(0.04, 0.12, base.b - base.r));
2253                let street_hi = smoothstep(0.36, 0.72, base_luma);
2254                let local_luma = (bm_srgb * (0.14 + 0.36 * urban_mat + 0.44 * street_hi))
2255                    * night_mask * local_city_w * 0.58;
2256                let warm_amber = vec3<f32>(0.97, 0.74, 0.38);
2257                let warm_white = vec3<f32>(1.0, 0.90, 0.68);
2258                rgb += mix(warm_amber, warm_white, city_core) * orbital_luma
2259                     + mix(vec3<f32>(0.96, 0.68, 0.32), vec3<f32>(1.0, 0.88, 0.66), street_hi) * local_luma;
2260            }
2261        }
2262    }
2263
2264    // --- Weather- & Sky-Matched Aerial Perspective / Precipitation Mist ---
2265    let morph_fade_2d = 1.0 - smoothstep(0.0, 0.55, map_2d);
2266    if (blend_25d > 0.01 && morph_fade_2d > 0.001) {
2267        let view_dist = length(in.view_rel);
2268        let haze_density = mix(0.000018, 0.00016, weather_haze);
2269        let haze_near = mix(3500.0, 420.0, weather_haze);
2270        let haze_far = mix(52000.0, 9500.0, weather_haze);
2271        let haze_start = smoothstep(haze_near, haze_far, view_dist);
2272        let aerial_haze = clamp((1.0 - exp(-view_dist * haze_density)) * haze_start * blend_25d * mix(0.68, 0.84, weather_haze), 0.0, 0.82) * morph_fade_2d;
2273
2274        let day_scale = clamp(max(cam.sky_bottom.b, max(cam.sky_bottom.r, cam.sky_bottom.g)), 0.0, 1.0);
2275        let classic_haze = vec3<f32>(0.73, 0.85, 0.96) * day_scale * mix(vec3<f32>(1.0), clamp(lit * 1.15, vec3<f32>(0.35), vec3<f32>(1.0)), dn_strength);
2276        let horiz_dir = normalize(in.view_rel - local_up * dot(in.view_rel, local_up) + local_up * 0.02);
2277        let phys_haze = eval_sky_reflection(horiz_dir, local_up, sun_dir, 1.0, weather_dark, cloud_cov);
2278        let horizon_haze_col = mix(classic_haze, phys_haze, max(real_sky_w, weather_haze * 0.65));
2279        rgb = mix(rgb, horizon_haze_col, aerial_haze);
2280    }
2281
2282    if (map_2d > 0.001) {
2283        rgb = mix(rgb, base.rgb, smoothstep(0.0, 0.95, map_2d));
2284    }
2285
2286    return vec4<f32>(rgb, base.a);
2287}
2288
2289@fragment
2290fn fs_terrain_opaque(in: TerrainVsOut) -> @location(0) vec4<f32> {
2291    let sampled = textureSample(terrain_atlas, terrain_sampler, in.uv, i32(in.tex_layer));
2292    return shade_terrain(in, sampled * in.tint);
2293}
2294
2295@fragment
2296fn fs_terrain(in: TerrainVsOut) -> @location(0) vec4<f32> {
2297    let sampled = textureSample(terrain_atlas, terrain_sampler, in.uv, i32(in.tex_layer));
2298    let base = sampled * in.tint;
2299    if (base.a <= 0.001) {
2300        discard;
2301    }
2302    return shade_terrain(in, base);
2303}
2304"#;
2305
2306const TERRAIN_SHADOW_WGSL: &str = r#"
2307struct GpuCameraUniforms {
2308    view_proj_rte: mat4x4<f32>,
2309    inv_view_proj_rte: mat4x4<f32>,
2310    ecef_from_icrf: mat4x4<f32>,
2311    icrf_from_ecef: mat4x4<f32>,
2312    light_view_proj_rte: mat4x4<f32>,
2313    eye_high: vec4<f32>,
2314    eye_low: vec4<f32>,
2315    sun_dir: vec4<f32>,
2316    sun_color: vec4<f32>,
2317    ambient_color: vec4<f32>,
2318    sky_top: vec4<f32>,
2319    sky_bottom: vec4<f32>,
2320    moon_dir: vec4<f32>,
2321    env_params: vec4<f32>,
2322    cloud_params: vec4<f32>,
2323    viewport_wh: vec4<f32>,
2324    atmo_25d_params: vec4<f32>,
2325    weather_opt_params: vec4<f32>,
2326    cloud_tint_params: vec4<f32>,
2327    view_flags: vec4<f32>,
2328}
2329
2330struct GpuTileVertex {
2331    pos_u: vec4<f32>,
2332    norm_v: vec4<f32>,
2333}
2334
2335struct GpuTileInstance {
2336    center_high: vec4<f32>,
2337    center_low: vec4<f32>,
2338    uv_rect: vec4<f32>,
2339    night_uv_rect: vec4<f32>,
2340    tint: vec4<f32>,
2341    tile_meta: vec4<u32>,
2342}
2343
2344@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
2345@group(0) @binding(1) var<storage, read> vertices: array<GpuTileVertex>;
2346@group(0) @binding(2) var<storage, read> instances: array<GpuTileInstance>;
2347
2348@vertex
2349fn vs_terrain_shadow(
2350    @builtin(vertex_index) local_v: u32,
2351    @builtin(instance_index) inst_id: u32,
2352) -> @builtin(position) vec4<f32> {
2353    let inst = instances[inst_id];
2354    let v = vertices[inst.tile_meta.x + local_v];
2355    let center_rel = (inst.center_high.xyz - cam.eye_high.xyz)
2356                   + (inst.center_low.xyz - cam.eye_low.xyz);
2357    let world_rel = center_rel + v.pos_u.xyz;
2358    return cam.light_view_proj_rte * vec4<f32>(world_rel, 1.0);
2359}
2360"#;
2361
2362const CLOUD_SHELL_WGSL: &str = r#"
2363struct GpuCameraUniforms {
2364    view_proj_rte: mat4x4<f32>,
2365    inv_view_proj_rte: mat4x4<f32>,
2366    ecef_from_icrf: mat4x4<f32>,
2367    icrf_from_ecef: mat4x4<f32>,
2368    light_view_proj_rte: mat4x4<f32>,
2369    eye_high: vec4<f32>,
2370    eye_low: vec4<f32>,
2371    sun_dir: vec4<f32>,
2372    sun_color: vec4<f32>,
2373    ambient_color: vec4<f32>,
2374    sky_top: vec4<f32>,
2375    sky_bottom: vec4<f32>,
2376    moon_dir: vec4<f32>,
2377    env_params: vec4<f32>,
2378    cloud_params: vec4<f32>,
2379    viewport_wh: vec4<f32>,
2380    atmo_25d_params: vec4<f32>,
2381    weather_opt_params: vec4<f32>,
2382    cloud_tint_params: vec4<f32>,
2383    view_flags: vec4<f32>,
2384}
2385
2386@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
2387@group(0) @binding(1) var cloud_tex: texture_2d<f32>;
2388@group(0) @binding(2) var cloud_sampler: sampler;
2389@group(0) @binding(3) var cloud_noise_tex: texture_2d<f32>;
2390@group(0) @binding(4) var cloud_noise_sampler: sampler;
2391
2392struct CloudOut {
2393    @builtin(position) clip_pos: vec4<f32>,
2394    @location(0) unit_pos: vec3<f32>,
2395    @location(1) uv_par: vec4<f32>,
2396    @location(2) params_fs: vec4<f32>,
2397    @location(3) light_ts_term: vec4<f32>,
2398    @location(4) view_ts_haze: vec4<f32>,
2399    @location(5) sun_ts_lod: vec4<f32>,
2400    @location(6) grad_step_bic: vec4<f32>,
2401}
2402
2403fn sample_cloud_density(uv: vec2<f32>, lod: f32) -> f32 {
2404    return textureSampleLevel(cloud_tex, cloud_sampler, uv, lod).r;
2405}
2406
2407fn sample_cloud_bicubic_density(uv: vec2<f32>, dims: vec2<f32>, inv_dims: vec2<f32>) -> f32 {
2408    let tc = uv * dims - vec2<f32>(0.5, 0.5);
2409    let i = floor(tc);
2410    let f = clamp(tc - i, vec2<f32>(0.0), vec2<f32>(1.0));
2411    let f2 = f * f;
2412    let f3 = f2 * f;
2413
2414    let omf = vec2<f32>(1.0) - f;
2415    let w0 = omf * omf * omf * (1.0 / 6.0);
2416    let w1 = (3.0 * f3 - 6.0 * f2 + vec2<f32>(4.0)) * (1.0 / 6.0);
2417    let w2 = (-3.0 * f3 + 3.0 * f2 + 3.0 * f + vec2<f32>(1.0)) * (1.0 / 6.0);
2418    let w3 = f3 * (1.0 / 6.0);
2419
2420    let g0 = w0 + w1;
2421    let g1 = w2 + w3;
2422    let u0 = fract((i.x - 0.5 + w1.x / max(g0.x, 1e-5)) * inv_dims.x);
2423    let u1 = fract((i.x + 1.5 + w3.x / max(g1.x, 1e-5)) * inv_dims.x);
2424    let v0 = clamp((i.y - 0.5 + w1.y / max(g0.y, 1e-5)) * inv_dims.y, 0.001, 0.999);
2425    let v1 = clamp((i.y + 1.5 + w3.y / max(g1.y, 1e-5)) * inv_dims.y, 0.001, 0.999);
2426
2427    let c00 = sample_cloud_density(vec2<f32>(u0, v0), 0.0);
2428    let c10 = sample_cloud_density(vec2<f32>(u1, v0), 0.0);
2429    let c01 = sample_cloud_density(vec2<f32>(u0, v1), 0.0);
2430    let c11 = sample_cloud_density(vec2<f32>(u1, v1), 0.0);
2431
2432    let top = mix(c10, c00, g0.x);
2433    let bot = mix(c11, c01, g0.x);
2434    return mix(bot, top, g0.y);
2435}
2436
2437fn cloud_density_to_height(d: f32) -> f32 {
2438    let x = clamp(d, 0.0, 1.0);
2439    let dome = smoothstep(0.06, 0.88, x);
2440    return dome * (0.65 + 0.35 * x * (2.0 - x));
2441}
2442
2443@vertex
2444fn vs_cloud(@location(0) pos_u: vec4<f32>, @location(1) norm_v: vec4<f32>) -> CloudOut {
2445    let base_cloud_r = 6391500.0;
2446    let r_earth = 6378137.0;
2447    let d = normalize(pos_u.xyz);
2448    let eye_pos = cam.eye_high.xyz + cam.eye_low.xyz;
2449    let eye_r = max(length(eye_pos), 1.0);
2450    let eye_alt = max(eye_r - r_earth, 0.0);
2451    let eye_dir = eye_pos / eye_r;
2452    let below_clouds = select(0.0, 1.0, eye_r < base_cloud_r);
2453    let horiz_cos = r_earth / max(eye_r, r_earth);
2454    let above_shell = max(eye_r - base_cloud_r, 0.0);
2455    let vert_disp_w = smoothstep(18000.0, 75000.0, above_shell)
2456        * (1.0 - smoothstep(110000.0, 220000.0, above_shell));
2457
2458    let u_unwrapped = atan2(d.y, d.x) * 0.15915494309 + 0.5;
2459    let v_unwrapped = clamp(0.5 - asin(clamp(d.z, -1.0, 1.0)) * 0.31830988618, 0.001, 0.999);
2460
2461    var cloud_r = base_cloud_r;
2462    if (vert_disp_w > 0.001 && dot(d, eye_dir) > horiz_cos - 0.16) {
2463        let u_v = fract(u_unwrapped + cam.cloud_params.y * 0.15915494309);
2464        let h_vert = cloud_density_to_height(sample_cloud_density(vec2<f32>(u_v, v_unwrapped), 2.5));
2465        cloud_r = mix(base_cloud_r, 6390200.0 + h_vert * 4200.0, vert_disp_w);
2466    }
2467
2468    let world_pos = d * cloud_r;
2469    let world_rel = (world_pos - cam.eye_high.xyz) - cam.eye_low.xyz;
2470    var clip = cam.view_proj_rte * vec4<f32>(world_rel, 1.0);
2471    if (clip.w > 0.0) {
2472        clip.z = min(clip.z, clip.w * 0.9995);
2473    }
2474
2475    let opacity = clamp(cam.cloud_params.x + cam.viewport_wh.w, 0.0, 1.0);
2476    let detail_w = 1.0 - smoothstep(120000.0, 2200000.0, eye_alt);
2477    let mode_25d = smoothstep(0.15, 0.75, clamp(max(detail_w, below_clouds), 0.0, 1.0));
2478    let gate_25d = smoothstep(0.85, 0.995, mode_25d);
2479    let cover_boost = clamp(cam.cloud_tint_params.w, 0.0, 1.0) * below_clouds;
2480    let coarse_gate = mix(0.014, mix(0.212, 0.015, cover_boost), gate_25d);
2481
2482    let shell_pos = d * base_cloud_r;
2483    let view_vec = shell_pos - eye_pos;
2484    let view_dist = max(length(view_vec), 1.0);
2485    let view_dir = view_vec / view_dist;
2486
2487    let above_fade = smoothstep(1500.0, 160000.0, max(eye_r - base_cloud_r, 0.0));
2488    let below_fade = smoothstep(1200.0, 9000.0, max(base_cloud_r - eye_r, 0.0));
2489    let plane_alt_fade = mix(0.24, 1.0, mix(above_fade, below_fade, below_clouds));
2490    let ray_prox_fade = mix(0.78, 1.0, smoothstep(600.0, 10000.0, view_dist));
2491    let horiz_sin = -sqrt(max(eye_r * eye_r - r_earth * r_earth, 0.0)) / max(eye_r, r_earth);
2492    let ray_elev = dot(view_dir, eye_dir) - horiz_sin;
2493    let sky_hemi_fade = mix(1.0, smoothstep(-0.015, 0.035, ray_elev), below_clouds);
2494    let cross_fade = plane_alt_fade * ray_prox_fade * sky_hemi_fade;
2495
2496    let low_alt_factor = 1.0 - smoothstep(40000.0, 350000.0, eye_alt);
2497    let horizon_graze = abs(dot(view_dir, d));
2498    let dist_persp_fade = 1.0 - 0.58 * smoothstep(55000.0, 260000.0, view_dist) * below_clouds;
2499    let horizon_fade = mix(1.0, smoothstep(0.004, 0.055, horizon_graze), low_alt_factor) * dist_persp_fade;
2500
2501    let sun_dir = normalize(cam.sun_dir.xyz);
2502    let ndotl = dot(d, sun_dir);
2503    let dn_strength = clamp(cam.env_params.x, 0.0, 1.0);
2504    let term = smoothstep(-0.14, 0.18, ndotl);
2505    let night_fade = mix(0.14, 1.0, mix(1.0, term, dn_strength));
2506    let lit_mask = mix(night_fade, 1.0, below_clouds);
2507    let layer_translucency = mix(1.0, mix(0.88, 0.96, cover_boost), below_clouds);
2508    let common_alpha = opacity * lit_mask * cross_fade * horizon_fade * layer_translucency;
2509
2510    let east_raw = vec3<f32>(-d.y, d.x, 0.0);
2511    let east_len = length(east_raw);
2512    let t_east = select(vec3<f32>(1.0, 0.0, 0.0), east_raw / max(east_len, 1e-5), east_len > 1e-4);
2513    let t_north = normalize(cross(d, t_east));
2514
2515    let v_east = dot(view_dir, t_east);
2516    let v_north = dot(view_dir, t_north);
2517    let v_up = dot(view_dir, d);
2518    let v_rad = max(abs(v_up), 0.25);
2519    let par_amp = mix(0.0015, 0.00075, mode_25d) / v_rad;
2520    let east_scale = clamp(east_len, 0.25, 1.0);
2521    let par_vec = vec2<f32>(v_east * par_amp * east_scale, v_north * par_amp);
2522
2523    let unlit_key = normalize(d * 0.52 + t_north * 0.62 - t_east * 0.58);
2524    let relief_light = normalize(mix(unlit_key, normalize(sun_dir + d * 0.28), max(dn_strength, cam.atmo_25d_params.x) * 0.75));
2525    let light_ts = vec3<f32>(dot(relief_light, t_east), dot(relief_light, t_north), dot(relief_light, d));
2526    let sun_ts = vec3<f32>(dot(sun_dir, t_east), dot(sun_dir, t_north), ndotl);
2527    let uv_lod = clamp(0.6931472 * smoothstep(2200000.0, 14000000.0, eye_alt), 0.0, 3.0);
2528    let cloud_haze_t = smoothstep(25000.0, 180000.0, view_dist) * 0.65 * below_clouds;
2529
2530    let dims = max(vec2<f32>(textureDimensions(cloud_tex, 0)), vec2<f32>(1.0));
2531    let step_scale = mix(1.75, 1.35, detail_w);
2532    let bicubic_w = 1.0 - smoothstep(70000.0, 220000.0, eye_alt);
2533
2534    var out: CloudOut;
2535    out.clip_pos = clip;
2536    out.unit_pos = d;
2537    out.uv_par = vec4<f32>(u_unwrapped, v_unwrapped, par_vec.x, par_vec.y);
2538    out.params_fs = vec4<f32>(common_alpha, coarse_gate, detail_w, mode_25d);
2539    out.light_ts_term = vec4<f32>(light_ts, term);
2540    out.view_ts_haze = vec4<f32>(v_east, v_north, v_up, cloud_haze_t);
2541    out.sun_ts_lod = vec4<f32>(sun_ts, uv_lod);
2542    out.grad_step_bic = vec4<f32>(step_scale / dims.x, step_scale / dims.y, bicubic_w, below_clouds);
2543    return out;
2544}
2545
2546@fragment
2547fn fs_cloud(in: CloudOut) -> @location(0) vec4<f32> {
2548    let common_alpha = in.params_fs.x;
2549    if (common_alpha <= 0.004) {
2550        return vec4<f32>(0.0);
2551    }
2552
2553    let d = in.unit_pos;
2554    var u_unwrapped = in.uv_par.x;
2555    var v_base = in.uv_par.y;
2556    let d_xy_r = sqrt(max(d.x * d.x + d.y * d.y, 0.0));
2557    if ((d.x < 0.0 && abs(d.y) < max(d_xy_r * 0.45, 0.06)) || abs(d.z) > 0.85) {
2558        let dn = normalize(d);
2559        let az = select(0.0, atan2(dn.y, dn.x), dot(dn.xy, dn.xy) > 1e-10);
2560        u_unwrapped = az * 0.15915494309 + 0.5;
2561        v_base = clamp(0.5 - asin(clamp(dn.z, -1.0, 1.0)) * 0.31830988618, 0.001, 0.999);
2562    }
2563    let u_base = fract(u_unwrapped + cam.cloud_params.y * 0.15915494309);
2564    let uv_lod = in.sun_ts_lod.w;
2565
2566    let cover_boost = clamp(cam.cloud_tint_params.w, 0.0, 1.0) * in.grad_step_bic.w;
2567    let d_coarse = sample_cloud_density(vec2<f32>(u_base, v_base), max(uv_lod, 2.0));
2568    if (d_coarse + cover_boost * 0.65 <= in.params_fs.y) {
2569        return vec4<f32>(0.0);
2570    }
2571
2572    let detail_w = in.params_fs.z;
2573    let mode_25d = in.params_fs.w;
2574    let h_off = cloud_density_to_height(d_coarse) - 0.22;
2575    let u = fract(u_base - in.uv_par.z * h_off);
2576    let v = clamp(v_base + in.uv_par.w * h_off, 0.001, 0.999);
2577
2578    let p_cloud2 = vec2<f32>(d.x - d.z * 0.618034, d.y + d.z * 0.618034);
2579    let noise_uv = p_cloud2 * 26.5625 + vec2<f32>(cam.cloud_params.z * 0.000005625, 0.0);
2580
2581    let d_c_lin = sample_cloud_density(vec2<f32>(u, v), uv_lod);
2582    let d_e = sample_cloud_density(vec2<f32>(fract(u + in.grad_step_bic.x), v), uv_lod);
2583    let d_n = sample_cloud_density(vec2<f32>(u, clamp(v - in.grad_step_bic.y, 0.001, 0.999)), uv_lod);
2584    let ns_all = textureSampleLevel(cloud_noise_tex, cloud_noise_sampler, noise_uv, 0.0);
2585
2586    var d_c_base = d_c_lin;
2587    let bicubic_w = in.grad_step_bic.z;
2588    if (bicubic_w > 0.02) {
2589        let dims = max(vec2<f32>(textureDimensions(cloud_tex, 0)), vec2<f32>(1.0));
2590        d_c_base = mix(d_c_lin, sample_cloud_bicubic_density(vec2<f32>(u, v), dims, 1.0 / dims), bicubic_w);
2591    }
2592    let warp_delta = (ns_all.ba - vec2<f32>(0.5)) * (0.55 * detail_w);
2593    let d_c = clamp(
2594        d_c_base + warp_delta.x * (d_e - d_c_lin) + warp_delta.y * (d_n - d_c_lin) + cover_boost * 0.55,
2595        0.0,
2596        1.0,
2597    );
2598
2599    let crisp_3d = d_c * (0.35 + 0.65 * d_c);
2600    let base_density = 0.56 * d_c + 0.22 * (d_e + d_n);
2601    let clear_cut = smoothstep(0.14, 0.54, base_density);
2602    let fbm = ns_all.x * 0.65 + ns_all.y * 0.35;
2603    let fbm_billow = (fbm - 0.5) * 0.16 * detail_w;
2604    let eroded = clamp(clear_cut * (0.44 + fbm * 1.16) - 0.13, 0.0, 1.0);
2605    let refined = mix(clear_cut, eroded, detail_w * 0.88);
2606
2607    let sigmoid_approx = smoothstep(0.11, 0.75, refined);
2608    let hard_zero_gate = smoothstep(0.13, 0.31, refined);
2609    let mask_25d = clamp(sigmoid_approx * hard_zero_gate * 1.04, 0.0, 1.0);
2610    let mask_density = mix(crisp_3d, mask_25d, mode_25d);
2611
2612    let alpha = mask_density * common_alpha;
2613    if (alpha <= 0.003) {
2614        return vec4<f32>(0.0);
2615    }
2616
2617    let h_c = clamp(cloud_density_to_height(d_c) + fbm_billow, 0.0, 1.0);
2618    let h_e = cloud_density_to_height(d_e);
2619    let h_n = cloud_density_to_height(d_n);
2620    let h_smooth = clamp(0.52 * h_c + 0.24 * (h_e + h_n), 0.0, 1.0);
2621
2622    let normal_amp = mix(3.4, 2.2, detail_w);
2623    let dh_east = (h_e - h_c) * 2.0;
2624    let dh_north = (h_n - h_c) * 2.0;
2625    let n_ts = normalize(vec3<f32>(-dh_east * normal_amp, -dh_north * normal_amp, 1.0));
2626
2627    let light_ts = in.light_ts_term.xyz;
2628    let slope_lit = clamp(dot(n_ts, light_ts), 0.0, 1.0);
2629    let horizon_shadow = clamp(-(dh_east * light_ts.x - dh_north * light_ts.y) * 1.15, -0.28, 0.28);
2630    let height_ao = mix(0.68, 1.06, smoothstep(0.05, 0.85, h_smooth));
2631    let rim_base = 1.0 - clamp(abs(dot(in.view_ts_haze.xyz, n_ts)), 0.0, 1.0);
2632    let silver_rim = (rim_base * rim_base * rim_base)
2633        * smoothstep(0.12, 0.52, d_c)
2634        * (1.0 - smoothstep(0.58, 0.92, d_c))
2635        * 0.18;
2636
2637    let below_clouds = in.grad_step_bic.w;
2638    let relief_factor = clamp(0.55 + slope_lit * 0.45 + horizon_shadow * 0.65, 0.0, 1.0);
2639    let tex_tint = clamp(height_ao * (0.86 + horizon_shadow * 0.45) + silver_rim, 0.68, 1.08);
2640    let shade_base = mix(
2641        vec3<f32>(0.62, 0.69, 0.79),
2642        vec3<f32>(0.995, 0.998, 1.0),
2643        clamp(h_smooth * 0.62 + relief_factor * 0.46, 0.0, 1.0),
2644    ) * tex_tint;
2645    let below_shade = mix(
2646        vec3<f32>(0.70, 0.76, 0.85),
2647        vec3<f32>(0.99, 0.995, 1.0),
2648        clamp((1.0 - h_smooth * 0.35) * 0.45 + relief_factor * 0.55, 0.0, 1.0),
2649    ) * clamp(tex_tint * 1.03, 0.74, 1.06);
2650    let flat_cloud = mix(shade_base, below_shade, below_clouds);
2651
2652    let ndotl = in.sun_ts_lod.z;
2653    let sn = ndotl * 7.5;
2654    let sn2 = sn * sn;
2655    let sunset = (1.0 / (1.0 + sn2 + 0.5 * sn2 * sn2)) * vec3<f32>(0.54, 0.24, 0.09);
2656    let sun_slope = smoothstep(-0.10, 0.65, dot(n_ts, in.sun_ts_lod.xyz));
2657    let term = in.light_ts_term.w;
2658    let dn_strength = clamp(cam.env_params.x, 0.0, 1.0);
2659    let real_sky_w = clamp(cam.atmo_25d_params.x, 0.0, 1.0);
2660    let weather_dark = clamp(cam.weather_opt_params.x, 0.0, 1.0);
2661
2662    let day_cloud = (vec3<f32>(0.04, 0.06, 0.10) + cam.sun_color.rgb * term * mix(0.76, 1.12, sun_slope) + sunset) * tex_tint;
2663    let below_lit_blend = max(dn_strength * (1.0 - below_clouds), real_sky_w * below_clouds);
2664    var rgb = mix(flat_cloud, day_cloud, below_lit_blend);
2665
2666    // Unified Base Weather API cloud storm darkening & tint (bright cumulus -> brooding nimbostratus!).
2667    let storm_dark_w = clamp(weather_dark, 0.0, 1.0) * below_clouds;
2668    if (storm_dark_w > 0.002) {
2669        let day_t = mix(1.0, smoothstep(-0.08, 0.22, ndotl), real_sky_w);
2670        let storm_underbelly = mix(vec3<f32>(0.03, 0.04, 0.06), vec3<f32>(0.24, 0.28, 0.34), day_t)
2671                             * mix(0.76, 1.12, relief_factor);
2672        rgb = mix(rgb, storm_underbelly, storm_dark_w * 0.78);
2673    }
2674    rgb *= cam.cloud_tint_params.xyz;
2675
2676    let cloud_haze_t = in.view_ts_haze.w;
2677    if (cloud_haze_t > 0.001) {
2678        let day_scale = clamp(max(cam.sky_bottom.b, max(cam.sky_bottom.r, cam.sky_bottom.g)), 0.0, 1.0);
2679        let classic_fog = vec3<f32>(0.75, 0.86, 0.96) * day_scale;
2680        let day_t = smoothstep(-0.08, 0.24, ndotl);
2681        let golden_t = exp(-pow((ndotl - 0.03) * 7.5, 2.0));
2682        var phys_fog = mix(vec3<f32>(0.022, 0.036, 0.066), mix(vec3<f32>(0.92, 0.48, 0.20), vec3<f32>(0.72, 0.85, 0.96), smoothstep(0.02, 0.32, ndotl)), day_t)
2683                     + vec3<f32>(0.25, 0.12, 0.06) * golden_t;
2684        phys_fog = mix(phys_fog, vec3<f32>(0.28, 0.32, 0.38) * max(day_t, 0.08), weather_dark * 0.72);
2685        rgb = mix(rgb, mix(classic_fog, phys_fog, real_sky_w), cloud_haze_t);
2686    }
2687
2688    return vec4<f32>(rgb, alpha);
2689}
2690"#;
2691
2692const DYNAMIC_MESH_WGSL: &str = r#"
2693struct GpuCameraUniforms {
2694    view_proj_rte: mat4x4<f32>,
2695    inv_view_proj_rte: mat4x4<f32>,
2696    ecef_from_icrf: mat4x4<f32>,
2697    icrf_from_ecef: mat4x4<f32>,
2698    light_view_proj_rte: mat4x4<f32>,
2699    eye_high: vec4<f32>,
2700    eye_low: vec4<f32>,
2701    sun_dir: vec4<f32>,
2702    sun_color: vec4<f32>,
2703    ambient_color: vec4<f32>,
2704    sky_top: vec4<f32>,
2705    sky_bottom: vec4<f32>,
2706    moon_dir: vec4<f32>,
2707    env_params: vec4<f32>,
2708    cloud_params: vec4<f32>,
2709    viewport_wh: vec4<f32>,
2710    atmo_25d_params: vec4<f32>,
2711    weather_opt_params: vec4<f32>,
2712    cloud_tint_params: vec4<f32>,
2713    view_flags: vec4<f32>,
2714}
2715
2716struct GpuDynamicUniforms {
2717    anchor_high: vec4<f32>,
2718    anchor_low: vec4<f32>,
2719    color: vec4<f32>,
2720    dyn_meta: vec4<u32>,
2721}
2722
2723@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
2724@group(0) @binding(1) var<uniform> dyn_u: GpuDynamicUniforms;
2725
2726struct DynVsOut {
2727    @builtin(position) clip_pos: vec4<f32>,
2728    @location(0) normal: vec3<f32>,
2729    @location(1) color: vec4<f32>,
2730    @location(2) @interpolate(flat) unlit: u32,
2731}
2732
2733@vertex
2734fn vs_dynamic(
2735    @location(0) pos_u: vec4<f32>,
2736    @location(1) norm_v: vec4<f32>,
2737) -> DynVsOut {
2738    let center_rel = (dyn_u.anchor_high.xyz - cam.eye_high.xyz)
2739                   + (dyn_u.anchor_low.xyz - cam.eye_low.xyz);
2740    let world_rel = center_rel + pos_u.xyz;
2741    var out: DynVsOut;
2742    out.clip_pos = cam.view_proj_rte * vec4<f32>(world_rel, 1.0);
2743    out.normal = norm_v.xyz;
2744    out.color = dyn_u.color;
2745    out.unlit = dyn_u.dyn_meta.x;
2746    return out;
2747}
2748
2749@fragment
2750fn fs_dynamic(in: DynVsOut) -> @location(0) vec4<f32> {
2751    if (in.unlit != 0u) {
2752        return in.color;
2753    }
2754    let len_sq = dot(in.normal, in.normal);
2755    let n = select(vec3<f32>(0.0, 1.0, 0.0), normalize(in.normal), len_sq > 0.0001);
2756    let ndotl = max(dot(n, normalize(cam.sun_dir.xyz)), 0.0);
2757    let dn = max(clamp(cam.env_params.x, 0.0, 1.0), clamp(cam.atmo_25d_params.z * cam.env_params.z, 0.0, 1.0));
2758    let flat_lit = vec3<f32>(0.85) + vec3<f32>(0.22) * ndotl;
2759    let day_lit = cam.ambient_color.rgb + cam.sun_color.rgb * ndotl;
2760    let lit = mix(flat_lit, day_lit, dn);
2761    return vec4<f32>(in.color.rgb * lit, in.color.a);
2762}
2763"#;
2764
2765const GEO_OBJECT_WGSL: &str = r#"
2766struct GpuCameraUniforms {
2767    view_proj_rte: mat4x4<f32>,
2768    inv_view_proj_rte: mat4x4<f32>,
2769    ecef_from_icrf: mat4x4<f32>,
2770    icrf_from_ecef: mat4x4<f32>,
2771    light_view_proj_rte: mat4x4<f32>,
2772    eye_high: vec4<f32>,
2773    eye_low: vec4<f32>,
2774    sun_dir: vec4<f32>,
2775    sun_color: vec4<f32>,
2776    ambient_color: vec4<f32>,
2777    sky_top: vec4<f32>,
2778    sky_bottom: vec4<f32>,
2779    moon_dir: vec4<f32>,
2780    env_params: vec4<f32>,
2781    cloud_params: vec4<f32>,
2782    viewport_wh: vec4<f32>,
2783    atmo_25d_params: vec4<f32>,
2784    weather_opt_params: vec4<f32>,
2785    cloud_tint_params: vec4<f32>,
2786    view_flags: vec4<f32>,
2787}
2788
2789struct GpuGeoInstance {
2790    anchor_high: vec4<f32>,
2791    anchor_low: vec4<f32>,
2792    col0: vec4<f32>,
2793    col1: vec4<f32>,
2794    col2: vec4<f32>,
2795    base_color: vec4<f32>,
2796    emissive: vec4<f32>,
2797}
2798
2799@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
2800@group(0) @binding(1) var<storage, read> geo_instances: array<GpuGeoInstance>;
2801@group(1) @binding(0) var shadow_map: texture_depth_2d;
2802@group(1) @binding(1) var shadow_sampler: sampler_comparison;
2803@group(2) @binding(0) var geo_albedo_tex: texture_2d<f32>;
2804@group(2) @binding(1) var geo_albedo_sampler: sampler;
2805
2806struct GeoVsOut {
2807    @builtin(position) clip_pos: vec4<f32>,
2808    @location(0) world_rel: vec3<f32>,
2809    @location(1) normal: vec3<f32>,
2810    @location(2) base_color: vec4<f32>,
2811    @location(3) emissive: vec4<f32>,
2812    @location(4) material_params: vec4<f32>,
2813    @location(5) uv: vec2<f32>,
2814}
2815
2816@vertex
2817fn vs_geo_object(
2818    @location(0) pos_u: vec4<f32>,
2819    @location(1) norm_v: vec4<f32>,
2820    @location(2) vert_color: vec4<f32>,
2821    @builtin(instance_index) inst_idx: u32,
2822) -> GeoVsOut {
2823    let inst = geo_instances[inst_idx];
2824    let c0 = inst.col0.xyz;
2825    let c1 = inst.col1.xyz;
2826    let c2 = inst.col2.xyz;
2827
2828    let center_rel = (inst.anchor_high.xyz - cam.eye_high.xyz)
2829                   + (inst.anchor_low.xyz - cam.eye_low.xyz);
2830    let local_offset = c0 * pos_u.x + c1 * pos_u.y + c2 * pos_u.z;
2831    let world_rel = center_rel + local_offset;
2832
2833    let adj0 = cross(c1, c2);
2834    let adj1 = cross(c2, c0);
2835    let adj2 = cross(c0, c1);
2836    var world_n = adj0 * norm_v.x + adj1 * norm_v.y + adj2 * norm_v.z;
2837    if (dot(world_n, world_n) < 1e-12) {
2838        world_n = c0 * norm_v.x + c1 * norm_v.y + c2 * norm_v.z;
2839    }
2840
2841    var out: GeoVsOut;
2842    out.clip_pos = cam.view_proj_rte * vec4<f32>(world_rel, 1.0);
2843    out.world_rel = world_rel;
2844    out.normal = world_n;
2845    out.base_color = inst.base_color * vert_color;
2846    out.emissive = inst.emissive;
2847    out.material_params = vec4<f32>(inst.col0.w, inst.col1.w, inst.col2.w, norm_v.w);
2848    out.uv = vec2<f32>(pos_u.w, norm_v.w);
2849    return out;
2850}
2851
2852fn sample_geo_shadow(world_rel: vec3<f32>, n: vec3<f32>, sun_dir: vec3<f32>, shadow_radius: f32) -> f32 {
2853    let ndotl = max(dot(n, sun_dir), 0.0);
2854    let normal_bias = max(shadow_radius * 0.0014, 0.35) * (1.2 - 0.7 * ndotl);
2855    let lclip = cam.light_view_proj_rte * vec4<f32>(world_rel + n * normal_bias, 1.0);
2856    let ndc = lclip.xyz / max(lclip.w, 1e-5);
2857    let uv = vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
2858    let depth_ref = clamp(ndc.z - 0.0005, 0.0, 0.9999);
2859    let dims = max(vec2<f32>(textureDimensions(shadow_map)), vec2<f32>(1.0));
2860    let texel = 1.0 / dims;
2861    var acc = 0.0;
2862    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(-texel.x, -texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
2863    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(texel.x, -texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
2864    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv, vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
2865    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(-texel.x, texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
2866    acc += textureSampleCompareLevel(shadow_map, shadow_sampler, clamp(uv + vec2<f32>(texel.x, texel.y), vec2<f32>(0.001), vec2<f32>(0.999)), depth_ref);
2867    let border = max(abs(ndc.x), abs(ndc.y));
2868    let in_bounds = (1.0 - smoothstep(0.84, 0.99, border)) * step(0.0, ndc.z) * step(ndc.z, 1.0);
2869    return mix(1.0, acc * 0.2, in_bounds);
2870}
2871
2872@fragment
2873fn fs_geo_object(in: GeoVsOut) -> @location(0) vec4<f32> {
2874    let tex = textureSample(geo_albedo_tex, geo_albedo_sampler, in.uv);
2875    let tinted = in.base_color * tex;
2876    let accent_t = clamp(in.material_params.w * in.emissive.w, 0.0, 1.0);
2877    let albedo = mix(tinted.rgb, vec3<f32>(0.97, 0.99, 1.0), accent_t);
2878
2879    if (in.material_params.z >= 0.5) {
2880        return vec4<f32>(clamp(albedo + in.emissive.rgb, vec3<f32>(0.0), vec3<f32>(1.0)), tinted.a);
2881    }
2882
2883    let len_sq = dot(in.normal, in.normal);
2884    let n = select(vec3<f32>(0.0, 0.0, 1.0), normalize(in.normal), len_sq > 1e-10);
2885    let view_dir = select(vec3<f32>(0.0, 0.0, 1.0), normalize(-in.world_rel), dot(in.world_rel, in.world_rel) > 1e-8);
2886    let sun_dir = normalize(cam.sun_dir.xyz);
2887
2888    let roughness = clamp(in.material_params.x, 0.05, 1.0);
2889    let metalness = clamp(in.material_params.y, 0.0, 1.0);
2890
2891    let dn = max(clamp(cam.env_params.x, 0.0, 1.0), clamp(cam.atmo_25d_params.z * cam.env_params.z, 0.0, 1.0));
2892    let shadow_w = clamp(cam.atmo_25d_params.w, 0.0, 1.0);
2893    var shadow_f = 1.0;
2894    if (shadow_w > 0.001) {
2895        shadow_f = mix(1.0, sample_geo_shadow(in.world_rel, n, sun_dir, max(cam.weather_opt_params.w, 10.0)), shadow_w * (1.0 - cam.weather_opt_params.x * 0.55));
2896    }
2897
2898    let ndotl_sun = max(dot(n, sun_dir), 0.0) * shadow_f;
2899    let ndotv = max(dot(n, view_dir), 0.0);
2900    let hemi = 0.5 + 0.5 * dot(n, view_dir);
2901
2902    let studio_lit = vec3<f32>(0.42 + 0.24 * hemi) + vec3<f32>(0.52) * max(ndotl_sun, ndotv * 0.65);
2903    let day_lit = cam.ambient_color.rgb * (0.75 + 0.45 * hemi) + cam.sun_color.rgb * ndotl_sun * (1.0 - cam.weather_opt_params.x * 0.55);
2904    let diffuse_light = mix(studio_lit, day_lit, dn);
2905
2906    let half_vec = select(view_dir, normalize(sun_dir + view_dir), dot(sun_dir + view_dir, sun_dir + view_dir) > 1e-6);
2907    let ndoth = max(dot(n, half_vec), 0.0);
2908    let shininess = mix(96.0, 8.0, roughness * roughness);
2909    let spec_strength = (1.0 - roughness * 0.75) * mix(0.22, 0.85, metalness);
2910    let f0 = mix(vec3<f32>(0.04), albedo, metalness);
2911    let spec = f0 * pow(ndoth, shininess) * spec_strength * max(ndotl_sun, 1.0 - dn);
2912
2913    let diffuse_albedo = albedo * (1.0 - metalness * 0.65);
2914    let color = clamp(diffuse_albedo * diffuse_light + spec + in.emissive.rgb, vec3<f32>(0.0), vec3<f32>(1.0));
2915    return vec4<f32>(color, tinted.a);
2916}
2917"#;
2918
2919const GEO_SHADOW_WGSL: &str = r#"
2920struct GpuCameraUniforms {
2921    view_proj_rte: mat4x4<f32>,
2922    inv_view_proj_rte: mat4x4<f32>,
2923    ecef_from_icrf: mat4x4<f32>,
2924    icrf_from_ecef: mat4x4<f32>,
2925    light_view_proj_rte: mat4x4<f32>,
2926    eye_high: vec4<f32>,
2927    eye_low: vec4<f32>,
2928    sun_dir: vec4<f32>,
2929    sun_color: vec4<f32>,
2930    ambient_color: vec4<f32>,
2931    sky_top: vec4<f32>,
2932    sky_bottom: vec4<f32>,
2933    moon_dir: vec4<f32>,
2934    env_params: vec4<f32>,
2935    cloud_params: vec4<f32>,
2936    viewport_wh: vec4<f32>,
2937    atmo_25d_params: vec4<f32>,
2938    weather_opt_params: vec4<f32>,
2939    cloud_tint_params: vec4<f32>,
2940    view_flags: vec4<f32>,
2941}
2942
2943struct GpuGeoInstance {
2944    anchor_high: vec4<f32>,
2945    anchor_low: vec4<f32>,
2946    col0: vec4<f32>,
2947    col1: vec4<f32>,
2948    col2: vec4<f32>,
2949    base_color: vec4<f32>,
2950    emissive: vec4<f32>,
2951}
2952
2953@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
2954@group(0) @binding(1) var<storage, read> geo_instances: array<GpuGeoInstance>;
2955
2956@vertex
2957fn vs_geo_shadow(
2958    @location(0) pos_u: vec4<f32>,
2959    @location(1) norm_v: vec4<f32>,
2960    @builtin(instance_index) inst_idx: u32,
2961) -> @builtin(position) vec4<f32> {
2962    let inst = geo_instances[inst_idx];
2963    let center_rel = (inst.anchor_high.xyz - cam.eye_high.xyz)
2964                   + (inst.anchor_low.xyz - cam.eye_low.xyz);
2965    let local_offset = inst.col0.xyz * pos_u.x + inst.col1.xyz * pos_u.y + inst.col2.xyz * pos_u.z;
2966    return cam.light_view_proj_rte * vec4<f32>(center_rel + local_offset, 1.0);
2967}
2968"#;
2969
2970const PARTICLE_VOLUME_WGSL: &str = r#"
2971struct GpuCameraUniforms {
2972    view_proj_rte: mat4x4<f32>,
2973    inv_view_proj_rte: mat4x4<f32>,
2974    ecef_from_icrf: mat4x4<f32>,
2975    icrf_from_ecef: mat4x4<f32>,
2976    light_view_proj_rte: mat4x4<f32>,
2977    eye_high: vec4<f32>,
2978    eye_low: vec4<f32>,
2979    sun_dir: vec4<f32>,
2980    sun_color: vec4<f32>,
2981    ambient_color: vec4<f32>,
2982    sky_top: vec4<f32>,
2983    sky_bottom: vec4<f32>,
2984    moon_dir: vec4<f32>,
2985    env_params: vec4<f32>,
2986    cloud_params: vec4<f32>,
2987    viewport_wh: vec4<f32>,
2988    atmo_25d_params: vec4<f32>,
2989    weather_opt_params: vec4<f32>,
2990    cloud_tint_params: vec4<f32>,
2991    view_flags: vec4<f32>,
2992}
2993
2994struct GpuParticleLayerUniforms {
2995    basis_east: vec4<f32>,
2996    basis_north: vec4<f32>,
2997    basis_up: vec4<f32>,
2998    forward_bias: vec4<f32>,
2999    cam_right_mpx: vec4<f32>,
3000    cam_up_pad: vec4<f32>,
3001    altitude_bounds: vec4<f32>,
3002    volume_params: vec4<f32>,
3003    motion_params: vec4<f32>,
3004    size_params: vec4<f32>,
3005    flutter_clamp: vec4<f32>,
3006    color: vec4<f32>,
3007    particle_meta: vec4<u32>,
3008}
3009
3010@group(0) @binding(0) var<uniform> cam: GpuCameraUniforms;
3011@group(0) @binding(1) var<uniform> layer: GpuParticleLayerUniforms;
3012@group(1) @binding(0) var sprite_tex: texture_2d<f32>;
3013@group(1) @binding(1) var sprite_sampler: sampler;
3014
3015struct ParticleVsOut {
3016    @builtin(position) clip_pos: vec4<f32>,
3017    @location(0) uv: vec2<f32>,
3018    @location(1) color: vec4<f32>,
3019    @location(2) @interpolate(flat) sprite_mode: u32,
3020}
3021
3022fn pcg_u32(v: u32) -> u32 {
3023    let state = v * 747796405u + 2891336453u;
3024    let word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
3025    return (word >> 22u) ^ word;
3026}
3027
3028fn hash01(seed: u32) -> f32 {
3029    return f32(pcg_u32(seed)) * (1.0 / 4294967296.0);
3030}
3031
3032@vertex
3033fn vs_particle(
3034    @builtin(vertex_index) vid: u32,
3035    @builtin(instance_index) inst_idx: u32,
3036) -> ParticleVsOut {
3037    var out: ParticleVsOut;
3038    out.clip_pos = vec4<f32>(2.0, 2.0, 2.0, 1.0);
3039    out.uv = vec2<f32>(0.5, 0.5);
3040    out.color = vec4<f32>(0.0);
3041    out.sprite_mode = layer.particle_meta.x;
3042
3043    let base_seed = inst_idx * 4u + layer.particle_meta.z * 1664525u + 1013904223u;
3044    let r0 = hash01(base_seed + 0u);
3045    let r1 = hash01(base_seed + 1u);
3046    let r2 = hash01(base_seed + 2u);
3047    let r3 = hash01(base_seed + 3u);
3048
3049    let extent_xy = max(layer.volume_params.x, 1.0);
3050    let extent_z = max(layer.volume_params.y, 1.0);
3051    let edge_fade_frac = clamp(layer.volume_params.z, 0.04, 0.48);
3052    let near_fade_m = max(layer.volume_params.w, 0.1);
3053
3054    let u_e = fract(r0 + layer.basis_east.w);
3055    let u_n = fract(r1 + layer.basis_north.w);
3056    let u_z = fract(r2 + layer.basis_up.w);
3057
3058    var rel_e = (u_e - 0.5) * extent_xy;
3059    var rel_n = (u_n - 0.5) * extent_xy;
3060    let rel_z = (u_z - 0.5) * extent_z;
3061
3062    let time_s = layer.motion_params.w;
3063    let flutter_amp = layer.flutter_clamp.x;
3064    if (flutter_amp > 0.0001) {
3065        let flutter_freq = layer.flutter_clamp.y;
3066        let phase = r3 * 6.2831853 + time_s * flutter_freq * (0.72 + 0.56 * fract(r0 * 17.31));
3067        let amp = flutter_amp * (0.55 + 0.90 * r3);
3068        rel_e += sin(phase) * amp;
3069        rel_n += cos(phase * 0.83 + r1 * 6.2831853) * amp;
3070    }
3071
3072    let east = layer.basis_east.xyz;
3073    let north = layer.basis_north.xyz;
3074    let up = layer.basis_up.xyz;
3075    let center_rel = east * rel_e + north * rel_n + up * rel_z + layer.forward_bias.xyz;
3076
3077    let center_clip = cam.view_proj_rte * vec4<f32>(center_rel, 1.0);
3078    if (center_clip.w <= 0.05) {
3079        return out;
3080    }
3081
3082    let dist = max(length(center_rel), 0.05);
3083    let nx = abs(rel_e) / (0.5 * extent_xy);
3084    let ny = abs(rel_n) / (0.5 * extent_xy);
3085    let nz = abs(rel_z) / (0.5 * extent_z);
3086    let box_r = max(max(nx, ny), nz);
3087    let edge_fade = 1.0 - smoothstep(1.0 - edge_fade_frac, 1.0, box_r);
3088    let near_fade = smoothstep(near_fade_m * 0.30, near_fade_m, dist);
3089
3090    // Physical altitude bounds: clip smoothly at ground terrain surface and cloud ceiling.
3091    let bias_alt = dot(layer.forward_bias.xyz, up);
3092    let particle_alt_msl = layer.altitude_bounds.x + rel_z + bias_alt;
3093    let ground_alt_msl = layer.altitude_bounds.y;
3094    let ceiling_alt_msl = layer.altitude_bounds.z;
3095    let ceiling_fade_m = max(layer.altitude_bounds.w, 1.0);
3096    let above_ground = smoothstep(ground_alt_msl - 0.5, ground_alt_msl + 2.5, particle_alt_msl);
3097    let below_ceiling = 1.0 - smoothstep(ceiling_alt_msl - ceiling_fade_m, ceiling_alt_msl, particle_alt_msl);
3098
3099    let alpha_mul = edge_fade * near_fade * above_ground * below_ceiling;
3100    if (alpha_mul <= 0.003 || layer.color.a <= 0.003) {
3101        return out;
3102    }
3103
3104    var corners = array<vec2<f32>, 6>(
3105        vec2<f32>(-1.0, -1.0),
3106        vec2<f32>(1.0, -1.0),
3107        vec2<f32>(1.0, 1.0),
3108        vec2<f32>(-1.0, -1.0),
3109        vec2<f32>(1.0, 1.0),
3110        vec2<f32>(-1.0, 1.0),
3111    );
3112    let corner = corners[vid % 6u];
3113
3114    let cam_right = layer.cam_right_mpx.xyz;
3115    let cam_up = layer.cam_up_pad.xyz;
3116    let m_per_px = dist * max(layer.cam_right_mpx.w, 1e-6);
3117    let min_px = max(layer.flutter_clamp.z, 0.75);
3118    let max_px = max(layer.flutter_clamp.w, min_px);
3119
3120    var right_axis = cam_right;
3121    var up_axis = cam_up;
3122    var hw = 0.05;
3123    var hh = 0.05;
3124    var uv = vec2<f32>(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5);
3125
3126    if (layer.particle_meta.y == 0u) {
3127        // VelocityAligned: align streak or far-field curtain vertically along 3D wind + gravity velocity vector.
3128        let fall_v = layer.motion_params.x;
3129        let wind_e = layer.motion_params.y;
3130        let wind_n = layer.motion_params.z;
3131        let vel = east * wind_e + north * wind_n - up * fall_v;
3132        let speed = max(length(vel), 0.05);
3133        let v_dir = vel / speed;
3134        let view_dir = center_rel / dist;
3135        let side_raw = cross(v_dir, view_dir);
3136        let side_len = length(side_raw);
3137        let foreshorten = mix(0.26, 1.0, smoothstep(0.06, 0.42, side_len));
3138
3139        if (side_len > 0.04) {
3140            right_axis = side_raw / side_len;
3141            up_axis = -v_dir;
3142        } else {
3143            right_axis = cam_right;
3144            up_axis = cam_up;
3145        }
3146
3147        let size_var = 0.75 + 0.50 * r3;
3148        let raw_hw = max(layer.size_params.x * 0.5 * size_var, 0.004);
3149        let raw_hh = max((layer.size_params.y + speed * layer.size_params.z) * 0.5 * size_var, raw_hw);
3150        if (layer.particle_meta.x == 4u) {
3151            // ProceduralCurtain: wide translucent rain-shaft / snow-squall veil without narrow streak clamp.
3152            hw = clamp(raw_hw, min_px * 0.5 * m_per_px, max_px * 0.5 * m_per_px);
3153            hh = clamp(raw_hh, min_px * 0.5 * m_per_px, max_px * 0.9 * m_per_px) * mix(0.45, 1.0, foreshorten);
3154        } else {
3155            let max_streak_w_px = min(max_px * 0.12, max(min_px * 2.2, 3.2));
3156            hw = clamp(raw_hw, min_px * 0.5 * m_per_px, max_streak_w_px * 0.5 * m_per_px);
3157            hh = clamp(raw_hh, min_px * 0.5 * m_per_px, max_px * 0.5 * m_per_px) * foreshorten;
3158            hh = max(hh, hw * 1.15);
3159        }
3160        uv = vec2<f32>(corner.x * 0.5 + 0.5, corner.y * 0.5 + 0.5);
3161    } else {
3162        // CameraFacing: 2D camera-aligned billboard with per-particle spin.
3163        let spin_dir = select(-1.0, 1.0, (inst_idx & 1u) == 0u);
3164        let ang = r3 * 6.2831853 + time_s * layer.size_params.w * spin_dir;
3165        let s = sin(ang);
3166        let c = cos(ang);
3167        right_axis = cam_right * c - cam_up * s;
3168        up_axis = cam_right * s + cam_up * c;
3169
3170        let size_var = 0.65 + 0.70 * r3;
3171        let raw_hw = max(layer.size_params.x * 0.5 * size_var, 0.005);
3172        let raw_hh = max(layer.size_params.y * 0.5 * size_var, 0.005);
3173        hw = clamp(raw_hw, min_px * 0.5 * m_per_px, max_px * 0.5 * m_per_px);
3174        hh = clamp(raw_hh, min_px * 0.5 * m_per_px, max_px * 0.5 * m_per_px);
3175        uv = vec2<f32>(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5);
3176    }
3177
3178    let world_rel = center_rel + right_axis * (corner.x * hw) + up_axis * (corner.y * hh);
3179    out.clip_pos = cam.view_proj_rte * vec4<f32>(world_rel, 1.0);
3180    out.uv = uv;
3181
3182    // Day/night/sunset lighting tint so precipitation responds naturally to sun elevation.
3183    let dn = max(clamp(cam.env_params.x, 0.0, 1.0), clamp(cam.atmo_25d_params.z * cam.env_params.z, 0.0, 1.0));
3184    let sun_elev = dot(normalize(up), normalize(cam.sun_dir.xyz));
3185    let sun_w = smoothstep(-0.10, 0.28, sun_elev);
3186    let golden_w = exp(-pow((sun_elev - 0.03) * 7.5, 2.0));
3187    let sun_warm = mix(vec3<f32>(1.0, 0.68, 0.42), cam.sun_color.rgb, smoothstep(0.0, 0.28, sun_elev));
3188    let day_lit = mix(
3189        vec3<f32>(0.22, 0.27, 0.38),
3190        cam.ambient_color.rgb * 0.85 + sun_warm * 0.92 + vec3<f32>(0.18, 0.09, 0.03) * golden_w,
3191        sun_w,
3192    );
3193    let lit = mix(vec3<f32>(0.96, 0.98, 1.0), clamp(day_lit, vec3<f32>(0.20), vec3<f32>(1.12)), dn);
3194    let depth_fade = 0.80 + 0.20 * (1.0 - clamp(dist / max(extent_xy, 1.0), 0.0, 1.0));
3195    out.color = vec4<f32>(layer.color.rgb * lit, layer.color.a * alpha_mul * depth_fade);
3196    return out;
3197}
3198
3199@fragment
3200fn fs_particle(in: ParticleVsOut) -> @location(0) vec4<f32> {
3201    let p = in.uv * 2.0 - vec2<f32>(1.0);
3202    let r = length(p);
3203
3204    // Pre-compute simplistic 6-fold mathematical snowflake SDF in uniform control flow for fwidth().
3205    let sector = 1.04719755;
3206    let safe_ang = select(0.0, atan2(p.y, p.x), r > 1e-4);
3207    let folded = abs(safe_ang - sector * floor(safe_ang / sector + 0.5));
3208    let su = r * cos(folded);
3209    let sv = r * sin(folded);
3210    let d_core = r - 0.18;
3211    let spoke_u = clamp(su, 0.0, 0.86);
3212    let d_spoke = length(vec2<f32>(su - spoke_u, sv)) - 0.062;
3213    let b_dir = vec2<f32>(0.5, 0.8660254);
3214    let b_rel = vec2<f32>(su - 0.44, sv);
3215    let b_proj = clamp(dot(b_rel, b_dir), 0.0, 0.29);
3216    let d_branch = length(b_rel - b_dir * b_proj) - 0.048;
3217    let d_crystal = min(d_core, min(d_spoke, d_branch));
3218    let aa_crystal = max(fwidth(d_crystal), 0.045);
3219
3220    var out_col = in.color;
3221    if (in.sprite_mode == 0u) {
3222        let texel = textureSampleLevel(sprite_tex, sprite_sampler, in.uv, 0.0);
3223        out_col = texel * in.color;
3224    } else if (in.sprite_mode == 1u) {
3225        // Pure mathematical tapered 2D raindrop streak.
3226        let t = clamp(in.uv.y, 0.0, 1.0);
3227        let width_prof = mix(0.76, 0.20, smoothstep(0.08, 1.0, t)) * smoothstep(0.0, 0.08, t);
3228        let x_norm = abs(p.x) / max(width_prof, 0.04);
3229        let core = exp(-x_norm * x_norm * 2.5);
3230        let tail_fade = (1.0 - smoothstep(0.14, 1.0, t)) * smoothstep(0.0, 0.06, t);
3231        let head_glint = exp(-((p.y + 0.72) * (p.y + 0.72) * 14.0 + p.x * p.x * 5.5)) * 0.35;
3232        let mask = clamp(core * tail_fade + head_glint * core, 0.0, 1.0);
3233        out_col = vec4<f32>(in.color.rgb + vec3<f32>(head_glint * 0.25), in.color.a * mask);
3234    } else if (in.sprite_mode == 2u) {
3235        // Simplistic mathematical 6-fold 2D snowflake crystal (zero asset files).
3236        let crystal = 1.0 - smoothstep(-aa_crystal, aa_crystal, d_crystal);
3237        let soft_halo = (1.0 - smoothstep(0.18, 0.94, r)) * 0.26;
3238        let mask = clamp(max(crystal, soft_halo), 0.0, 1.0) * (1.0 - smoothstep(0.92, 1.0, r));
3239        out_col = vec4<f32>(in.color.rgb, in.color.a * mask);
3240    } else if (in.sprite_mode == 4u) {
3241        // ProceduralCurtain: ultra-soft atmospheric regional rain-shaft / snow-squall mist veil.
3242        let x_env = exp(-p.x * p.x * 2.4);
3243        let y_env = smoothstep(0.0, 0.34, in.uv.y) * (1.0 - smoothstep(0.62, 1.0, in.uv.y));
3244        let soft_stria = 0.86 + 0.14 * sin(in.uv.x * 9.4248 + in.uv.y * 1.8) * cos(in.uv.x * 15.708 - in.uv.y * 2.4);
3245        let mask = clamp(x_env * y_env * soft_stria, 0.0, 1.0);
3246        out_col = vec4<f32>(in.color.rgb, in.color.a * mask);
3247    } else {
3248        // ProceduralPellet: compact translucent sleet / graupel ice pellet.
3249        let pr = length(vec2<f32>(p.x * 1.18, p.y * 0.85));
3250        let mask = (1.0 - smoothstep(0.35, 0.95, pr));
3251        let glint = exp(-pr * pr * 5.0) * 0.25;
3252        out_col = vec4<f32>(in.color.rgb + vec3<f32>(glint), in.color.a * mask);
3253    }
3254
3255    if (out_col.a <= 0.004) {
3256        discard;
3257    }
3258    return out_col;
3259}
3260"#;
3261
3262const OVERLAY_COMPOSITE_WGSL: &str = r#"
3263@group(0) @binding(0) var overlay_tex: texture_2d<f32>;
3264@group(0) @binding(1) var overlay_sampler: sampler;
3265
3266struct OverlayOut {
3267    @builtin(position) pos: vec4<f32>,
3268    @location(0) uv: vec2<f32>,
3269}
3270
3271@vertex
3272fn vs_overlay(@builtin(vertex_index) vid: u32) -> OverlayOut {
3273    var positions = array<vec2<f32>, 3>(
3274        vec2<f32>(-1.0, -3.0),
3275        vec2<f32>(3.0, 1.0),
3276        vec2<f32>(-1.0, 1.0),
3277    );
3278    let p = positions[vid];
3279    var out: OverlayOut;
3280    out.pos = vec4<f32>(p, 0.0, 1.0);
3281    out.uv = vec2<f32>((p.x + 1.0) * 0.5, (1.0 - p.y) * 0.5);
3282    return out;
3283}
3284
3285@fragment
3286fn fs_overlay(in: OverlayOut) -> @location(0) vec4<f32> {
3287    let c = textureSample(overlay_tex, overlay_sampler, in.uv);
3288    if (c.a <= 0.001) {
3289        return vec4<f32>(0.0);
3290    }
3291    return c;
3292}
3293"#;
3294
3295#[derive(Clone, Copy)]
3296struct SlabEntry {
3297    revision: u64,
3298    offset: u32,
3299    len: u32,
3300    grid_res: u32,
3301    has_skirts: bool,
3302    last_used_frame: u64,
3303}
3304
3305/// Free-list GPU vertex slab allocator holding tile-local RTC vertices across frames.
3306struct GpuTileSlabAllocator {
3307    buffer: wgpu::Buffer,
3308    capacity_vertices: u32,
3309    resident: HashMap<TileKeyId, SlabEntry>,
3310    free_blocks: Vec<(u32, u32)>, // (offset, len)
3311    bump_cursor: u32,
3312}
3313
3314impl GpuTileSlabAllocator {
3315    fn new(device: &wgpu::Device, initial_capacity_vertices: u32) -> Self {
3316        let cap = initial_capacity_vertices.max(65_536);
3317        let buffer = device.create_buffer(&wgpu::BufferDescriptor {
3318            label: Some("strata_earth_tile_vertex_slab"),
3319            size: (cap as u64) * (std::mem::size_of::<RteTileVertex>() as u64),
3320            usage: wgpu::BufferUsages::STORAGE
3321                | wgpu::BufferUsages::COPY_DST
3322                | wgpu::BufferUsages::COPY_SRC,
3323            mapped_at_creation: false,
3324        });
3325        Self {
3326            buffer,
3327            capacity_vertices: cap,
3328            resident: HashMap::new(),
3329            free_blocks: Vec::new(),
3330            bump_cursor: 0,
3331        }
3332    }
3333
3334    fn alloc_range(
3335        &mut self,
3336        device: &wgpu::Device,
3337        queue: &wgpu::Queue,
3338        needed: u32,
3339        current_frame: u64,
3340    ) -> (u32, bool) {
3341        // 1. Reuse best-fit free block.
3342        if let Some((idx, (off, len))) = self
3343            .free_blocks
3344            .iter()
3345            .copied()
3346            .enumerate()
3347            .filter(|(_, (_, l))| *l >= needed)
3348            .min_by_key(|(_, (_, l))| *l)
3349        {
3350            self.free_blocks.swap_remove(idx);
3351            if len > needed {
3352                self.free_blocks.push((off + needed, len - needed));
3353            }
3354            return (off, false);
3355        }
3356
3357        // 2. Bump allocate if space remains.
3358        if self.bump_cursor + needed <= self.capacity_vertices {
3359            let off = self.bump_cursor;
3360            self.bump_cursor += needed;
3361            return (off, false);
3362        }
3363
3364        // 3. Evict LRU tiles not used this frame.
3365        let mut stale: Vec<(TileKeyId, SlabEntry)> = self
3366            .resident
3367            .iter()
3368            .filter(|(_, e)| e.last_used_frame < current_frame)
3369            .map(|(k, e)| (*k, *e))
3370            .collect();
3371        stale.sort_by_key(|(_, e)| e.last_used_frame);
3372
3373        let mut reclaimed = 0u32;
3374        for (k, e) in stale {
3375            self.resident.remove(&k);
3376            self.free_blocks.push((e.offset, e.len));
3377            reclaimed += e.len;
3378            if reclaimed >= needed {
3379                break;
3380            }
3381        }
3382        self.coalesce_free_blocks();
3383
3384        if let Some((idx, (off, len))) = self
3385            .free_blocks
3386            .iter()
3387            .copied()
3388            .enumerate()
3389            .filter(|(_, (_, l))| *l >= needed)
3390            .min_by_key(|(_, (_, l))| *l)
3391        {
3392            self.free_blocks.swap_remove(idx);
3393            if len > needed {
3394                self.free_blocks.push((off + needed, len - needed));
3395            }
3396            return (off, false);
3397        }
3398
3399        // 4. Grow buffer if still tight.
3400        let new_cap = (self.capacity_vertices * 2).max(self.bump_cursor + needed + 65_536);
3401        let new_buf = device.create_buffer(&wgpu::BufferDescriptor {
3402            label: Some("strata_earth_tile_vertex_slab_grown"),
3403            size: (new_cap as u64) * (std::mem::size_of::<RteTileVertex>() as u64),
3404            usage: wgpu::BufferUsages::STORAGE
3405                | wgpu::BufferUsages::COPY_DST
3406                | wgpu::BufferUsages::COPY_SRC,
3407            mapped_at_creation: false,
3408        });
3409        let copy_bytes = (self.bump_cursor as u64) * (std::mem::size_of::<RteTileVertex>() as u64);
3410        if copy_bytes > 0 {
3411            let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
3412                label: Some("strata_earth_slab_grow_copy"),
3413            });
3414            enc.copy_buffer_to_buffer(&self.buffer, 0, &new_buf, 0, copy_bytes);
3415            queue.submit(Some(enc.finish()));
3416        }
3417        self.buffer = new_buf;
3418        self.capacity_vertices = new_cap;
3419        let off = self.bump_cursor;
3420        self.bump_cursor += needed;
3421        (off, true)
3422    }
3423
3424    fn coalesce_free_blocks(&mut self) {
3425        if self.free_blocks.len() < 2 {
3426            return;
3427        }
3428        self.free_blocks.sort_unstable_by_key(|(o, _)| *o);
3429        let mut merged: Vec<(u32, u32)> = Vec::with_capacity(self.free_blocks.len());
3430        for (o, l) in self.free_blocks.drain(..) {
3431            if let Some(last) = merged.last_mut() {
3432                if last.0 + last.1 == o {
3433                    last.1 += l;
3434                    continue;
3435                }
3436            }
3437            merged.push((o, l));
3438        }
3439        // Reclaim tail back into bump_cursor.
3440        while let Some(&(o, l)) = merged.last() {
3441            if o + l == self.bump_cursor {
3442                self.bump_cursor = o;
3443                merged.pop();
3444            } else {
3445                break;
3446            }
3447        }
3448        self.free_blocks = merged;
3449    }
3450
3451    fn upload_meshes(
3452        &mut self,
3453        device: &wgpu::Device,
3454        queue: &wgpu::Queue,
3455        meshes: &[Arc<RetainedTileMesh>],
3456        frame_idx: u64,
3457        budget: usize,
3458    ) -> (bool, bool) {
3459        let mut bind_group_dirty = false;
3460        let mut deferred_any = false;
3461        let mut uploaded = 0usize;
3462
3463        // First mark already-resident entries for visible keys as fresh this frame so LRU never evicts a fallback.
3464        for mesh in meshes {
3465            if let Some(entry) = self.resident.get_mut(&mesh.key) {
3466                if entry.len == mesh.vertices.len() as u32
3467                    && entry.grid_res == mesh.grid_res
3468                    && entry.has_skirts == mesh.has_skirts
3469                {
3470                    entry.last_used_frame = frame_idx;
3471                }
3472            }
3473        }
3474
3475        for mesh in meshes {
3476            let needed = mesh.vertices.len() as u32;
3477            if needed == 0 {
3478                continue;
3479            }
3480            if let Some(entry) = self.resident.get(&mesh.key) {
3481                if entry.revision == mesh.revision
3482                    && entry.len == needed
3483                    && entry.grid_res == mesh.grid_res
3484                    && entry.has_skirts == mesh.has_skirts
3485                {
3486                    continue;
3487                }
3488            }
3489            if uploaded >= budget {
3490                deferred_any = true;
3491                continue;
3492            }
3493            if let Some(old) = self.resident.remove(&mesh.key) {
3494                self.free_blocks.push((old.offset, old.len));
3495                self.coalesce_free_blocks();
3496            }
3497            let (off, grew) = self.alloc_range(device, queue, needed, frame_idx);
3498            if grew {
3499                bind_group_dirty = true;
3500            }
3501            let byte_offset = (off as u64) * (std::mem::size_of::<RteTileVertex>() as u64);
3502            queue.write_buffer(
3503                &self.buffer,
3504                byte_offset,
3505                bytemuck::cast_slice(&mesh.vertices),
3506            );
3507            self.resident.insert(
3508                mesh.key,
3509                SlabEntry {
3510                    revision: mesh.revision,
3511                    offset: off,
3512                    len: needed,
3513                    grid_res: mesh.grid_res,
3514                    has_skirts: mesh.has_skirts,
3515                    last_used_frame: frame_idx,
3516                },
3517            );
3518            uploaded += 1;
3519        }
3520        (bind_group_dirty, deferred_any)
3521    }
3522
3523    fn resident_slot(&self, key: TileKeyId, revision: u64) -> Option<(u32, u32, bool)> {
3524        let entry = self.resident.get(&key)?;
3525        let _ = revision;
3526        Some((entry.offset, entry.grid_res, entry.has_skirts))
3527    }
3528}
3529
3530#[derive(Clone, Copy)]
3531struct AtlasSlot {
3532    tex_id: u64,
3533    revision: u64,
3534    layer: u32,
3535    last_used_frame: u64,
3536}
3537
3538/// LRU `Texture2DArray` tile imagery atlas (layer 0 = solid white fallback).
3539struct GpuImageryAtlas {
3540    _texture: wgpu::Texture,
3541    view: wgpu::TextureView,
3542    slots_by_id: HashMap<u64, AtlasSlot>,
3543    layer_owner: Vec<Option<u64>>,
3544}
3545
3546impl GpuImageryAtlas {
3547    fn new(
3548        device: &wgpu::Device,
3549        queue: &wgpu::Queue,
3550        layers: u32,
3551        color_format: wgpu::TextureFormat,
3552    ) -> Self {
3553        let layers = layers.max(16);
3554        let format = if color_format.is_srgb() {
3555            wgpu::TextureFormat::Rgba8UnormSrgb
3556        } else {
3557            wgpu::TextureFormat::Rgba8Unorm
3558        };
3559        let texture = device.create_texture(&wgpu::TextureDescriptor {
3560            label: Some("strata_earth_imagery_atlas"),
3561            size: wgpu::Extent3d {
3562                width: ATLAS_TILE_SIZE,
3563                height: ATLAS_TILE_SIZE,
3564                depth_or_array_layers: layers,
3565            },
3566            mip_level_count: 1,
3567            sample_count: 1,
3568            dimension: wgpu::TextureDimension::D2,
3569            format,
3570            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3571            view_formats: &[],
3572        });
3573
3574        // Layer 0: solid white fallback texture.
3575        let white = vec![255u8; (ATLAS_TILE_SIZE * ATLAS_TILE_SIZE * 4) as usize];
3576        Self::write_layer(queue, &texture, 0, ATLAS_TILE_SIZE, ATLAS_TILE_SIZE, &white);
3577
3578        let view = texture.create_view(&wgpu::TextureViewDescriptor {
3579            label: Some("strata_earth_imagery_atlas_view"),
3580            dimension: Some(wgpu::TextureViewDimension::D2Array),
3581            ..Default::default()
3582        });
3583
3584        Self {
3585            _texture: texture,
3586            view,
3587            slots_by_id: HashMap::new(),
3588            layer_owner: vec![None; layers as usize],
3589        }
3590    }
3591
3592    fn write_layer(
3593        queue: &wgpu::Queue,
3594        texture: &wgpu::Texture,
3595        layer: u32,
3596        w: u32,
3597        h: u32,
3598        rgba: &[u8],
3599    ) {
3600        if w == ATLAS_TILE_SIZE
3601            && h == ATLAS_TILE_SIZE
3602            && rgba.len() >= (ATLAS_TILE_SIZE * ATLAS_TILE_SIZE * 4) as usize
3603        {
3604            queue.write_texture(
3605                wgpu::TexelCopyTextureInfo {
3606                    texture,
3607                    mip_level: 0,
3608                    origin: wgpu::Origin3d {
3609                        x: 0,
3610                        y: 0,
3611                        z: layer,
3612                    },
3613                    aspect: wgpu::TextureAspect::All,
3614                },
3615                &rgba[..(ATLAS_TILE_SIZE * ATLAS_TILE_SIZE * 4) as usize],
3616                wgpu::TexelCopyBufferLayout {
3617                    offset: 0,
3618                    bytes_per_row: Some(ATLAS_TILE_SIZE * 4),
3619                    rows_per_image: Some(ATLAS_TILE_SIZE),
3620                },
3621                wgpu::Extent3d {
3622                    width: ATLAS_TILE_SIZE,
3623                    height: ATLAS_TILE_SIZE,
3624                    depth_or_array_layers: 1,
3625                },
3626            );
3627            return;
3628        }
3629        // Nearest/bilinear resample into ATLAS_TILE_SIZE x ATLAS_TILE_SIZE on CPU edge case.
3630        let mut resampled = vec![255u8; (ATLAS_TILE_SIZE * ATLAS_TILE_SIZE * 4) as usize];
3631        if w > 0 && h > 0 && rgba.len() >= (w * h * 4) as usize {
3632            for dy in 0..ATLAS_TILE_SIZE {
3633                let sy = ((dy as u64 * h as u64) / ATLAS_TILE_SIZE as u64).min(h as u64 - 1) as u32;
3634                for dx in 0..ATLAS_TILE_SIZE {
3635                    let sx =
3636                        ((dx as u64 * w as u64) / ATLAS_TILE_SIZE as u64).min(w as u64 - 1) as u32;
3637                    let si = ((sy * w + sx) * 4) as usize;
3638                    let di = ((dy * ATLAS_TILE_SIZE + dx) * 4) as usize;
3639                    resampled[di..di + 4].copy_from_slice(&rgba[si..si + 4]);
3640                }
3641            }
3642        }
3643        queue.write_texture(
3644            wgpu::TexelCopyTextureInfo {
3645                texture,
3646                mip_level: 0,
3647                origin: wgpu::Origin3d {
3648                    x: 0,
3649                    y: 0,
3650                    z: layer,
3651                },
3652                aspect: wgpu::TextureAspect::All,
3653            },
3654            &resampled,
3655            wgpu::TexelCopyBufferLayout {
3656                offset: 0,
3657                bytes_per_row: Some(ATLAS_TILE_SIZE * 4),
3658                rows_per_image: Some(ATLAS_TILE_SIZE),
3659            },
3660            wgpu::Extent3d {
3661                width: ATLAS_TILE_SIZE,
3662                height: ATLAS_TILE_SIZE,
3663                depth_or_array_layers: 1,
3664            },
3665        );
3666    }
3667
3668    fn upload_textures(
3669        &mut self,
3670        queue: &wgpu::Queue,
3671        textures: &[Arc<RetainedTileTexture>],
3672        frame_idx: u64,
3673        budget: usize,
3674    ) -> bool {
3675        for tex in textures {
3676            if let Some(slot) = self.slots_by_id.get_mut(&tex.id) {
3677                if slot.revision == tex.revision {
3678                    slot.last_used_frame = frame_idx;
3679                }
3680            }
3681        }
3682        let mut uploaded = 0usize;
3683        let mut deferred_any = false;
3684        for tex in textures {
3685            if let Some(slot) = self.slots_by_id.get(&tex.id) {
3686                if slot.revision == tex.revision {
3687                    continue;
3688                }
3689            }
3690            if uploaded >= budget {
3691                deferred_any = true;
3692                continue;
3693            }
3694            let target_layer = if let Some(existing) = self.slots_by_id.get(&tex.id) {
3695                existing.layer
3696            } else if let Some((idx, _)) = self
3697                .layer_owner
3698                .iter()
3699                .enumerate()
3700                .skip(1)
3701                .find(|(_, owner)| owner.is_none())
3702            {
3703                idx as u32
3704            } else if let Some((victim_id, victim_layer)) = self
3705                .slots_by_id
3706                .values()
3707                .filter(|s| s.last_used_frame < frame_idx)
3708                .min_by_key(|s| s.last_used_frame)
3709                .map(|s| (s.tex_id, s.layer))
3710            {
3711                self.slots_by_id.remove(&victim_id);
3712                victim_layer
3713            } else {
3714                continue;
3715            };
3716
3717            Self::write_layer(
3718                queue,
3719                &self._texture,
3720                target_layer,
3721                tex.width,
3722                tex.height,
3723                &tex.rgba8,
3724            );
3725            self.layer_owner[target_layer as usize] = Some(tex.id);
3726            self.slots_by_id.insert(
3727                tex.id,
3728                AtlasSlot {
3729                    tex_id: tex.id,
3730                    revision: tex.revision,
3731                    layer: target_layer,
3732                    last_used_frame: frame_idx,
3733                },
3734            );
3735            uploaded += 1;
3736        }
3737        deferred_any
3738    }
3739
3740    #[inline]
3741    fn layer_for(&self, tex_id: Option<u64>, revision: u64) -> u32 {
3742        let Some(id) = tex_id else {
3743            return 0;
3744        };
3745        let _ = revision;
3746        self.slots_by_id.get(&id).map(|s| s.layer).unwrap_or(0)
3747    }
3748}
3749
3750struct CachedIndexTopology {
3751    buffer: wgpu::Buffer,
3752    index_count: u32,
3753}
3754
3755#[repr(C)]
3756#[derive(Clone, Copy, Pod, Zeroable)]
3757struct GpuGeoVertex {
3758    pos_u: [f32; 4],
3759    norm_v: [f32; 4],
3760    color: [f32; 4],
3761}
3762
3763struct CachedDynamicGpuMesh {
3764    revision: u64,
3765    vbuf: wgpu::Buffer,
3766    ibuf: wgpu::Buffer,
3767    index_count: u32,
3768    last_used_seq: u64,
3769}
3770
3771struct CachedGeoGpuMesh {
3772    revision: u64,
3773    vbuf: wgpu::Buffer,
3774    ibuf: wgpu::Buffer,
3775    index_count: u32,
3776    has_vertex_alpha: bool,
3777    albedo_tex_id: Option<u64>,
3778    last_used_seq: u64,
3779}
3780
3781struct CachedGeoTexture {
3782    revision: u64,
3783    width: u32,
3784    height: u32,
3785    has_alpha: bool,
3786    _texture: wgpu::Texture,
3787    bind_group: wgpu::BindGroup,
3788    last_used_seq: u64,
3789}
3790
3791struct OffscreenTarget {
3792    width: u32,
3793    height: u32,
3794    format: wgpu::TextureFormat,
3795    color: wgpu::Texture,
3796    color_view: wgpu::TextureView,
3797    _depth: wgpu::Texture,
3798    depth_view: wgpu::TextureView,
3799    readback: wgpu::Buffer,
3800    padded_bytes_per_row: u32,
3801}
3802
3803struct GpuEnvironmentState {
3804    land_mask_id_rev: Option<(u64, u64)>,
3805    cloud_map_id_rev: Option<(u64, u64)>,
3806    moon_tex_id_rev: Option<(u64, u64)>,
3807    skybox_cube_id_rev: Option<(u64, u64)>,
3808    stars_ptr: usize,
3809    stars_len: usize,
3810    land_mask_view: wgpu::TextureView,
3811    cloud_map_view: wgpu::TextureView,
3812    cloud_noise_view: wgpu::TextureView,
3813    moon_view: wgpu::TextureView,
3814    skybox_cube_view: wgpu::TextureView,
3815    env_sampler: wgpu::Sampler,
3816    cloud_noise_sampler: wgpu::Sampler,
3817    star_buffer: wgpu::Buffer,
3818    star_capacity: usize,
3819    star_count: u32,
3820}
3821
3822struct SrgbDownsampleLuts {
3823    to_lin_div4_scaled: [f32; 256],
3824    to_srgb: [u8; 16384],
3825}
3826
3827fn srgb_downsample_luts() -> &'static SrgbDownsampleLuts {
3828    static LUTS: std::sync::OnceLock<SrgbDownsampleLuts> = std::sync::OnceLock::new();
3829    LUTS.get_or_init(|| {
3830        const MAX_IDX: f32 = 16383.0;
3831        let mut to_lin_div4_scaled = [0.0f32; 256];
3832        for (i, slot) in to_lin_div4_scaled.iter_mut().enumerate() {
3833            let x = i as f32 / 255.0;
3834            let lin = if x <= 0.04045 {
3835                x / 12.92
3836            } else {
3837                ((x + 0.055) / 1.055).powf(2.4)
3838            };
3839            *slot = lin * (0.25 * MAX_IDX);
3840        }
3841        let mut to_srgb = [0u8; 16384];
3842        for (i, slot) in to_srgb.iter_mut().enumerate() {
3843            let x = (i as f32 / MAX_IDX).clamp(0.0, 1.0);
3844            let s = if x <= 0.0031308 {
3845                x * 12.92
3846            } else {
3847                1.055 * x.powf(1.0 / 2.4) - 0.055
3848            };
3849            *slot = (s * 255.0).round().clamp(0.0, 255.0) as u8;
3850        }
3851        SrgbDownsampleLuts {
3852            to_lin_div4_scaled,
3853            to_srgb,
3854        }
3855    })
3856}
3857
3858fn downsample_srgb_rows(
3859    src: &[u8],
3860    w: u32,
3861    h: u32,
3862    nw: u32,
3863    y_start: u32,
3864    out_slice: &mut [u8],
3865    luts: &SrgbDownsampleLuts,
3866) {
3867    let w_usize = w as usize;
3868    let nw_usize = nw as usize;
3869    let row_stride = w_usize * 4;
3870    let lin = &luts.to_lin_div4_scaled;
3871    let srgb = &luts.to_srgb;
3872    let fast_x = w >= nw * 2;
3873    let y_count = out_slice.len() / (nw_usize * 4);
3874
3875    for dy in 0..y_count {
3876        let y = y_start + dy as u32;
3877        let sy0 = (y * 2).min(h - 1) as usize;
3878        let sy1 = (y * 2 + 1).min(h - 1) as usize;
3879        let row0 = &src[sy0 * row_stride..(sy0 + 1) * row_stride];
3880        let row1 = &src[sy1 * row_stride..(sy1 + 1) * row_stride];
3881        let out_row = &mut out_slice[dy * nw_usize * 4..(dy + 1) * nw_usize * 4];
3882
3883        if fast_x {
3884            for x in 0..nw_usize {
3885                let s = x * 8;
3886                let a = &row0[s..s + 8];
3887                let b = &row1[s..s + 8];
3888                let ir = (lin[a[0] as usize]
3889                    + lin[a[4] as usize]
3890                    + lin[b[0] as usize]
3891                    + lin[b[4] as usize]
3892                    + 0.5) as usize;
3893                let ig = (lin[a[1] as usize]
3894                    + lin[a[5] as usize]
3895                    + lin[b[1] as usize]
3896                    + lin[b[5] as usize]
3897                    + 0.5) as usize;
3898                let ib = (lin[a[2] as usize]
3899                    + lin[a[6] as usize]
3900                    + lin[b[2] as usize]
3901                    + lin[b[6] as usize]
3902                    + 0.5) as usize;
3903                let alpha = (a[3] as u32 + a[7] as u32 + b[3] as u32 + b[7] as u32 + 2) >> 2;
3904                let d = x * 4;
3905                out_row[d] = srgb[ir.min(16383)];
3906                out_row[d + 1] = srgb[ig.min(16383)];
3907                out_row[d + 2] = srgb[ib.min(16383)];
3908                out_row[d + 3] = alpha as u8;
3909            }
3910        } else {
3911            for x in 0..nw_usize {
3912                let sx0 = ((x * 2) as u32).min(w - 1) as usize * 4;
3913                let sx1 = ((x * 2 + 1) as u32).min(w - 1) as usize * 4;
3914                let ir = (lin[row0[sx0] as usize]
3915                    + lin[row0[sx1] as usize]
3916                    + lin[row1[sx0] as usize]
3917                    + lin[row1[sx1] as usize]
3918                    + 0.5) as usize;
3919                let ig = (lin[row0[sx0 + 1] as usize]
3920                    + lin[row0[sx1 + 1] as usize]
3921                    + lin[row1[sx0 + 1] as usize]
3922                    + lin[row1[sx1 + 1] as usize]
3923                    + 0.5) as usize;
3924                let ib = (lin[row0[sx0 + 2] as usize]
3925                    + lin[row0[sx1 + 2] as usize]
3926                    + lin[row1[sx0 + 2] as usize]
3927                    + lin[row1[sx1 + 2] as usize]
3928                    + 0.5) as usize;
3929                let alpha = (row0[sx0 + 3] as u32
3930                    + row0[sx1 + 3] as u32
3931                    + row1[sx0 + 3] as u32
3932                    + row1[sx1 + 3] as u32
3933                    + 2)
3934                    >> 2;
3935                let d = x * 4;
3936                out_row[d] = srgb[ir.min(16383)];
3937                out_row[d + 1] = srgb[ig.min(16383)];
3938                out_row[d + 2] = srgb[ib.min(16383)];
3939                out_row[d + 3] = alpha as u8;
3940            }
3941        }
3942    }
3943}
3944
3945fn parallel_downsample_rgba8<F>(w: u32, h: u32, row_fn: F) -> (u32, u32, Vec<u8>)
3946where
3947    F: Fn(u32, &mut [u8]) + Sync,
3948{
3949    let nw = (w / 2).max(1);
3950    let nh = (h / 2).max(1);
3951    let mut out = vec![0u8; (nw as usize) * (nh as usize) * 4];
3952    if nw * nh >= 262_144 && nh >= 64 {
3953        let workers = std::thread::available_parallelism()
3954            .map(|n| n.get())
3955            .unwrap_or(4)
3956            .clamp(2, 6);
3957        let rows_per_chunk = ((nh as usize) + workers - 1) / workers;
3958        let chunk_bytes = rows_per_chunk * (nw as usize) * 4;
3959        std::thread::scope(|s| {
3960            for (chunk_idx, chunk) in out.chunks_mut(chunk_bytes).enumerate() {
3961                let y_start = (chunk_idx * rows_per_chunk) as u32;
3962                let rf = &row_fn;
3963                s.spawn(move || rf(y_start, chunk));
3964            }
3965        });
3966    } else {
3967        row_fn(0, &mut out);
3968    }
3969    (nw, nh, out)
3970}
3971
3972fn downsample_srgb_rgba8_half(src: &[u8], w: u32, h: u32) -> (u32, u32, Vec<u8>) {
3973    let luts = srgb_downsample_luts();
3974    let nw = (w / 2).max(1);
3975    parallel_downsample_rgba8(w, h, |y_start, chunk| {
3976        downsample_srgb_rows(src, w, h, nw, y_start, chunk, luts);
3977    })
3978}
3979
3980fn downsample_linear_rows(
3981    src: &[u8],
3982    w: u32,
3983    h: u32,
3984    nw: u32,
3985    y_start: u32,
3986    out_slice: &mut [u8],
3987) {
3988    let w_usize = w as usize;
3989    let nw_usize = nw as usize;
3990    let row_stride = w_usize * 4;
3991    let fast_x = w >= nw * 2;
3992    let y_count = out_slice.len() / (nw_usize * 4);
3993
3994    for dy in 0..y_count {
3995        let y = y_start + dy as u32;
3996        let sy0 = (y * 2).min(h - 1) as usize;
3997        let sy1 = (y * 2 + 1).min(h - 1) as usize;
3998        let row0 = &src[sy0 * row_stride..(sy0 + 1) * row_stride];
3999        let row1 = &src[sy1 * row_stride..(sy1 + 1) * row_stride];
4000        let out_row = &mut out_slice[dy * nw_usize * 4..(dy + 1) * nw_usize * 4];
4001        if fast_x {
4002            for x in 0..nw_usize {
4003                let s = x * 8;
4004                let a = &row0[s..s + 8];
4005                let b = &row1[s..s + 8];
4006                let d = x * 4;
4007                for c in 0..4 {
4008                    out_row[d + c] =
4009                        ((a[c] as u32 + a[4 + c] as u32 + b[c] as u32 + b[4 + c] as u32 + 2) >> 2)
4010                            as u8;
4011                }
4012            }
4013        } else {
4014            for x in 0..nw_usize {
4015                let sx0 = ((x * 2) as u32).min(w - 1) as usize * 4;
4016                let sx1 = ((x * 2 + 1) as u32).min(w - 1) as usize * 4;
4017                let d = x * 4;
4018                for c in 0..4 {
4019                    out_row[d + c] = ((row0[sx0 + c] as u32
4020                        + row0[sx1 + c] as u32
4021                        + row1[sx0 + c] as u32
4022                        + row1[sx1 + c] as u32
4023                        + 2)
4024                        >> 2) as u8;
4025                }
4026            }
4027        }
4028    }
4029}
4030
4031fn downsample_linear_rgba8_half(src: &[u8], w: u32, h: u32) -> (u32, u32, Vec<u8>) {
4032    let nw = (w / 2).max(1);
4033    parallel_downsample_rgba8(w, h, |y_start, chunk| {
4034        downsample_linear_rows(src, w, h, nw, y_start, chunk);
4035    })
4036}
4037
4038fn downsample_srgb_rgba8_half_single(src: &[u8], w: u32, h: u32) -> (u32, u32, Vec<u8>) {
4039    let luts = srgb_downsample_luts();
4040    let nw = (w / 2).max(1);
4041    let nh = (h / 2).max(1);
4042    let mut out = vec![0u8; (nw as usize) * (nh as usize) * 4];
4043    downsample_srgb_rows(src, w, h, nw, 0, &mut out, luts);
4044    (nw, nh, out)
4045}
4046
4047fn create_rgba8_cube_view(
4048    device: &wgpu::Device,
4049    queue: &wgpu::Queue,
4050    label: &str,
4051    face_size: u32,
4052    faces: &[std::sync::Arc<Vec<u8>>; 6],
4053    format: wgpu::TextureFormat,
4054) -> wgpu::TextureView {
4055    let max_dim = device.limits().max_texture_dimension_2d.max(1);
4056    let mut size = face_size.max(1);
4057    let mut base_override: Option<[Vec<u8>; 6]> = None;
4058
4059    if size > max_dim && size > 1 {
4060        let mut owned: [Vec<u8>; 6] = std::array::from_fn(|i| {
4061            let expected = (size as usize) * (size as usize) * 4;
4062            if faces[i].len() >= expected {
4063                faces[i][..expected].to_vec()
4064            } else {
4065                vec![0u8; expected]
4066            }
4067        });
4068        while size > max_dim && size > 1 {
4069            let cur_size = size;
4070            let mut next_size = size;
4071            let next_owned: [Vec<u8>; 6] = std::thread::scope(|s| {
4072                let handles: [_; 6] = std::array::from_fn(|i| {
4073                    let buf = owned[i].as_slice();
4074                    s.spawn(move || downsample_srgb_rgba8_half_single(buf, cur_size, cur_size))
4075                });
4076                handles.map(|h| {
4077                    let (nw, _, down) = h.join().expect("cube downsample thread panicked");
4078                    next_size = nw;
4079                    down
4080                })
4081            });
4082            owned = next_owned;
4083            size = next_size;
4084        }
4085        base_override = Some(owned);
4086    }
4087
4088    let mip_level_count = if size > 1 {
4089        32 - size.leading_zeros()
4090    } else {
4091        1
4092    };
4093    let tex = device.create_texture(&wgpu::TextureDescriptor {
4094        label: Some(label),
4095        size: wgpu::Extent3d {
4096            width: size,
4097            height: size,
4098            depth_or_array_layers: 6,
4099        },
4100        mip_level_count,
4101        sample_count: 1,
4102        dimension: wgpu::TextureDimension::D2,
4103        format,
4104        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4105        view_formats: &[],
4106    });
4107
4108    let build_face_mips = |base: &[u8]| -> Vec<(u32, Vec<u8>)> {
4109        let mut mips = Vec::with_capacity((mip_level_count.saturating_sub(1)) as usize);
4110        if mip_level_count <= 1 {
4111            return mips;
4112        }
4113        let expected0 = (size as usize) * (size as usize) * 4;
4114        if base.len() < expected0 {
4115            return mips;
4116        }
4117        let (mut cur_w, _, cur_buf) =
4118            downsample_srgb_rgba8_half_single(&base[..expected0], size, size);
4119        mips.push((cur_w, cur_buf));
4120        for _ in 2..mip_level_count {
4121            let prev = &mips.last().expect("pushed mip").1;
4122            let (nw, _, next) = downsample_srgb_rgba8_half_single(prev, cur_w, cur_w);
4123            cur_w = nw;
4124            mips.push((cur_w, next));
4125        }
4126        mips
4127    };
4128
4129    // Generate mip levels 1..N across all 6 cube faces in parallel without copying mip 0.
4130    let base_refs: [&[u8]; 6] = match &base_override {
4131        Some(owned) => std::array::from_fn(|i| owned[i].as_slice()),
4132        None => std::array::from_fn(|i| faces[i].as_slice()),
4133    };
4134    let extra_mips: [Vec<(u32, Vec<u8>)>; 6] = if mip_level_count > 1 && size >= 64 {
4135        let _ = srgb_downsample_luts();
4136        std::thread::scope(|s| {
4137            let handles: [_; 6] = std::array::from_fn(|i| {
4138                let base = base_refs[i];
4139                s.spawn(move || build_face_mips(base))
4140            });
4141            handles.map(|h| h.join().expect("cube mip thread panicked"))
4142        })
4143    } else {
4144        std::array::from_fn(|i| build_face_mips(base_refs[i]))
4145    };
4146
4147    for layer in 0..6u32 {
4148        let expected0 = (size as usize) * (size as usize) * 4;
4149        if base_refs[layer as usize].len() >= expected0 {
4150            queue.write_texture(
4151                wgpu::TexelCopyTextureInfo {
4152                    texture: &tex,
4153                    mip_level: 0,
4154                    origin: wgpu::Origin3d {
4155                        x: 0,
4156                        y: 0,
4157                        z: layer,
4158                    },
4159                    aspect: wgpu::TextureAspect::All,
4160                },
4161                &base_refs[layer as usize][..expected0],
4162                wgpu::TexelCopyBufferLayout {
4163                    offset: 0,
4164                    bytes_per_row: Some(size * 4),
4165                    rows_per_image: Some(size),
4166                },
4167                wgpu::Extent3d {
4168                    width: size,
4169                    height: size,
4170                    depth_or_array_layers: 1,
4171                },
4172            );
4173        }
4174        for (idx, (mip_w, buf)) in extra_mips[layer as usize].iter().enumerate() {
4175            let mip = (idx + 1) as u32;
4176            let expected = (*mip_w as usize) * (*mip_w as usize) * 4;
4177            if buf.len() >= expected {
4178                queue.write_texture(
4179                    wgpu::TexelCopyTextureInfo {
4180                        texture: &tex,
4181                        mip_level: mip,
4182                        origin: wgpu::Origin3d {
4183                            x: 0,
4184                            y: 0,
4185                            z: layer,
4186                        },
4187                        aspect: wgpu::TextureAspect::All,
4188                    },
4189                    &buf[..expected],
4190                    wgpu::TexelCopyBufferLayout {
4191                        offset: 0,
4192                        bytes_per_row: Some(*mip_w * 4),
4193                        rows_per_image: Some(*mip_w),
4194                    },
4195                    wgpu::Extent3d {
4196                        width: *mip_w,
4197                        height: *mip_w,
4198                        depth_or_array_layers: 1,
4199                    },
4200                );
4201            }
4202        }
4203    }
4204
4205    tex.create_view(&wgpu::TextureViewDescriptor {
4206        label: Some(label),
4207        dimension: Some(wgpu::TextureViewDimension::Cube),
4208        ..Default::default()
4209    })
4210}
4211
4212#[derive(Clone, Copy)]
4213enum MipGenMode {
4214    Srgb,
4215    LinearBox,
4216}
4217
4218fn create_rgba8_2d_view(
4219    device: &wgpu::Device,
4220    queue: &wgpu::Queue,
4221    label: &str,
4222    width: u32,
4223    height: u32,
4224    rgba: &[u8],
4225) -> wgpu::TextureView {
4226    create_rgba8_2d_view_opts(device, queue, label, width, height, rgba, MipGenMode::Srgb)
4227}
4228
4229fn create_rgba8_2d_view_opts(
4230    device: &wgpu::Device,
4231    queue: &wgpu::Queue,
4232    label: &str,
4233    width: u32,
4234    height: u32,
4235    rgba: &[u8],
4236    mip_mode: MipGenMode,
4237) -> wgpu::TextureView {
4238    let max_dim = device.limits().max_texture_dimension_2d.max(1);
4239    let mut w = width.max(1);
4240    let mut h = height.max(1);
4241    let mut scaled: Option<Vec<u8>> = None;
4242    let initial_expected = (w as usize) * (h as usize) * 4;
4243    if rgba.len() >= initial_expected && (w > max_dim || h > max_dim) {
4244        let mut buf = rgba[..initial_expected].to_vec();
4245        while (w > max_dim || h > max_dim) && w > 1 && h > 1 {
4246            let (nw, nh, next) = match mip_mode {
4247                MipGenMode::LinearBox => downsample_linear_rgba8_half(&buf, w, h),
4248                MipGenMode::Srgb => downsample_srgb_rgba8_half(&buf, w, h),
4249            };
4250            w = nw;
4251            h = nh;
4252            buf = next;
4253        }
4254        scaled = Some(buf);
4255    }
4256    let data: &[u8] = scaled.as_deref().unwrap_or(rgba);
4257
4258    let expected = (w as usize) * (h as usize) * 4;
4259    let max_mips = if matches!(mip_mode, MipGenMode::LinearBox) {
4260        6
4261    } else {
4262        5
4263    };
4264    let mip_level_count = if data.len() >= expected && w >= 64 && h >= 64 {
4265        (32 - w.min(h).leading_zeros()).min(max_mips)
4266    } else {
4267        1
4268    };
4269
4270    let tex = device.create_texture(&wgpu::TextureDescriptor {
4271        label: Some(label),
4272        size: wgpu::Extent3d {
4273            width: w,
4274            height: h,
4275            depth_or_array_layers: 1,
4276        },
4277        mip_level_count,
4278        sample_count: 1,
4279        dimension: wgpu::TextureDimension::D2,
4280        format: wgpu::TextureFormat::Rgba8Unorm,
4281        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4282        view_formats: &[],
4283    });
4284    if data.len() >= expected {
4285        let mut cur_w = w;
4286        let mut cur_h = h;
4287        let mut mip_owned: Option<Vec<u8>> = None;
4288        for mip in 0..mip_level_count {
4289            let mip_bytes = mip_owned.as_deref().unwrap_or(&data[..expected]);
4290            let mip_exp = (cur_w as usize) * (cur_h as usize) * 4;
4291            if mip_bytes.len() >= mip_exp {
4292                queue.write_texture(
4293                    wgpu::TexelCopyTextureInfo {
4294                        texture: &tex,
4295                        mip_level: mip,
4296                        origin: wgpu::Origin3d::ZERO,
4297                        aspect: wgpu::TextureAspect::All,
4298                    },
4299                    &mip_bytes[..mip_exp],
4300                    wgpu::TexelCopyBufferLayout {
4301                        offset: 0,
4302                        bytes_per_row: Some(cur_w * 4),
4303                        rows_per_image: Some(cur_h),
4304                    },
4305                    wgpu::Extent3d {
4306                        width: cur_w,
4307                        height: cur_h,
4308                        depth_or_array_layers: 1,
4309                    },
4310                );
4311            }
4312            if mip + 1 < mip_level_count {
4313                let (nw, nh, next) = match mip_mode {
4314                    MipGenMode::LinearBox => downsample_linear_rgba8_half(mip_bytes, cur_w, cur_h),
4315                    MipGenMode::Srgb => downsample_srgb_rgba8_half(mip_bytes, cur_w, cur_h),
4316                };
4317                cur_w = nw;
4318                cur_h = nh;
4319                mip_owned = Some(next);
4320            }
4321        }
4322    }
4323    tex.create_view(&Default::default())
4324}
4325
4326fn downsample_cloud_r8_half(src: &[u8], w: u32, h: u32) -> (u32, u32, Vec<u8>) {
4327    let nw = (w / 2).max(1);
4328    let nh = (h / 2).max(1);
4329    let mut out = vec![0u8; (nw as usize) * (nh as usize)];
4330    let w_usize = w as usize;
4331    let nw_usize = nw as usize;
4332    for y in 0..(nh as usize) {
4333        let y0 = ((y * 2) as u32).min(h - 1) as usize * w_usize;
4334        let y1 = ((y * 2 + 1) as u32).min(h - 1) as usize * w_usize;
4335        let out_row = &mut out[y * nw_usize..(y + 1) * nw_usize];
4336        for (x, dst) in out_row.iter_mut().enumerate() {
4337            let x0 = ((x * 2) as u32).min(w - 1) as usize;
4338            let x1 = ((x * 2 + 1) as u32).min(w - 1) as usize;
4339            let a = src[y0 + x0] as u32;
4340            let b = src[y0 + x1] as u32;
4341            let c = src[y1 + x0] as u32;
4342            let d = src[y1 + x1] as u32;
4343            let avg = (a + b + c + d + 2) >> 2;
4344            let m = a.max(b).max(c).max(d);
4345            *dst = ((avg * 7 + m + 4) >> 3) as u8;
4346        }
4347    }
4348    (nw, nh, out)
4349}
4350
4351fn create_cloud_density_r8_view(
4352    device: &wgpu::Device,
4353    queue: &wgpu::Queue,
4354    label: &str,
4355    width: u32,
4356    height: u32,
4357    rgba: &[u8],
4358) -> wgpu::TextureView {
4359    let max_dim = device.limits().max_texture_dimension_2d.max(1);
4360    let mut w = width.max(1);
4361    let mut h = height.max(1);
4362    let initial_px = (w as usize) * (h as usize);
4363    let mut r8 = vec![0u8; initial_px];
4364    if rgba.len() >= initial_px * 4 {
4365        for (i, px) in rgba[..initial_px * 4].chunks_exact(4).enumerate() {
4366            let r = px[0];
4367            let g = px[1];
4368            let b = px[2];
4369            let a = px[3];
4370            if a == 255 {
4371                r8[i] = ((77 * r as u32 + 150 * g as u32 + 29 * b as u32 + 128) >> 8) as u8;
4372            } else if a > 0 {
4373                let inv = 1.0 / 255.0;
4374                let af = a as f32 * inv;
4375                let luma = (0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32) * inv;
4376                let t = ((af - 0.97) * (1.0 / 0.029)).clamp(0.0, 1.0);
4377                let sm = t * t * (3.0 - 2.0 * t);
4378                let d = af * (luma * sm + (1.0 - sm));
4379                r8[i] = (d.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
4380            }
4381        }
4382    }
4383    while (w > max_dim || h > max_dim) && w > 1 && h > 1 {
4384        let (nw, nh, next) = downsample_cloud_r8_half(&r8, w, h);
4385        w = nw;
4386        h = nh;
4387        r8 = next;
4388    }
4389
4390    let mip_level_count = if w >= 64 && h >= 64 {
4391        (32 - w.min(h).leading_zeros()).min(6)
4392    } else {
4393        1
4394    };
4395    let tex = device.create_texture(&wgpu::TextureDescriptor {
4396        label: Some(label),
4397        size: wgpu::Extent3d {
4398            width: w,
4399            height: h,
4400            depth_or_array_layers: 1,
4401        },
4402        mip_level_count,
4403        sample_count: 1,
4404        dimension: wgpu::TextureDimension::D2,
4405        format: wgpu::TextureFormat::R8Unorm,
4406        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4407        view_formats: &[],
4408    });
4409
4410    let mut cur_w = w;
4411    let mut cur_h = h;
4412    let mut cur_buf = r8;
4413    for mip in 0..mip_level_count {
4414        let mip_exp = (cur_w as usize) * (cur_h as usize);
4415        if cur_buf.len() >= mip_exp {
4416            queue.write_texture(
4417                wgpu::TexelCopyTextureInfo {
4418                    texture: &tex,
4419                    mip_level: mip,
4420                    origin: wgpu::Origin3d::ZERO,
4421                    aspect: wgpu::TextureAspect::All,
4422                },
4423                &cur_buf[..mip_exp],
4424                wgpu::TexelCopyBufferLayout {
4425                    offset: 0,
4426                    bytes_per_row: Some(cur_w),
4427                    rows_per_image: Some(cur_h),
4428                },
4429                wgpu::Extent3d {
4430                    width: cur_w,
4431                    height: cur_h,
4432                    depth_or_array_layers: 1,
4433                },
4434            );
4435        }
4436        if mip + 1 < mip_level_count {
4437            let (nw, nh, next) = downsample_cloud_r8_half(&cur_buf, cur_w, cur_h);
4438            cur_w = nw;
4439            cur_h = nh;
4440            cur_buf = next;
4441        }
4442    }
4443    tex.create_view(&Default::default())
4444}
4445
4446fn create_cloud_noise_lut_view(device: &wgpu::Device, queue: &wgpu::Queue) -> wgpu::TextureView {
4447    const DIM: u32 = 128;
4448    let hash_cell = |ix: u32, iy: u32, period: u32, seed: u32| -> f32 {
4449        let x = ix % period;
4450        let y = iy % period;
4451        let mut h = x
4452            .wrapping_mul(0x9e37_79b1)
4453            .wrapping_add(y.wrapping_mul(0x85eb_ca77))
4454            .wrapping_add(seed.wrapping_mul(0xc2b2_ae3d));
4455        h ^= h >> 16;
4456        h = h.wrapping_mul(0x27d4_eb2f);
4457        h ^= h >> 15;
4458        (h & 0xffff) as f32 * (1.0 / 65535.0)
4459    };
4460    let sample_periodic = |u: f32, v: f32, period: u32, seed: u32| -> u8 {
4461        let x = u * (period as f32);
4462        let y = v * (period as f32);
4463        let ix = x.floor() as u32;
4464        let iy = y.floor() as u32;
4465        let fx = x - x.floor();
4466        let fy = y - y.floor();
4467        let ux = fx * fx * (3.0 - 2.0 * fx);
4468        let uy = fy * fy * (3.0 - 2.0 * fy);
4469        let n00 = hash_cell(ix, iy, period, seed);
4470        let n10 = hash_cell(ix + 1, iy, period, seed);
4471        let n01 = hash_cell(ix, iy + 1, period, seed);
4472        let n11 = hash_cell(ix + 1, iy + 1, period, seed);
4473        let nx0 = n00 + (n10 - n00) * ux;
4474        let nx1 = n01 + (n11 - n01) * ux;
4475        let val = nx0 + (nx1 - nx0) * uy;
4476        (val.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
4477    };
4478
4479    let mut rgba = vec![0u8; (DIM * DIM * 4) as usize];
4480    let inv = 1.0 / (DIM as f32);
4481    for y in 0..DIM {
4482        let v = (y as f32 + 0.5) * inv;
4483        for x in 0..DIM {
4484            let u = (x as f32 + 0.5) * inv;
4485            let idx = ((y * DIM + x) * 4) as usize;
4486            rgba[idx] = sample_periodic(u, v, 32, 1);
4487            rgba[idx + 1] = sample_periodic(u, v, 96, 2);
4488            rgba[idx + 2] = sample_periodic(u, v, 32, 3);
4489            rgba[idx + 3] = sample_periodic(u, v, 32, 4);
4490        }
4491    }
4492
4493    let tex = device.create_texture(&wgpu::TextureDescriptor {
4494        label: Some("strata_env_cloud_noise_lut"),
4495        size: wgpu::Extent3d {
4496            width: DIM,
4497            height: DIM,
4498            depth_or_array_layers: 1,
4499        },
4500        mip_level_count: 1,
4501        sample_count: 1,
4502        dimension: wgpu::TextureDimension::D2,
4503        format: wgpu::TextureFormat::Rgba8Unorm,
4504        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4505        view_formats: &[],
4506    });
4507    queue.write_texture(
4508        wgpu::TexelCopyTextureInfo {
4509            texture: &tex,
4510            mip_level: 0,
4511            origin: wgpu::Origin3d::ZERO,
4512            aspect: wgpu::TextureAspect::All,
4513        },
4514        &rgba,
4515        wgpu::TexelCopyBufferLayout {
4516            offset: 0,
4517            bytes_per_row: Some(DIM * 4),
4518            rows_per_image: Some(DIM),
4519        },
4520        wgpu::Extent3d {
4521            width: DIM,
4522            height: DIM,
4523            depth_or_array_layers: 1,
4524        },
4525    );
4526    tex.create_view(&Default::default())
4527}
4528
4529fn build_unit_icosphere(subdivisions: u32) -> (Vec<RteTileVertex>, Vec<u32>) {
4530    let t = (1.0f32 + 5.0f32.sqrt()) * 0.5;
4531    let raw = [
4532        [-1.0, t, 0.0],
4533        [1.0, t, 0.0],
4534        [-1.0, -t, 0.0],
4535        [1.0, -t, 0.0],
4536        [0.0, -1.0, t],
4537        [0.0, 1.0, t],
4538        [0.0, -1.0, -t],
4539        [0.0, 1.0, -t],
4540        [t, 0.0, -1.0],
4541        [t, 0.0, 1.0],
4542        [-t, 0.0, -1.0],
4543        [-t, 0.0, 1.0],
4544    ];
4545    let norm = |p: [f32; 3]| -> [f32; 3] {
4546        let l = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt().max(1e-6);
4547        [p[0] / l, p[1] / l, p[2] / l]
4548    };
4549    let mut verts: Vec<[f32; 3]> = raw.iter().map(|p| norm(*p)).collect();
4550    let mut tris: Vec<[u32; 3]> = vec![
4551        [0, 11, 5],
4552        [0, 5, 1],
4553        [0, 1, 7],
4554        [0, 7, 10],
4555        [0, 10, 11],
4556        [1, 5, 9],
4557        [5, 11, 4],
4558        [11, 10, 2],
4559        [10, 7, 6],
4560        [7, 1, 8],
4561        [3, 9, 4],
4562        [3, 4, 2],
4563        [3, 2, 6],
4564        [3, 6, 8],
4565        [3, 8, 9],
4566        [4, 9, 5],
4567        [2, 4, 11],
4568        [6, 2, 10],
4569        [8, 6, 7],
4570        [9, 8, 1],
4571    ];
4572
4573    for _ in 0..subdivisions {
4574        let mut mid_cache: HashMap<(u32, u32), u32> = HashMap::new();
4575        let mut get_mid = |a: u32, b: u32, vs: &mut Vec<[f32; 3]>| -> u32 {
4576            let key = if a < b { (a, b) } else { (b, a) };
4577            if let Some(&idx) = mid_cache.get(&key) {
4578                return idx;
4579            }
4580            let pa = vs[a as usize];
4581            let pb = vs[b as usize];
4582            let m = norm([
4583                (pa[0] + pb[0]) * 0.5,
4584                (pa[1] + pb[1]) * 0.5,
4585                (pa[2] + pb[2]) * 0.5,
4586            ]);
4587            let idx = vs.len() as u32;
4588            vs.push(m);
4589            mid_cache.insert(key, idx);
4590            idx
4591        };
4592        let mut next_tris = Vec::with_capacity(tris.len() * 4);
4593        for [a, b, c] in tris {
4594            let ab = get_mid(a, b, &mut verts);
4595            let bc = get_mid(b, c, &mut verts);
4596            let ca = get_mid(c, a, &mut verts);
4597            next_tris.push([a, ab, ca]);
4598            next_tris.push([b, bc, ab]);
4599            next_tris.push([c, ca, bc]);
4600            next_tris.push([ab, bc, ca]);
4601        }
4602        tris = next_tris;
4603    }
4604
4605    let rte_verts: Vec<RteTileVertex> = verts
4606        .into_iter()
4607        .map(|p| RteTileVertex::new(p, p, [0.0, 0.0]))
4608        .collect();
4609    let mut indices = Vec::with_capacity(tris.len() * 3);
4610    for [a, b, c] in tris {
4611        indices.push(a);
4612        indices.push(b);
4613        indices.push(c);
4614    }
4615    (rte_verts, indices)
4616}
4617
4618struct CachedParticleTexture {
4619    revision: u64,
4620    width: u32,
4621    height: u32,
4622    _texture: wgpu::Texture,
4623    bind_group: wgpu::BindGroup,
4624}
4625
4626/// Hardware GPU pass durations resolved asynchronously from `wgpu::Features::TIMESTAMP_QUERY`.
4627#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
4628pub struct GpuPassTimings {
4629    /// True when the active adapter/device supports `wgpu::Features::TIMESTAMP_QUERY`.
4630    pub supported: bool,
4631    /// Directional shadow-map pass duration on GPU (microseconds).
4632    pub shadow_pass_us: u32,
4633    /// Main 3D scene pass (terrain/atmosphere/ocean/buildings/clouds/objects) duration on GPU (microseconds).
4634    pub scene_3d_pass_us: u32,
4635    /// Standalone 2D overlay / cached-3D blit+composite pass duration on GPU (microseconds).
4636    pub overlay_pass_us: u32,
4637    /// Combined 3D GPU duration (`shadow_pass_us + scene_3d_pass_us`).
4638    pub total_3d_gpu_us: u32,
4639}
4640
4641const GPU_TS_SLOTS: usize = 3;
4642const GPU_TS_QUERY_COUNT: u32 = 6; // [0..2]=shadow, [2..4]=main 3D, [4..6]=overlay/blit
4643const GPU_TS_RESOLVE_STRIDE: u64 = 256; // WebGPU QUERY_RESOLVE_BUFFER_ALIGNMENT
4644
4645struct TimestampSlot {
4646    query_set: wgpu::QuerySet,
4647    resolve_buffer: wgpu::Buffer,
4648    readback_buffer: wgpu::Buffer,
4649    mapped_ready: Arc<std::sync::atomic::AtomicBool>,
4650    in_flight: bool,
4651    wrote_shadow: bool,
4652    wrote_main: bool,
4653    wrote_overlay: bool,
4654}
4655
4656struct GpuTimestampProfiler {
4657    slots: Vec<TimestampSlot>,
4658    next_slot: usize,
4659    timestamp_period_ns: f64,
4660    last_timings: GpuPassTimings,
4661}
4662
4663impl GpuTimestampProfiler {
4664    fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
4665        let mut slots = Vec::with_capacity(GPU_TS_SLOTS);
4666        let resolve_bytes = GPU_TS_RESOLVE_STRIDE * 3;
4667        let readback_bytes = (GPU_TS_QUERY_COUNT as u64) * 8;
4668        for i in 0..GPU_TS_SLOTS {
4669            let query_set = device.create_query_set(&wgpu::QuerySetDescriptor {
4670                label: Some(&format!("strata_gpu_ts_query_set_{i}")),
4671                ty: wgpu::QueryType::Timestamp,
4672                count: GPU_TS_QUERY_COUNT,
4673            });
4674            let resolve_buffer = device.create_buffer(&wgpu::BufferDescriptor {
4675                label: Some(&format!("strata_gpu_ts_resolve_{i}")),
4676                size: resolve_bytes,
4677                usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
4678                mapped_at_creation: false,
4679            });
4680            let readback_buffer = device.create_buffer(&wgpu::BufferDescriptor {
4681                label: Some(&format!("strata_gpu_ts_readback_{i}")),
4682                size: readback_bytes,
4683                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
4684                mapped_at_creation: false,
4685            });
4686            slots.push(TimestampSlot {
4687                query_set,
4688                resolve_buffer,
4689                readback_buffer,
4690                mapped_ready: Arc::new(std::sync::atomic::AtomicBool::new(false)),
4691                in_flight: false,
4692                wrote_shadow: false,
4693                wrote_main: false,
4694                wrote_overlay: false,
4695            });
4696        }
4697        Self {
4698            slots,
4699            next_slot: 0,
4700            timestamp_period_ns: (queue.get_timestamp_period() as f64).max(0.0),
4701            last_timings: GpuPassTimings {
4702                supported: true,
4703                ..Default::default()
4704            },
4705        }
4706    }
4707
4708    fn poll_ready(&mut self, device: &wgpu::Device) {
4709        device.poll(wgpu::Maintain::Poll);
4710        let period_ns = self.timestamp_period_ns;
4711        for slot in &mut self.slots {
4712            if !slot.in_flight
4713                || !slot
4714                    .mapped_ready
4715                    .load(std::sync::atomic::Ordering::Acquire)
4716            {
4717                continue;
4718            }
4719            {
4720                let view = slot.readback_buffer.slice(..).get_mapped_range();
4721                if view.len() >= (GPU_TS_QUERY_COUNT as usize) * 8 {
4722                    let read_u64 = |idx: usize| -> u64 {
4723                        let off = idx * 8;
4724                        u64::from_le_bytes(view[off..off + 8].try_into().unwrap_or([0; 8]))
4725                    };
4726                    let ticks_to_us = |start: u64, end: u64| -> u32 {
4727                        let delta = end.saturating_sub(start) as f64;
4728                        ((delta * period_ns) / 1000.0).round().clamp(0.0, u32::MAX as f64) as u32
4729                    };
4730                    if slot.wrote_shadow {
4731                        self.last_timings.shadow_pass_us = ticks_to_us(read_u64(0), read_u64(1));
4732                    } else if slot.wrote_main {
4733                        self.last_timings.shadow_pass_us = 0;
4734                    }
4735                    if slot.wrote_main {
4736                        self.last_timings.scene_3d_pass_us = ticks_to_us(read_u64(2), read_u64(3));
4737                        self.last_timings.total_3d_gpu_us = self
4738                            .last_timings
4739                            .shadow_pass_us
4740                            .saturating_add(self.last_timings.scene_3d_pass_us);
4741                    }
4742                    if slot.wrote_overlay {
4743                        self.last_timings.overlay_pass_us = ticks_to_us(read_u64(4), read_u64(5));
4744                    }
4745                }
4746            }
4747            slot.readback_buffer.unmap();
4748            slot.mapped_ready
4749                .store(false, std::sync::atomic::Ordering::Release);
4750            slot.in_flight = false;
4751            slot.wrote_shadow = false;
4752            slot.wrote_main = false;
4753            slot.wrote_overlay = false;
4754        }
4755    }
4756
4757    fn acquire_idle_slot(&mut self, device: &wgpu::Device) -> Option<usize> {
4758        self.poll_ready(device);
4759        let n = self.slots.len();
4760        for off in 0..n {
4761            let idx = (self.next_slot + off) % n;
4762            if !self.slots[idx].in_flight {
4763                self.next_slot = (idx + 1) % n;
4764                let s = &mut self.slots[idx];
4765                s.wrote_shadow = false;
4766                s.wrote_main = false;
4767                s.wrote_overlay = false;
4768                return Some(idx);
4769            }
4770        }
4771        None
4772    }
4773
4774    fn resolve_and_copy(&self, slot_idx: usize, encoder: &mut wgpu::CommandEncoder) {
4775        let slot = &self.slots[slot_idx];
4776        // Vulkan requires resolving ONLY query indices that were actually written in this submission;
4777        // resolving unwritten queries blocks forever on VK_QUERY_RESULT_WAIT_BIT.
4778        if slot.wrote_shadow {
4779            encoder.resolve_query_set(&slot.query_set, 0..2, &slot.resolve_buffer, 0);
4780            encoder.copy_buffer_to_buffer(&slot.resolve_buffer, 0, &slot.readback_buffer, 0, 16);
4781        }
4782        if slot.wrote_main {
4783            encoder.resolve_query_set(
4784                &slot.query_set,
4785                2..4,
4786                &slot.resolve_buffer,
4787                GPU_TS_RESOLVE_STRIDE,
4788            );
4789            encoder.copy_buffer_to_buffer(
4790                &slot.resolve_buffer,
4791                GPU_TS_RESOLVE_STRIDE,
4792                &slot.readback_buffer,
4793                16,
4794                16,
4795            );
4796        }
4797        if slot.wrote_overlay {
4798            encoder.resolve_query_set(
4799                &slot.query_set,
4800                4..6,
4801                &slot.resolve_buffer,
4802                GPU_TS_RESOLVE_STRIDE * 2,
4803            );
4804            encoder.copy_buffer_to_buffer(
4805                &slot.resolve_buffer,
4806                GPU_TS_RESOLVE_STRIDE * 2,
4807                &slot.readback_buffer,
4808                32,
4809                16,
4810            );
4811        }
4812    }
4813
4814    fn begin_async_map(&mut self, slot_idx: usize) {
4815        let slot = &mut self.slots[slot_idx];
4816        if !slot.wrote_shadow && !slot.wrote_main && !slot.wrote_overlay {
4817            return;
4818        }
4819        slot.in_flight = true;
4820        slot.mapped_ready
4821            .store(false, std::sync::atomic::Ordering::Release);
4822        let ready = Arc::clone(&slot.mapped_ready);
4823        slot.readback_buffer
4824            .slice(..)
4825            .map_async(wgpu::MapMode::Read, move |res| {
4826                if res.is_ok() {
4827                    ready.store(true, std::sync::atomic::Ordering::Release);
4828                }
4829            });
4830    }
4831}
4832
4833/// Hardware-accelerated `wgpu` 3D renderer capable of rendering directly into any `TextureView`
4834/// (swapchain surface) or offscreen RGBA target.
4835pub struct Wgpu3DRenderer {
4836    device: Arc<wgpu::Device>,
4837    queue: Arc<wgpu::Queue>,
4838    color_format: wgpu::TextureFormat,
4839    camera_buffer: wgpu::Buffer,
4840    sky_pipeline: wgpu::RenderPipeline,
4841    sky_opaque_pipeline: wgpu::RenderPipeline,
4842    sky_bind_group_layout: wgpu::BindGroupLayout,
4843    sky_bind_group: wgpu::BindGroup,
4844    star_pipeline: wgpu::RenderPipeline,
4845    star_bind_group_layout: wgpu::BindGroupLayout,
4846    star_bind_group: wgpu::BindGroup,
4847    cloud_pipeline: wgpu::RenderPipeline,
4848    cloud_inside_pipeline: wgpu::RenderPipeline,
4849    cloud_twosided_pipeline: wgpu::RenderPipeline,
4850    cloud_bind_group_layout: wgpu::BindGroupLayout,
4851    cloud_bind_group: wgpu::BindGroup,
4852    cloud_vbuf: wgpu::Buffer,
4853    cloud_ibuf: wgpu::Buffer,
4854    cloud_index_count: u32,
4855    env_state: GpuEnvironmentState,
4856    terrain_pipeline: wgpu::RenderPipeline,
4857    terrain_opaque_pipeline: wgpu::RenderPipeline,
4858    terrain_shadow_pipeline: wgpu::RenderPipeline,
4859    terrain_bind_group_layout: wgpu::BindGroupLayout,
4860    terrain_bind_group: wgpu::BindGroup,
4861    terrain_sampler: wgpu::Sampler,
4862    shadow_ocean_bgl: wgpu::BindGroupLayout,
4863    shadow_ocean_bind_group: wgpu::BindGroup,
4864    shadow_sampler: wgpu::Sampler,
4865    _shadow_fallback_tex: wgpu::Texture,
4866    shadow_fallback_view: wgpu::TextureView,
4867    shadow_target: Option<(u32, wgpu::Texture, wgpu::TextureView)>,
4868    ocean_uniform_buffer: wgpu::Buffer,
4869    coastal_sdf_sampler: wgpu::Sampler,
4870    _coastal_sdf_fallback_tex: wgpu::Texture,
4871    coastal_sdf_fallback_view: wgpu::TextureView,
4872    coastal_sdf_cached: Option<(u64, u64, u32, u32, wgpu::Texture, wgpu::TextureView)>,
4873    instance_buffer: wgpu::Buffer,
4874    instance_capacity: usize,
4875    slab: GpuTileSlabAllocator,
4876    atlas: GpuImageryAtlas,
4877    topologies: HashMap<(u32, bool), CachedIndexTopology>,
4878    dynamic_pipeline: wgpu::RenderPipeline,
4879    dynamic_bind_group_layout: wgpu::BindGroupLayout,
4880    dynamic_uniform_buffer: wgpu::Buffer,
4881    dynamic_uniform_capacity: usize,
4882    dynamic_uniform_stride: u32,
4883    dynamic_bind_group: wgpu::BindGroup,
4884    dynamic_meshes: HashMap<u64, CachedDynamicGpuMesh>,
4885    geo_object_pipeline: wgpu::RenderPipeline,
4886    geo_object_transparent_pipeline: wgpu::RenderPipeline,
4887    geo_shadow_pipeline: wgpu::RenderPipeline,
4888    geo_object_bind_group_layout: wgpu::BindGroupLayout,
4889    geo_object_bind_group: wgpu::BindGroup,
4890    geo_tex_bgl: wgpu::BindGroupLayout,
4891    geo_sampler: wgpu::Sampler,
4892    geo_default_tex_bg: wgpu::BindGroup,
4893    geo_instance_buffer: wgpu::Buffer,
4894    geo_instance_capacity: usize,
4895    geo_meshes: HashMap<u64, CachedGeoGpuMesh>,
4896    geo_textures: HashMap<u64, CachedGeoTexture>,
4897    particle_pipeline: wgpu::RenderPipeline,
4898    particle_common_bgl: wgpu::BindGroupLayout,
4899    particle_tex_bgl: wgpu::BindGroupLayout,
4900    particle_sampler: wgpu::Sampler,
4901    particle_uniform_buffer: wgpu::Buffer,
4902    particle_uniform_capacity: usize,
4903    particle_uniform_stride: u32,
4904    particle_common_bind_group: wgpu::BindGroup,
4905    particle_default_tex_bg: wgpu::BindGroup,
4906    particle_textures: HashMap<u64, CachedParticleTexture>,
4907    overlay_pipeline: wgpu::RenderPipeline,
4908    overlay_main_pass_pipeline: wgpu::RenderPipeline,
4909    scene_blit_pipeline: wgpu::RenderPipeline,
4910    overlay_bind_group_layout: wgpu::BindGroupLayout,
4911    overlay_sampler: wgpu::Sampler,
4912    depth_target: Option<(u32, u32, wgpu::TextureView)>,
4913    offscreen: Option<OffscreenTarget>,
4914    timestamp_profiler: Option<GpuTimestampProfiler>,
4915    frame_index: u64,
4916    last_geometry_rev: u64,
4917    last_terrain_frame: Option<Arc<RetainedTerrainFrame>>,
4918    cached_fallback_frames: HashMap<(usize, u32, u32), (u64, Arc<RetainedTerrainFrame>)>,
4919}
4920
4921/// Returns adapter-supported [`wgpu::Limits`] requesting up to [`MAX_ATLAS_LAYERS`] texture array layers.
4922pub fn preferred_wgpu_limits(adapter: &wgpu::Adapter) -> wgpu::Limits {
4923    let mut limits = wgpu::Limits::default();
4924    limits.max_texture_array_layers = adapter
4925        .limits()
4926        .max_texture_array_layers
4927        .min(MAX_ATLAS_LAYERS)
4928        .max(limits.max_texture_array_layers);
4929    limits
4930}
4931
4932/// Acquires the first compatible [`wgpu::Adapter`] whose `request_device` succeeds,
4933/// preferring discrete GPUs first and automatically failing over across integrated/software
4934/// adapters when the primary GPU driver reports device loss or resource exhaustion.
4935pub fn request_working_adapter_and_device(
4936    instance: &wgpu::Instance,
4937    compatible_surface: Option<&wgpu::Surface<'_>>,
4938    label: &str,
4939) -> Result<(wgpu::Adapter, wgpu::Device, wgpu::Queue), String> {
4940    let mut candidates: Vec<wgpu::Adapter> = Vec::new();
4941    let mut seen: Vec<(u32, u32, wgpu::DeviceType, wgpu::Backend, String)> = Vec::new();
4942    let mut push_unique = |adapter: wgpu::Adapter| {
4943        if let Some(surface) = compatible_surface {
4944            if !adapter.is_surface_supported(surface) {
4945                return;
4946            }
4947        }
4948        let info = adapter.get_info();
4949        let key = (
4950            info.vendor,
4951            info.device,
4952            info.device_type,
4953            info.backend,
4954            info.name,
4955        );
4956        if !seen.contains(&key) {
4957            seen.push(key);
4958            candidates.push(adapter);
4959        }
4960    };
4961
4962    if let Some(preferred) = pollster::block_on(instance.request_adapter(
4963        &wgpu::RequestAdapterOptions {
4964            power_preference: wgpu::PowerPreference::HighPerformance,
4965            compatible_surface,
4966            force_fallback_adapter: false,
4967        },
4968    )) {
4969        push_unique(preferred);
4970    }
4971
4972    let mut enumerated: Vec<wgpu::Adapter> = instance
4973        .enumerate_adapters(wgpu::Backends::all())
4974        .into_iter()
4975        .collect();
4976    enumerated.sort_by_key(|a| {
4977        let info = a.get_info();
4978        let dev_rank = match info.device_type {
4979            wgpu::DeviceType::DiscreteGpu => 0u8,
4980            wgpu::DeviceType::IntegratedGpu => 1,
4981            wgpu::DeviceType::VirtualGpu => 2,
4982            wgpu::DeviceType::Cpu => 3,
4983            wgpu::DeviceType::Other => 4,
4984        };
4985        let backend_rank = match info.backend {
4986            wgpu::Backend::Vulkan => 0u8,
4987            wgpu::Backend::Metal | wgpu::Backend::Dx12 => 1,
4988            wgpu::Backend::Gl => 2,
4989            _ => 3,
4990        };
4991        (dev_rank, backend_rank)
4992    });
4993    for adapter in enumerated {
4994        push_unique(adapter);
4995    }
4996
4997    if candidates.is_empty() {
4998        return Err(if compatible_surface.is_some() {
4999            "no compatible wgpu adapter for window surface".to_string()
5000        } else {
5001            "no wgpu adapter available".to_string()
5002        });
5003    }
5004
5005    let mut errors = Vec::new();
5006    for adapter in candidates {
5007        let info = adapter.get_info();
5008        let required_limits = preferred_wgpu_limits(&adapter);
5009        let optional_ts = adapter.features() & wgpu::Features::TIMESTAMP_QUERY;
5010        let first_try = pollster::block_on(adapter.request_device(
5011            &wgpu::DeviceDescriptor {
5012                label: Some(label),
5013                required_features: optional_ts,
5014                required_limits: required_limits.clone(),
5015                memory_hints: wgpu::MemoryHints::Performance,
5016            },
5017            None,
5018        ));
5019        match first_try {
5020            Ok((device, queue)) => return Ok((adapter, device, queue)),
5021            Err(_) if !optional_ts.is_empty() => {
5022                // Gracefully fall back if driver advertises TIMESTAMP_QUERY but rejects device creation.
5023                match pollster::block_on(adapter.request_device(
5024                    &wgpu::DeviceDescriptor {
5025                        label: Some(label),
5026                        required_features: wgpu::Features::empty(),
5027                        required_limits,
5028                        memory_hints: wgpu::MemoryHints::Performance,
5029                    },
5030                    None,
5031                )) {
5032                    Ok((device, queue)) => return Ok((adapter, device, queue)),
5033                    Err(e) => {
5034                        errors.push(format!(
5035                            "{} ({:?}/{:?}): {e}",
5036                            info.name, info.backend, info.device_type
5037                        ));
5038                    }
5039                }
5040            }
5041            Err(e) => {
5042                errors.push(format!(
5043                    "{} ({:?}/{:?}): {e}",
5044                    info.name, info.backend, info.device_type
5045                ));
5046            }
5047        }
5048    }
5049
5050    Err(format!("request_device failed: {}", errors.join("; ")))
5051}
5052
5053impl Wgpu3DRenderer {
5054    /// Creates a headless `Wgpu3DRenderer` using any available hardware or software Vulkan/GL adapter.
5055    pub fn new_headless(color_format: wgpu::TextureFormat) -> Result<Self, String> {
5056        let instance = wgpu::Instance::default();
5057        let (_adapter, device, queue) =
5058            request_working_adapter_and_device(&instance, None, "strata_render_wgpu_device")?;
5059        Ok(Self::from_device(
5060            Arc::new(device),
5061            Arc::new(queue),
5062            color_format,
5063        ))
5064    }
5065
5066    /// Creates a `Wgpu3DRenderer` bound to an existing `wgpu::Device` & `wgpu::Queue` (e.g., from a window surface).
5067    pub fn from_device(
5068        device: Arc<wgpu::Device>,
5069        queue: Arc<wgpu::Queue>,
5070        color_format: wgpu::TextureFormat,
5071    ) -> Self {
5072        let camera_buffer = device.create_buffer(&wgpu::BufferDescriptor {
5073            label: Some("strata_3d_camera_uniforms"),
5074            size: std::mem::size_of::<GpuCameraUniforms>() as u64,
5075            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
5076            mapped_at_creation: false,
5077        });
5078
5079        let initial_instances = 1024usize;
5080        let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
5081            label: Some("strata_3d_tile_instances"),
5082            size: (initial_instances * std::mem::size_of::<GpuTileInstance>()) as u64,
5083            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
5084            mapped_at_creation: false,
5085        });
5086
5087        let slab = GpuTileSlabAllocator::new(&device, 262_144);
5088        let atlas_layers = MAX_ATLAS_LAYERS.min(device.limits().max_texture_array_layers.max(1));
5089        let atlas = GpuImageryAtlas::new(&device, &queue, atlas_layers, color_format);
5090
5091        let terrain_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
5092            label: Some("strata_3d_terrain_sampler"),
5093            mag_filter: wgpu::FilterMode::Linear,
5094            min_filter: wgpu::FilterMode::Linear,
5095            mipmap_filter: wgpu::FilterMode::Linear,
5096            address_mode_u: wgpu::AddressMode::ClampToEdge,
5097            address_mode_v: wgpu::AddressMode::ClampToEdge,
5098            ..Default::default()
5099        });
5100
5101        let env_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
5102            label: Some("strata_3d_env_sampler"),
5103            mag_filter: wgpu::FilterMode::Linear,
5104            min_filter: wgpu::FilterMode::Linear,
5105            mipmap_filter: wgpu::FilterMode::Linear,
5106            address_mode_u: wgpu::AddressMode::Repeat,
5107            address_mode_v: wgpu::AddressMode::ClampToEdge,
5108            ..Default::default()
5109        });
5110        let cloud_noise_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
5111            label: Some("strata_3d_cloud_noise_sampler"),
5112            mag_filter: wgpu::FilterMode::Linear,
5113            min_filter: wgpu::FilterMode::Linear,
5114            mipmap_filter: wgpu::FilterMode::Nearest,
5115            address_mode_u: wgpu::AddressMode::Repeat,
5116            address_mode_v: wgpu::AddressMode::Repeat,
5117            ..Default::default()
5118        });
5119        let land_mask_view = create_rgba8_2d_view(
5120            &device,
5121            &queue,
5122            "strata_env_land_fallback",
5123            1,
5124            1,
5125            &[255, 255, 255, 255],
5126        );
5127        let cloud_map_view = create_cloud_density_r8_view(
5128            &device,
5129            &queue,
5130            "strata_env_cloud_fallback",
5131            1,
5132            1,
5133            &[255, 255, 255, 0],
5134        );
5135        let cloud_noise_view = create_cloud_noise_lut_view(&device, &queue);
5136        let moon_view = create_rgba8_2d_view(
5137            &device,
5138            &queue,
5139            "strata_env_moon_fallback",
5140            1,
5141            1,
5142            &[190, 190, 190, 255],
5143        );
5144        let black_face = Arc::new(vec![0u8, 0, 0, 0]);
5145        let skybox_cube_view = create_rgba8_cube_view(
5146            &device,
5147            &queue,
5148            "strata_env_skybox_fallback",
5149            1,
5150            &[
5151                Arc::clone(&black_face),
5152                Arc::clone(&black_face),
5153                Arc::clone(&black_face),
5154                Arc::clone(&black_face),
5155                Arc::clone(&black_face),
5156                black_face,
5157            ],
5158            wgpu::TextureFormat::Rgba8Unorm,
5159        );
5160        let star_capacity = 64usize;
5161        let star_buffer = device.create_buffer(&wgpu::BufferDescriptor {
5162            label: Some("strata_3d_stars"),
5163            size: (star_capacity * std::mem::size_of::<GpuStar>()) as u64,
5164            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
5165            mapped_at_creation: false,
5166        });
5167        let env_state = GpuEnvironmentState {
5168            land_mask_id_rev: None,
5169            cloud_map_id_rev: None,
5170            moon_tex_id_rev: None,
5171            skybox_cube_id_rev: None,
5172            stars_ptr: 0,
5173            stars_len: 0,
5174            land_mask_view,
5175            cloud_map_view,
5176            cloud_noise_view,
5177            moon_view,
5178            skybox_cube_view,
5179            env_sampler,
5180            cloud_noise_sampler,
5181            star_buffer,
5182            star_capacity,
5183            star_count: 0,
5184        };
5185
5186        // Sky + Moon + Sun + Milky Way pass
5187        let sky_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5188            label: Some("strata_3d_sky_wgsl"),
5189            source: wgpu::ShaderSource::Wgsl(SKY_WGSL.into()),
5190        });
5191        let sky_bind_group_layout =
5192            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5193                label: Some("strata_3d_sky_bgl"),
5194                entries: &[
5195                    wgpu::BindGroupLayoutEntry {
5196                        binding: 0,
5197                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5198                        ty: wgpu::BindingType::Buffer {
5199                            ty: wgpu::BufferBindingType::Uniform,
5200                            has_dynamic_offset: false,
5201                            min_binding_size: None,
5202                        },
5203                        count: None,
5204                    },
5205                    wgpu::BindGroupLayoutEntry {
5206                        binding: 1,
5207                        visibility: wgpu::ShaderStages::FRAGMENT,
5208                        ty: wgpu::BindingType::Texture {
5209                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
5210                            view_dimension: wgpu::TextureViewDimension::D2,
5211                            multisampled: false,
5212                        },
5213                        count: None,
5214                    },
5215                    wgpu::BindGroupLayoutEntry {
5216                        binding: 2,
5217                        visibility: wgpu::ShaderStages::FRAGMENT,
5218                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
5219                        count: None,
5220                    },
5221                    wgpu::BindGroupLayoutEntry {
5222                        binding: 3,
5223                        visibility: wgpu::ShaderStages::FRAGMENT,
5224                        ty: wgpu::BindingType::Texture {
5225                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
5226                            view_dimension: wgpu::TextureViewDimension::Cube,
5227                            multisampled: false,
5228                        },
5229                        count: None,
5230                    },
5231                ],
5232            });
5233        let sky_bind_group = Self::create_sky_bind_group(
5234            &device,
5235            &sky_bind_group_layout,
5236            &camera_buffer,
5237            &env_state.moon_view,
5238            &env_state.env_sampler,
5239            &env_state.skybox_cube_view,
5240        );
5241        let sky_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
5242            label: Some("strata_3d_sky_pl"),
5243            bind_group_layouts: &[&sky_bind_group_layout],
5244            push_constant_ranges: &[],
5245        });
5246        let make_sky_pipeline = |label: &str, blend: Option<wgpu::BlendState>| {
5247            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
5248                label: Some(label),
5249                layout: Some(&sky_layout),
5250                vertex: wgpu::VertexState {
5251                    module: &sky_shader,
5252                    entry_point: Some("vs_sky"),
5253                    buffers: &[],
5254                    compilation_options: Default::default(),
5255                },
5256                fragment: Some(wgpu::FragmentState {
5257                    module: &sky_shader,
5258                    entry_point: Some("fs_sky"),
5259                    targets: &[Some(wgpu::ColorTargetState {
5260                        format: color_format,
5261                        blend,
5262                        write_mask: wgpu::ColorWrites::ALL,
5263                    })],
5264                    compilation_options: Default::default(),
5265                }),
5266                primitive: wgpu::PrimitiveState::default(),
5267                depth_stencil: Some(wgpu::DepthStencilState {
5268                    format: wgpu::TextureFormat::Depth32Float,
5269                    depth_write_enabled: false,
5270                    depth_compare: wgpu::CompareFunction::LessEqual,
5271                    stencil: wgpu::StencilState::default(),
5272                    bias: wgpu::DepthBiasState::default(),
5273                }),
5274                multisample: wgpu::MultisampleState::default(),
5275                multiview: None,
5276                cache: None,
5277            })
5278        };
5279        let sky_pipeline = make_sky_pipeline(
5280            "strata_3d_sky_pipeline",
5281            Some(wgpu::BlendState::ALPHA_BLENDING),
5282        );
5283        let sky_opaque_pipeline = make_sky_pipeline("strata_3d_sky_opaque_pipeline", None);
5284
5285        // Scientific J2000 starfield pass
5286        let star_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5287            label: Some("strata_3d_stars_wgsl"),
5288            source: wgpu::ShaderSource::Wgsl(STARS_WGSL.into()),
5289        });
5290        let star_bind_group_layout =
5291            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5292                label: Some("strata_3d_stars_bgl"),
5293                entries: &[
5294                    wgpu::BindGroupLayoutEntry {
5295                        binding: 0,
5296                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5297                        ty: wgpu::BindingType::Buffer {
5298                            ty: wgpu::BufferBindingType::Uniform,
5299                            has_dynamic_offset: false,
5300                            min_binding_size: None,
5301                        },
5302                        count: None,
5303                    },
5304                    wgpu::BindGroupLayoutEntry {
5305                        binding: 1,
5306                        visibility: wgpu::ShaderStages::VERTEX,
5307                        ty: wgpu::BindingType::Buffer {
5308                            ty: wgpu::BufferBindingType::Storage { read_only: true },
5309                            has_dynamic_offset: false,
5310                            min_binding_size: None,
5311                        },
5312                        count: None,
5313                    },
5314                ],
5315            });
5316        let star_bind_group = Self::create_star_bind_group(
5317            &device,
5318            &star_bind_group_layout,
5319            &camera_buffer,
5320            &env_state.star_buffer,
5321        );
5322        let star_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
5323            label: Some("strata_3d_stars_pl"),
5324            bind_group_layouts: &[&star_bind_group_layout],
5325            push_constant_ranges: &[],
5326        });
5327        let star_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
5328            label: Some("strata_3d_star_pipeline"),
5329            layout: Some(&star_layout),
5330            vertex: wgpu::VertexState {
5331                module: &star_shader,
5332                entry_point: Some("vs_star"),
5333                buffers: &[],
5334                compilation_options: Default::default(),
5335            },
5336            fragment: Some(wgpu::FragmentState {
5337                module: &star_shader,
5338                entry_point: Some("fs_star"),
5339                targets: &[Some(wgpu::ColorTargetState {
5340                    format: color_format,
5341                    blend: Some(wgpu::BlendState {
5342                        color: wgpu::BlendComponent {
5343                            src_factor: wgpu::BlendFactor::One,
5344                            dst_factor: wgpu::BlendFactor::One,
5345                            operation: wgpu::BlendOperation::Add,
5346                        },
5347                        alpha: wgpu::BlendComponent {
5348                            src_factor: wgpu::BlendFactor::One,
5349                            dst_factor: wgpu::BlendFactor::One,
5350                            operation: wgpu::BlendOperation::Add,
5351                        },
5352                    }),
5353                    write_mask: wgpu::ColorWrites::ALL,
5354                })],
5355                compilation_options: Default::default(),
5356            }),
5357            primitive: wgpu::PrimitiveState::default(),
5358            depth_stencil: Some(wgpu::DepthStencilState {
5359                format: wgpu::TextureFormat::Depth32Float,
5360                depth_write_enabled: false,
5361                depth_compare: wgpu::CompareFunction::LessEqual,
5362                stencil: wgpu::StencilState::default(),
5363                bias: wgpu::DepthBiasState::default(),
5364            }),
5365            multisample: wgpu::MultisampleState::default(),
5366            multiview: None,
5367            cache: None,
5368        });
5369
5370        // 3D global cloud shell pipeline + static icosphere
5371        let cloud_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5372            label: Some("strata_3d_cloud_shell_wgsl"),
5373            source: wgpu::ShaderSource::Wgsl(CLOUD_SHELL_WGSL.into()),
5374        });
5375        let cloud_bind_group_layout =
5376            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5377                label: Some("strata_3d_cloud_bgl"),
5378                entries: &[
5379                    wgpu::BindGroupLayoutEntry {
5380                        binding: 0,
5381                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5382                        ty: wgpu::BindingType::Buffer {
5383                            ty: wgpu::BufferBindingType::Uniform,
5384                            has_dynamic_offset: false,
5385                            min_binding_size: None,
5386                        },
5387                        count: None,
5388                    },
5389                    wgpu::BindGroupLayoutEntry {
5390                        binding: 1,
5391                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5392                        ty: wgpu::BindingType::Texture {
5393                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
5394                            view_dimension: wgpu::TextureViewDimension::D2,
5395                            multisampled: false,
5396                        },
5397                        count: None,
5398                    },
5399                    wgpu::BindGroupLayoutEntry {
5400                        binding: 2,
5401                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5402                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
5403                        count: None,
5404                    },
5405                    wgpu::BindGroupLayoutEntry {
5406                        binding: 3,
5407                        visibility: wgpu::ShaderStages::FRAGMENT,
5408                        ty: wgpu::BindingType::Texture {
5409                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
5410                            view_dimension: wgpu::TextureViewDimension::D2,
5411                            multisampled: false,
5412                        },
5413                        count: None,
5414                    },
5415                    wgpu::BindGroupLayoutEntry {
5416                        binding: 4,
5417                        visibility: wgpu::ShaderStages::FRAGMENT,
5418                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
5419                        count: None,
5420                    },
5421                ],
5422            });
5423        let cloud_bind_group = Self::create_cloud_bind_group(
5424            &device,
5425            &cloud_bind_group_layout,
5426            "strata_3d_cloud_bg",
5427            &camera_buffer,
5428            &env_state.cloud_map_view,
5429            &env_state.env_sampler,
5430            &env_state.cloud_noise_view,
5431            &env_state.cloud_noise_sampler,
5432        );
5433        let cloud_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
5434            label: Some("strata_3d_cloud_pl"),
5435            bind_group_layouts: &[&cloud_bind_group_layout],
5436            push_constant_ranges: &[],
5437        });
5438        let make_cloud_pipeline = |label: &str, cull_mode: Option<wgpu::Face>| {
5439            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
5440                label: Some(label),
5441                layout: Some(&cloud_layout),
5442                vertex: wgpu::VertexState {
5443                    module: &cloud_shader,
5444                    entry_point: Some("vs_cloud"),
5445                    buffers: &[wgpu::VertexBufferLayout {
5446                        array_stride: std::mem::size_of::<RteTileVertex>() as u64,
5447                        step_mode: wgpu::VertexStepMode::Vertex,
5448                        attributes: &[
5449                            wgpu::VertexAttribute {
5450                                format: wgpu::VertexFormat::Float32x4,
5451                                offset: 0,
5452                                shader_location: 0,
5453                            },
5454                            wgpu::VertexAttribute {
5455                                format: wgpu::VertexFormat::Float32x4,
5456                                offset: 16,
5457                                shader_location: 1,
5458                            },
5459                        ],
5460                    }],
5461                    compilation_options: Default::default(),
5462                },
5463                fragment: Some(wgpu::FragmentState {
5464                    module: &cloud_shader,
5465                    entry_point: Some("fs_cloud"),
5466                    targets: &[Some(wgpu::ColorTargetState {
5467                        format: color_format,
5468                        blend: Some(wgpu::BlendState::ALPHA_BLENDING),
5469                        write_mask: wgpu::ColorWrites::ALL,
5470                    })],
5471                    compilation_options: Default::default(),
5472                }),
5473                primitive: wgpu::PrimitiveState {
5474                    topology: wgpu::PrimitiveTopology::TriangleList,
5475                    cull_mode,
5476                    front_face: wgpu::FrontFace::Ccw,
5477                    ..Default::default()
5478                },
5479                depth_stencil: Some(wgpu::DepthStencilState {
5480                    format: wgpu::TextureFormat::Depth32Float,
5481                    depth_write_enabled: false,
5482                    depth_compare: wgpu::CompareFunction::LessEqual,
5483                    stencil: wgpu::StencilState::default(),
5484                    bias: wgpu::DepthBiasState::default(),
5485                }),
5486                multisample: wgpu::MultisampleState::default(),
5487                multiview: None,
5488                cache: None,
5489            })
5490        };
5491        let cloud_pipeline =
5492            make_cloud_pipeline("strata_3d_cloud_pipeline", Some(wgpu::Face::Back));
5493        let cloud_inside_pipeline =
5494            make_cloud_pipeline("strata_3d_cloud_inside_pipeline", Some(wgpu::Face::Front));
5495        let cloud_twosided_pipeline =
5496            make_cloud_pipeline("strata_3d_cloud_twosided_pipeline", None);
5497        let (ico_v, ico_i) = build_unit_icosphere(4);
5498        let cloud_vbuf = device.create_buffer(&wgpu::BufferDescriptor {
5499            label: Some("strata_3d_cloud_vb"),
5500            size: (ico_v.len() * std::mem::size_of::<RteTileVertex>()) as u64,
5501            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
5502            mapped_at_creation: false,
5503        });
5504        queue.write_buffer(&cloud_vbuf, 0, bytemuck::cast_slice(&ico_v));
5505        let cloud_ibuf = device.create_buffer(&wgpu::BufferDescriptor {
5506            label: Some("strata_3d_cloud_ib"),
5507            size: (ico_i.len() * 4) as u64,
5508            usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
5509            mapped_at_creation: false,
5510        });
5511        queue.write_buffer(&cloud_ibuf, 0, bytemuck::cast_slice(&ico_i));
5512        let cloud_index_count = ico_i.len() as u32;
5513
5514        // Terrain vertex-pulling pipeline
5515        let terrain_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5516            label: Some("strata_3d_terrain_pull_wgsl"),
5517            source: wgpu::ShaderSource::Wgsl(TERRAIN_PULL_WGSL.into()),
5518        });
5519        let terrain_bind_group_layout =
5520            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5521                label: Some("strata_3d_terrain_bgl"),
5522                entries: &[
5523                    wgpu::BindGroupLayoutEntry {
5524                        binding: 0,
5525                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5526                        ty: wgpu::BindingType::Buffer {
5527                            ty: wgpu::BufferBindingType::Uniform,
5528                            has_dynamic_offset: false,
5529                            min_binding_size: None,
5530                        },
5531                        count: None,
5532                    },
5533                    wgpu::BindGroupLayoutEntry {
5534                        binding: 1,
5535                        visibility: wgpu::ShaderStages::VERTEX,
5536                        ty: wgpu::BindingType::Buffer {
5537                            ty: wgpu::BufferBindingType::Storage { read_only: true },
5538                            has_dynamic_offset: false,
5539                            min_binding_size: None,
5540                        },
5541                        count: None,
5542                    },
5543                    wgpu::BindGroupLayoutEntry {
5544                        binding: 2,
5545                        visibility: wgpu::ShaderStages::VERTEX,
5546                        ty: wgpu::BindingType::Buffer {
5547                            ty: wgpu::BufferBindingType::Storage { read_only: true },
5548                            has_dynamic_offset: false,
5549                            min_binding_size: None,
5550                        },
5551                        count: None,
5552                    },
5553                    wgpu::BindGroupLayoutEntry {
5554                        binding: 3,
5555                        visibility: wgpu::ShaderStages::FRAGMENT,
5556                        ty: wgpu::BindingType::Texture {
5557                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
5558                            view_dimension: wgpu::TextureViewDimension::D2Array,
5559                            multisampled: false,
5560                        },
5561                        count: None,
5562                    },
5563                    wgpu::BindGroupLayoutEntry {
5564                        binding: 4,
5565                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5566                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
5567                        count: None,
5568                    },
5569                    wgpu::BindGroupLayoutEntry {
5570                        binding: 5,
5571                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5572                        ty: wgpu::BindingType::Texture {
5573                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
5574                            view_dimension: wgpu::TextureViewDimension::D2,
5575                            multisampled: false,
5576                        },
5577                        count: None,
5578                    },
5579                    wgpu::BindGroupLayoutEntry {
5580                        binding: 6,
5581                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5582                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
5583                        count: None,
5584                    },
5585                ],
5586            });
5587        let terrain_bind_group = Self::create_terrain_bind_group(
5588            &device,
5589            &terrain_bind_group_layout,
5590            &camera_buffer,
5591            &slab.buffer,
5592            &instance_buffer,
5593            &atlas.view,
5594            &terrain_sampler,
5595            &env_state.land_mask_view,
5596            &env_state.env_sampler,
5597        );
5598        let shadow_ocean_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5599            label: Some("strata_3d_shadow_ocean_bgl"),
5600            entries: &[
5601                wgpu::BindGroupLayoutEntry {
5602                    binding: 0,
5603                    visibility: wgpu::ShaderStages::FRAGMENT,
5604                    ty: wgpu::BindingType::Texture {
5605                        sample_type: wgpu::TextureSampleType::Depth,
5606                        view_dimension: wgpu::TextureViewDimension::D2,
5607                        multisampled: false,
5608                    },
5609                    count: None,
5610                },
5611                wgpu::BindGroupLayoutEntry {
5612                    binding: 1,
5613                    visibility: wgpu::ShaderStages::FRAGMENT,
5614                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
5615                    count: None,
5616                },
5617                wgpu::BindGroupLayoutEntry {
5618                    binding: 2,
5619                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5620                    ty: wgpu::BindingType::Buffer {
5621                        ty: wgpu::BufferBindingType::Uniform,
5622                        has_dynamic_offset: false,
5623                        min_binding_size: None,
5624                    },
5625                    count: None,
5626                },
5627                wgpu::BindGroupLayoutEntry {
5628                    binding: 3,
5629                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5630                    ty: wgpu::BindingType::Texture {
5631                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
5632                        view_dimension: wgpu::TextureViewDimension::D2,
5633                        multisampled: false,
5634                    },
5635                    count: None,
5636                },
5637                wgpu::BindGroupLayoutEntry {
5638                    binding: 4,
5639                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5640                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
5641                    count: None,
5642                },
5643            ],
5644        });
5645        let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
5646            label: Some("strata_3d_shadow_cmp_sampler"),
5647            address_mode_u: wgpu::AddressMode::ClampToEdge,
5648            address_mode_v: wgpu::AddressMode::ClampToEdge,
5649            address_mode_w: wgpu::AddressMode::ClampToEdge,
5650            mag_filter: wgpu::FilterMode::Linear,
5651            min_filter: wgpu::FilterMode::Linear,
5652            compare: Some(wgpu::CompareFunction::LessEqual),
5653            ..Default::default()
5654        });
5655        let shadow_fallback_tex = device.create_texture(&wgpu::TextureDescriptor {
5656            label: Some("strata_3d_shadow_fallback_1x1"),
5657            size: wgpu::Extent3d {
5658                width: 1,
5659                height: 1,
5660                depth_or_array_layers: 1,
5661            },
5662            mip_level_count: 1,
5663            sample_count: 1,
5664            dimension: wgpu::TextureDimension::D2,
5665            format: wgpu::TextureFormat::Depth32Float,
5666            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
5667            view_formats: &[],
5668        });
5669        let shadow_fallback_view = shadow_fallback_tex.create_view(&wgpu::TextureViewDescriptor::default());
5670        // Clear 1x1 fallback depth texture to 1.0 once so comparisons always pass when shadows are off.
5671        {
5672            let mut init_enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
5673                label: Some("strata_3d_shadow_fallback_init"),
5674            });
5675            let _ = init_enc.begin_render_pass(&wgpu::RenderPassDescriptor {
5676                label: Some("strata_3d_shadow_fallback_clear"),
5677                color_attachments: &[],
5678                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
5679                    view: &shadow_fallback_view,
5680                    depth_ops: Some(wgpu::Operations {
5681                        load: wgpu::LoadOp::Clear(1.0),
5682                        store: wgpu::StoreOp::Store,
5683                    }),
5684                    stencil_ops: None,
5685                }),
5686                timestamp_writes: None,
5687                occlusion_query_set: None,
5688            });
5689            queue.submit(Some(init_enc.finish()));
5690        }
5691
5692        let ocean_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
5693            label: Some("strata_3d_ocean_uniforms"),
5694            size: std::mem::size_of::<GpuOceanUniforms>() as u64,
5695            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
5696            mapped_at_creation: false,
5697        });
5698        queue.write_buffer(
5699            &ocean_uniform_buffer,
5700            0,
5701            bytemuck::bytes_of(&GpuOceanUniforms::disabled()),
5702        );
5703        let coastal_sdf_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
5704            label: Some("strata_3d_coastal_sdf_sampler"),
5705            address_mode_u: wgpu::AddressMode::ClampToEdge,
5706            address_mode_v: wgpu::AddressMode::ClampToEdge,
5707            address_mode_w: wgpu::AddressMode::ClampToEdge,
5708            mag_filter: wgpu::FilterMode::Linear,
5709            min_filter: wgpu::FilterMode::Linear,
5710            ..Default::default()
5711        });
5712        let coastal_sdf_fallback_tex = device.create_texture(&wgpu::TextureDescriptor {
5713            label: Some("strata_3d_coastal_sdf_fallback_1x1"),
5714            size: wgpu::Extent3d {
5715                width: 1,
5716                height: 1,
5717                depth_or_array_layers: 1,
5718            },
5719            mip_level_count: 1,
5720            sample_count: 1,
5721            dimension: wgpu::TextureDimension::D2,
5722            format: wgpu::TextureFormat::Rgba8Unorm,
5723            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
5724            view_formats: &[],
5725        });
5726        queue.write_texture(
5727            wgpu::TexelCopyTextureInfo {
5728                texture: &coastal_sdf_fallback_tex,
5729                mip_level: 0,
5730                origin: wgpu::Origin3d::ZERO,
5731                aspect: wgpu::TextureAspect::All,
5732            },
5733            &[255u8, 255, 128, 128],
5734            wgpu::TexelCopyBufferLayout {
5735                offset: 0,
5736                bytes_per_row: Some(4),
5737                rows_per_image: Some(1),
5738            },
5739            wgpu::Extent3d {
5740                width: 1,
5741                height: 1,
5742                depth_or_array_layers: 1,
5743            },
5744        );
5745        let coastal_sdf_fallback_view =
5746            coastal_sdf_fallback_tex.create_view(&wgpu::TextureViewDescriptor::default());
5747        let shadow_ocean_bind_group = Self::create_shadow_ocean_bind_group(
5748            &device,
5749            &shadow_ocean_bgl,
5750            &shadow_fallback_view,
5751            &shadow_sampler,
5752            &ocean_uniform_buffer,
5753            &coastal_sdf_fallback_view,
5754            &coastal_sdf_sampler,
5755        );
5756
5757        let terrain_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
5758            label: Some("strata_3d_terrain_pl"),
5759            bind_group_layouts: &[&terrain_bind_group_layout, &shadow_ocean_bgl],
5760            push_constant_ranges: &[],
5761        });
5762        let make_terrain_pipeline = |label: &str, blend: Option<wgpu::BlendState>| {
5763            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
5764                label: Some(label),
5765                layout: Some(&terrain_layout),
5766                vertex: wgpu::VertexState {
5767                    module: &terrain_shader,
5768                    entry_point: Some("vs_terrain"),
5769                    buffers: &[],
5770                    compilation_options: Default::default(),
5771                },
5772                fragment: Some(wgpu::FragmentState {
5773                    module: &terrain_shader,
5774                    entry_point: Some(if blend.is_none() {
5775                        "fs_terrain_opaque"
5776                    } else {
5777                        "fs_terrain"
5778                    }),
5779                    targets: &[Some(wgpu::ColorTargetState {
5780                        format: color_format,
5781                        blend,
5782                        write_mask: wgpu::ColorWrites::ALL,
5783                    })],
5784                    compilation_options: Default::default(),
5785                }),
5786                primitive: wgpu::PrimitiveState {
5787                    topology: wgpu::PrimitiveTopology::TriangleList,
5788                    cull_mode: Some(wgpu::Face::Back),
5789                    front_face: wgpu::FrontFace::Ccw,
5790                    ..Default::default()
5791                },
5792                depth_stencil: Some(wgpu::DepthStencilState {
5793                    format: wgpu::TextureFormat::Depth32Float,
5794                    depth_write_enabled: true,
5795                    depth_compare: wgpu::CompareFunction::LessEqual,
5796                    stencil: wgpu::StencilState::default(),
5797                    bias: wgpu::DepthBiasState::default(),
5798                }),
5799                multisample: wgpu::MultisampleState::default(),
5800                multiview: None,
5801                cache: None,
5802            })
5803        };
5804        let terrain_pipeline = make_terrain_pipeline(
5805            "strata_3d_terrain_pipeline",
5806            Some(wgpu::BlendState::ALPHA_BLENDING),
5807        );
5808        let terrain_opaque_pipeline =
5809            make_terrain_pipeline("strata_3d_terrain_opaque_pipeline", None);
5810
5811        let terrain_shadow_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5812            label: Some("strata_3d_terrain_shadow_wgsl"),
5813            source: wgpu::ShaderSource::Wgsl(TERRAIN_SHADOW_WGSL.into()),
5814        });
5815        let terrain_shadow_layout =
5816            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
5817                label: Some("strata_3d_terrain_shadow_pl"),
5818                bind_group_layouts: &[&terrain_bind_group_layout],
5819                push_constant_ranges: &[],
5820            });
5821        let terrain_shadow_pipeline =
5822            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
5823                label: Some("strata_3d_terrain_shadow_pipeline"),
5824                layout: Some(&terrain_shadow_layout),
5825                vertex: wgpu::VertexState {
5826                    module: &terrain_shadow_shader,
5827                    entry_point: Some("vs_terrain_shadow"),
5828                    buffers: &[],
5829                    compilation_options: Default::default(),
5830                },
5831                fragment: None,
5832                primitive: wgpu::PrimitiveState {
5833                    topology: wgpu::PrimitiveTopology::TriangleList,
5834                    cull_mode: None,
5835                    front_face: wgpu::FrontFace::Ccw,
5836                    ..Default::default()
5837                },
5838                depth_stencil: Some(wgpu::DepthStencilState {
5839                    format: wgpu::TextureFormat::Depth32Float,
5840                    depth_write_enabled: true,
5841                    depth_compare: wgpu::CompareFunction::LessEqual,
5842                    stencil: wgpu::StencilState::default(),
5843                    bias: wgpu::DepthBiasState {
5844                        constant: 2,
5845                        slope_scale: 2.0,
5846                        clamp: 0.0,
5847                    },
5848                }),
5849                multisample: wgpu::MultisampleState::default(),
5850                multiview: None,
5851                cache: None,
5852            });
5853
5854        // Dynamic RTC mesh pipeline (buildings, entities, fallback meshes)
5855        let dynamic_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5856            label: Some("strata_3d_dynamic_wgsl"),
5857            source: wgpu::ShaderSource::Wgsl(DYNAMIC_MESH_WGSL.into()),
5858        });
5859        let align = device.limits().min_uniform_buffer_offset_alignment.max(256);
5860        let dyn_size = std::mem::size_of::<GpuDynamicUniforms>() as u32;
5861        let dynamic_uniform_stride = dyn_size.div_ceil(align) * align;
5862        let dynamic_uniform_capacity = 64usize;
5863        let dynamic_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
5864            label: Some("strata_3d_dynamic_uniforms"),
5865            size: (dynamic_uniform_capacity * dynamic_uniform_stride as usize) as u64,
5866            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
5867            mapped_at_creation: false,
5868        });
5869        let dynamic_bind_group_layout =
5870            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5871                label: Some("strata_3d_dynamic_bgl"),
5872                entries: &[
5873                    wgpu::BindGroupLayoutEntry {
5874                        binding: 0,
5875                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5876                        ty: wgpu::BindingType::Buffer {
5877                            ty: wgpu::BufferBindingType::Uniform,
5878                            has_dynamic_offset: false,
5879                            min_binding_size: None,
5880                        },
5881                        count: None,
5882                    },
5883                    wgpu::BindGroupLayoutEntry {
5884                        binding: 1,
5885                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5886                        ty: wgpu::BindingType::Buffer {
5887                            ty: wgpu::BufferBindingType::Uniform,
5888                            has_dynamic_offset: true,
5889                            min_binding_size: std::num::NonZeroU64::new(std::mem::size_of::<
5890                                GpuDynamicUniforms,
5891                            >(
5892                            )
5893                                as u64),
5894                        },
5895                        count: None,
5896                    },
5897                ],
5898            });
5899        let dynamic_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
5900            label: Some("strata_3d_dynamic_bg"),
5901            layout: &dynamic_bind_group_layout,
5902            entries: &[
5903                wgpu::BindGroupEntry {
5904                    binding: 0,
5905                    resource: camera_buffer.as_entire_binding(),
5906                },
5907                wgpu::BindGroupEntry {
5908                    binding: 1,
5909                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
5910                        buffer: &dynamic_uniform_buffer,
5911                        offset: 0,
5912                        size: std::num::NonZeroU64::new(
5913                            std::mem::size_of::<GpuDynamicUniforms>() as u64
5914                        ),
5915                    }),
5916                },
5917            ],
5918        });
5919        let dynamic_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
5920            label: Some("strata_3d_dynamic_pl"),
5921            bind_group_layouts: &[&dynamic_bind_group_layout],
5922            push_constant_ranges: &[],
5923        });
5924        let dynamic_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
5925            label: Some("strata_3d_dynamic_pipeline"),
5926            layout: Some(&dynamic_layout),
5927            vertex: wgpu::VertexState {
5928                module: &dynamic_shader,
5929                entry_point: Some("vs_dynamic"),
5930                buffers: &[wgpu::VertexBufferLayout {
5931                    array_stride: std::mem::size_of::<RteTileVertex>() as u64,
5932                    step_mode: wgpu::VertexStepMode::Vertex,
5933                    attributes: &[
5934                        wgpu::VertexAttribute {
5935                            format: wgpu::VertexFormat::Float32x4,
5936                            offset: 0,
5937                            shader_location: 0,
5938                        },
5939                        wgpu::VertexAttribute {
5940                            format: wgpu::VertexFormat::Float32x4,
5941                            offset: 16,
5942                            shader_location: 1,
5943                        },
5944                    ],
5945                }],
5946                compilation_options: Default::default(),
5947            },
5948            fragment: Some(wgpu::FragmentState {
5949                module: &dynamic_shader,
5950                entry_point: Some("fs_dynamic"),
5951                targets: &[Some(wgpu::ColorTargetState {
5952                    format: color_format,
5953                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
5954                    write_mask: wgpu::ColorWrites::ALL,
5955                })],
5956                compilation_options: Default::default(),
5957            }),
5958            primitive: wgpu::PrimitiveState {
5959                topology: wgpu::PrimitiveTopology::TriangleList,
5960                cull_mode: None,
5961                front_face: wgpu::FrontFace::Ccw,
5962                ..Default::default()
5963            },
5964            depth_stencil: Some(wgpu::DepthStencilState {
5965                format: wgpu::TextureFormat::Depth32Float,
5966                depth_write_enabled: true,
5967                depth_compare: wgpu::CompareFunction::LessEqual,
5968                stencil: wgpu::StencilState::default(),
5969                bias: wgpu::DepthBiasState::default(),
5970            }),
5971            multisample: wgpu::MultisampleState::default(),
5972            multiview: None,
5973            cache: None,
5974        });
5975
5976        // Hardware-instanced geodetic 3D object pipeline (storage buffer + double-single RTE + 3x3 cofactor normals)
5977        let geo_object_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
5978            label: Some("strata_3d_geo_object_wgsl"),
5979            source: wgpu::ShaderSource::Wgsl(GEO_OBJECT_WGSL.into()),
5980        });
5981        let geo_instance_capacity = 256usize;
5982        let geo_instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
5983            label: Some("strata_3d_geo_instances"),
5984            size: (geo_instance_capacity * std::mem::size_of::<GpuGeoInstance>()) as u64,
5985            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
5986            mapped_at_creation: false,
5987        });
5988        let geo_object_bind_group_layout =
5989            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
5990                label: Some("strata_3d_geo_object_bgl"),
5991                entries: &[
5992                    wgpu::BindGroupLayoutEntry {
5993                        binding: 0,
5994                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
5995                        ty: wgpu::BindingType::Buffer {
5996                            ty: wgpu::BufferBindingType::Uniform,
5997                            has_dynamic_offset: false,
5998                            min_binding_size: None,
5999                        },
6000                        count: None,
6001                    },
6002                    wgpu::BindGroupLayoutEntry {
6003                        binding: 1,
6004                        visibility: wgpu::ShaderStages::VERTEX,
6005                        ty: wgpu::BindingType::Buffer {
6006                            ty: wgpu::BufferBindingType::Storage { read_only: true },
6007                            has_dynamic_offset: false,
6008                            min_binding_size: None,
6009                        },
6010                        count: None,
6011                    },
6012                ],
6013            });
6014        let geo_object_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
6015            label: Some("strata_3d_geo_object_bg"),
6016            layout: &geo_object_bind_group_layout,
6017            entries: &[
6018                wgpu::BindGroupEntry {
6019                    binding: 0,
6020                    resource: camera_buffer.as_entire_binding(),
6021                },
6022                wgpu::BindGroupEntry {
6023                    binding: 1,
6024                    resource: geo_instance_buffer.as_entire_binding(),
6025                },
6026            ],
6027        });
6028        let geo_tex_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
6029            label: Some("strata_3d_geo_tex_bgl"),
6030            entries: &[
6031                wgpu::BindGroupLayoutEntry {
6032                    binding: 0,
6033                    visibility: wgpu::ShaderStages::FRAGMENT,
6034                    ty: wgpu::BindingType::Texture {
6035                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
6036                        view_dimension: wgpu::TextureViewDimension::D2,
6037                        multisampled: false,
6038                    },
6039                    count: None,
6040                },
6041                wgpu::BindGroupLayoutEntry {
6042                    binding: 1,
6043                    visibility: wgpu::ShaderStages::FRAGMENT,
6044                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
6045                    count: None,
6046                },
6047            ],
6048        });
6049        let geo_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
6050            label: Some("strata_3d_geo_albedo_sampler"),
6051            address_mode_u: wgpu::AddressMode::Repeat,
6052            address_mode_v: wgpu::AddressMode::Repeat,
6053            mag_filter: wgpu::FilterMode::Linear,
6054            min_filter: wgpu::FilterMode::Linear,
6055            ..Default::default()
6056        });
6057        let default_geo_tex = device.create_texture(&wgpu::TextureDescriptor {
6058            label: Some("strata_3d_geo_default_1x1_white"),
6059            size: wgpu::Extent3d {
6060                width: 1,
6061                height: 1,
6062                depth_or_array_layers: 1,
6063            },
6064            mip_level_count: 1,
6065            sample_count: 1,
6066            dimension: wgpu::TextureDimension::D2,
6067            format: wgpu::TextureFormat::Rgba8Unorm,
6068            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
6069            view_formats: &[],
6070        });
6071        queue.write_texture(
6072            wgpu::TexelCopyTextureInfo {
6073                texture: &default_geo_tex,
6074                mip_level: 0,
6075                origin: wgpu::Origin3d::ZERO,
6076                aspect: wgpu::TextureAspect::All,
6077            },
6078            &[255u8, 255, 255, 255],
6079            wgpu::TexelCopyBufferLayout {
6080                offset: 0,
6081                bytes_per_row: Some(4),
6082                rows_per_image: Some(1),
6083            },
6084            wgpu::Extent3d {
6085                width: 1,
6086                height: 1,
6087                depth_or_array_layers: 1,
6088            },
6089        );
6090        let default_geo_view = default_geo_tex.create_view(&Default::default());
6091        let geo_default_tex_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
6092            label: Some("strata_3d_geo_default_tex_bg"),
6093            layout: &geo_tex_bgl,
6094            entries: &[
6095                wgpu::BindGroupEntry {
6096                    binding: 0,
6097                    resource: wgpu::BindingResource::TextureView(&default_geo_view),
6098                },
6099                wgpu::BindGroupEntry {
6100                    binding: 1,
6101                    resource: wgpu::BindingResource::Sampler(&geo_sampler),
6102                },
6103            ],
6104        });
6105        let geo_object_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
6106            label: Some("strata_3d_geo_object_pl"),
6107            bind_group_layouts: &[&geo_object_bind_group_layout, &shadow_ocean_bgl, &geo_tex_bgl],
6108            push_constant_ranges: &[],
6109        });
6110        let make_geo_pipeline = |label: &str, depth_write_enabled: bool, blend: Option<wgpu::BlendState>| {
6111            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
6112                label: Some(label),
6113                layout: Some(&geo_object_layout),
6114                vertex: wgpu::VertexState {
6115                    module: &geo_object_shader,
6116                    entry_point: Some("vs_geo_object"),
6117                    buffers: &[wgpu::VertexBufferLayout {
6118                        array_stride: std::mem::size_of::<GpuGeoVertex>() as u64,
6119                        step_mode: wgpu::VertexStepMode::Vertex,
6120                        attributes: &[
6121                            wgpu::VertexAttribute {
6122                                format: wgpu::VertexFormat::Float32x4,
6123                                offset: 0,
6124                                shader_location: 0,
6125                            },
6126                            wgpu::VertexAttribute {
6127                                format: wgpu::VertexFormat::Float32x4,
6128                                offset: 16,
6129                                shader_location: 1,
6130                            },
6131                            wgpu::VertexAttribute {
6132                                format: wgpu::VertexFormat::Float32x4,
6133                                offset: 32,
6134                                shader_location: 2,
6135                            },
6136                        ],
6137                    }],
6138                    compilation_options: Default::default(),
6139                },
6140                fragment: Some(wgpu::FragmentState {
6141                    module: &geo_object_shader,
6142                    entry_point: Some("fs_geo_object"),
6143                    targets: &[Some(wgpu::ColorTargetState {
6144                        format: color_format,
6145                        blend,
6146                        write_mask: wgpu::ColorWrites::ALL,
6147                    })],
6148                    compilation_options: Default::default(),
6149                }),
6150                primitive: wgpu::PrimitiveState {
6151                    topology: wgpu::PrimitiveTopology::TriangleList,
6152                    cull_mode: None,
6153                    front_face: wgpu::FrontFace::Ccw,
6154                    ..Default::default()
6155                },
6156                depth_stencil: Some(wgpu::DepthStencilState {
6157                    format: wgpu::TextureFormat::Depth32Float,
6158                    depth_write_enabled,
6159                    depth_compare: wgpu::CompareFunction::LessEqual,
6160                    stencil: wgpu::StencilState::default(),
6161                    bias: wgpu::DepthBiasState::default(),
6162                }),
6163                multisample: wgpu::MultisampleState::default(),
6164                multiview: None,
6165                cache: None,
6166            })
6167        };
6168        let geo_object_pipeline =
6169            make_geo_pipeline("strata_3d_geo_object_pipeline", true, None);
6170        let geo_object_transparent_pipeline = make_geo_pipeline(
6171            "strata_3d_geo_object_transparent_pipeline",
6172            false,
6173            Some(wgpu::BlendState::ALPHA_BLENDING),
6174        );
6175        let geo_shadow_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
6176            label: Some("strata_3d_geo_shadow_wgsl"),
6177            source: wgpu::ShaderSource::Wgsl(GEO_SHADOW_WGSL.into()),
6178        });
6179        let geo_shadow_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
6180            label: Some("strata_3d_geo_shadow_pl"),
6181            bind_group_layouts: &[&geo_object_bind_group_layout],
6182            push_constant_ranges: &[],
6183        });
6184        let geo_shadow_pipeline =
6185            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
6186                label: Some("strata_3d_geo_shadow_pipeline"),
6187                layout: Some(&geo_shadow_layout),
6188                vertex: wgpu::VertexState {
6189                    module: &geo_shadow_shader,
6190                    entry_point: Some("vs_geo_shadow"),
6191                    buffers: &[wgpu::VertexBufferLayout {
6192                        array_stride: std::mem::size_of::<GpuGeoVertex>() as u64,
6193                        step_mode: wgpu::VertexStepMode::Vertex,
6194                        attributes: &[
6195                            wgpu::VertexAttribute {
6196                                format: wgpu::VertexFormat::Float32x4,
6197                                offset: 0,
6198                                shader_location: 0,
6199                            },
6200                            wgpu::VertexAttribute {
6201                                format: wgpu::VertexFormat::Float32x4,
6202                                offset: 16,
6203                                shader_location: 1,
6204                            },
6205                        ],
6206                    }],
6207                    compilation_options: Default::default(),
6208                },
6209                fragment: None,
6210                primitive: wgpu::PrimitiveState {
6211                    topology: wgpu::PrimitiveTopology::TriangleList,
6212                    cull_mode: None,
6213                    front_face: wgpu::FrontFace::Ccw,
6214                    ..Default::default()
6215                },
6216                depth_stencil: Some(wgpu::DepthStencilState {
6217                    format: wgpu::TextureFormat::Depth32Float,
6218                    depth_write_enabled: true,
6219                    depth_compare: wgpu::CompareFunction::LessEqual,
6220                    stencil: wgpu::StencilState::default(),
6221                    bias: wgpu::DepthBiasState {
6222                        constant: 2,
6223                        slope_scale: 2.0,
6224                        clamp: 0.0,
6225                    },
6226                }),
6227                multisample: wgpu::MultisampleState::default(),
6228                multiview: None,
6229                cache: None,
6230            });
6231
6232        // GPU-instanced 2D camera-local toroidal particle volume pipeline (rain, snow, custom 2D sprites)
6233        let particle_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
6234            label: Some("strata_3d_particle_volume_wgsl"),
6235            source: wgpu::ShaderSource::Wgsl(PARTICLE_VOLUME_WGSL.into()),
6236        });
6237        let ubo_align = device.limits().min_uniform_buffer_offset_alignment.max(256);
6238        let particle_u_size = std::mem::size_of::<GpuParticleLayerUniforms>() as u32;
6239        let particle_uniform_stride = particle_u_size.div_ceil(ubo_align) * ubo_align;
6240        let particle_uniform_capacity = 16usize;
6241        let particle_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
6242            label: Some("strata_3d_particle_uniforms"),
6243            size: (particle_uniform_capacity as u64) * (particle_uniform_stride as u64),
6244            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
6245            mapped_at_creation: false,
6246        });
6247        let particle_common_bgl =
6248            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
6249                label: Some("strata_3d_particle_common_bgl"),
6250                entries: &[
6251                    wgpu::BindGroupLayoutEntry {
6252                        binding: 0,
6253                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
6254                        ty: wgpu::BindingType::Buffer {
6255                            ty: wgpu::BufferBindingType::Uniform,
6256                            has_dynamic_offset: false,
6257                            min_binding_size: None,
6258                        },
6259                        count: None,
6260                    },
6261                    wgpu::BindGroupLayoutEntry {
6262                        binding: 1,
6263                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
6264                        ty: wgpu::BindingType::Buffer {
6265                            ty: wgpu::BufferBindingType::Uniform,
6266                            has_dynamic_offset: true,
6267                            min_binding_size: std::num::NonZeroU64::new(particle_u_size as u64),
6268                        },
6269                        count: None,
6270                    },
6271                ],
6272            });
6273        let particle_common_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
6274            label: Some("strata_3d_particle_common_bg"),
6275            layout: &particle_common_bgl,
6276            entries: &[
6277                wgpu::BindGroupEntry {
6278                    binding: 0,
6279                    resource: camera_buffer.as_entire_binding(),
6280                },
6281                wgpu::BindGroupEntry {
6282                    binding: 1,
6283                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
6284                        buffer: &particle_uniform_buffer,
6285                        offset: 0,
6286                        size: std::num::NonZeroU64::new(particle_u_size as u64),
6287                    }),
6288                },
6289            ],
6290        });
6291        let particle_tex_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
6292            label: Some("strata_3d_particle_tex_bgl"),
6293            entries: &[
6294                wgpu::BindGroupLayoutEntry {
6295                    binding: 0,
6296                    visibility: wgpu::ShaderStages::FRAGMENT,
6297                    ty: wgpu::BindingType::Texture {
6298                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
6299                        view_dimension: wgpu::TextureViewDimension::D2,
6300                        multisampled: false,
6301                    },
6302                    count: None,
6303                },
6304                wgpu::BindGroupLayoutEntry {
6305                    binding: 1,
6306                    visibility: wgpu::ShaderStages::FRAGMENT,
6307                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
6308                    count: None,
6309                },
6310            ],
6311        });
6312        let particle_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
6313            label: Some("strata_3d_particle_sampler"),
6314            address_mode_u: wgpu::AddressMode::ClampToEdge,
6315            address_mode_v: wgpu::AddressMode::ClampToEdge,
6316            mag_filter: wgpu::FilterMode::Linear,
6317            min_filter: wgpu::FilterMode::Linear,
6318            ..Default::default()
6319        });
6320        let default_p_tex = device.create_texture(&wgpu::TextureDescriptor {
6321            label: Some("strata_3d_particle_default_1x1"),
6322            size: wgpu::Extent3d {
6323                width: 1,
6324                height: 1,
6325                depth_or_array_layers: 1,
6326            },
6327            mip_level_count: 1,
6328            sample_count: 1,
6329            dimension: wgpu::TextureDimension::D2,
6330            format: wgpu::TextureFormat::Rgba8Unorm,
6331            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
6332            view_formats: &[],
6333        });
6334        queue.write_texture(
6335            wgpu::TexelCopyTextureInfo {
6336                texture: &default_p_tex,
6337                mip_level: 0,
6338                origin: wgpu::Origin3d::ZERO,
6339                aspect: wgpu::TextureAspect::All,
6340            },
6341            &[255u8, 255, 255, 255],
6342            wgpu::TexelCopyBufferLayout {
6343                offset: 0,
6344                bytes_per_row: Some(4),
6345                rows_per_image: Some(1),
6346            },
6347            wgpu::Extent3d {
6348                width: 1,
6349                height: 1,
6350                depth_or_array_layers: 1,
6351            },
6352        );
6353        let default_p_view = default_p_tex.create_view(&Default::default());
6354        let particle_default_tex_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
6355            label: Some("strata_3d_particle_default_tex_bg"),
6356            layout: &particle_tex_bgl,
6357            entries: &[
6358                wgpu::BindGroupEntry {
6359                    binding: 0,
6360                    resource: wgpu::BindingResource::TextureView(&default_p_view),
6361                },
6362                wgpu::BindGroupEntry {
6363                    binding: 1,
6364                    resource: wgpu::BindingResource::Sampler(&particle_sampler),
6365                },
6366            ],
6367        });
6368        let particle_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
6369            label: Some("strata_3d_particle_pl"),
6370            bind_group_layouts: &[&particle_common_bgl, &particle_tex_bgl],
6371            push_constant_ranges: &[],
6372        });
6373        let particle_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
6374            label: Some("strata_3d_particle_pipeline"),
6375            layout: Some(&particle_layout),
6376            vertex: wgpu::VertexState {
6377                module: &particle_shader,
6378                entry_point: Some("vs_particle"),
6379                buffers: &[],
6380                compilation_options: Default::default(),
6381            },
6382            fragment: Some(wgpu::FragmentState {
6383                module: &particle_shader,
6384                entry_point: Some("fs_particle"),
6385                targets: &[Some(wgpu::ColorTargetState {
6386                    format: color_format,
6387                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
6388                    write_mask: wgpu::ColorWrites::ALL,
6389                })],
6390                compilation_options: Default::default(),
6391            }),
6392            primitive: wgpu::PrimitiveState {
6393                topology: wgpu::PrimitiveTopology::TriangleList,
6394                cull_mode: None,
6395                front_face: wgpu::FrontFace::Ccw,
6396                ..Default::default()
6397            },
6398            depth_stencil: Some(wgpu::DepthStencilState {
6399                format: wgpu::TextureFormat::Depth32Float,
6400                depth_write_enabled: false,
6401                depth_compare: wgpu::CompareFunction::LessEqual,
6402                stencil: wgpu::StencilState::default(),
6403                bias: wgpu::DepthBiasState::default(),
6404            }),
6405            multisample: wgpu::MultisampleState::default(),
6406            multiview: None,
6407            cache: None,
6408        });
6409
6410        // 2D overlay composite pipeline
6411        let overlay_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
6412            label: Some("strata_2d_overlay_wgsl"),
6413            source: wgpu::ShaderSource::Wgsl(OVERLAY_COMPOSITE_WGSL.into()),
6414        });
6415        let overlay_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
6416            label: Some("strata_2d_overlay_sampler"),
6417            mag_filter: wgpu::FilterMode::Linear,
6418            min_filter: wgpu::FilterMode::Linear,
6419            ..Default::default()
6420        });
6421        let overlay_bind_group_layout =
6422            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
6423                label: Some("strata_2d_overlay_bgl"),
6424                entries: &[
6425                    wgpu::BindGroupLayoutEntry {
6426                        binding: 0,
6427                        visibility: wgpu::ShaderStages::FRAGMENT,
6428                        ty: wgpu::BindingType::Texture {
6429                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
6430                            view_dimension: wgpu::TextureViewDimension::D2,
6431                            multisampled: false,
6432                        },
6433                        count: None,
6434                    },
6435                    wgpu::BindGroupLayoutEntry {
6436                        binding: 1,
6437                        visibility: wgpu::ShaderStages::FRAGMENT,
6438                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
6439                        count: None,
6440                    },
6441                ],
6442            });
6443        let overlay_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
6444            label: Some("strata_2d_overlay_pl"),
6445            bind_group_layouts: &[&overlay_bind_group_layout],
6446            push_constant_ranges: &[],
6447        });
6448        let overlay_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
6449            label: Some("strata_2d_overlay_pipeline"),
6450            layout: Some(&overlay_layout),
6451            vertex: wgpu::VertexState {
6452                module: &overlay_shader,
6453                entry_point: Some("vs_overlay"),
6454                buffers: &[],
6455                compilation_options: Default::default(),
6456            },
6457            fragment: Some(wgpu::FragmentState {
6458                module: &overlay_shader,
6459                entry_point: Some("fs_overlay"),
6460                targets: &[Some(wgpu::ColorTargetState {
6461                    format: color_format,
6462                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
6463                    write_mask: wgpu::ColorWrites::ALL,
6464                })],
6465                compilation_options: Default::default(),
6466            }),
6467            primitive: wgpu::PrimitiveState::default(),
6468            depth_stencil: None,
6469            multisample: wgpu::MultisampleState::default(),
6470            multiview: None,
6471            cache: None,
6472        });
6473        let overlay_main_pass_pipeline =
6474            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
6475                label: Some("strata_2d_overlay_main_pass_pipeline"),
6476                layout: Some(&overlay_layout),
6477                vertex: wgpu::VertexState {
6478                    module: &overlay_shader,
6479                    entry_point: Some("vs_overlay"),
6480                    buffers: &[],
6481                    compilation_options: Default::default(),
6482                },
6483                fragment: Some(wgpu::FragmentState {
6484                    module: &overlay_shader,
6485                    entry_point: Some("fs_overlay"),
6486                    targets: &[Some(wgpu::ColorTargetState {
6487                        format: color_format,
6488                        blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
6489                        write_mask: wgpu::ColorWrites::ALL,
6490                    })],
6491                    compilation_options: Default::default(),
6492                }),
6493                primitive: wgpu::PrimitiveState::default(),
6494                depth_stencil: Some(wgpu::DepthStencilState {
6495                    format: wgpu::TextureFormat::Depth32Float,
6496                    depth_write_enabled: false,
6497                    depth_compare: wgpu::CompareFunction::Always,
6498                    stencil: wgpu::StencilState::default(),
6499                    bias: wgpu::DepthBiasState::default(),
6500                }),
6501                multisample: wgpu::MultisampleState::default(),
6502                multiview: None,
6503                cache: None,
6504            });
6505        let scene_blit_pipeline =
6506            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
6507                label: Some("strata_cached_3d_scene_blit_pipeline"),
6508                layout: Some(&overlay_layout),
6509                vertex: wgpu::VertexState {
6510                    module: &overlay_shader,
6511                    entry_point: Some("vs_overlay"),
6512                    buffers: &[],
6513                    compilation_options: Default::default(),
6514                },
6515                fragment: Some(wgpu::FragmentState {
6516                    module: &overlay_shader,
6517                    entry_point: Some("fs_overlay"),
6518                    targets: &[Some(wgpu::ColorTargetState {
6519                        format: color_format,
6520                        blend: None,
6521                        write_mask: wgpu::ColorWrites::ALL,
6522                    })],
6523                    compilation_options: Default::default(),
6524                }),
6525                primitive: wgpu::PrimitiveState::default(),
6526                depth_stencil: None,
6527                multisample: wgpu::MultisampleState::default(),
6528                multiview: None,
6529                cache: None,
6530            });
6531        let timestamp_profiler = if device
6532            .features()
6533            .contains(wgpu::Features::TIMESTAMP_QUERY)
6534        {
6535            Some(GpuTimestampProfiler::new(&device, &queue))
6536        } else {
6537            None
6538        };
6539
6540        Self {
6541            device,
6542            queue,
6543            color_format,
6544            camera_buffer,
6545            sky_pipeline,
6546            sky_opaque_pipeline,
6547            sky_bind_group_layout,
6548            sky_bind_group,
6549            star_pipeline,
6550            star_bind_group_layout,
6551            star_bind_group,
6552            cloud_pipeline,
6553            cloud_inside_pipeline,
6554            cloud_twosided_pipeline,
6555            cloud_bind_group_layout,
6556            cloud_bind_group,
6557            cloud_vbuf,
6558            cloud_ibuf,
6559            cloud_index_count,
6560            env_state,
6561            terrain_pipeline,
6562            terrain_opaque_pipeline,
6563            terrain_shadow_pipeline,
6564            terrain_bind_group_layout,
6565            terrain_bind_group,
6566            terrain_sampler,
6567            shadow_ocean_bgl,
6568            shadow_ocean_bind_group,
6569            shadow_sampler,
6570            _shadow_fallback_tex: shadow_fallback_tex,
6571            shadow_fallback_view,
6572            shadow_target: None,
6573            ocean_uniform_buffer,
6574            coastal_sdf_sampler,
6575            _coastal_sdf_fallback_tex: coastal_sdf_fallback_tex,
6576            coastal_sdf_fallback_view,
6577            coastal_sdf_cached: None,
6578            instance_buffer,
6579            instance_capacity: initial_instances,
6580            slab,
6581            atlas,
6582            topologies: HashMap::new(),
6583            dynamic_pipeline,
6584            dynamic_bind_group_layout,
6585            dynamic_uniform_buffer,
6586            dynamic_uniform_capacity,
6587            dynamic_uniform_stride,
6588            dynamic_bind_group,
6589            dynamic_meshes: HashMap::new(),
6590            geo_object_pipeline,
6591            geo_object_transparent_pipeline,
6592            geo_shadow_pipeline,
6593            geo_object_bind_group_layout,
6594            geo_object_bind_group,
6595            geo_tex_bgl,
6596            geo_sampler,
6597            geo_default_tex_bg,
6598            geo_instance_buffer,
6599            geo_instance_capacity,
6600            geo_meshes: HashMap::new(),
6601            geo_textures: HashMap::new(),
6602            particle_pipeline,
6603            particle_common_bgl,
6604            particle_tex_bgl,
6605            particle_sampler,
6606            particle_uniform_buffer,
6607            particle_uniform_capacity,
6608            particle_uniform_stride,
6609            particle_common_bind_group,
6610            particle_default_tex_bg,
6611            particle_textures: HashMap::new(),
6612            overlay_pipeline,
6613            overlay_main_pass_pipeline,
6614            scene_blit_pipeline,
6615            overlay_bind_group_layout,
6616            overlay_sampler,
6617            depth_target: None,
6618            offscreen: None,
6619            timestamp_profiler,
6620            frame_index: 0,
6621            last_geometry_rev: 0,
6622            last_terrain_frame: None,
6623            cached_fallback_frames: HashMap::new(),
6624        }
6625    }
6626
6627    pub fn device(&self) -> &Arc<wgpu::Device> {
6628        &self.device
6629    }
6630
6631    pub fn queue(&self) -> &Arc<wgpu::Queue> {
6632        &self.queue
6633    }
6634
6635    pub fn color_format(&self) -> wgpu::TextureFormat {
6636        self.color_format
6637    }
6638
6639    /// Number of currently cached GPU geodetic object mesh buffers.
6640    pub fn cached_geo_mesh_count(&self) -> usize {
6641        self.geo_meshes.len()
6642    }
6643
6644    /// Number of currently cached GPU geodetic object albedo textures.
6645    pub fn cached_geo_texture_count(&self) -> usize {
6646        self.geo_textures.len()
6647    }
6648
6649    /// Polls any completed asynchronous GPU timestamp query readbacks without stalling.
6650    pub fn poll_gpu_timestamps(&mut self) {
6651        if let Some(ref mut profiler) = self.timestamp_profiler {
6652            profiler.poll_ready(&self.device);
6653        }
6654    }
6655
6656    /// Returns the most recently resolved hardware GPU pass timings (or `supported: false`
6657    /// when `wgpu::Features::TIMESTAMP_QUERY` is unavailable on the active adapter).
6658    pub fn last_gpu_pass_timings(&self) -> GpuPassTimings {
6659        self.timestamp_profiler
6660            .as_ref()
6661            .map(|p| p.last_timings)
6662            .unwrap_or_default()
6663    }
6664
6665    /// Total GPU buffer, texture atlas, and render-target memory allocated by this 3D renderer.
6666    pub fn gpu_memory_bytes(&self) -> u64 {
6667        let mut bytes = self.camera_buffer.size()
6668            + self.instance_buffer.size()
6669            + self.ocean_uniform_buffer.size()
6670            + self.dynamic_uniform_buffer.size()
6671            + self.geo_instance_buffer.size()
6672            + self.particle_uniform_buffer.size()
6673            + self.env_state.star_buffer.size()
6674            + self.cloud_vbuf.size()
6675            + self.cloud_ibuf.size()
6676            + self.slab.buffer.size()
6677            + (ATLAS_TILE_SIZE as u64)
6678                * (ATLAS_TILE_SIZE as u64)
6679                * 4
6680                * (self.atlas.layer_owner.len() as u64);
6681
6682        for topo in self.topologies.values() {
6683            bytes += topo.buffer.size();
6684        }
6685        for dm in self.dynamic_meshes.values() {
6686            bytes += dm.vbuf.size() + dm.ibuf.size();
6687        }
6688        for gm in self.geo_meshes.values() {
6689            bytes += gm.vbuf.size() + gm.ibuf.size();
6690        }
6691        for gt in self.geo_textures.values() {
6692            bytes += (gt.width as u64) * (gt.height as u64) * 4;
6693        }
6694        for pt in self.particle_textures.values() {
6695            bytes += (pt.width as u64) * (pt.height as u64) * 4;
6696        }
6697        if let Some((sz, _, _)) = self.shadow_target {
6698            bytes += (sz as u64) * (sz as u64) * 4;
6699        }
6700        if let Some((_, _, w, h, _, _)) = self.coastal_sdf_cached {
6701            bytes += (w as u64) * (h as u64) * 4;
6702        }
6703        if let Some((w, h, _)) = self.depth_target {
6704            bytes += (w as u64) * (h as u64) * 4;
6705        }
6706        if let Some(ref off) = self.offscreen {
6707            bytes += (off.width as u64) * (off.height as u64) * 8
6708                + (off.padded_bytes_per_row as u64) * (off.height as u64);
6709        }
6710        bytes
6711    }
6712
6713    fn ensure_geo_texture(
6714        &mut self,
6715        tex: &crate::scene3d::RetainedTileTexture,
6716        seq: u64,
6717    ) -> Option<(u64, bool)> {
6718        if tex.width == 0
6719            || tex.height == 0
6720            || tex.rgba8.len() < (tex.width as usize) * (tex.height as usize) * 4
6721        {
6722            return None;
6723        }
6724        let need_upload = match self.geo_textures.get_mut(&tex.id) {
6725            Some(existing) => {
6726                existing.last_used_seq = seq;
6727                if existing.revision == tex.revision
6728                    && existing.width == tex.width
6729                    && existing.height == tex.height
6730                {
6731                    return Some((tex.id, existing.has_alpha));
6732                }
6733                true
6734            }
6735            None => true,
6736        };
6737        if need_upload {
6738            let byte_len = (tex.width as usize) * (tex.height as usize) * 4;
6739            let bytes = &tex.rgba8[..byte_len];
6740            let has_alpha = bytes.chunks_exact(4).any(|px| px[3] < 255);
6741            let gpu_tex = self.device.create_texture(&wgpu::TextureDescriptor {
6742                label: Some("strata_3d_geo_albedo_tex"),
6743                size: wgpu::Extent3d {
6744                    width: tex.width,
6745                    height: tex.height,
6746                    depth_or_array_layers: 1,
6747                },
6748                mip_level_count: 1,
6749                sample_count: 1,
6750                dimension: wgpu::TextureDimension::D2,
6751                format: wgpu::TextureFormat::Rgba8Unorm,
6752                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
6753                view_formats: &[],
6754            });
6755            self.queue.write_texture(
6756                wgpu::TexelCopyTextureInfo {
6757                    texture: &gpu_tex,
6758                    mip_level: 0,
6759                    origin: wgpu::Origin3d::ZERO,
6760                    aspect: wgpu::TextureAspect::All,
6761                },
6762                bytes,
6763                wgpu::TexelCopyBufferLayout {
6764                    offset: 0,
6765                    bytes_per_row: Some(tex.width * 4),
6766                    rows_per_image: Some(tex.height),
6767                },
6768                wgpu::Extent3d {
6769                    width: tex.width,
6770                    height: tex.height,
6771                    depth_or_array_layers: 1,
6772                },
6773            );
6774            let view = gpu_tex.create_view(&Default::default());
6775            let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
6776                label: Some("strata_3d_geo_albedo_bg"),
6777                layout: &self.geo_tex_bgl,
6778                entries: &[
6779                    wgpu::BindGroupEntry {
6780                        binding: 0,
6781                        resource: wgpu::BindingResource::TextureView(&view),
6782                    },
6783                    wgpu::BindGroupEntry {
6784                        binding: 1,
6785                        resource: wgpu::BindingResource::Sampler(&self.geo_sampler),
6786                    },
6787                ],
6788            });
6789            self.geo_textures.insert(
6790                tex.id,
6791                CachedGeoTexture {
6792                    revision: tex.revision,
6793                    width: tex.width,
6794                    height: tex.height,
6795                    has_alpha,
6796                    _texture: gpu_tex,
6797                    bind_group,
6798                    last_used_seq: seq,
6799                },
6800            );
6801            return Some((tex.id, has_alpha));
6802        }
6803        None
6804    }
6805
6806    #[allow(clippy::too_many_arguments)]
6807    fn create_cloud_bind_group(
6808        device: &wgpu::Device,
6809        layout: &wgpu::BindGroupLayout,
6810        label: &str,
6811        camera_buffer: &wgpu::Buffer,
6812        cloud_view: &wgpu::TextureView,
6813        cloud_sampler: &wgpu::Sampler,
6814        noise_view: &wgpu::TextureView,
6815        noise_sampler: &wgpu::Sampler,
6816    ) -> wgpu::BindGroup {
6817        device.create_bind_group(&wgpu::BindGroupDescriptor {
6818            label: Some(label),
6819            layout,
6820            entries: &[
6821                wgpu::BindGroupEntry {
6822                    binding: 0,
6823                    resource: camera_buffer.as_entire_binding(),
6824                },
6825                wgpu::BindGroupEntry {
6826                    binding: 1,
6827                    resource: wgpu::BindingResource::TextureView(cloud_view),
6828                },
6829                wgpu::BindGroupEntry {
6830                    binding: 2,
6831                    resource: wgpu::BindingResource::Sampler(cloud_sampler),
6832                },
6833                wgpu::BindGroupEntry {
6834                    binding: 3,
6835                    resource: wgpu::BindingResource::TextureView(noise_view),
6836                },
6837                wgpu::BindGroupEntry {
6838                    binding: 4,
6839                    resource: wgpu::BindingResource::Sampler(noise_sampler),
6840                },
6841            ],
6842        })
6843    }
6844
6845    fn create_sky_bind_group(
6846        device: &wgpu::Device,
6847        layout: &wgpu::BindGroupLayout,
6848        camera_buffer: &wgpu::Buffer,
6849        moon_view: &wgpu::TextureView,
6850        sampler: &wgpu::Sampler,
6851        skybox_cube_view: &wgpu::TextureView,
6852    ) -> wgpu::BindGroup {
6853        device.create_bind_group(&wgpu::BindGroupDescriptor {
6854            label: Some("strata_3d_sky_bg"),
6855            layout,
6856            entries: &[
6857                wgpu::BindGroupEntry {
6858                    binding: 0,
6859                    resource: camera_buffer.as_entire_binding(),
6860                },
6861                wgpu::BindGroupEntry {
6862                    binding: 1,
6863                    resource: wgpu::BindingResource::TextureView(moon_view),
6864                },
6865                wgpu::BindGroupEntry {
6866                    binding: 2,
6867                    resource: wgpu::BindingResource::Sampler(sampler),
6868                },
6869                wgpu::BindGroupEntry {
6870                    binding: 3,
6871                    resource: wgpu::BindingResource::TextureView(skybox_cube_view),
6872                },
6873            ],
6874        })
6875    }
6876
6877    fn create_star_bind_group(
6878        device: &wgpu::Device,
6879        layout: &wgpu::BindGroupLayout,
6880        camera_buffer: &wgpu::Buffer,
6881        star_buffer: &wgpu::Buffer,
6882    ) -> wgpu::BindGroup {
6883        device.create_bind_group(&wgpu::BindGroupDescriptor {
6884            label: Some("strata_3d_stars_bg"),
6885            layout,
6886            entries: &[
6887                wgpu::BindGroupEntry {
6888                    binding: 0,
6889                    resource: camera_buffer.as_entire_binding(),
6890                },
6891                wgpu::BindGroupEntry {
6892                    binding: 1,
6893                    resource: star_buffer.as_entire_binding(),
6894                },
6895            ],
6896        })
6897    }
6898
6899    #[allow(clippy::too_many_arguments)]
6900    fn create_shadow_ocean_bind_group(
6901        device: &wgpu::Device,
6902        layout: &wgpu::BindGroupLayout,
6903        shadow_view: &wgpu::TextureView,
6904        shadow_sampler: &wgpu::Sampler,
6905        ocean_buffer: &wgpu::Buffer,
6906        coastal_sdf_view: &wgpu::TextureView,
6907        coastal_sdf_sampler: &wgpu::Sampler,
6908    ) -> wgpu::BindGroup {
6909        device.create_bind_group(&wgpu::BindGroupDescriptor {
6910            label: Some("strata_3d_shadow_ocean_bg"),
6911            layout,
6912            entries: &[
6913                wgpu::BindGroupEntry {
6914                    binding: 0,
6915                    resource: wgpu::BindingResource::TextureView(shadow_view),
6916                },
6917                wgpu::BindGroupEntry {
6918                    binding: 1,
6919                    resource: wgpu::BindingResource::Sampler(shadow_sampler),
6920                },
6921                wgpu::BindGroupEntry {
6922                    binding: 2,
6923                    resource: ocean_buffer.as_entire_binding(),
6924                },
6925                wgpu::BindGroupEntry {
6926                    binding: 3,
6927                    resource: wgpu::BindingResource::TextureView(coastal_sdf_view),
6928                },
6929                wgpu::BindGroupEntry {
6930                    binding: 4,
6931                    resource: wgpu::BindingResource::Sampler(coastal_sdf_sampler),
6932                },
6933            ],
6934        })
6935    }
6936
6937    fn sync_shadow_and_ocean_resources(
6938        &mut self,
6939        shadows_active: bool,
6940        shadow_size: u32,
6941        ocean_opt: Option<&RetainedOceanSurface>,
6942    ) {
6943        let mut need_rebind = false;
6944        let clamped_shadow = shadow_size.clamp(512, 4096);
6945        if shadows_active {
6946            let needs_alloc = match self.shadow_target {
6947                Some((sz, _, _)) => sz != clamped_shadow,
6948                None => true,
6949            };
6950            if needs_alloc {
6951                let tex = self.device.create_texture(&wgpu::TextureDescriptor {
6952                    label: Some("strata_3d_shadow_map"),
6953                    size: wgpu::Extent3d {
6954                        width: clamped_shadow,
6955                        height: clamped_shadow,
6956                        depth_or_array_layers: 1,
6957                    },
6958                    mip_level_count: 1,
6959                    sample_count: 1,
6960                    dimension: wgpu::TextureDimension::D2,
6961                    format: wgpu::TextureFormat::Depth32Float,
6962                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT
6963                        | wgpu::TextureUsages::TEXTURE_BINDING,
6964                    view_formats: &[],
6965                });
6966                let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
6967                self.shadow_target = Some((clamped_shadow, tex, view));
6968                need_rebind = true;
6969            }
6970        }
6971
6972        let mut has_sdf = false;
6973        if let Some(ocean) = ocean_opt {
6974            if ocean.enabled && ocean.coastal_shoaling {
6975                if let Some(ref sdf) = ocean.coastal_sdf {
6976                    let expected_bytes = (sdf.width as usize)
6977                        .saturating_mul(sdf.height as usize)
6978                        .saturating_mul(4);
6979                    if sdf.width > 0 && sdf.height > 0 && sdf.rgba8.len() == expected_bytes {
6980                        has_sdf = true;
6981                        let needs_upload = match self.coastal_sdf_cached {
6982                            Some((id, rev, w, h, _, _)) => {
6983                                id != sdf.id || rev != sdf.revision || w != sdf.width || h != sdf.height
6984                            }
6985                            None => true,
6986                        };
6987                        if needs_upload {
6988                            let same_dims = match self.coastal_sdf_cached {
6989                                Some((_, _, w, h, _, _)) => w == sdf.width && h == sdf.height,
6990                                None => false,
6991                            };
6992                            if same_dims {
6993                                if let Some((id, rev, w, h, ref tex, _)) = self.coastal_sdf_cached.as_mut() {
6994                                    self.queue.write_texture(
6995                                        wgpu::TexelCopyTextureInfo {
6996                                            texture: tex,
6997                                            mip_level: 0,
6998                                            origin: wgpu::Origin3d::ZERO,
6999                                            aspect: wgpu::TextureAspect::All,
7000                                        },
7001                                        &sdf.rgba8,
7002                                        wgpu::TexelCopyBufferLayout {
7003                                            offset: 0,
7004                                            bytes_per_row: Some(*w * 4),
7005                                            rows_per_image: Some(*h),
7006                                        },
7007                                        wgpu::Extent3d {
7008                                            width: *w,
7009                                            height: *h,
7010                                            depth_or_array_layers: 1,
7011                                        },
7012                                    );
7013                                    *id = sdf.id;
7014                                    *rev = sdf.revision;
7015                                }
7016                            } else {
7017                                let tex = self.device.create_texture(&wgpu::TextureDescriptor {
7018                                    label: Some("strata_3d_coastal_sdf_tex"),
7019                                    size: wgpu::Extent3d {
7020                                        width: sdf.width,
7021                                        height: sdf.height,
7022                                        depth_or_array_layers: 1,
7023                                    },
7024                                    mip_level_count: 1,
7025                                    sample_count: 1,
7026                                    dimension: wgpu::TextureDimension::D2,
7027                                    format: wgpu::TextureFormat::Rgba8Unorm,
7028                                    usage: wgpu::TextureUsages::TEXTURE_BINDING
7029                                        | wgpu::TextureUsages::COPY_DST,
7030                                    view_formats: &[],
7031                                });
7032                                self.queue.write_texture(
7033                                    wgpu::TexelCopyTextureInfo {
7034                                        texture: &tex,
7035                                        mip_level: 0,
7036                                        origin: wgpu::Origin3d::ZERO,
7037                                        aspect: wgpu::TextureAspect::All,
7038                                    },
7039                                    &sdf.rgba8,
7040                                    wgpu::TexelCopyBufferLayout {
7041                                        offset: 0,
7042                                        bytes_per_row: Some(sdf.width * 4),
7043                                        rows_per_image: Some(sdf.height),
7044                                    },
7045                                    wgpu::Extent3d {
7046                                        width: sdf.width,
7047                                        height: sdf.height,
7048                                        depth_or_array_layers: 1,
7049                                    },
7050                                );
7051                                let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
7052                                self.coastal_sdf_cached =
7053                                    Some((sdf.id, sdf.revision, sdf.width, sdf.height, tex, view));
7054                                need_rebind = true;
7055                            }
7056                        }
7057                    }
7058                }
7059            }
7060            let gpu_ocean = GpuOceanUniforms::from_retained(ocean, has_sdf);
7061            self.queue.write_buffer(
7062                &self.ocean_uniform_buffer,
7063                0,
7064                bytemuck::bytes_of(&gpu_ocean),
7065            );
7066        } else {
7067            self.queue.write_buffer(
7068                &self.ocean_uniform_buffer,
7069                0,
7070                bytemuck::bytes_of(&GpuOceanUniforms::disabled()),
7071            );
7072        }
7073
7074        if need_rebind {
7075            let shadow_view = self
7076                .shadow_target
7077                .as_ref()
7078                .map(|(_, _, v)| v)
7079                .unwrap_or(&self.shadow_fallback_view);
7080            let sdf_view = self
7081                .coastal_sdf_cached
7082                .as_ref()
7083                .map(|(_, _, _, _, _, v)| v)
7084                .unwrap_or(&self.coastal_sdf_fallback_view);
7085            self.shadow_ocean_bind_group = Self::create_shadow_ocean_bind_group(
7086                &self.device,
7087                &self.shadow_ocean_bgl,
7088                shadow_view,
7089                &self.shadow_sampler,
7090                &self.ocean_uniform_buffer,
7091                sdf_view,
7092                &self.coastal_sdf_sampler,
7093            );
7094        }
7095    }
7096
7097    fn create_terrain_bind_group(
7098        device: &wgpu::Device,
7099        layout: &wgpu::BindGroupLayout,
7100        camera_buffer: &wgpu::Buffer,
7101        slab_buffer: &wgpu::Buffer,
7102        instance_buffer: &wgpu::Buffer,
7103        atlas_view: &wgpu::TextureView,
7104        sampler: &wgpu::Sampler,
7105        land_mask_view: &wgpu::TextureView,
7106        env_wrap_sampler: &wgpu::Sampler,
7107    ) -> wgpu::BindGroup {
7108        device.create_bind_group(&wgpu::BindGroupDescriptor {
7109            label: Some("strata_3d_terrain_bg"),
7110            layout,
7111            entries: &[
7112                wgpu::BindGroupEntry {
7113                    binding: 0,
7114                    resource: camera_buffer.as_entire_binding(),
7115                },
7116                wgpu::BindGroupEntry {
7117                    binding: 1,
7118                    resource: slab_buffer.as_entire_binding(),
7119                },
7120                wgpu::BindGroupEntry {
7121                    binding: 2,
7122                    resource: instance_buffer.as_entire_binding(),
7123                },
7124                wgpu::BindGroupEntry {
7125                    binding: 3,
7126                    resource: wgpu::BindingResource::TextureView(atlas_view),
7127                },
7128                wgpu::BindGroupEntry {
7129                    binding: 4,
7130                    resource: wgpu::BindingResource::Sampler(sampler),
7131                },
7132                wgpu::BindGroupEntry {
7133                    binding: 5,
7134                    resource: wgpu::BindingResource::TextureView(land_mask_view),
7135                },
7136                wgpu::BindGroupEntry {
7137                    binding: 6,
7138                    resource: wgpu::BindingResource::Sampler(env_wrap_sampler),
7139                },
7140            ],
7141        })
7142    }
7143
7144    fn upload_environment_assets(&mut self, env: &RetainedEnvironmentAssets) -> bool {
7145        let perf = gpu_perf_logging_enabled();
7146        let mut terrain_rebind = false;
7147
7148        if let Some(ref land) = env.land_mask {
7149            let key = Some((land.id, land.revision));
7150            if self.env_state.land_mask_id_rev != key {
7151                let t0 = std::time::Instant::now();
7152                self.env_state.land_mask_view = create_rgba8_2d_view_opts(
7153                    &self.device,
7154                    &self.queue,
7155                    "strata_env_land_mask",
7156                    land.width,
7157                    land.height,
7158                    &land.rgba8,
7159                    MipGenMode::LinearBox,
7160                );
7161                if perf {
7162                    eprintln!("[perf] env land_mask {}x{} -> {:.2}ms", land.width, land.height, t0.elapsed().as_secs_f64() * 1000.0);
7163                }
7164                self.env_state.land_mask_id_rev = key;
7165                terrain_rebind = true;
7166            }
7167        }
7168
7169        if let Some(ref clouds) = env.cloud_map {
7170            let key = Some((clouds.id, clouds.revision));
7171            if self.env_state.cloud_map_id_rev != key {
7172                let t0 = std::time::Instant::now();
7173                self.env_state.cloud_map_view = create_cloud_density_r8_view(
7174                    &self.device,
7175                    &self.queue,
7176                    "strata_env_cloud_map",
7177                    clouds.width,
7178                    clouds.height,
7179                    &clouds.rgba8,
7180                );
7181                if perf {
7182                    eprintln!("[perf] env cloud_map {}x{} -> {:.2}ms", clouds.width, clouds.height, t0.elapsed().as_secs_f64() * 1000.0);
7183                }
7184                self.env_state.cloud_map_id_rev = key;
7185                self.cloud_bind_group = Self::create_cloud_bind_group(
7186                    &self.device,
7187                    &self.cloud_bind_group_layout,
7188                    "strata_3d_cloud_bg",
7189                    &self.camera_buffer,
7190                    &self.env_state.cloud_map_view,
7191                    &self.env_state.env_sampler,
7192                    &self.env_state.cloud_noise_view,
7193                    &self.env_state.cloud_noise_sampler,
7194                );
7195            }
7196        }
7197
7198        let mut sky_rebind = false;
7199
7200        if let Some(ref moon) = env.moon_texture {
7201            let key = Some((moon.id, moon.revision));
7202            if self.env_state.moon_tex_id_rev != key {
7203                let t0 = std::time::Instant::now();
7204                self.env_state.moon_view = create_rgba8_2d_view(
7205                    &self.device,
7206                    &self.queue,
7207                    "strata_env_moon_tex",
7208                    moon.width,
7209                    moon.height,
7210                    &moon.rgba8,
7211                );
7212                if perf {
7213                    eprintln!("[perf] env moon {}x{} -> {:.2}ms", moon.width, moon.height, t0.elapsed().as_secs_f64() * 1000.0);
7214                }
7215                self.env_state.moon_tex_id_rev = key;
7216                sky_rebind = true;
7217            }
7218        }
7219
7220        match &env.skybox_cubemap {
7221            Some(cube) => {
7222                let key = Some((cube.id, cube.revision));
7223                if self.env_state.skybox_cube_id_rev != key {
7224                    let t0 = std::time::Instant::now();
7225                    self.env_state.skybox_cube_view = create_rgba8_cube_view(
7226                        &self.device,
7227                        &self.queue,
7228                        "strata_env_skybox_cube",
7229                        cube.face_size,
7230                        &cube.faces_rgba8,
7231                        wgpu::TextureFormat::Rgba8Unorm,
7232                    );
7233                    if perf {
7234                        eprintln!("[perf] env skybox 6x{} -> {:.2}ms", cube.face_size, t0.elapsed().as_secs_f64() * 1000.0);
7235                    }
7236                    self.env_state.skybox_cube_id_rev = key;
7237                    sky_rebind = true;
7238                }
7239            }
7240            None => {
7241                if self.env_state.skybox_cube_id_rev.is_some() {
7242                    let black_face = Arc::new(vec![0u8, 0, 0, 0]);
7243                    self.env_state.skybox_cube_view = create_rgba8_cube_view(
7244                        &self.device,
7245                        &self.queue,
7246                        "strata_env_skybox_fallback",
7247                        1,
7248                        &[
7249                            Arc::clone(&black_face),
7250                            Arc::clone(&black_face),
7251                            Arc::clone(&black_face),
7252                            Arc::clone(&black_face),
7253                            Arc::clone(&black_face),
7254                            black_face,
7255                        ],
7256                        wgpu::TextureFormat::Rgba8Unorm,
7257                    );
7258                    self.env_state.skybox_cube_id_rev = None;
7259                    sky_rebind = true;
7260                }
7261            }
7262        }
7263
7264        if sky_rebind {
7265            self.sky_bind_group = Self::create_sky_bind_group(
7266                &self.device,
7267                &self.sky_bind_group_layout,
7268                &self.camera_buffer,
7269                &self.env_state.moon_view,
7270                &self.env_state.env_sampler,
7271                &self.env_state.skybox_cube_view,
7272            );
7273        }
7274
7275        if let Some(ref stars) = env.stars {
7276            let ptr = Arc::as_ptr(stars) as usize;
7277            let len = stars.len();
7278            if self.env_state.stars_ptr != ptr || self.env_state.stars_len != len {
7279                let gpu_stars: Vec<GpuStar> = stars
7280                    .iter()
7281                    .map(|s: &RetainedStar| GpuStar {
7282                        icrf_dir_mag: [s.icrf_dir[0], s.icrf_dir[1], s.icrf_dir[2], s.vmag],
7283                        color: s.color,
7284                    })
7285                    .collect();
7286                if gpu_stars.len() > self.env_state.star_capacity {
7287                    let new_cap = gpu_stars.len().next_power_of_two().max(64);
7288                    self.env_state.star_buffer =
7289                        self.device.create_buffer(&wgpu::BufferDescriptor {
7290                            label: Some("strata_3d_stars_grown"),
7291                            size: (new_cap * std::mem::size_of::<GpuStar>()) as u64,
7292                            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
7293                            mapped_at_creation: false,
7294                        });
7295                    self.env_state.star_capacity = new_cap;
7296                    self.star_bind_group = Self::create_star_bind_group(
7297                        &self.device,
7298                        &self.star_bind_group_layout,
7299                        &self.camera_buffer,
7300                        &self.env_state.star_buffer,
7301                    );
7302                }
7303                if !gpu_stars.is_empty() {
7304                    self.queue.write_buffer(
7305                        &self.env_state.star_buffer,
7306                        0,
7307                        bytemuck::cast_slice(&gpu_stars),
7308                    );
7309                }
7310                self.env_state.stars_ptr = ptr;
7311                self.env_state.stars_len = len;
7312                self.env_state.star_count = gpu_stars.len() as u32;
7313            }
7314        }
7315
7316        terrain_rebind
7317    }
7318
7319    fn ensure_topology(&mut self, grid_res: u32, has_skirts: bool) -> (wgpu::Buffer, u32) {
7320        if let Some(cached) = self.topologies.get(&(grid_res, has_skirts)) {
7321            return (cached.buffer.clone(), cached.index_count);
7322        }
7323        let indices = build_terrain_grid_indices(grid_res, has_skirts);
7324        let count = indices.len() as u32;
7325        let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
7326            label: Some("strata_3d_grid_topology"),
7327            size: (indices.len() * 4) as u64,
7328            usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
7329            mapped_at_creation: false,
7330        });
7331        if !indices.is_empty() {
7332            self.queue
7333                .write_buffer(&buffer, 0, bytemuck::cast_slice(&indices));
7334        }
7335        self.topologies.insert(
7336            (grid_res, has_skirts),
7337            CachedIndexTopology {
7338                buffer: buffer.clone(),
7339                index_count: count,
7340            },
7341        );
7342        (buffer, count)
7343    }
7344
7345    fn ensure_depth_view(&mut self, width: u32, height: u32) -> wgpu::TextureView {
7346        if let Some((w, h, view)) = &self.depth_target {
7347            if *w == width && *h == height {
7348                return view.clone();
7349            }
7350        }
7351        let tex = self.device.create_texture(&wgpu::TextureDescriptor {
7352            label: Some("strata_3d_depth"),
7353            size: wgpu::Extent3d {
7354                width: width.max(1),
7355                height: height.max(1),
7356                depth_or_array_layers: 1,
7357            },
7358            mip_level_count: 1,
7359            sample_count: 1,
7360            dimension: wgpu::TextureDimension::D2,
7361            format: wgpu::TextureFormat::Depth32Float,
7362            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
7363            view_formats: &[],
7364        });
7365        let view = tex.create_view(&Default::default());
7366        self.depth_target = Some((width, height, view.clone()));
7367        view
7368    }
7369
7370    /// Creates an RGBA `wgpu::BindGroup` for compositing a 2D UI HUD texture over a 3D frame.
7371    pub fn create_overlay_bind_group(&self, overlay_view: &wgpu::TextureView) -> wgpu::BindGroup {
7372        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
7373            label: Some("strata_2d_overlay_bg"),
7374            layout: &self.overlay_bind_group_layout,
7375            entries: &[
7376                wgpu::BindGroupEntry {
7377                    binding: 0,
7378                    resource: wgpu::BindingResource::TextureView(overlay_view),
7379                },
7380                wgpu::BindGroupEntry {
7381                    binding: 1,
7382                    resource: wgpu::BindingResource::Sampler(&self.overlay_sampler),
7383                },
7384            ],
7385        })
7386    }
7387
7388    /// Draws `scene` (or its [`RetainedScene3D`] / [`RetainedTerrainFrame`]) directly into `target_view`.
7389    ///
7390    /// When `viewport` is `Some([x, y, w, h])`, restricts rendering to that sub-rectangle of the
7391    /// render target and uses `w/h` as the projection aspect ratio.
7392    pub fn render_scene_to_view(
7393        &mut self,
7394        scene: &Scene3D,
7395        target_view: &wgpu::TextureView,
7396        target_width: u32,
7397        target_height: u32,
7398        viewport: Option<[f32; 4]>,
7399        unlimited_upload_budget: bool,
7400    ) {
7401        self.render_scene_and_overlay_to_view(
7402            scene,
7403            target_view,
7404            target_width,
7405            target_height,
7406            viewport,
7407            unlimited_upload_budget,
7408            None,
7409        );
7410    }
7411
7412    /// Draws `scene` and optionally composites the cached 2D HUD `overlay_bind_group` into
7413    /// `target_view` using a single `CommandEncoder` and a single `queue.submit`.
7414    pub fn render_scene_and_overlay_to_view(
7415        &mut self,
7416        scene: &Scene3D,
7417        target_view: &wgpu::TextureView,
7418        target_width: u32,
7419        target_height: u32,
7420        viewport: Option<[f32; 4]>,
7421        unlimited_upload_budget: bool,
7422        overlay_bind_group: Option<&wgpu::BindGroup>,
7423    ) {
7424        self.render_scene_to_view_internal(
7425            scene,
7426            target_view,
7427            target_width,
7428            target_height,
7429            viewport,
7430            unlimited_upload_budget,
7431            true,
7432            false,
7433            overlay_bind_group,
7434        );
7435    }
7436
7437    /// Renders `scene` into `target_view` inside `viewport` without clearing prior color pixels,
7438    /// allowing previously rendered 2D UI layers behind the 3D viewport to remain intact.
7439    pub fn render_scene_preserving_color_to_view(
7440        &mut self,
7441        scene: &Scene3D,
7442        target_view: &wgpu::TextureView,
7443        target_width: u32,
7444        target_height: u32,
7445        viewport: Option<[f32; 4]>,
7446        unlimited_upload_budget: bool,
7447    ) {
7448        self.render_scene_to_view_internal(
7449            scene,
7450            target_view,
7451            target_width,
7452            target_height,
7453            viewport,
7454            unlimited_upload_budget,
7455            false,
7456            true,
7457            None,
7458        );
7459    }
7460
7461    /// Renders multiple 3D viewports (`(viewport_rect, scene)`) sequentially into `target_view`
7462    /// without clearing prior viewports, and composites `overlay_bind_group` once on the final pass.
7463    pub fn render_viewports_and_overlay_to_view(
7464        &mut self,
7465        viewports: &[([f32; 4], &Scene3D)],
7466        target_view: &wgpu::TextureView,
7467        target_width: u32,
7468        target_height: u32,
7469        unlimited_upload_budget: bool,
7470        overlay_bind_group: Option<&wgpu::BindGroup>,
7471    ) {
7472        if viewports.is_empty() {
7473            if let Some(ov_bg) = overlay_bind_group {
7474                self.composite_overlay_to_view(target_view, ov_bg);
7475            }
7476            return;
7477        }
7478        let multi = viewports.len() > 1;
7479        for (idx, &(vp, scene)) in viewports.iter().enumerate() {
7480            let is_first = idx == 0;
7481            let is_last = idx + 1 == viewports.len();
7482            self.render_scene_to_view_internal(
7483                scene,
7484                target_view,
7485                target_width,
7486                target_height,
7487                Some(vp),
7488                unlimited_upload_budget,
7489                is_first,
7490                multi,
7491                if is_last { overlay_bind_group } else { None },
7492            );
7493        }
7494    }
7495
7496    #[allow(clippy::too_many_arguments)]
7497    fn render_scene_to_view_internal(
7498        &mut self,
7499        scene: &Scene3D,
7500        target_view: &wgpu::TextureView,
7501        target_width: u32,
7502        target_height: u32,
7503        viewport: Option<[f32; 4]>,
7504        unlimited_upload_budget: bool,
7505        clear_color_target: bool,
7506        multi_viewport_mode: bool,
7507        overlay_bind_group: Option<&wgpu::BindGroup>,
7508    ) {
7509        let perf = gpu_perf_logging_enabled();
7510        let t_start = std::time::Instant::now();
7511        let mut t_env = 0.0f64;
7512        let mut t_slab = 0.0f64;
7513        let mut t_atlas = 0.0f64;
7514        let mut t_inst = 0.0f64;
7515        let mut t_dyn = 0.0f64;
7516
7517        self.frame_index += 1;
7518        let frame_idx = self.frame_index;
7519        let mesh_budget = usize::MAX;
7520        let tex_budget = if unlimited_upload_budget || frame_idx <= 2 {
7521            usize::MAX
7522        } else {
7523            DEFAULT_TEXTURE_UPLOAD_BUDGET
7524        };
7525
7526        let vp_w_u32 = viewport
7527            .map(|v| v[2].max(1.0).round() as u32)
7528            .unwrap_or_else(|| target_width.max(1));
7529        let vp_h_u32 = viewport
7530            .map(|v| v[3].max(1.0).round() as u32)
7531            .unwrap_or_else(|| target_height.max(1));
7532
7533        let (cam, terrain_frame_opt) = if let Some(retained) = scene.retained_handle() {
7534            let terrain = retained.snapshot_terrain();
7535            let cam = retained.camera();
7536            (cam, terrain)
7537        } else if let Some(terrain) = scene.retained_terrain() {
7538            (terrain.camera, Some(Arc::clone(terrain)))
7539        } else {
7540            let scene_key = (scene as *const Scene3D as usize, vp_w_u32, vp_h_u32);
7541            let frame = if let Some((seq, existing)) = self.cached_fallback_frames.get_mut(&scene_key)
7542            {
7543                *seq = frame_idx;
7544                Arc::clone(existing)
7545            } else {
7546                let built = Arc::new(fallback_frame_from_scene3d(
7547                    scene,
7548                    vp_w_u32 as f32,
7549                    vp_h_u32 as f32,
7550                ));
7551                self.cached_fallback_frames
7552                    .insert(scene_key, (frame_idx, Arc::clone(&built)));
7553                built
7554            };
7555            (frame.camera, Some(frame))
7556        };
7557
7558        // 1. Update camera uniform buffer unconditionally (O(1) tiny uniform write).
7559        let vp_w = viewport
7560            .map(|v| v[2])
7561            .unwrap_or_else(|| target_width.max(1) as f32)
7562            .max(1.0);
7563        let vp_h = viewport
7564            .map(|v| v[3])
7565            .unwrap_or_else(|| target_height.max(1) as f32)
7566            .max(1.0);
7567        let (light_vp_rte, shadow_radius_m, shadows_active) =
7568            compute_shadow_light_vp_rte(&cam, cam.shadow_map_size);
7569        let gpu_cam = GpuCameraUniforms::from_retained(
7570            &cam,
7571            vp_w,
7572            vp_h,
7573            light_vp_rte,
7574            shadow_radius_m,
7575            shadows_active,
7576        );
7577        self.queue
7578            .write_buffer(&self.camera_buffer, 0, bytemuck::bytes_of(&gpu_cam));
7579
7580        // 2. Upload incremental tile meshes/textures, environment assets, and prepare draw instances.
7581        let mut draw_count = 0usize;
7582        let mut all_terrain_opaque = true;
7583        let mut terrain_batches: Vec<((u32, bool), std::ops::Range<u32>)> = Vec::new();
7584        let mut dynamic_draws: Vec<(u64, [f64; 3], [f32; 4], bool)> = Vec::new();
7585        let mut geo_opaque_batches: Vec<(u64, Option<u64>, std::ops::Range<u32>)> = Vec::new();
7586        let mut geo_transparent_batches: Vec<(u64, Option<u64>, std::ops::Range<u32>)> = Vec::new();
7587        let mut staged_geo_instances: Vec<GpuGeoInstance> = Vec::new();
7588
7589        if let Some(frame) = terrain_frame_opt.as_ref() {
7590            let frame_changed = frame.geometry_revision != self.last_geometry_rev
7591                || self
7592                    .last_terrain_frame
7593                    .as_ref()
7594                    .map(|p| !Arc::ptr_eq(p, frame))
7595                    .unwrap_or(true);
7596            let _ = frame_changed;
7597            self.last_geometry_rev = frame.geometry_revision;
7598            self.last_terrain_frame = Some(Arc::clone(frame));
7599
7600            let tp0 = std::time::Instant::now();
7601            let env_dirty = if let Some(ref env) = frame.environment {
7602                self.upload_environment_assets(env)
7603            } else {
7604                false
7605            };
7606            t_env = tp0.elapsed().as_secs_f64() * 1000.0;
7607
7608            let tp1 = std::time::Instant::now();
7609            let (bg_dirty, mesh_deferred) = self.slab.upload_meshes(
7610                &self.device,
7611                &self.queue,
7612                &frame.meshes,
7613                frame_idx,
7614                mesh_budget,
7615            );
7616            t_slab = tp1.elapsed().as_secs_f64() * 1000.0;
7617
7618            let tp2 = std::time::Instant::now();
7619            let tex_deferred = self
7620                .atlas
7621                .upload_textures(&self.queue, &frame.textures, frame_idx, tex_budget);
7622            t_atlas = tp2.elapsed().as_secs_f64() * 1000.0;
7623
7624            if mesh_deferred || tex_deferred {
7625                if let Some(retained) = scene.retained_handle() {
7626                    retained.request_gpu_continuation();
7627                }
7628            }
7629
7630            let tp3 = std::time::Instant::now();
7631            let mut tagged_instances: Vec<((u32, bool), GpuTileInstance)> =
7632                Vec::with_capacity(frame.instances.len());
7633            for inst in &frame.instances {
7634                let Some((base_v, grid_res, has_skirts)) =
7635                    self.slab.resident_slot(inst.key, inst.mesh_revision)
7636                else {
7637                    continue;
7638                };
7639                let (cx_hi, cx_lo) = split_f64_to_f32(inst.center_ecef[0]);
7640                let (cy_hi, cy_lo) = split_f64_to_f32(inst.center_ecef[1]);
7641                let (cz_hi, cz_lo) = split_f64_to_f32(inst.center_ecef[2]);
7642                let tex_layer = self.atlas.layer_for(inst.texture_id, inst.texture_revision);
7643                let night_layer = self
7644                    .atlas
7645                    .layer_for(inst.night_texture_id, inst.night_texture_revision);
7646                let eff_tint = if inst.texture_id.is_some() && tex_layer == 0 {
7647                    [0.14, 0.19, 0.27, 1.0]
7648                } else {
7649                    inst.tint
7650                };
7651                if eff_tint[3] < 0.999 {
7652                    all_terrain_opaque = false;
7653                }
7654                tagged_instances.push((
7655                    (grid_res, has_skirts),
7656                    GpuTileInstance {
7657                        center_high: [cx_hi, cy_hi, cz_hi, 0.0],
7658                        center_low: [cx_lo, cy_lo, cz_lo, 0.0],
7659                        uv_rect: inst.uv_rect,
7660                        night_uv_rect: inst.night_uv_rect,
7661                        tint: eff_tint,
7662                        tile_meta: [base_v, tex_layer, u32::from(inst.unlit), night_layer],
7663                    },
7664                ));
7665            }
7666            tagged_instances.sort_by_key(|(topo, _)| *topo);
7667            let mut instances_gpu: Vec<GpuTileInstance> =
7668                Vec::with_capacity(tagged_instances.len());
7669            for (topo, gpu_inst) in tagged_instances {
7670                let idx = instances_gpu.len() as u32;
7671                instances_gpu.push(gpu_inst);
7672                if let Some((last_topo, range)) = terrain_batches.last_mut() {
7673                    if *last_topo == topo && range.end == idx {
7674                        range.end = idx + 1;
7675                        continue;
7676                    }
7677                }
7678                terrain_batches.push((topo, idx..(idx + 1)));
7679            }
7680
7681            let mut instance_resized = false;
7682            if instances_gpu.len() > self.instance_capacity {
7683                let new_cap = instances_gpu.len().next_power_of_two().max(1024);
7684                self.instance_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
7685                    label: Some("strata_3d_tile_instances_grown"),
7686                    size: (new_cap * std::mem::size_of::<GpuTileInstance>()) as u64,
7687                    usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
7688                    mapped_at_creation: false,
7689                });
7690                self.instance_capacity = new_cap;
7691                instance_resized = true;
7692            }
7693            if bg_dirty || instance_resized || env_dirty {
7694                self.terrain_bind_group = Self::create_terrain_bind_group(
7695                    &self.device,
7696                    &self.terrain_bind_group_layout,
7697                    &self.camera_buffer,
7698                    &self.slab.buffer,
7699                    &self.instance_buffer,
7700                    &self.atlas.view,
7701                    &self.terrain_sampler,
7702                    &self.env_state.land_mask_view,
7703                    &self.env_state.env_sampler,
7704                );
7705            }
7706            if !instances_gpu.is_empty() {
7707                self.queue.write_buffer(
7708                    &self.instance_buffer,
7709                    0,
7710                    bytemuck::cast_slice(&instances_gpu),
7711                );
7712                draw_count = instances_gpu.len();
7713            }
7714            t_inst = tp3.elapsed().as_secs_f64() * 1000.0;
7715
7716            let tp4 = std::time::Instant::now();
7717            for dm in &frame.dynamic_meshes {
7718                if dm.vertices.is_empty() || dm.indices.is_empty() {
7719                    continue;
7720                }
7721                let vb_bytes: &[u8] = bytemuck::cast_slice(&dm.vertices);
7722                let ib_bytes: &[u8] = bytemuck::cast_slice(&dm.indices);
7723                let mut need_recreate = true;
7724                if let Some(existing) = self.dynamic_meshes.get_mut(&dm.id) {
7725                    existing.last_used_seq = frame_idx;
7726                    if existing.revision == dm.revision {
7727                        need_recreate = false;
7728                    } else if existing.vbuf.size() >= vb_bytes.len() as u64
7729                        && existing.ibuf.size() >= ib_bytes.len() as u64
7730                    {
7731                        self.queue.write_buffer(&existing.vbuf, 0, vb_bytes);
7732                        self.queue.write_buffer(&existing.ibuf, 0, ib_bytes);
7733                        existing.revision = dm.revision;
7734                        existing.index_count = dm.indices.len() as u32;
7735                        need_recreate = false;
7736                    }
7737                }
7738                if need_recreate {
7739                    let vbuf = self.device.create_buffer(&wgpu::BufferDescriptor {
7740                        label: Some("strata_3d_dyn_vb"),
7741                        size: (vb_bytes.len() as u64).next_power_of_two().max(256),
7742                        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
7743                        mapped_at_creation: false,
7744                    });
7745                    self.queue.write_buffer(&vbuf, 0, vb_bytes);
7746                    let ibuf = self.device.create_buffer(&wgpu::BufferDescriptor {
7747                        label: Some("strata_3d_dyn_ib"),
7748                        size: (ib_bytes.len() as u64).next_power_of_two().max(64),
7749                        usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
7750                        mapped_at_creation: false,
7751                    });
7752                    self.queue.write_buffer(&ibuf, 0, ib_bytes);
7753                    self.dynamic_meshes.insert(
7754                        dm.id,
7755                        CachedDynamicGpuMesh {
7756                            revision: dm.revision,
7757                            vbuf,
7758                            ibuf,
7759                            index_count: dm.indices.len() as u32,
7760                            last_used_seq: frame_idx,
7761                        },
7762                    );
7763                }
7764                dynamic_draws.push((dm.id, dm.anchor_ecef, dm.color, dm.unlit));
7765            }
7766
7767            for asset in frame.geo_mesh_assets.iter() {
7768                if asset.vertices.is_empty() || asset.indices.is_empty() {
7769                    continue;
7770                }
7771                let asset_tex_id = asset
7772                    .albedo_texture
7773                    .as_deref()
7774                    .and_then(|tex| self.ensure_geo_texture(tex, frame_idx))
7775                    .map(|(tid, _)| tid);
7776                let mut need_upload = true;
7777                if let Some(existing) = self.geo_meshes.get_mut(&asset.id) {
7778                    existing.last_used_seq = frame_idx;
7779                    existing.albedo_tex_id = asset_tex_id;
7780                    if existing.revision == asset.revision {
7781                        need_upload = false;
7782                    }
7783                }
7784                if need_upload {
7785                    let mut packed_verts: Vec<GpuGeoVertex> =
7786                        Vec::with_capacity(asset.vertices.len());
7787                    let mut has_vertex_alpha = false;
7788                    let vcols = asset.vertex_colors.as_deref();
7789                    for (vi, v) in asset.vertices.iter().enumerate() {
7790                        let c = vcols
7791                            .and_then(|cols| cols.get(vi).copied())
7792                            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
7793                        if c[3] < 0.999 {
7794                            has_vertex_alpha = true;
7795                        }
7796                        packed_verts.push(GpuGeoVertex {
7797                            pos_u: v.pos_u,
7798                            norm_v: v.norm_v,
7799                            color: c,
7800                        });
7801                    }
7802                    let vb_bytes: &[u8] = bytemuck::cast_slice(&packed_verts);
7803                    let ib_bytes: &[u8] = bytemuck::cast_slice(&asset.indices);
7804                    let mut need_recreate = true;
7805                    if let Some(existing) = self.geo_meshes.get_mut(&asset.id) {
7806                        if existing.vbuf.size() >= vb_bytes.len() as u64
7807                            && existing.ibuf.size() >= ib_bytes.len() as u64
7808                        {
7809                            self.queue.write_buffer(&existing.vbuf, 0, vb_bytes);
7810                            self.queue.write_buffer(&existing.ibuf, 0, ib_bytes);
7811                            existing.revision = asset.revision;
7812                            existing.index_count = asset.indices.len() as u32;
7813                            existing.has_vertex_alpha = has_vertex_alpha;
7814                            existing.albedo_tex_id = asset_tex_id;
7815                            existing.last_used_seq = frame_idx;
7816                            need_recreate = false;
7817                        }
7818                    }
7819                    if need_recreate {
7820                        let vbuf = self.device.create_buffer(&wgpu::BufferDescriptor {
7821                            label: Some("strata_3d_geo_vb"),
7822                            size: (vb_bytes.len() as u64).next_power_of_two().max(256),
7823                            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
7824                            mapped_at_creation: false,
7825                        });
7826                        self.queue.write_buffer(&vbuf, 0, vb_bytes);
7827                        let ibuf = self.device.create_buffer(&wgpu::BufferDescriptor {
7828                            label: Some("strata_3d_geo_ib"),
7829                            size: (ib_bytes.len() as u64).next_power_of_two().max(64),
7830                            usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
7831                            mapped_at_creation: false,
7832                        });
7833                        self.queue.write_buffer(&ibuf, 0, ib_bytes);
7834                        self.geo_meshes.insert(
7835                            asset.id,
7836                            CachedGeoGpuMesh {
7837                                revision: asset.revision,
7838                                vbuf,
7839                                ibuf,
7840                                index_count: asset.indices.len() as u32,
7841                                has_vertex_alpha,
7842                                albedo_tex_id: asset_tex_id,
7843                                last_used_seq: frame_idx,
7844                            },
7845                        );
7846                    }
7847                }
7848            }
7849
7850            if !frame.geo_instances.is_empty() {
7851                let mut opaque_items: Vec<(u64, Option<u64>, GpuGeoInstance)> =
7852                    Vec::with_capacity(frame.geo_instances.len());
7853                let mut transparent_items: Vec<(f64, u64, Option<u64>, GpuGeoInstance)> =
7854                    Vec::new();
7855
7856                for inst in frame.geo_instances.iter() {
7857                    let inst_tex_info = inst
7858                        .albedo_texture
7859                        .as_deref()
7860                        .and_then(|tex| self.ensure_geo_texture(tex, frame_idx));
7861                    let Some((mesh_has_alpha, mesh_tex_id)) =
7862                        self.geo_meshes.get_mut(&inst.mesh_id).map(|m| {
7863                            m.last_used_seq = frame_idx;
7864                            (m.has_vertex_alpha, m.albedo_tex_id)
7865                        })
7866                    else {
7867                        continue;
7868                    };
7869                    let (eff_tex_id, tex_has_alpha) = if let Some((tid, t_alpha)) = inst_tex_info {
7870                        (Some(tid), t_alpha)
7871                    } else if let Some(tid) = mesh_tex_id {
7872                        let t_alpha = self
7873                            .geo_textures
7874                            .get_mut(&tid)
7875                            .map(|t| {
7876                                t.last_used_seq = frame_idx;
7877                                t.has_alpha
7878                            })
7879                            .unwrap_or(false);
7880                        (Some(tid), t_alpha)
7881                    } else {
7882                        (None, false)
7883                    };
7884
7885                    let (ax_hi, ax_lo) = split_f64_to_f32(inst.anchor_ecef[0]);
7886                    let (ay_hi, ay_lo) = split_f64_to_f32(inst.anchor_ecef[1]);
7887                    let (az_hi, az_lo) = split_f64_to_f32(inst.anchor_ecef[2]);
7888                    let gpu_inst = GpuGeoInstance {
7889                        anchor_high: [ax_hi, ay_hi, az_hi, 0.0],
7890                        anchor_low: [ax_lo, ay_lo, az_lo, 0.0],
7891                        col0: [
7892                            inst.model_cols[0][0],
7893                            inst.model_cols[0][1],
7894                            inst.model_cols[0][2],
7895                            inst.roughness,
7896                        ],
7897                        col1: [
7898                            inst.model_cols[1][0],
7899                            inst.model_cols[1][1],
7900                            inst.model_cols[1][2],
7901                            inst.metalness,
7902                        ],
7903                        col2: [
7904                            inst.model_cols[2][0],
7905                            inst.model_cols[2][1],
7906                            inst.model_cols[2][2],
7907                            if inst.unlit { 1.0 } else { 0.0 },
7908                        ],
7909                        base_color: inst.base_color,
7910                        emissive: [
7911                            inst.emissive_rgb[0],
7912                            inst.emissive_rgb[1],
7913                            inst.emissive_rgb[2],
7914                            inst.accent_mix,
7915                        ],
7916                    };
7917                    let is_transparent =
7918                        inst.base_color[3] < 0.999 || mesh_has_alpha || tex_has_alpha;
7919                    if !is_transparent {
7920                        opaque_items.push((inst.mesh_id, eff_tex_id, gpu_inst));
7921                    } else {
7922                        let dx = inst.anchor_ecef[0] - cam.eye_ecef[0];
7923                        let dy = inst.anchor_ecef[1] - cam.eye_ecef[1];
7924                        let dz = inst.anchor_ecef[2] - cam.eye_ecef[2];
7925                        let dist_sq = dx * dx + dy * dy + dz * dz;
7926                        transparent_items.push((dist_sq, inst.mesh_id, eff_tex_id, gpu_inst));
7927                    }
7928                }
7929
7930                opaque_items.sort_by_key(|(mesh_id, tex_id, _)| (*mesh_id, *tex_id));
7931                // Sort transparent instances back-to-front (largest distance from camera eye first).
7932                transparent_items.sort_by(|a, b| b.0.total_cmp(&a.0));
7933                staged_geo_instances.reserve(opaque_items.len() + transparent_items.len());
7934
7935                let push_batches =
7936                    |items: Vec<(u64, Option<u64>, GpuGeoInstance)>,
7937                     staged: &mut Vec<GpuGeoInstance>,
7938                     batches: &mut Vec<(u64, Option<u64>, std::ops::Range<u32>)>| {
7939                        for (mesh_id, tex_id, gpu_inst) in items {
7940                            let idx = staged.len() as u32;
7941                            staged.push(gpu_inst);
7942                            if let Some((last_id, last_tex, range)) = batches.last_mut() {
7943                                if *last_id == mesh_id && *last_tex == tex_id && range.end == idx {
7944                                    range.end = idx + 1;
7945                                    continue;
7946                                }
7947                            }
7948                            batches.push((mesh_id, tex_id, idx..(idx + 1)));
7949                        }
7950                    };
7951                push_batches(
7952                    opaque_items,
7953                    &mut staged_geo_instances,
7954                    &mut geo_opaque_batches,
7955                );
7956                let sorted_transparent: Vec<(u64, Option<u64>, GpuGeoInstance)> = transparent_items
7957                    .into_iter()
7958                    .map(|(_, mid, tid, gi)| (mid, tid, gi))
7959                    .collect();
7960                push_batches(
7961                    sorted_transparent,
7962                    &mut staged_geo_instances,
7963                    &mut geo_transparent_batches,
7964                );
7965            }
7966
7967            // Evict deleted/unreferenced geo meshes, geo textures, dynamic meshes, and fallback scenes
7968            // after a 32-frame grace window (prevents VRAM leaks while allowing multi-viewport sharing).
7969            const GEO_CACHE_EVICT_FRAMES: u64 = 32;
7970            self.geo_meshes
7971                .retain(|_, m| frame_idx.saturating_sub(m.last_used_seq) <= GEO_CACHE_EVICT_FRAMES);
7972            self.geo_textures
7973                .retain(|_, t| frame_idx.saturating_sub(t.last_used_seq) <= GEO_CACHE_EVICT_FRAMES);
7974            self.dynamic_meshes
7975                .retain(|_, m| frame_idx.saturating_sub(m.last_used_seq) <= GEO_CACHE_EVICT_FRAMES);
7976            self.cached_fallback_frames
7977                .retain(|_, (seq, _)| frame_idx.saturating_sub(*seq) <= GEO_CACHE_EVICT_FRAMES);
7978
7979            t_dyn = tp4.elapsed().as_secs_f64() * 1000.0;
7980        }
7981
7982        if !staged_geo_instances.is_empty() {
7983            if staged_geo_instances.len() > self.geo_instance_capacity {
7984                let new_cap = staged_geo_instances.len().next_power_of_two().max(256);
7985                self.geo_instance_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
7986                    label: Some("strata_3d_geo_instances_grown"),
7987                    size: (new_cap * std::mem::size_of::<GpuGeoInstance>()) as u64,
7988                    usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
7989                    mapped_at_creation: false,
7990                });
7991                self.geo_instance_capacity = new_cap;
7992                self.geo_object_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
7993                    label: Some("strata_3d_geo_object_bg_grown"),
7994                    layout: &self.geo_object_bind_group_layout,
7995                    entries: &[
7996                        wgpu::BindGroupEntry {
7997                            binding: 0,
7998                            resource: self.camera_buffer.as_entire_binding(),
7999                        },
8000                        wgpu::BindGroupEntry {
8001                            binding: 1,
8002                            resource: self.geo_instance_buffer.as_entire_binding(),
8003                        },
8004                    ],
8005                });
8006            }
8007            self.queue.write_buffer(
8008                &self.geo_instance_buffer,
8009                0,
8010                bytemuck::cast_slice(&staged_geo_instances),
8011            );
8012        }
8013
8014        if !dynamic_draws.is_empty() {
8015            let stride = self.dynamic_uniform_stride as usize;
8016            if dynamic_draws.len() > self.dynamic_uniform_capacity {
8017                let new_cap = dynamic_draws.len().next_power_of_two().max(64);
8018                self.dynamic_uniform_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
8019                    label: Some("strata_3d_dynamic_uniforms_grown"),
8020                    size: (new_cap * stride) as u64,
8021                    usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
8022                    mapped_at_creation: false,
8023                });
8024                self.dynamic_uniform_capacity = new_cap;
8025                self.dynamic_bind_group =
8026                    self.device.create_bind_group(&wgpu::BindGroupDescriptor {
8027                        label: Some("strata_3d_dynamic_bg_grown"),
8028                        layout: &self.dynamic_bind_group_layout,
8029                        entries: &[
8030                            wgpu::BindGroupEntry {
8031                                binding: 0,
8032                                resource: self.camera_buffer.as_entire_binding(),
8033                            },
8034                            wgpu::BindGroupEntry {
8035                                binding: 1,
8036                                resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
8037                                    buffer: &self.dynamic_uniform_buffer,
8038                                    offset: 0,
8039                                    size: std::num::NonZeroU64::new(std::mem::size_of::<
8040                                        GpuDynamicUniforms,
8041                                    >(
8042                                    )
8043                                        as u64),
8044                                }),
8045                            },
8046                        ],
8047                    });
8048            }
8049            let mut staged = vec![0u8; dynamic_draws.len() * stride];
8050            for (i, (_, anchor, color, unlit)) in dynamic_draws.iter().enumerate() {
8051                let (ax_hi, ax_lo) = split_f64_to_f32(anchor[0]);
8052                let (ay_hi, ay_lo) = split_f64_to_f32(anchor[1]);
8053                let (az_hi, az_lo) = split_f64_to_f32(anchor[2]);
8054                let dyn_u = GpuDynamicUniforms {
8055                    anchor_high: [ax_hi, ay_hi, az_hi, 0.0],
8056                    anchor_low: [ax_lo, ay_lo, az_lo, 0.0],
8057                    color: *color,
8058                    dyn_meta: [u32::from(*unlit), 0, 0, 0],
8059                };
8060                let bytes = bytemuck::bytes_of(&dyn_u);
8061                staged[i * stride..i * stride + bytes.len()].copy_from_slice(bytes);
8062            }
8063            self.queue
8064                .write_buffer(&self.dynamic_uniform_buffer, 0, &staged);
8065        }
8066
8067        let mut particle_draws: Vec<(u32, Option<u64>)> = Vec::new();
8068        if let Some(frame) = terrain_frame_opt.as_ref() {
8069            if !frame.particle_layers.is_empty() {
8070                for tex in frame.particle_textures.iter() {
8071                    if tex.width == 0
8072                        || tex.height == 0
8073                        || tex.rgba8.len() < (tex.width as usize) * (tex.height as usize) * 4
8074                    {
8075                        continue;
8076                    }
8077                    let need_upload = match self.particle_textures.get(&tex.id) {
8078                        Some(cached) => {
8079                            cached.revision != tex.revision
8080                                || cached.width != tex.width
8081                                || cached.height != tex.height
8082                        }
8083                        None => true,
8084                    };
8085                    if need_upload {
8086                        let gpu_tex = self.device.create_texture(&wgpu::TextureDescriptor {
8087                            label: Some("strata_3d_particle_sprite_tex"),
8088                            size: wgpu::Extent3d {
8089                                width: tex.width,
8090                                height: tex.height,
8091                                depth_or_array_layers: 1,
8092                            },
8093                            mip_level_count: 1,
8094                            sample_count: 1,
8095                            dimension: wgpu::TextureDimension::D2,
8096                            format: wgpu::TextureFormat::Rgba8Unorm,
8097                            usage: wgpu::TextureUsages::TEXTURE_BINDING
8098                                | wgpu::TextureUsages::COPY_DST,
8099                            view_formats: &[],
8100                        });
8101                        self.queue.write_texture(
8102                            wgpu::TexelCopyTextureInfo {
8103                                texture: &gpu_tex,
8104                                mip_level: 0,
8105                                origin: wgpu::Origin3d::ZERO,
8106                                aspect: wgpu::TextureAspect::All,
8107                            },
8108                            &tex.rgba8[..(tex.width as usize) * (tex.height as usize) * 4],
8109                            wgpu::TexelCopyBufferLayout {
8110                                offset: 0,
8111                                bytes_per_row: Some(tex.width * 4),
8112                                rows_per_image: Some(tex.height),
8113                            },
8114                            wgpu::Extent3d {
8115                                width: tex.width,
8116                                height: tex.height,
8117                                depth_or_array_layers: 1,
8118                            },
8119                        );
8120                        let view = gpu_tex.create_view(&Default::default());
8121                        let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
8122                            label: Some("strata_3d_particle_sprite_bg"),
8123                            layout: &self.particle_tex_bgl,
8124                            entries: &[
8125                                wgpu::BindGroupEntry {
8126                                    binding: 0,
8127                                    resource: wgpu::BindingResource::TextureView(&view),
8128                                },
8129                                wgpu::BindGroupEntry {
8130                                    binding: 1,
8131                                    resource: wgpu::BindingResource::Sampler(
8132                                        &self.particle_sampler,
8133                                    ),
8134                                },
8135                            ],
8136                        });
8137                        self.particle_textures.insert(
8138                            tex.id,
8139                            CachedParticleTexture {
8140                                revision: tex.revision,
8141                                width: tex.width,
8142                                height: tex.height,
8143                                _texture: gpu_tex,
8144                                bind_group: bg,
8145                            },
8146                        );
8147                    }
8148                }
8149
8150                let norm3 = |v: [f32; 3], fallback: [f32; 3]| -> [f32; 3] {
8151                    let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
8152                    if l > 1e-6 {
8153                        [v[0] / l, v[1] / l, v[2] / l]
8154                    } else {
8155                        fallback
8156                    }
8157                };
8158                let cam_right = norm3(
8159                    [cam.view_rot[0][0], cam.view_rot[1][0], cam.view_rot[2][0]],
8160                    [1.0, 0.0, 0.0],
8161                );
8162                let cam_up = norm3(
8163                    [cam.view_rot[0][1], cam.view_rot[1][1], cam.view_rot[2][1]],
8164                    [0.0, 1.0, 0.0],
8165                );
8166                let meters_per_px_at_1m = 2.0 / (vp_h * cam.proj[1][1].abs().max(0.05));
8167
8168                let active_layers: Vec<&RetainedParticleLayer> = frame
8169                    .particle_layers
8170                    .iter()
8171                    .filter(|l| l.particle_count > 0 && l.color[3] > 0.002)
8172                    .collect();
8173                if !active_layers.is_empty() {
8174                    let stride = self.particle_uniform_stride as usize;
8175                    if active_layers.len() > self.particle_uniform_capacity {
8176                        let new_cap = active_layers.len().next_power_of_two().max(16);
8177                        let u_size = std::mem::size_of::<GpuParticleLayerUniforms>() as u64;
8178                        self.particle_uniform_buffer =
8179                            self.device.create_buffer(&wgpu::BufferDescriptor {
8180                                label: Some("strata_3d_particle_uniforms_grown"),
8181                                size: (new_cap * stride) as u64,
8182                                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
8183                                mapped_at_creation: false,
8184                            });
8185                        self.particle_uniform_capacity = new_cap;
8186                        self.particle_common_bind_group =
8187                            self.device.create_bind_group(&wgpu::BindGroupDescriptor {
8188                                label: Some("strata_3d_particle_common_bg_grown"),
8189                                layout: &self.particle_common_bgl,
8190                                entries: &[
8191                                    wgpu::BindGroupEntry {
8192                                        binding: 0,
8193                                        resource: self.camera_buffer.as_entire_binding(),
8194                                    },
8195                                    wgpu::BindGroupEntry {
8196                                        binding: 1,
8197                                        resource: wgpu::BindingResource::Buffer(
8198                                            wgpu::BufferBinding {
8199                                                buffer: &self.particle_uniform_buffer,
8200                                                offset: 0,
8201                                                size: std::num::NonZeroU64::new(u_size),
8202                                            },
8203                                        ),
8204                                    },
8205                                ],
8206                            });
8207                    }
8208                    let mut staged = vec![0u8; active_layers.len() * stride];
8209                    for (i, layer) in active_layers.iter().enumerate() {
8210                        let (sprite_mode, tex_id_opt) = match layer.sprite {
8211                            RetainedParticleSprite::Textured(tid) => (0u32, Some(tid)),
8212                            RetainedParticleSprite::ProceduralStreak => (1u32, None),
8213                            RetainedParticleSprite::ProceduralSnowflake => (2u32, None),
8214                            RetainedParticleSprite::ProceduralPellet => (3u32, None),
8215                            RetainedParticleSprite::ProceduralCurtain => (4u32, None),
8216                        };
8217                        let billboard_mode = match layer.billboard {
8218                            RetainedParticleBillboard::VelocityAligned => 0u32,
8219                            RetainedParticleBillboard::CameraFacing => 1u32,
8220                        };
8221                        let gpu_u = GpuParticleLayerUniforms {
8222                            basis_east: [
8223                                layer.basis_east[0],
8224                                layer.basis_east[1],
8225                                layer.basis_east[2],
8226                                layer.wrapped_phase[0],
8227                            ],
8228                            basis_north: [
8229                                layer.basis_north[0],
8230                                layer.basis_north[1],
8231                                layer.basis_north[2],
8232                                layer.wrapped_phase[1],
8233                            ],
8234                            basis_up: [
8235                                layer.basis_up[0],
8236                                layer.basis_up[1],
8237                                layer.basis_up[2],
8238                                layer.wrapped_phase[2],
8239                            ],
8240                            forward_bias: [
8241                                layer.forward_bias_world[0],
8242                                layer.forward_bias_world[1],
8243                                layer.forward_bias_world[2],
8244                                0.0,
8245                            ],
8246                            cam_right_mpx: [
8247                                cam_right[0],
8248                                cam_right[1],
8249                                cam_right[2],
8250                                meters_per_px_at_1m,
8251                            ],
8252                            cam_up_pad: [cam_up[0], cam_up[1], cam_up[2], 0.0],
8253                            altitude_bounds: layer.altitude_bounds,
8254                            volume_params: layer.volume_params,
8255                            motion_params: layer.motion_params,
8256                            size_params: layer.size_params,
8257                            flutter_clamp: layer.flutter_clamp,
8258                            color: layer.color,
8259                            meta: [sprite_mode, billboard_mode, layer.seed, layer.particle_count],
8260                        };
8261                        let bytes = bytemuck::bytes_of(&gpu_u);
8262                        staged[i * stride..i * stride + bytes.len()].copy_from_slice(bytes);
8263                        particle_draws.push((layer.particle_count, tex_id_opt));
8264                    }
8265                    self.queue
8266                        .write_buffer(&self.particle_uniform_buffer, 0, &staged);
8267                }
8268            }
8269        }
8270
8271        let ocean_opt = terrain_frame_opt.as_ref().and_then(|f| f.ocean.as_deref());
8272        self.sync_shadow_and_ocean_resources(shadows_active, cam.shadow_map_size, ocean_opt);
8273
8274        let topology_batches: Vec<(wgpu::Buffer, u32, std::ops::Range<u32>)> = terrain_batches
8275            .into_iter()
8276            .filter_map(|((g, s), range)| {
8277                let (buf, cnt) = self.ensure_topology(g, s);
8278                if cnt > 0 && !range.is_empty() {
8279                    Some((buf, cnt, range))
8280                } else {
8281                    None
8282                }
8283            })
8284            .collect();
8285        let depth_view = self.ensure_depth_view(target_width.max(1), target_height.max(1));
8286
8287        let clear_op = if !clear_color_target {
8288            wgpu::LoadOp::Load
8289        } else if multi_viewport_mode {
8290            wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
8291        } else {
8292            match cam.background {
8293                Background3D::Transparent => wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
8294                Background3D::Solid(c) => wgpu::LoadOp::Clear(wgpu::Color {
8295                    r: c.r() as f64,
8296                    g: c.g() as f64,
8297                    b: c.b() as f64,
8298                    a: c.a() as f64,
8299                }),
8300                Background3D::VerticalGradient { .. } => wgpu::LoadOp::Clear(wgpu::Color::BLACK),
8301            }
8302        };
8303
8304        let tp_pass = std::time::Instant::now();
8305        let ts_slot = self
8306            .timestamp_profiler
8307            .as_mut()
8308            .and_then(|p| p.acquire_idle_slot(&self.device));
8309        let mut encoder = self
8310            .device
8311            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
8312                label: Some("strata_3d_render_encoder"),
8313            });
8314
8315        // Opt-in directional shadow map pass for 2.5D mountains & opaque 3D objects (0.00 ms when off).
8316        let mut wrote_shadow_ts = false;
8317        if shadows_active && (draw_count > 0 || !geo_opaque_batches.is_empty()) {
8318            if let Some((_, _, ref shadow_view)) = self.shadow_target {
8319                let shadow_ts = ts_slot.and_then(|slot_idx| {
8320                    self.timestamp_profiler.as_ref().map(|p| {
8321                        wrote_shadow_ts = true;
8322                        wgpu::RenderPassTimestampWrites {
8323                            query_set: &p.slots[slot_idx].query_set,
8324                            beginning_of_pass_write_index: Some(0),
8325                            end_of_pass_write_index: Some(1),
8326                        }
8327                    })
8328                });
8329                let mut spass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
8330                    label: Some("strata_3d_shadow_pass"),
8331                    color_attachments: &[],
8332                    depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
8333                        view: shadow_view,
8334                        depth_ops: Some(wgpu::Operations {
8335                            load: wgpu::LoadOp::Clear(1.0),
8336                            store: wgpu::StoreOp::Store,
8337                        }),
8338                        stencil_ops: None,
8339                    }),
8340                    timestamp_writes: shadow_ts,
8341                    occlusion_query_set: None,
8342                });
8343                if !topology_batches.is_empty() {
8344                    spass.set_pipeline(&self.terrain_shadow_pipeline);
8345                    spass.set_bind_group(0, &self.terrain_bind_group, &[]);
8346                    for (idx_buf, idx_count, range) in &topology_batches {
8347                        spass.set_index_buffer(idx_buf.slice(..), wgpu::IndexFormat::Uint32);
8348                        spass.draw_indexed(0..*idx_count, 0, range.clone());
8349                    }
8350                }
8351                if !geo_opaque_batches.is_empty() {
8352                    spass.set_pipeline(&self.geo_shadow_pipeline);
8353                    spass.set_bind_group(0, &self.geo_object_bind_group, &[]);
8354                    for (mesh_id, _, range) in &geo_opaque_batches {
8355                        let Some(gpu_mesh) = self.geo_meshes.get(mesh_id) else {
8356                            continue;
8357                        };
8358                        spass.set_vertex_buffer(0, gpu_mesh.vbuf.slice(..));
8359                        spass.set_index_buffer(gpu_mesh.ibuf.slice(..), wgpu::IndexFormat::Uint32);
8360                        spass.draw_indexed(0..gpu_mesh.index_count, 0, range.clone());
8361                    }
8362                }
8363            }
8364        }
8365
8366        {
8367            let main_ts = ts_slot.and_then(|slot_idx| {
8368                self.timestamp_profiler.as_ref().map(|p| {
8369                    wgpu::RenderPassTimestampWrites {
8370                        query_set: &p.slots[slot_idx].query_set,
8371                        beginning_of_pass_write_index: Some(2),
8372                        end_of_pass_write_index: Some(3),
8373                    }
8374                })
8375            });
8376            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
8377                label: Some("strata_3d_main_pass"),
8378                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
8379                    view: target_view,
8380                    resolve_target: None,
8381                    ops: wgpu::Operations {
8382                        load: clear_op,
8383                        store: wgpu::StoreOp::Store,
8384                    },
8385                })],
8386                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
8387                    view: &depth_view,
8388                    depth_ops: Some(wgpu::Operations {
8389                        load: wgpu::LoadOp::Clear(1.0),
8390                        store: wgpu::StoreOp::Discard,
8391                    }),
8392                    stencil_ops: None,
8393                }),
8394                timestamp_writes: main_ts,
8395                occlusion_query_set: None,
8396            });
8397
8398            if let Some([vx, vy, vw, vh]) = viewport {
8399                let x = vx.max(0.0).min((target_width.saturating_sub(1)) as f32);
8400                let y = vy.max(0.0).min((target_height.saturating_sub(1)) as f32);
8401                let max_w = (target_width as f32 - x).max(1.0);
8402                let max_h = (target_height as f32 - y).max(1.0);
8403                let w = vw.max(1.0).min(max_w);
8404                let h = vh.max(1.0).min(max_h);
8405                let xi = (x.floor() as u32).min(target_width.saturating_sub(1));
8406                let yi = (y.floor() as u32).min(target_height.saturating_sub(1));
8407                let wi = (w.round() as u32)
8408                    .max(1)
8409                    .min(target_width.saturating_sub(xi).max(1));
8410                let hi = (h.round() as u32)
8411                    .max(1)
8412                    .min(target_height.saturating_sub(yi).max(1));
8413                pass.set_viewport(x, y, w, h, 0.0, 1.0);
8414                pass.set_scissor_rect(xi, yi, wi, hi);
8415            }
8416
8417            let terrain_first = draw_count > 0
8418                && all_terrain_opaque
8419                && !matches!(cam.background, Background3D::Transparent);
8420
8421            if terrain_first && !topology_batches.is_empty() {
8422                pass.set_pipeline(&self.terrain_opaque_pipeline);
8423                pass.set_bind_group(0, &self.terrain_bind_group, &[]);
8424                pass.set_bind_group(1, &self.shadow_ocean_bind_group, &[]);
8425                for (idx_buf, idx_count, range) in &topology_batches {
8426                    pass.set_index_buffer(idx_buf.slice(..), wgpu::IndexFormat::Uint32);
8427                    pass.draw_indexed(0..*idx_count, 0, range.clone());
8428                }
8429            }
8430
8431            let need_scissored_solid_bg = (multi_viewport_mode || !clear_color_target)
8432                && matches!(cam.background, Background3D::Solid(_));
8433            if need_scissored_solid_bg
8434                || matches!(cam.background, Background3D::VerticalGradient { .. })
8435                || cam.stars_visible
8436                || cam.sun_visible
8437                || cam.moon_visible
8438                || cam.realistic_25d_sky > 0.001
8439            {
8440                let grad_opaque = match cam.background {
8441                    Background3D::VerticalGradient { top, bottom } => {
8442                        (multi_viewport_mode || !clear_color_target)
8443                            && top.a() >= 0.999
8444                            && bottom.a() >= 0.999
8445                    }
8446                    Background3D::Solid(c) => c.a() >= 0.999,
8447                    Background3D::Transparent => false,
8448                };
8449                let sky_opaque = grad_opaque
8450                    || cam.stars_visible
8451                    || cam.sun_visible
8452                    || cam.moon_visible
8453                    || cam.realistic_25d_sky > 0.001;
8454                pass.set_pipeline(if sky_opaque {
8455                    &self.sky_opaque_pipeline
8456                } else {
8457                    &self.sky_pipeline
8458                });
8459                pass.set_bind_group(0, &self.sky_bind_group, &[]);
8460                pass.draw(0..3, 0..1);
8461            }
8462
8463            if cam.stars_visible
8464                && cam.stars_intensity > 0.001
8465                && self.env_state.star_count > 0
8466                && (cam.local_25d_blend < 0.85 || cam.night_stars_25d > 0.001)
8467            {
8468                pass.set_pipeline(&self.star_pipeline);
8469                pass.set_bind_group(0, &self.star_bind_group, &[]);
8470                pass.draw(0..6, 0..self.env_state.star_count);
8471            }
8472
8473            if !terrain_first && !topology_batches.is_empty() {
8474                pass.set_pipeline(&self.terrain_pipeline);
8475                pass.set_bind_group(0, &self.terrain_bind_group, &[]);
8476                pass.set_bind_group(1, &self.shadow_ocean_bind_group, &[]);
8477                for (idx_buf, idx_count, range) in &topology_batches {
8478                    pass.set_index_buffer(idx_buf.slice(..), wgpu::IndexFormat::Uint32);
8479                    pass.draw_indexed(0..*idx_count, 0, range.clone());
8480                }
8481            }
8482
8483            if !geo_opaque_batches.is_empty() {
8484                pass.set_pipeline(&self.geo_object_pipeline);
8485                pass.set_bind_group(0, &self.geo_object_bind_group, &[]);
8486                pass.set_bind_group(1, &self.shadow_ocean_bind_group, &[]);
8487                for (mesh_id, tex_id_opt, range) in &geo_opaque_batches {
8488                    let Some(gpu_mesh) = self.geo_meshes.get(mesh_id) else {
8489                        continue;
8490                    };
8491                    let tex_bg = tex_id_opt
8492                        .and_then(|tid| self.geo_textures.get(&tid))
8493                        .map(|t| &t.bind_group)
8494                        .unwrap_or(&self.geo_default_tex_bg);
8495                    pass.set_bind_group(2, tex_bg, &[]);
8496                    pass.set_vertex_buffer(0, gpu_mesh.vbuf.slice(..));
8497                    pass.set_index_buffer(gpu_mesh.ibuf.slice(..), wgpu::IndexFormat::Uint32);
8498                    pass.draw_indexed(0..gpu_mesh.index_count, 0, range.clone());
8499                }
8500            }
8501
8502            if (cam.cloud_layer_opacity > 0.004 || cam.local_cloud_opacity > 0.004)
8503                && self.cloud_index_count > 0
8504            {
8505                let eye_r2 = cam.eye_ecef[0] * cam.eye_ecef[0]
8506                    + cam.eye_ecef[1] * cam.eye_ecef[1]
8507                    + cam.eye_ecef[2] * cam.eye_ecef[2];
8508                let cloud_pl = if eye_r2 > 6_396_000.0 * 6_396_000.0 {
8509                    &self.cloud_pipeline
8510                } else if eye_r2 < 6_390_000.0 * 6_390_000.0 {
8511                    &self.cloud_inside_pipeline
8512                } else {
8513                    &self.cloud_twosided_pipeline
8514                };
8515                pass.set_pipeline(cloud_pl);
8516                pass.set_bind_group(0, &self.cloud_bind_group, &[]);
8517                pass.set_vertex_buffer(0, self.cloud_vbuf.slice(..));
8518                pass.set_index_buffer(self.cloud_ibuf.slice(..), wgpu::IndexFormat::Uint32);
8519                pass.draw_indexed(0..self.cloud_index_count, 0, 0..1);
8520            }
8521
8522            if !dynamic_draws.is_empty() {
8523                pass.set_pipeline(&self.dynamic_pipeline);
8524                for (i, (id, _, _, _)) in dynamic_draws.iter().enumerate() {
8525                    let Some(gpu_mesh) = self.dynamic_meshes.get(id) else {
8526                        continue;
8527                    };
8528                    let offset = (i as u32) * self.dynamic_uniform_stride;
8529                    pass.set_bind_group(0, &self.dynamic_bind_group, &[offset]);
8530                    pass.set_vertex_buffer(0, gpu_mesh.vbuf.slice(..));
8531                    pass.set_index_buffer(gpu_mesh.ibuf.slice(..), wgpu::IndexFormat::Uint32);
8532                    pass.draw_indexed(0..gpu_mesh.index_count, 0, 0..1);
8533                }
8534            }
8535
8536            if !geo_transparent_batches.is_empty() {
8537                pass.set_pipeline(&self.geo_object_transparent_pipeline);
8538                pass.set_bind_group(0, &self.geo_object_bind_group, &[]);
8539                pass.set_bind_group(1, &self.shadow_ocean_bind_group, &[]);
8540                for (mesh_id, tex_id_opt, range) in &geo_transparent_batches {
8541                    let Some(gpu_mesh) = self.geo_meshes.get(mesh_id) else {
8542                        continue;
8543                    };
8544                    let tex_bg = tex_id_opt
8545                        .and_then(|tid| self.geo_textures.get(&tid))
8546                        .map(|t| &t.bind_group)
8547                        .unwrap_or(&self.geo_default_tex_bg);
8548                    pass.set_bind_group(2, tex_bg, &[]);
8549                    pass.set_vertex_buffer(0, gpu_mesh.vbuf.slice(..));
8550                    pass.set_index_buffer(gpu_mesh.ibuf.slice(..), wgpu::IndexFormat::Uint32);
8551                    pass.draw_indexed(0..gpu_mesh.index_count, 0, range.clone());
8552                }
8553            }
8554
8555            if !particle_draws.is_empty() {
8556                pass.set_pipeline(&self.particle_pipeline);
8557                for (i, (count, tex_id_opt)) in particle_draws.iter().enumerate() {
8558                    let offset = (i as u32) * self.particle_uniform_stride;
8559                    pass.set_bind_group(0, &self.particle_common_bind_group, &[offset]);
8560                    let tex_bg = tex_id_opt
8561                        .and_then(|tid| self.particle_textures.get(&tid))
8562                        .map(|c| &c.bind_group)
8563                        .unwrap_or(&self.particle_default_tex_bg);
8564                    pass.set_bind_group(1, tex_bg, &[]);
8565                    pass.draw(0..6, 0..*count);
8566                }
8567            }
8568
8569            if let Some(ov_bg) = overlay_bind_group {
8570                if viewport.is_some() {
8571                    let tw = target_width.max(1);
8572                    let th = target_height.max(1);
8573                    pass.set_viewport(0.0, 0.0, tw as f32, th as f32, 0.0, 1.0);
8574                    pass.set_scissor_rect(0, 0, tw, th);
8575                }
8576                pass.set_pipeline(&self.overlay_main_pass_pipeline);
8577                pass.set_bind_group(0, ov_bg, &[]);
8578                pass.draw(0..3, 0..1);
8579            }
8580        }
8581        let tp_sub = std::time::Instant::now();
8582        if let (Some(slot_idx), Some(ref mut profiler)) = (ts_slot, self.timestamp_profiler.as_mut())
8583        {
8584            profiler.slots[slot_idx].wrote_shadow = wrote_shadow_ts;
8585            profiler.slots[slot_idx].wrote_main = true;
8586            profiler.resolve_and_copy(slot_idx, &mut encoder);
8587        }
8588        self.queue.submit(Some(encoder.finish()));
8589        if let (Some(slot_idx), Some(ref mut profiler)) = (ts_slot, self.timestamp_profiler.as_mut())
8590        {
8591            profiler.begin_async_map(slot_idx);
8592        }
8593        if perf {
8594            let tot = t_start.elapsed().as_secs_f64() * 1000.0;
8595            if tot > 3.0 {
8596                eprintln!(
8597                    "[perf] render_scene_to_view tot={:.2}ms (env={:.2} slab={:.2} atlas={:.2} inst={:.2} dyn={:.2} rec={:.2} sub={:.2})",
8598                    tot,
8599                    t_env,
8600                    t_slab,
8601                    t_atlas,
8602                    t_inst,
8603                    t_dyn,
8604                    tp_sub.duration_since(tp_pass).as_secs_f64() * 1000.0,
8605                    tp_sub.elapsed().as_secs_f64() * 1000.0
8606                );
8607            }
8608        }
8609    }
8610
8611    fn record_overlay_pass(
8612        &self,
8613        encoder: &mut wgpu::CommandEncoder,
8614        target_view: &wgpu::TextureView,
8615        overlay_bind_group: &wgpu::BindGroup,
8616    ) {
8617        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
8618            label: Some("strata_2d_overlay_pass"),
8619            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
8620                view: target_view,
8621                resolve_target: None,
8622                ops: wgpu::Operations {
8623                    load: wgpu::LoadOp::Load,
8624                    store: wgpu::StoreOp::Store,
8625                },
8626            })],
8627            depth_stencil_attachment: None,
8628            timestamp_writes: None,
8629            occlusion_query_set: None,
8630        });
8631        pass.set_pipeline(&self.overlay_pipeline);
8632        pass.set_bind_group(0, overlay_bind_group, &[]);
8633        pass.draw(0..3, 0..1);
8634    }
8635
8636    /// Composites a GPU 2D UI HUD overlay bind group on top of `target_view` (preserving alpha).
8637    pub fn composite_overlay_to_view(
8638        &self,
8639        target_view: &wgpu::TextureView,
8640        overlay_bind_group: &wgpu::BindGroup,
8641    ) {
8642        let mut encoder = self
8643            .device
8644            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
8645                label: Some("strata_2d_overlay_encoder"),
8646            });
8647        self.record_overlay_pass(&mut encoder, target_view, overlay_bind_group);
8648        self.queue.submit(Some(encoder.finish()));
8649    }
8650
8651    /// Blits a cached offscreen 3D scene color attachment into `target_view` and composites
8652    /// an optional 2D UI overlay on top in a single lightweight fullscreen render pass.
8653    pub fn composite_cached_scene_and_overlay_to_view(
8654        &mut self,
8655        target_view: &wgpu::TextureView,
8656        cached_scene_bind_group: &wgpu::BindGroup,
8657        overlay_bind_group: Option<&wgpu::BindGroup>,
8658    ) {
8659        let ts_slot = self
8660            .timestamp_profiler
8661            .as_mut()
8662            .and_then(|p| p.acquire_idle_slot(&self.device));
8663        let mut encoder = self
8664            .device
8665            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
8666                label: Some("strata_cached_3d_composite_encoder"),
8667            });
8668        {
8669            let ov_ts = ts_slot.and_then(|slot_idx| {
8670                self.timestamp_profiler.as_ref().map(|p| {
8671                    wgpu::RenderPassTimestampWrites {
8672                        query_set: &p.slots[slot_idx].query_set,
8673                        beginning_of_pass_write_index: Some(4),
8674                        end_of_pass_write_index: Some(5),
8675                    }
8676                })
8677            });
8678            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
8679                label: Some("strata_cached_3d_composite_pass"),
8680                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
8681                    view: target_view,
8682                    resolve_target: None,
8683                    ops: wgpu::Operations {
8684                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
8685                        store: wgpu::StoreOp::Store,
8686                    },
8687                })],
8688                depth_stencil_attachment: None,
8689                timestamp_writes: ov_ts,
8690                occlusion_query_set: None,
8691            });
8692            pass.set_pipeline(&self.scene_blit_pipeline);
8693            pass.set_bind_group(0, cached_scene_bind_group, &[]);
8694            pass.draw(0..3, 0..1);
8695            if let Some(ov_bg) = overlay_bind_group {
8696                pass.set_pipeline(&self.overlay_pipeline);
8697                pass.set_bind_group(0, ov_bg, &[]);
8698                pass.draw(0..3, 0..1);
8699            }
8700        }
8701        if let (Some(slot_idx), Some(ref mut profiler)) = (ts_slot, self.timestamp_profiler.as_mut())
8702        {
8703            profiler.slots[slot_idx].wrote_overlay = true;
8704            profiler.resolve_and_copy(slot_idx, &mut encoder);
8705        }
8706        self.queue.submit(Some(encoder.finish()));
8707        if let (Some(slot_idx), Some(ref mut profiler)) = (ts_slot, self.timestamp_profiler.as_mut())
8708        {
8709            profiler.begin_async_map(slot_idx);
8710        }
8711    }
8712
8713    /// Renders `scene` into a persistent offscreen texture and performs GPU->CPU readback only
8714    /// when `readback` is `true` (pure GPU timing benchmarks pass `readback = false`).
8715    pub fn render_offscreen(
8716        &mut self,
8717        scene: &Scene3D,
8718        width: u32,
8719        height: u32,
8720        readback: bool,
8721        unlimited_upload_budget: bool,
8722    ) -> Result<Vec<u8>, String> {
8723        let w = width.max(1);
8724        let h = height.max(1);
8725        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
8726        let unpadded = w * 4;
8727        let padded = unpadded.div_ceil(align) * align;
8728
8729        let recreate = self
8730            .offscreen
8731            .as_ref()
8732            .map(|o| o.width != w || o.height != h || o.format != self.color_format)
8733            .unwrap_or(true);
8734        if recreate {
8735            let color = self.device.create_texture(&wgpu::TextureDescriptor {
8736                label: Some("strata_3d_offscreen_color"),
8737                size: wgpu::Extent3d {
8738                    width: w,
8739                    height: h,
8740                    depth_or_array_layers: 1,
8741                },
8742                mip_level_count: 1,
8743                sample_count: 1,
8744                dimension: wgpu::TextureDimension::D2,
8745                format: self.color_format,
8746                usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
8747                view_formats: &[],
8748            });
8749            let color_view = color.create_view(&Default::default());
8750            let depth = self.device.create_texture(&wgpu::TextureDescriptor {
8751                label: Some("strata_3d_offscreen_depth"),
8752                size: wgpu::Extent3d {
8753                    width: w,
8754                    height: h,
8755                    depth_or_array_layers: 1,
8756                },
8757                mip_level_count: 1,
8758                sample_count: 1,
8759                dimension: wgpu::TextureDimension::D2,
8760                format: wgpu::TextureFormat::Depth32Float,
8761                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
8762                view_formats: &[],
8763            });
8764            let depth_view = depth.create_view(&Default::default());
8765            let rb = self.device.create_buffer(&wgpu::BufferDescriptor {
8766                label: Some("strata_3d_offscreen_readback"),
8767                size: (padded * h) as u64,
8768                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
8769                mapped_at_creation: false,
8770            });
8771            self.offscreen = Some(OffscreenTarget {
8772                width: w,
8773                height: h,
8774                format: self.color_format,
8775                color,
8776                color_view,
8777                _depth: depth,
8778                depth_view,
8779                readback: rb,
8780                padded_bytes_per_row: padded,
8781            });
8782        }
8783
8784        let target_view = self.offscreen.as_ref().unwrap().color_view.clone();
8785        self.depth_target = Some((w, h, self.offscreen.as_ref().unwrap().depth_view.clone()));
8786        self.render_scene_to_view(scene, &target_view, w, h, None, unlimited_upload_budget);
8787
8788        if !readback {
8789            self.device.poll(wgpu::Maintain::Wait);
8790            return Ok(Vec::new());
8791        }
8792
8793        let off = self.offscreen.as_ref().unwrap();
8794        let mut enc = self
8795            .device
8796            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
8797                label: Some("strata_3d_readback_encoder"),
8798            });
8799        enc.copy_texture_to_buffer(
8800            wgpu::TexelCopyTextureInfo {
8801                texture: &off.color,
8802                mip_level: 0,
8803                origin: wgpu::Origin3d::ZERO,
8804                aspect: wgpu::TextureAspect::All,
8805            },
8806            wgpu::TexelCopyBufferInfo {
8807                buffer: &off.readback,
8808                layout: wgpu::TexelCopyBufferLayout {
8809                    offset: 0,
8810                    bytes_per_row: Some(off.padded_bytes_per_row),
8811                    rows_per_image: Some(h),
8812                },
8813            },
8814            wgpu::Extent3d {
8815                width: w,
8816                height: h,
8817                depth_or_array_layers: 1,
8818            },
8819        );
8820        self.queue.submit(Some(enc.finish()));
8821
8822        let slice = off.readback.slice(..);
8823        let (tx, rx) = std::sync::mpsc::channel();
8824        slice.map_async(wgpu::MapMode::Read, move |res| {
8825            let _ = tx.send(res);
8826        });
8827        self.device.poll(wgpu::Maintain::Wait);
8828        rx.recv()
8829            .map_err(|e| format!("readback recv error: {e}"))?
8830            .map_err(|e| format!("readback map error: {e:?}"))?;
8831
8832        let data = slice.get_mapped_range();
8833        let mut out = vec![0u8; (w * h * 4) as usize];
8834        for row in 0..h as usize {
8835            let src_start = row * off.padded_bytes_per_row as usize;
8836            let dst_start = row * (w as usize * 4);
8837            out[dst_start..dst_start + w as usize * 4]
8838                .copy_from_slice(&data[src_start..src_start + w as usize * 4]);
8839        }
8840        drop(data);
8841        off.readback.unmap();
8842        Ok(out)
8843    }
8844}
8845
8846/// Converts a regular [`Scene3D`] (primitives/custom meshes) into a [`RetainedTerrainFrame`]
8847/// so standard 3D scenes also accelerate seamlessly through [`Wgpu3DRenderer`].
8848pub fn fallback_frame_from_scene3d(
8849    scene: &Scene3D,
8850    viewport_w: f32,
8851    viewport_h: f32,
8852) -> RetainedTerrainFrame {
8853    let camera = retained_camera_from_scene3d(scene, viewport_w, viewport_h);
8854    let mut dynamic_meshes = Vec::new();
8855    for (idx, mesh) in scene.meshes.iter().enumerate() {
8856        if let Some((verts, inds, color, unlit)) = mesh3d_to_rte(mesh) {
8857            dynamic_meshes.push(RetainedDynamicMesh {
8858                id: idx as u64 + 1,
8859                revision: 1,
8860                anchor_ecef: [
8861                    mesh.transform.position[0] as f64,
8862                    mesh.transform.position[1] as f64,
8863                    mesh.transform.position[2] as f64,
8864                ],
8865                vertices: Arc::new(verts),
8866                indices: Arc::new(inds),
8867                color,
8868                unlit,
8869            });
8870        }
8871    }
8872    RetainedTerrainFrame {
8873        camera,
8874        geometry_revision: 1,
8875        meshes: Vec::new(),
8876        instances: Vec::new(),
8877        textures: Vec::new(),
8878        dynamic_meshes,
8879        ..Default::default()
8880    }
8881}
8882
8883fn retained_camera_from_scene3d(
8884    scene: &Scene3D,
8885    width: f32,
8886    height: f32,
8887) -> RetainedCameraUniforms {
8888    let aspect = (width.max(1.0) / height.max(1.0)).max(0.01);
8889    let (eye, target, proj) = match scene.camera {
8890        Camera3D::Perspective {
8891            fov_horizontal_deg,
8892            near,
8893            far,
8894            position,
8895            target,
8896        } => {
8897            let hfov_rad = fov_horizontal_deg.to_radians().max(0.05);
8898            let half_w = (hfov_rad * 0.5).tan();
8899            let vfov_rad = 2.0 * (half_w / aspect).atan();
8900            (
8901                position,
8902                target,
8903                perspective_rh_zo(vfov_rad, aspect, near.max(0.01), far.max(near + 1.0)),
8904            )
8905        }
8906        Camera3D::Orthographic {
8907            left,
8908            right,
8909            top,
8910            bottom,
8911            near,
8912            far,
8913            position,
8914            target,
8915        } => (
8916            position,
8917            target,
8918            ortho_rh_zo(left, right, bottom, top, near, far),
8919        ),
8920    };
8921
8922    let up_hint = scene.camera_up().unwrap_or([0.0, 1.0, 0.0]);
8923    let view_rot = look_rot_rh(eye, target, up_hint);
8924    let view_proj_rte = mul_mat4(proj, view_rot);
8925
8926    let mut sun_dir = [0.577_350_26f32, 0.577_350_26, 0.577_350_26];
8927    let mut sun_color = [1.0f32, 0.98, 0.95];
8928    let mut ambient_color = [0.22f32, 0.24, 0.28];
8929    for light in &scene.lights {
8930        match light {
8931            Light3D::Ambient { color, intensity } => {
8932                ambient_color = [
8933                    color.r() * intensity,
8934                    color.g() * intensity,
8935                    color.b() * intensity,
8936                ];
8937            }
8938            Light3D::Directional {
8939                position,
8940                color,
8941                intensity,
8942                ..
8943            } => {
8944                let len = (position[0] * position[0]
8945                    + position[1] * position[1]
8946                    + position[2] * position[2])
8947                    .sqrt()
8948                    .max(1e-6);
8949                sun_dir = [position[0] / len, position[1] / len, position[2] / len];
8950                sun_color = [
8951                    color.r() * intensity,
8952                    color.g() * intensity,
8953                    color.b() * intensity,
8954                ];
8955            }
8956            Light3D::Point { .. } => {}
8957        }
8958    }
8959
8960    RetainedCameraUniforms {
8961        proj,
8962        view_rot,
8963        view_proj_rte,
8964        eye_ecef: [eye[0] as f64, eye[1] as f64, eye[2] as f64],
8965        sun_dir,
8966        sun_color,
8967        ambient_color,
8968        background: scene.background(),
8969        near: 0.1,
8970        far: 100_000_000.0,
8971        ..Default::default()
8972    }
8973}
8974
8975fn perspective_rh_zo(vfov_rad: f32, aspect: f32, near: f32, far: f32) -> [[f32; 4]; 4] {
8976    let f = 1.0 / (vfov_rad * 0.5).tan();
8977    let nf = 1.0 / (near - far);
8978    [
8979        [f / aspect, 0.0, 0.0, 0.0],
8980        [0.0, f, 0.0, 0.0],
8981        [0.0, 0.0, far * nf, -1.0],
8982        [0.0, 0.0, (far * near) * nf, 0.0],
8983    ]
8984}
8985
8986fn ortho_rh_zo(l: f32, r: f32, b: f32, t: f32, n: f32, f: f32) -> [[f32; 4]; 4] {
8987    let rml = (r - l).max(1e-5);
8988    let tmb = (t - b).max(1e-5);
8989    let fmn = (f - n).max(1e-5);
8990    [
8991        [2.0 / rml, 0.0, 0.0, 0.0],
8992        [0.0, 2.0 / tmb, 0.0, 0.0],
8993        [0.0, 0.0, -1.0 / fmn, 0.0],
8994        [-(r + l) / rml, -(t + b) / tmb, -n / fmn, 1.0],
8995    ]
8996}
8997
8998fn look_rot_rh(eye: [f32; 3], target: [f32; 3], up_hint: [f64; 3]) -> [[f32; 4]; 4] {
8999    let fx = (target[0] - eye[0]) as f64;
9000    let fy = (target[1] - eye[1]) as f64;
9001    let fz = (target[2] - eye[2]) as f64;
9002    let flen = (fx * fx + fy * fy + fz * fz).sqrt().max(1e-9);
9003    let f = [fx / flen, fy / flen, fz / flen];
9004    let mut s = [
9005        f[1] * up_hint[2] - f[2] * up_hint[1],
9006        f[2] * up_hint[0] - f[0] * up_hint[2],
9007        f[0] * up_hint[1] - f[1] * up_hint[0],
9008    ];
9009    let mut slen = (s[0] * s[0] + s[1] * s[1] + s[2] * s[2]).sqrt();
9010    if slen < 1e-6 {
9011        let alt = if f[1].abs() < 0.9 {
9012            [0.0, 1.0, 0.0]
9013        } else {
9014            [1.0, 0.0, 0.0]
9015        };
9016        s = [
9017            f[1] * alt[2] - f[2] * alt[1],
9018            f[2] * alt[0] - f[0] * alt[2],
9019            f[0] * alt[1] - f[1] * alt[0],
9020        ];
9021        slen = (s[0] * s[0] + s[1] * s[1] + s[2] * s[2]).sqrt().max(1e-9);
9022    }
9023    let s = [s[0] / slen, s[1] / slen, s[2] / slen];
9024    let u = [
9025        s[1] * f[2] - s[2] * f[1],
9026        s[2] * f[0] - s[0] * f[2],
9027        s[0] * f[1] - s[1] * f[0],
9028    ];
9029    [
9030        [s[0] as f32, u[0] as f32, -f[0] as f32, 0.0],
9031        [s[1] as f32, u[1] as f32, -f[1] as f32, 0.0],
9032        [s[2] as f32, u[2] as f32, -f[2] as f32, 0.0],
9033        [0.0, 0.0, 0.0, 1.0],
9034    ]
9035}
9036
9037fn mul_mat4(a: [[f32; 4]; 4], b: [[f32; 4]; 4]) -> [[f32; 4]; 4] {
9038    let mut out = [[0.0f32; 4]; 4];
9039    for c in 0..4 {
9040        for r in 0..4 {
9041            out[c][r] =
9042                a[0][r] * b[c][0] + a[1][r] * b[c][1] + a[2][r] * b[c][2] + a[3][r] * b[c][3];
9043        }
9044    }
9045    out
9046}
9047
9048fn mesh3d_to_rte(mesh: &Mesh3D) -> Option<(Vec<RteTileVertex>, Vec<u32>, [f32; 4], bool)> {
9049    let (color, unlit) = match &mesh.material {
9050        Material3D::Standard { color, .. } | Material3D::Physical { color, .. } => {
9051            ([color.r(), color.g(), color.b(), color.a()], false)
9052        }
9053        Material3D::Basic { color } => ([color.r(), color.g(), color.b(), color.a()], true),
9054        Material3D::Textured(tm) => (
9055            [
9056                tm.tint.r(),
9057                tm.tint.g(),
9058                tm.tint.b(),
9059                tm.tint.a() * tm.opacity,
9060            ],
9061            !tm.lit,
9062        ),
9063        Material3D::TexturedBatch(tb) => {
9064            let tint = tb
9065                .draws
9066                .first()
9067                .map(|d| d.material.tint)
9068                .unwrap_or(strata_style::Color::WHITE);
9069            ([tint.r(), tint.g(), tint.b(), tint.a()], false)
9070        }
9071        Material3D::Shader { .. } => ([0.8, 0.8, 0.8, 1.0], false),
9072    };
9073
9074    let scale = mesh.transform.scale;
9075    let map_pos = |x: f32, y: f32, z: f32| [x * scale[0], y * scale[1], z * scale[2]];
9076
9077    match &mesh.geometry {
9078        Geometry3D::Custom { vertices, indices } => {
9079            let mut out_v = Vec::with_capacity(vertices.len() / 6);
9080            for chunk in vertices.chunks_exact(6) {
9081                out_v.push(RteTileVertex::new(
9082                    map_pos(chunk[0], chunk[1], chunk[2]),
9083                    [chunk[3], chunk[4], chunk[5]],
9084                    [0.0, 0.0],
9085                ));
9086            }
9087            Some((out_v, indices.clone(), color, unlit))
9088        }
9089        Geometry3D::CustomTextured { vertices, indices } => {
9090            let mut out_v = Vec::with_capacity(vertices.len() / 8);
9091            for chunk in vertices.chunks_exact(8) {
9092                out_v.push(RteTileVertex::new(
9093                    map_pos(chunk[0], chunk[1], chunk[2]),
9094                    [chunk[3], chunk[4], chunk[5]],
9095                    [chunk[6], chunk[7]],
9096                ));
9097            }
9098            Some((out_v, indices.clone(), color, unlit))
9099        }
9100        Geometry3D::Box {
9101            width,
9102            height,
9103            depth,
9104        } => {
9105            let hw = width * 0.5;
9106            let hh = height * 0.5;
9107            let hd = depth * 0.5;
9108            let corners = [
9109                [-hw, -hh, -hd],
9110                [hw, -hh, -hd],
9111                [hw, hh, -hd],
9112                [-hw, hh, -hd],
9113                [-hw, -hh, hd],
9114                [hw, -hh, hd],
9115                [hw, hh, hd],
9116                [-hw, hh, hd],
9117            ];
9118            let faces: [([usize; 4], [f32; 3]); 6] = [
9119                ([4, 5, 6, 7], [0.0, 0.0, 1.0]),
9120                ([1, 0, 3, 2], [0.0, 0.0, -1.0]),
9121                ([5, 1, 2, 6], [1.0, 0.0, 0.0]),
9122                ([0, 4, 7, 3], [-1.0, 0.0, 0.0]),
9123                ([7, 6, 2, 3], [0.0, 1.0, 0.0]),
9124                ([0, 1, 5, 4], [0.0, -1.0, 0.0]),
9125            ];
9126            let mut verts = Vec::with_capacity(24);
9127            let mut inds = Vec::with_capacity(36);
9128            for (f_idx, (c, n)) in faces.into_iter().enumerate() {
9129                let b = (f_idx * 4) as u32;
9130                verts.push(RteTileVertex::new(
9131                    map_pos(corners[c[0]][0], corners[c[0]][1], corners[c[0]][2]),
9132                    n,
9133                    [0.0, 0.0],
9134                ));
9135                verts.push(RteTileVertex::new(
9136                    map_pos(corners[c[1]][0], corners[c[1]][1], corners[c[1]][2]),
9137                    n,
9138                    [1.0, 0.0],
9139                ));
9140                verts.push(RteTileVertex::new(
9141                    map_pos(corners[c[2]][0], corners[c[2]][1], corners[c[2]][2]),
9142                    n,
9143                    [1.0, 1.0],
9144                ));
9145                verts.push(RteTileVertex::new(
9146                    map_pos(corners[c[3]][0], corners[c[3]][1], corners[c[3]][2]),
9147                    n,
9148                    [0.0, 1.0],
9149                ));
9150                inds.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]);
9151            }
9152            Some((verts, inds, color, unlit))
9153        }
9154        Geometry3D::Plane { width, height } => {
9155            let hw = width * 0.5;
9156            let hh = height * 0.5;
9157            let verts = vec![
9158                RteTileVertex::new(map_pos(-hw, 0.0, -hh), [0.0, 1.0, 0.0], [0.0, 0.0]),
9159                RteTileVertex::new(map_pos(hw, 0.0, -hh), [0.0, 1.0, 0.0], [1.0, 0.0]),
9160                RteTileVertex::new(map_pos(hw, 0.0, hh), [0.0, 1.0, 0.0], [1.0, 1.0]),
9161                RteTileVertex::new(map_pos(-hw, 0.0, hh), [0.0, 1.0, 0.0], [0.0, 1.0]),
9162            ];
9163            Some((verts, vec![0, 1, 2, 0, 2, 3], color, unlit))
9164        }
9165        Geometry3D::Sphere {
9166            radius,
9167            width_segments,
9168            height_segments,
9169        } => {
9170            let ws = (*width_segments).max(6);
9171            let hs = (*height_segments).max(4);
9172            let mut verts = Vec::new();
9173            let mut inds = Vec::new();
9174            for iy in 0..=hs {
9175                let v = iy as f32 / hs as f32;
9176                let phi = v * std::f32::consts::PI;
9177                for ix in 0..=ws {
9178                    let u = ix as f32 / ws as f32;
9179                    let theta = u * std::f32::consts::TAU;
9180                    let nx = -phi.sin() * theta.cos();
9181                    let ny = phi.cos();
9182                    let nz = phi.sin() * theta.sin();
9183                    verts.push(RteTileVertex::new(
9184                        map_pos(nx * radius, ny * radius, nz * radius),
9185                        [nx, ny, nz],
9186                        [u, v],
9187                    ));
9188                }
9189            }
9190            for iy in 0..hs {
9191                for ix in 0..ws {
9192                    let a = iy * (ws + 1) + ix;
9193                    let b = a + 1;
9194                    let c = (iy + 1) * (ws + 1) + ix;
9195                    let d = c + 1;
9196                    inds.extend_from_slice(&[a, c, d, a, d, b]);
9197                }
9198            }
9199            Some((verts, inds, color, unlit))
9200        }
9201        Geometry3D::Cylinder {
9202            radius_top,
9203            radius_bottom,
9204            height,
9205            radial_segments,
9206        } => {
9207            let segs = (*radial_segments).max(6);
9208            let hh = height * 0.5;
9209            let mut verts = Vec::new();
9210            let mut inds = Vec::new();
9211            for i in 0..=segs {
9212                let u = i as f32 / segs as f32;
9213                let a = u * std::f32::consts::TAU;
9214                let (sa, ca) = a.sin_cos();
9215                verts.push(RteTileVertex::new(
9216                    map_pos(ca * radius_top, hh, sa * radius_top),
9217                    [ca, 0.0, sa],
9218                    [u, 0.0],
9219                ));
9220                verts.push(RteTileVertex::new(
9221                    map_pos(ca * radius_bottom, -hh, sa * radius_bottom),
9222                    [ca, 0.0, sa],
9223                    [u, 1.0],
9224                ));
9225            }
9226            for i in 0..segs {
9227                let t0 = i * 2;
9228                let b0 = t0 + 1;
9229                let t1 = t0 + 2;
9230                let b1 = t0 + 3;
9231                inds.extend_from_slice(&[t0, b0, b1, t0, b1, t1]);
9232            }
9233            Some((verts, inds, color, unlit))
9234        }
9235    }
9236}
9237
9238// Keep unused collection imports suppressed cleanly if any.
9239#[allow(dead_code)]
9240fn _assert_collections_used(_: BTreeMap<u64, u64>, _: HashSet<u64>) {}