nightshade-renderer 0.57.0

GPU-driven wgpu renderer with a built-in frame graph.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
use super::brdf_lut;
use super::glyph_atlas;
use super::passes;
use super::rendergraph;
use crate::wgpu::rendergraph::{
    render_graph_add_color_texture, render_graph_add_depth_texture, render_graph_add_pass,
};

/// Selects a present mode, returning `Fifo` when vsync is enabled and the lowest-latency supported mode otherwise.
pub(super) fn pick_present_mode(
    modes: &[wgpu::PresentMode],
    vsync_enabled: bool,
) -> wgpu::PresentMode {
    if vsync_enabled {
        return wgpu::PresentMode::Fifo;
    }
    let preferred: &[wgpu::PresentMode] = if cfg!(target_os = "macos") {
        &[wgpu::PresentMode::Immediate, wgpu::PresentMode::FifoRelaxed]
    } else {
        &[wgpu::PresentMode::Mailbox, wgpu::PresentMode::FifoRelaxed]
    };
    for candidate in preferred.iter().copied() {
        if modes.contains(&candidate) {
            return candidate;
        }
    }
    wgpu::PresentMode::Fifo
}

/// The device features, limits, and bindless capability the renderer asks an
/// adapter for.
pub struct DeviceConfig {
    /// Features to request when creating the device.
    pub required_features: wgpu::Features,
    /// Limits to request when creating the device.
    pub required_limits: wgpu::Limits,
    /// Whether bindless material textures are available, and at what capacity.
    pub bindless: crate::wgpu::material_texture_arrays::BindlessConfig,
}

/// Resolves what the renderer needs from an adapter, negotiating optional
/// features down to what the adapter actually offers.
///
/// Shared so that a host creating the device itself asks for exactly what
/// [`WgpuRenderer::new_async`] would. An OpenXR session creates the Vulkan
/// device on the renderer's behalf and must run this before it does, since the
/// device cannot gain features afterward; duplicating the logic instead is how
/// the two silently drift apart.
pub fn negotiate_device_config(
    adapter_features: wgpu::Features,
    adapter_limits: &wgpu::Limits,
    adapter_info: &wgpu::AdapterInfo,
) -> DeviceConfig {
    let mut required_features = wgpu::Features::INDIRECT_FIRST_INSTANCE;

    if !cfg!(target_os = "macos") && !cfg!(target_arch = "wasm32") {
        required_features |= wgpu::Features::MULTI_DRAW_INDIRECT_COUNT;
    }

    // A host that keeps its heightfield in a float32 texture and reconstructs it
    // in a vertex shader needs a filtering sampler on that format, and a
    // point-sampled fallback is a different surface rather than a cheaper one.
    // Requested where the adapter has it, which is every desktop backend.
    if adapter_features.contains(wgpu::Features::FLOAT32_FILTERABLE) {
        required_features |= wgpu::Features::FLOAT32_FILTERABLE;
    }

    // The frame timing brackets every submission with a timestamp pair, which
    // needs to stamp from an encoder rather than from a pass, since the graph
    // decides for itself how many passes a frame has. Both are capability reads
    // on the backends rather than driver switches, so an adapter that has them
    // costs nothing to ask. Usually absent on the web, where browsers keep
    // timestamps behind a flag for timing-attack reasons.
    let timestamps =
        wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS;
    if adapter_features.contains(timestamps) {
        required_features |= timestamps;
    }

    const BINDLESS_MAX_TEXTURES: u32 = 4096;
    const BINDLESS_MIN_TEXTURES: u32 = 512;
    let bindless_features = wgpu::Features::TEXTURE_BINDING_ARRAY
        | wgpu::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING
        | wgpu::Features::PARTIALLY_BOUND_BINDING_ARRAY;
    let bindless_capacity = adapter_limits
        .max_binding_array_elements_per_shader_stage
        .min(BINDLESS_MAX_TEXTURES);
    let bindless_enabled = !cfg!(target_arch = "wasm32")
        && adapter_features.contains(bindless_features)
        && bindless_capacity >= BINDLESS_MIN_TEXTURES;
    if bindless_enabled {
        required_features |= bindless_features;
    }
    let bindless_config = crate::wgpu::material_texture_arrays::BindlessConfig {
        enabled: bindless_enabled,
        max_textures: bindless_capacity,
    };

    let base_limits = if adapter_info.backend == wgpu::Backend::Gl {
        wgpu::Limits::downlevel_webgl2_defaults()
    } else {
        wgpu::Limits::default()
    };
    let mut required_limits = base_limits.using_resolution(adapter_limits.clone());
    required_limits.max_bind_groups = if cfg!(target_arch = "wasm32") { 4 } else { 8 };
    required_limits.max_sampled_textures_per_shader_stage =
        adapter_limits.max_sampled_textures_per_shader_stage.min(64);
    required_limits.max_samplers_per_shader_stage =
        adapter_limits.max_samplers_per_shader_stage.min(64);
    if bindless_enabled {
        required_limits.max_binding_array_elements_per_shader_stage = bindless_capacity;
    }
    // Rasterizing a cluster in compute needs one atomic to settle both
    // visibility and payload: depth in a value's high bits and the cluster
    // and triangle in its low bits means a single max over sixty four bits
    // is the depth test, with no fixed function rasterizer and no quads. A
    // hardware rasterizer costs a two by two quad per triangle however
    // small it is, which is most of its throughput once a level of detail
    // cut has made triangles land on single pixels. Requested where the
    // adapter has it, and the pass falls back to hardware alone where it
    // does not.
    //
    // Three features, because they answer different questions:
    // TEXTURE_INT64_ATOMIC allows the R64Uint format at all, TEXTURE_ATOMIC
    // allows a texture to carry the atomic usage, and SHADER_INT64 allows
    // the shader to hold the packed value. Asking for less than all three
    // fails later rather than here.
    #[cfg(feature = "meshlet")]
    {
        let wanted = wgpu::Features::TEXTURE_INT64_ATOMIC
            | wgpu::Features::TEXTURE_ATOMIC
            | wgpu::Features::SHADER_INT64;
        if adapter_features.contains(wanted) {
            required_features |= wanted;
        } else {
            tracing::info!(
                "adapter has no 64 bit texture atomics: meshlet clusters rasterize on the \
                     hardware rasterizer alone, which costs a quad per triangle however small"
            );
        }
    }
    // The default caps a single storage binding at 128mb, which is a
    // conservative floor rather than anything the hardware minds. Virtualized
    // geometry keeps every asset's vertices in one shared stream, so a scene
    // with tens of millions of unique vertices passes that in one buffer.
    // Take whatever the adapter offers.
    #[cfg(feature = "meshlet")]
    {
        required_limits.max_storage_buffer_binding_size =
            adapter_limits.max_storage_buffer_binding_size;
        required_limits.max_buffer_size = adapter_limits.max_buffer_size;
    }

    DeviceConfig {
        required_features,
        required_limits,
        bindless: bindless_config,
    }
}

impl super::WgpuRenderer {
    /// Builds the renderer and its full render graph for the given window surface.
    pub async fn new_async<W>(
        window_handle: W,
        initial_width: u32,
        initial_height: u32,
    ) -> Result<Self, Box<dyn std::error::Error>>
    where
        W: Into<wgpu::SurfaceTarget<'static>>,
    {
        let instance =
            wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
        let surface = instance.create_surface(window_handle)?;

        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::default(),
                compatible_surface: Some(&surface),
                force_fallback_adapter: false,
            })
            .await
            .expect("Failed to request adapter!");

        let adapter_info = adapter.get_info();
        let DeviceConfig {
            required_features,
            required_limits,
            bindless,
        } = negotiate_device_config(adapter.features(), &adapter.limits(), &adapter_info);

        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor {
                label: Some("WGPU Device"),
                memory_hints: wgpu::MemoryHints::default(),
                required_features,
                required_limits,
                experimental_features: wgpu::ExperimentalFeatures::disabled(),
                trace: wgpu::Trace::Off,
            })
            .await?;

        let surface_capabilities = surface.get_capabilities(&adapter);
        let surface_format = surface_capabilities
            .formats
            .iter()
            .copied()
            .find(|f| !f.is_srgb())
            .unwrap_or(surface_capabilities.formats[0]);

        Self::new_with_device(
            &adapter,
            device,
            queue,
            surface,
            surface_format,
            bindless,
            initial_width,
            initial_height,
        )
        .await
    }

    /// Builds the renderer and its full render graph over a device the caller
    /// already created, presenting through `surface` in `surface_format`.
    ///
    /// [`new_async`](Self::new_async) is this plus the instance, surface, and
    /// device bring-up. Split out for hosts that cannot let wgpu create the
    /// device: an OpenXR runtime dictates the Vulkan instance, physical device,
    /// and logical device, so the session creates them, the caller adopts them
    /// with `wgpu::Instance::from_hal` and friends, and hands them here.
    ///
    /// `bindless` must come from [`negotiate_device_config`] run against the same
    /// adapter, since a device cannot gain features after creation.
    #[allow(clippy::too_many_arguments)]
    pub async fn new_with_device(
        adapter: &wgpu::Adapter,
        device: wgpu::Device,
        queue: wgpu::Queue,
        surface: wgpu::Surface<'static>,
        surface_format: wgpu::TextureFormat,
        bindless_config: crate::wgpu::material_texture_arrays::BindlessConfig,
        initial_width: u32,
        initial_height: u32,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let adapter_info = adapter.get_info();

        tracing::info!("wgpu device features: {:?}", device.features());

        let gpu_profile = build_gpu_profile(&adapter_info);
        tracing::info!(
            "gpu adapter: {} ({:?} / {:?})",
            gpu_profile.name,
            gpu_profile.backend,
            gpu_profile.device_type
        );

        let surface_capabilities = surface.get_capabilities(adapter);
        if surface_capabilities.formats.is_empty() {
            return Err(
                "the selected adapter cannot present to this surface: no supported formats".into(),
            );
        }

        let present_mode = pick_present_mode(&surface_capabilities.present_modes, true);
        tracing::info!(
            "Surface present modes available: {:?}, selected: {:?}",
            surface_capabilities.present_modes,
            present_mode
        );
        let surface_config = wgpu::SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format: surface_format,
            width: initial_width,
            height: initial_height,
            present_mode,
            alpha_mode: surface_capabilities.alpha_modes[0],
            view_formats: vec![],
            desired_maximum_frame_latency: 2,
        };

        surface.configure(&device, &surface_config);

        let depth_format = wgpu::TextureFormat::Depth32Float;
        let hdr_format = wgpu::TextureFormat::Rgba16Float;
        let sky_pass = passes::SkyPass::new(&device, hdr_format, depth_format);
        let grid_pass = passes::GridPass::new(&device, hdr_format, depth_format);

        crate::wgpu::stagger::yield_to_event_loop(&queue).await;
        let shadow_depth_pass = passes::ShadowDepthPass::new(&device, &queue).await;

        let material_texture_arrays = if bindless_config.enabled {
            crate::wgpu::material_texture_arrays::MaterialTextureArrays::new_bindless(
                &device,
                &queue,
                bindless_config.max_textures,
            )
        } else {
            crate::wgpu::material_texture_arrays::MaterialTextureArrays::new(&device)
        };
        let mip_generator = crate::wgpu::mip_generator::MipGenerator::new(&device);

        crate::wgpu::stagger::yield_to_event_loop(&queue).await;
        let mut mesh_pass = passes::MeshPass::new(
            &device,
            &queue,
            hdr_format,
            depth_format,
            (initial_width, initial_height),
            bindless_config,
        )
        .await;
        mesh_pass.apply_material_textures(&device, &material_texture_arrays);

        crate::wgpu::stagger::yield_to_event_loop(&queue).await;
        let mut skinned_mesh_pass = passes::SkinnedMeshPass::new(
            &device,
            &queue,
            hdr_format,
            depth_format,
            bindless_config,
        )
        .await;
        skinned_mesh_pass.apply_material_textures(&device, &material_texture_arrays);

        crate::wgpu::stagger::yield_to_event_loop(&queue).await;
        let lines_pass = passes::LinesPass::new(&device, hdr_format);

        let particle_pass = passes::ParticlePass::new(&device, hdr_format);

        let text_pass = passes::TextPass::new(&device, hdr_format, depth_format);

        crate::wgpu::stagger::yield_to_event_loop(&queue).await;
        let cloth_pass = passes::ClothPass::new(&device);

        #[cfg(feature = "terrain")]
        let terrain_pass = passes::TerrainPass::new(&device, hdr_format);
        #[cfg(feature = "grass")]
        let grass_pass = passes::GrassPass::new(&device, hdr_format);

        crate::wgpu::stagger::yield_to_event_loop(&queue).await;
        let ui_texture_array = crate::wgpu::texture_array_pool::create_texture_array_pool(
            &device,
            crate::paint::TEXTURE_LAYER_SIZE,
            crate::paint::TEXTURE_MAX_LAYERS,
        );
        let mut ui_image_pass = passes::PaintImagePass::new(&device, surface_format);
        ui_image_pass.set_texture_bind_group(
            &device,
            &ui_texture_array.view,
            &ui_texture_array.sampler,
        );

        #[cfg(feature = "debug_render")]
        let selection_mask_pass = passes::SelectionMaskPass::new(&device, depth_format);

        let mut graph = rendergraph::render_graph_new();

        let depth_id = render_graph_add_depth_texture(&mut graph, "depth")
            .size(initial_width.max(1), initial_height.max(1))
            .usage(
                wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::TEXTURE_BINDING
                    | wgpu::TextureUsages::COPY_SRC,
            )
            .clear_depth(0.0)
            .transient();

        let scene_color_id = render_graph_add_color_texture(&mut graph, "scene_color")
            .format(wgpu::TextureFormat::Rgba16Float)
            .size(initial_width.max(1), initial_height.max(1))
            .usage(
                wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::TEXTURE_BINDING
                    | wgpu::TextureUsages::COPY_SRC,
            )
            .clear_color(wgpu::Color {
                r: 0.0,
                g: 0.0,
                b: 0.0,
                a: 1.0,
            })
            .transient();

        let compute_output_id = render_graph_add_color_texture(&mut graph, "compute_output")
            .format(surface_format)
            .size(initial_width.max(1), initial_height.max(1))
            .usage(
                wgpu::TextureUsages::TEXTURE_BINDING
                    | wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::COPY_SRC,
            )
            .clear_color(wgpu::Color::BLACK)
            .transient();

        let swapchain_id = render_graph_add_color_texture(&mut graph, "swapchain")
            .format(surface_format)
            .external();

        let viewport_resource_id = render_graph_add_color_texture(&mut graph, "viewport_output")
            .format(surface_format)
            .external();

        let shadow_map_size = passes::CASCADE_ATLAS_SIZE;
        let shadow_depth_id = render_graph_add_depth_texture(&mut graph, "shadow_depth")
            .size(shadow_map_size, shadow_map_size)
            .format(wgpu::TextureFormat::Depth32Float)
            .clear_depth(0.0)
            .fixed_size()
            .transient();

        let spotlight_shadow_atlas_size = if cfg!(target_arch = "wasm32") {
            1024
        } else {
            4096
        };
        let spotlight_shadow_atlas_id =
            render_graph_add_depth_texture(&mut graph, "spotlight_shadow_atlas")
                .format(wgpu::TextureFormat::Depth32Float)
                .external();
        let spotlight_shadow_atlas_texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("Spotlight Shadow Atlas"),
            size: wgpu::Extent3d {
                width: spotlight_shadow_atlas_size,
                height: spotlight_shadow_atlas_size,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Depth32Float,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let spotlight_shadow_atlas_view =
            spotlight_shadow_atlas_texture.create_view(&wgpu::TextureViewDescriptor::default());

        #[cfg(feature = "debug_render")]
        let selection_mask_id = render_graph_add_color_texture(&mut graph, "selection_mask")
            .format(wgpu::TextureFormat::R8Unorm)
            .size(initial_width.max(1), initial_height.max(1))
            .clear_color(wgpu::Color::TRANSPARENT)
            .transient();

        let entity_id_id = render_graph_add_color_texture(&mut graph, "entity_id")
            .format(wgpu::TextureFormat::R32Float)
            .size(initial_width.max(1), initial_height.max(1))
            .usage(wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING)
            .clear_color(wgpu::Color::TRANSPARENT)
            .transient();

        let view_normals_id = render_graph_add_color_texture(&mut graph, "view_normals")
            .format(wgpu::TextureFormat::Rgba16Float)
            .size(initial_width.max(1), initial_height.max(1))
            .usage(wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING)
            .clear_color(wgpu::Color::TRANSPARENT)
            .transient();

        let velocity_id = render_graph_add_color_texture(&mut graph, "velocity")
            .format(wgpu::TextureFormat::Rg16Float)
            .size(initial_width.max(1), initial_height.max(1))
            .usage(wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING)
            .clear_color(wgpu::Color {
                r: 2.0,
                g: 2.0,
                b: 0.0,
                a: 0.0,
            })
            .transient();

        let ssao_half_width = (initial_width / 2).max(1);
        let ssao_half_height = (initial_height / 2).max(1);

        let ssao_raw_id = render_graph_add_color_texture(&mut graph, "ssao_raw")
            .format(wgpu::TextureFormat::R8Unorm)
            .size(ssao_half_width, ssao_half_height)
            .usage(wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING)
            .clear_color(wgpu::Color::WHITE)
            .transient();

        let ssao_id = render_graph_add_color_texture(&mut graph, "ssao")
            .format(wgpu::TextureFormat::R8Unorm)
            .size(ssao_half_width, ssao_half_height)
            .usage(wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING)
            .clear_color(wgpu::Color::WHITE)
            .transient();

        let ssgi_half_width = (initial_width / 2).max(1);
        let ssgi_half_height = (initial_height / 2).max(1);

        let ssgi_raw_id = render_graph_add_color_texture(&mut graph, "ssgi_raw")
            .format(wgpu::TextureFormat::Rgba16Float)
            .size(ssgi_half_width, ssgi_half_height)
            .usage(wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING)
            .clear_color(wgpu::Color::TRANSPARENT)
            .transient();

        let ssgi_id = render_graph_add_color_texture(&mut graph, "ssgi")
            .format(wgpu::TextureFormat::Rgba16Float)
            .size(ssgi_half_width, ssgi_half_height)
            .usage(wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING)
            .clear_color(wgpu::Color::TRANSPARENT)
            .transient();

        let ssr_half_width = (initial_width / 2).max(1);
        let ssr_half_height = (initial_height / 2).max(1);

        let ssr_raw_id = render_graph_add_color_texture(&mut graph, "ssr_raw")
            .format(wgpu::TextureFormat::Rgba16Float)
            .size(ssr_half_width, ssr_half_height)
            .usage(wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING)
            .clear_color(wgpu::Color::TRANSPARENT)
            .transient();

        let ssr_id = render_graph_add_color_texture(&mut graph, "ssr")
            .format(wgpu::TextureFormat::Rgba16Float)
            .size(initial_width.max(1), initial_height.max(1))
            .usage(wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING)
            .clear_color(wgpu::Color::TRANSPARENT)
            .transient();

        let ui_depth_id = render_graph_add_depth_texture(&mut graph, "ui_depth")
            .size(initial_width.max(1), initial_height.max(1))
            .format(wgpu::TextureFormat::Depth32Float)
            .clear_depth(0.0)
            .transient();

        render_graph_add_pass(&mut graph, Box::new(sky_pass), &[("color", scene_color_id)])?;

        render_graph_add_pass(
            &mut graph,
            Box::new(shadow_depth_pass),
            &[
                ("shadow_depth", shadow_depth_id),
                ("spotlight_shadow_atlas", spotlight_shadow_atlas_id),
            ],
        )?;

        // Terrain and grass are opaque ground and must populate scene color and
        // depth before the mesh passes composite their transparency. Otherwise a
        // transparent surface in front of the ground composites over the bare sky
        // and its depth prepass occludes the ground that renders afterward.
        #[cfg(feature = "terrain")]
        render_graph_add_pass(
            &mut graph,
            Box::new(terrain_pass),
            &[
                ("color", scene_color_id),
                ("depth", depth_id),
                ("entity_id", entity_id_id),
                ("shadow_depth", shadow_depth_id),
            ],
        )?;

        #[cfg(feature = "grass")]
        render_graph_add_pass(
            &mut graph,
            Box::new(grass_pass),
            &[("color", scene_color_id), ("depth", depth_id)],
        )?;

        render_graph_add_pass(
            &mut graph,
            Box::new(mesh_pass),
            &[
                ("color", scene_color_id),
                ("depth", depth_id),
                ("shadow_depth", shadow_depth_id),
                ("spotlight_shadow_atlas", spotlight_shadow_atlas_id),
                ("entity_id", entity_id_id),
                ("view_normals", view_normals_id),
                ("velocity", velocity_id),
            ],
        )?;

        // Meshlet geometry rasterizes after the mesh passes have laid down
        // depth, so its visibility buffer only keeps pixels that survive against
        // the rest of the scene, and writes depth of its own so the passes that
        // follow occlude against it.
        #[cfg(feature = "meshlet")]
        {
            // The pass owns its visibility buffer rather than naming a graph
            // slot: with 64 bit atomics it is an R64Uint texture, which cannot be
            // a render attachment, so there is nothing here to schedule.
            let mut meshlet_pass = passes::MeshletPass::new(
                &device,
                hdr_format,
                depth_format,
                device.features().contains(
                    wgpu::Features::TEXTURE_INT64_ATOMIC
                        | wgpu::Features::TEXTURE_ATOMIC
                        | wgpu::Features::SHADER_INT64,
                ),
                bindless_config
                    .enabled
                    .then_some(bindless_config.max_textures),
            );
            meshlet_pass.apply_material_textures(&device, &material_texture_arrays);
            render_graph_add_pass(
                &mut graph,
                Box::new(meshlet_pass),
                &[("color", scene_color_id), ("depth", depth_id)],
            )?;
        }

        render_graph_add_pass(
            &mut graph,
            Box::new(skinned_mesh_pass),
            &[
                ("color", scene_color_id),
                ("depth", depth_id),
                ("shadow_depth", shadow_depth_id),
                ("spotlight_shadow_atlas", spotlight_shadow_atlas_id),
                ("entity_id", entity_id_id),
                ("velocity", velocity_id),
            ],
        )?;

        render_graph_add_pass(
            &mut graph,
            Box::new(passes::DecalPass::new(&device, hdr_format)),
            &[("color", scene_color_id), ("depth", depth_id)],
        )?;

        render_graph_add_pass(
            &mut graph,
            Box::new(passes::WaterPass::new(&device, hdr_format)),
            &[
                ("color", scene_color_id),
                ("depth", depth_id),
                ("velocity", velocity_id),
            ],
        )?;

        let scene_overlay_pass = passes::SceneOverlayPass {
            grid: grid_pass,
            lines: lines_pass,
            particles: particle_pass,
            text: text_pass,
        };
        render_graph_add_pass(
            &mut graph,
            Box::new(scene_overlay_pass),
            &[("color", scene_color_id), ("depth", depth_id)],
        )?;

        render_graph_add_pass(
            &mut graph,
            Box::new(cloth_pass),
            &[("color", scene_color_id), ("depth", depth_id)],
        )?;

        #[cfg(feature = "debug_render")]
        {
            render_graph_add_pass(
                &mut graph,
                Box::new(selection_mask_pass),
                &[
                    ("selection_mask", selection_mask_id),
                    ("entity_id", entity_id_id),
                ],
            )?;

            let outline_pass = passes::OutlinePass::new(&device, hdr_format);
            render_graph_add_pass(
                &mut graph,
                Box::new(outline_pass),
                &[
                    ("selection_mask", selection_mask_id),
                    ("color", scene_color_id),
                ],
            )?;
        }

        let bloom_texture_id = render_graph_add_color_texture(&mut graph, "bloom")
            .format(hdr_format)
            .size((initial_width / 2).max(1), (initial_height / 2).max(1))
            .clear_color(wgpu::Color::BLACK)
            .transient();

        let dof_output_id = render_graph_add_color_texture(&mut graph, "dof_output")
            .format(hdr_format)
            .size(initial_width.max(1), initial_height.max(1))
            .clear_color(wgpu::Color::BLACK)
            .transient();

        crate::wgpu::stagger::yield_to_event_loop(&queue).await;
        let bloom_pass =
            passes::BloomPass::new(&device, initial_width.max(1), initial_height.max(1));
        render_graph_add_pass(
            &mut graph,
            Box::new(bloom_pass),
            &[("hdr", scene_color_id), ("bloom", bloom_texture_id)],
        )?;

        let dof_pass = passes::DepthOfFieldPass::new(
            &device,
            hdr_format,
            initial_width.max(1),
            initial_height.max(1),
        );
        render_graph_add_pass(
            &mut graph,
            Box::new(dof_pass),
            &[
                ("hdr", scene_color_id),
                ("depth", depth_id),
                ("dof_output", dof_output_id),
            ],
        )?;

        crate::wgpu::stagger::yield_to_event_loop(&queue).await;
        let ssao_pass = passes::SsaoPass::new(&device);
        render_graph_add_pass(
            &mut graph,
            Box::new(ssao_pass),
            &[
                ("depth", depth_id),
                ("view_normals", view_normals_id),
                ("ssao_raw", ssao_raw_id),
            ],
        )?;

        let ssao_blur_pass = passes::SsaoBlurPass::new(&device);
        render_graph_add_pass(
            &mut graph,
            Box::new(ssao_blur_pass),
            &[
                ("ssao_raw", ssao_raw_id),
                ("depth", depth_id),
                ("view_normals", view_normals_id),
                ("ssao", ssao_id),
            ],
        )?;

        crate::wgpu::stagger::yield_to_event_loop(&queue).await;
        let postprocess_pass = passes::PostProcessPass::new(&device, surface_format, 1.0);
        render_graph_add_pass(
            &mut graph,
            Box::new(postprocess_pass),
            &[
                ("hdr", dof_output_id),
                ("scene_color", scene_color_id),
                ("bloom", bloom_texture_id),
                ("ssao", ssao_id),
                ("output", compute_output_id),
            ],
        )?;

        let aa_output_id = render_graph_add_color_texture(&mut graph, "aa_output")
            .format(surface_format)
            .size(initial_width.max(1), initial_height.max(1))
            .clear_color(wgpu::Color::BLACK)
            .transient();

        crate::wgpu::stagger::yield_to_event_loop(&queue).await;
        let taa_pass = passes::TaaPass::new(&device, surface_format);
        render_graph_add_pass(
            &mut graph,
            Box::new(taa_pass),
            &[
                ("input", compute_output_id),
                ("depth", depth_id),
                ("velocity", velocity_id),
                ("output", aa_output_id),
            ],
        )?;

        let taa_passthrough_pass =
            passes::BlitPass::new(&device, surface_format).with_name("taa_passthrough");
        render_graph_add_pass(
            &mut graph,
            Box::new(taa_passthrough_pass),
            &[("input", compute_output_id), ("output", aa_output_id)],
        )?;

        crate::wgpu::stagger::yield_to_event_loop(&queue).await;
        let (brdf_lut_texture, brdf_lut_view) = brdf_lut::generate_brdf_lut(&device, &queue);

        crate::wgpu::stagger::yield_to_event_loop(&queue).await;
        let depth_pick_shader = crate::wgpu::shader_compose::compile_wgsl(
            &device,
            "Depth Pick Shader",
            include_str!("shaders/depth_pick.wgsl"),
        );

        let depth_pick_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("Depth Pick Bind Group Layout"),
                entries: &[
                    wgpu::BindGroupLayoutEntry {
                        binding: 0,
                        visibility: wgpu::ShaderStages::COMPUTE,
                        ty: wgpu::BindingType::Texture {
                            sample_type: wgpu::TextureSampleType::Depth,
                            view_dimension: wgpu::TextureViewDimension::D2,
                            multisampled: false,
                        },
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 1,
                        visibility: wgpu::ShaderStages::COMPUTE,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Storage { read_only: false },
                            has_dynamic_offset: false,
                            min_binding_size: None,
                        },
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 2,
                        visibility: wgpu::ShaderStages::COMPUTE,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Uniform,
                            has_dynamic_offset: false,
                            min_binding_size: None,
                        },
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 3,
                        visibility: wgpu::ShaderStages::COMPUTE,
                        ty: wgpu::BindingType::Texture {
                            sample_type: wgpu::TextureSampleType::Float { filterable: false },
                            view_dimension: wgpu::TextureViewDimension::D2,
                            multisampled: false,
                        },
                        count: None,
                    },
                ],
            });

        let depth_pick_pipeline_layout =
            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Depth Pick Pipeline Layout"),
                bind_group_layouts: &[Some(&depth_pick_bind_group_layout)],
                immediate_size: 0,
            });

        let depth_pick_compute_pipeline =
            device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
                label: Some("Depth Pick Compute Pipeline"),
                layout: Some(&depth_pick_pipeline_layout),
                module: &depth_pick_shader,
                entry_point: Some("main"),
                compilation_options: Default::default(),
                cache: None,
            });

        let depth_pick_buffer_size =
            (super::DEPTH_PICK_SAMPLE_SIZE * super::DEPTH_PICK_SAMPLE_SIZE * 8) as u64;
        let depth_pick_storage_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Depth Pick Storage Buffer"),
            size: depth_pick_buffer_size,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
            mapped_at_creation: false,
        });

        let depth_pick_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Depth Pick Uniform Buffer"),
            size: 16,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let depth_pick_staging_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Depth Pick Staging Buffer"),
            size: depth_pick_buffer_size,
            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            mapped_at_creation: false,
        });

        #[cfg(all(not(target_arch = "wasm32"), feature = "screenshot"))]
        let screenshot_staging_buffer = {
            let bytes_per_pixel = 4u32;
            let unpadded_bytes_per_row = initial_width.max(1) * bytes_per_pixel;
            let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
            let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;
            let buffer_size = (padded_bytes_per_row * initial_height.max(1)) as u64;
            device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("Screenshot Staging Buffer"),
                size: buffer_size,
                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
                mapped_at_creation: false,
            })
        };

        crate::wgpu::stagger::yield_to_event_loop(&queue).await;
        let glyph_atlas = glyph_atlas::GlyphAtlas::new(&device);
        crate::wgpu::stagger::drain_queued_work(&queue).await;

        let timing = crate::wgpu::timing::GpuTiming::new(&device, &queue);

        Ok(Self {
            surface,
            device,
            queue,
            surface_config,
            surface_format,
            supported_present_modes: surface_capabilities.present_modes,
            graph,
            targets: super::RenderTargets {
                depth: depth_id,
                scene_color: scene_color_id,
                compute_output: compute_output_id,
                aa_output: aa_output_id,
                swapchain: swapchain_id,
                viewport_resource: viewport_resource_id,
                ui_depth: ui_depth_id,
                entity_id: entity_id_id,
                view_normals: view_normals_id,
                velocity: velocity_id,
                ssao_raw: ssao_raw_id,
                ssao: ssao_id,
                ssgi_raw: ssgi_raw_id,
                ssgi: ssgi_id,
                ssr_raw: ssr_raw_id,
                ssr: ssr_id,
                spotlight_shadow_atlas: spotlight_shadow_atlas_id,
            },
            spotlight_shadow_atlas_texture,
            spotlight_shadow_atlas_view,
            ui_image_pass: Some(Box::new(ui_image_pass)),
            glyph_atlas,
            camera_viewports: std::collections::HashMap::new(),
            _brdf_lut_texture: brdf_lut_texture,
            brdf_lut_view,
            material_texture_arrays,
            ui_texture_array,
            mip_generator,
            timing,
            depth_pick: super::DepthPickState {
                compute_pipeline: depth_pick_compute_pipeline,
                bind_group_layout: depth_pick_bind_group_layout,
                storage_buffer: depth_pick_storage_buffer,
                uniform_buffer: depth_pick_uniform_buffer,
                staging_buffer: depth_pick_staging_buffer,
                bind_group: None,
                pending: false,
                map_complete: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
                center: (0, 0),
                texture_size: (1, 1),
                camera: None,
            },
            #[cfg(all(not(target_arch = "wasm32"), feature = "screenshot"))]
            screenshot: super::ScreenshotState {
                staging_buffer: screenshot_staging_buffer,
                pending: false,
                map_complete: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
                path: None,
                width: initial_width.max(1),
                height: initial_height.max(1),
                max_dimension: None,
            },
            render_buffer_size: (initial_width.max(1), initial_height.max(1)),
            window_render_state: super::WindowRenderState::default(),
            frame_state: super::FrameState {
                index: 0,
                last_settings_signature: None,
                text_mesh_signatures: std::collections::HashMap::new(),
                #[cfg(feature = "hdr")]
                captured_ibl_atmosphere: None,
                #[cfg(feature = "hdr")]
                captured_ibl_hour: 0.0,
                #[cfg(feature = "hdr")]
                captured_day_night_snapshots: false,
            },
            texture_store: crate::wgpu::texture_cache::TextureStore::default(),
            gpu_profile,
            ibl_views: crate::config::IblViews::default(),
            meshlet_frozen_cull_view: None,
        })
    }
}

/// Translates the selected adapter's `wgpu::AdapterInfo` into the engine's
/// backend-agnostic `GpuProfile` so apps can read it without depending on wgpu.
fn build_gpu_profile(info: &wgpu::AdapterInfo) -> crate::config::GpuProfile {
    use crate::config::{GpuBackend, GpuDeviceType, GpuProfile};

    let backend = match info.backend {
        wgpu::Backend::Vulkan => GpuBackend::Vulkan,
        wgpu::Backend::Metal => GpuBackend::Metal,
        wgpu::Backend::Dx12 => GpuBackend::Dx12,
        wgpu::Backend::Gl => {
            if cfg!(target_arch = "wasm32") {
                GpuBackend::WebGl
            } else {
                GpuBackend::Gl
            }
        }
        wgpu::Backend::BrowserWebGpu => GpuBackend::WebGpu,
        _ => GpuBackend::Other,
    };
    let device_type = match info.device_type {
        wgpu::DeviceType::IntegratedGpu => GpuDeviceType::IntegratedGpu,
        wgpu::DeviceType::DiscreteGpu => GpuDeviceType::DiscreteGpu,
        wgpu::DeviceType::VirtualGpu => GpuDeviceType::VirtualGpu,
        wgpu::DeviceType::Cpu => GpuDeviceType::Cpu,
        wgpu::DeviceType::Other => GpuDeviceType::Other,
    };
    GpuProfile {
        backend,
        device_type,
        name: info.name.clone(),
    }
}