concinnity-device 0.19.1

GPU backends (Metal, Vulkan, DirectX) behind a device facade for Concinnity
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
// src/vulkan/post/reflection_composite.rs
//
// Roughness-aware reflection composite for the Vulkan backend. The SSR and RT
// resolves now write reflected radiance (.rgb) + a Fresnel/gloss weight (.a) into
// their output target instead of compositing inline; this two-pass effect blurs
// that reflection by surface roughness and composites it over the base HDR scene
// into `output`, the scene-with-reflections the TAA / bloom / composite / glass
// passes consume. Mirrors src/metal/post/ssr.rs (the composite half) +
// src/directx/post/reflection_composite.rs.
//
//   pass 1 (blur, reduced resolution): weight-averages the reflection over a
//       roughness-scaled cone into `blur`. The expensive multi-tap part, run at a
//       fraction of the pixels.
//   pass 2 (composite, full resolution): lerps the sharp full-res reflection
//       against the upsampled half-res blur by roughness, then composites over the
//       scene into `output`.
//
// Both reflection paths feed one composite: `encode_ssr_resolve` /
// `encode_rt_reflections` each render their resolve target, then call
// `encode_reflection_composite` with that target's view; the composite's reflection
// binding is re-pointed to it per encode (the two paths are mutually exclusive).

use ash::vk;

use crate::vulkan::owned::{
    OwnedDescriptorPool, OwnedFramebuffer, OwnedPipeline, OwnedPipelineLayout, OwnedRenderPass,
    OwnedSampler, OwnedSetLayout, VkDevice,
};

use super::super::context::{HDR_FORMAT, VkContext};
use super::super::pipeline::*;
use super::super::resources::{alloc_descriptor_sets, create_descriptor_set_layout};
use super::super::texture::*;
use crate::vulkan::slang_builtins::SlangCompile;

// Reflection-composite resources, held by `VkContext` when the SSR resolve or RT
// reflections are active (both feed this composite). All `vk::*` handles are owned
// here and freed on `destroy`.
pub(in crate::vulkan) struct ReflectionCompositeResources {
    // Composited scene (full render resolution): the scene image the post stack
    // consumes in place of the raw SSR / RT resolve output.
    pub(in crate::vulkan) output: GpuImage,
    output_framebuffer: OwnedFramebuffer,

    // Reduced-resolution roughness blur of the reflection target (pass 1 writes it,
    // the composite upsamples it). Sized at render / `blur_scale`.
    blur: GpuImage,
    blur_framebuffer: OwnedFramebuffer,
    blur_extent: vk::Extent2D,

    // One render pass (RGBA16F colour, DONT_CARE load, ends shader-readable) shared
    // by both passes; the framebuffer selects the target.
    render_pass: OwnedRenderPass,

    // Pass 1 (blur) reads reflection + roughness; pass 2 (composite) reads those
    // plus scene + G-buffer normal+depth + blur.
    _blur_set_layout: OwnedSetLayout,
    _composite_set_layout: OwnedSetLayout,
    blur_pipeline_layout: OwnedPipelineLayout,
    composite_pipeline_layout: OwnedPipelineLayout,
    blur_pso: OwnedPipeline,
    composite_pso: OwnedPipeline,

    _descriptor_pool: OwnedDescriptorPool,
    // Per-frame sets. Binding 0 (the reflection target) is re-pointed each encode to
    // the resolve that just ran; the rest are wired at init / resize.
    blur_sets: Vec<vk::DescriptorSet>,
    composite_sets: Vec<vk::DescriptorSet>,

    sampler: OwnedSampler,

    // Per-axis divisor the blur target is sized by (from the world's
    // `reflection_blur_resolution`). Held so `rebuild` reuses the same scale.
    blur_scale: u32,
}

// SAFETY: Raw per-frame sets are render-thread-only; the struct lives inside `VkContext`,
// already `unsafe impl Send`.
unsafe impl Send for ReflectionCompositeResources {}

// SPIR-V blobs for the composite pipelines.
pub(in crate::vulkan) struct ReflectionCompositeShaders {
    pub vs: Vec<u8>,
    pub blur_fs: Vec<u8>,
    pub composite_fs: Vec<u8>,
}

// Compile the shared fullscreen vertex shader + the blur + composite fragments.
// The vertex shader is the SSR resolve's fullscreen triangle (same no-flip
// [0,1] UV convention, so the composite taps line up with the resolve's).
pub(in crate::vulkan) fn compile_reflection_composite_shaders(
    hot_reload: bool,
) -> Result<ReflectionCompositeShaders, String> {
    use super::super::{builtins, slang_builtins};
    let ctx = builtins::Ctx::plain(hot_reload);
    Ok(ReflectionCompositeShaders {
        vs: slang_builtins::FULLSCREEN_VERT.compile(&ctx)?,
        blur_fs: slang_builtins::REFLECTION_BLUR.compile(&ctx)?,
        composite_fs: slang_builtins::REFLECTION_COMPOSITE.compile(&ctx)?,
    })
}

// Replacement composite pipelines from a shader hot-reload.
pub(in crate::vulkan) struct RebuiltReflectionComposite {
    pub blur: OwnedPipeline,
    pub composite: OwnedPipeline,
}

pub(in crate::vulkan) fn rebuild_reflection_composite_pipelines(
    device: &VkDevice,
    rc: &ReflectionCompositeResources,
    hot_reload: bool,
) -> Result<RebuiltReflectionComposite, String> {
    let shaders = compile_reflection_composite_shaders(hot_reload)?;
    let blur = create_composite_pipeline(
        device,
        rc.render_pass.handle(),
        rc.blur_pipeline_layout.handle(),
        &shaders.vs,
        &shaders.blur_fs,
    )?;
    let composite = create_composite_pipeline(
        device,
        rc.render_pass.handle(),
        rc.composite_pipeline_layout.handle(),
        &shaders.vs,
        &shaders.composite_fs,
    )?;
    Ok(RebuiltReflectionComposite { blur, composite })
}

// Composite render pass: one HDR-format colour attachment, no depth. The fullscreen
// triangle overwrites every pixel so DONT_CARE is safe on load. Ends shader-readable
// for the next pass (composite -> bloom/TAA; blur -> composite). Mirrors the SSR
// resolve render pass.
fn create_composite_render_pass(device: &VkDevice) -> Result<OwnedRenderPass, String> {
    let attachment = vk::AttachmentDescription::default()
        .format(HDR_FORMAT)
        .samples(vk::SampleCountFlags::TYPE_1)
        .load_op(vk::AttachmentLoadOp::DONT_CARE)
        .store_op(vk::AttachmentStoreOp::STORE)
        .stencil_load_op(vk::AttachmentLoadOp::DONT_CARE)
        .stencil_store_op(vk::AttachmentStoreOp::DONT_CARE)
        .initial_layout(vk::ImageLayout::UNDEFINED)
        .final_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL);
    let color_ref = vk::AttachmentReference::default()
        .attachment(0)
        .layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL);
    let subpass = vk::SubpassDescription::default()
        .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS)
        .color_attachments(std::slice::from_ref(&color_ref));
    // Synchronise every prior colour write + shader read (the resolve output, the
    // pass-1 blur write, the scene + G-buffer) against this pass's reads + write.
    let dep = vk::SubpassDependency::default()
        .src_subpass(vk::SUBPASS_EXTERNAL)
        .dst_subpass(0)
        .src_stage_mask(
            vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT
                | vk::PipelineStageFlags::FRAGMENT_SHADER,
        )
        .src_access_mask(vk::AccessFlags::COLOR_ATTACHMENT_WRITE | vk::AccessFlags::SHADER_READ)
        .dst_stage_mask(
            vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT
                | vk::PipelineStageFlags::FRAGMENT_SHADER,
        )
        .dst_access_mask(vk::AccessFlags::COLOR_ATTACHMENT_WRITE | vk::AccessFlags::SHADER_READ);
    let info = vk::RenderPassCreateInfo::default()
        .attachments(std::slice::from_ref(&attachment))
        .subpasses(std::slice::from_ref(&subpass))
        .dependencies(std::slice::from_ref(&dep));
    device
        .create_render_pass(&info)
        .map_err(|e| format!("reflection composite render pass: {e}"))
}

// Per-frame G-buffer / scene input view slices feeding the composite's static
// bindings: the scene HDR resolve, the unified pre-pass normal+depth, and the
// roughness views. Wired at init / resize; the reflection binding is re-pointed
// per encode.
#[derive(Clone, Copy)]
pub(in crate::vulkan) struct CompositeInputViews<'a> {
    pub hdr_resolve_views: &'a [vk::ImageView],
    pub normal_depth_views: &'a [vk::ImageView],
    pub roughness_views: &'a [vk::ImageView],
}

// One full-screen colour target pre-transitioned to SHADER_READ_ONLY_OPTIMAL so the
// descriptor sets bound to it at init see a valid layout before the first encode.
fn create_target(ctx: &GpuUploadContext, width: u32, height: u32) -> Result<GpuImage, String> {
    let &GpuUploadContext {
        alloc,
        device,
        command_pool,
        queue,
    } = ctx;
    let pooled = create_image(
        alloc,
        &super::super::texture::ImageSpec {
            width,
            height,
            format: HDR_FORMAT,
            tiling: vk::ImageTiling::OPTIMAL,
            // TRANSFER_SRC so the transparent (glass) pass can snapshot the
            // post-reflection scene for its refraction tap, the same usage the SSR
            // output carried before the composite owned the scene image.
            usage: vk::ImageUsageFlags::COLOR_ATTACHMENT
                | vk::ImageUsageFlags::SAMPLED
                | vk::ImageUsageFlags::TRANSFER_SRC,
            mem_props: vk::MemoryPropertyFlags::DEVICE_LOCAL,
            samples: vk::SampleCountFlags::TYPE_1,
        },
    )?;
    let image = pooled.image();
    one_shot_submit(device, command_pool, queue, |cmd| {
        transition_image_layout(
            device,
            cmd,
            image,
            vk::ImageLayout::UNDEFINED,
            vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
            vk::ImageAspectFlags::COLOR,
        );
    })?;
    let view = create_image_view(device, image, HDR_FORMAT, vk::ImageAspectFlags::COLOR)?;
    Ok(GpuImage::from_pooled(pooled, view))
}

// Fullscreen pipeline: no vertex input, no depth, no blend; writes one HDR target.
// Mirrors the SSR resolve pipeline.
fn create_composite_pipeline(
    device: &VkDevice,
    render_pass: vk::RenderPass,
    layout: vk::PipelineLayout,
    vert_spv: &[u8],
    frag_spv: &[u8],
) -> Result<OwnedPipeline, String> {
    let vert_mod = spv_module(device, vert_spv)?;
    let frag_mod = spv_module(device, frag_spv)?;
    let entry = std::ffi::CString::new("main").unwrap();

    let stages = [
        vk::PipelineShaderStageCreateInfo::default()
            .stage(vk::ShaderStageFlags::VERTEX)
            .module(vert_mod.handle())
            .name(&entry),
        vk::PipelineShaderStageCreateInfo::default()
            .stage(vk::ShaderStageFlags::FRAGMENT)
            .module(frag_mod.handle())
            .name(&entry),
    ];
    let vert_input = vk::PipelineVertexInputStateCreateInfo::default();
    let input_assembly = vk::PipelineInputAssemblyStateCreateInfo::default()
        .topology(vk::PrimitiveTopology::TRIANGLE_LIST);
    let viewport_state = vk::PipelineViewportStateCreateInfo::default()
        .viewport_count(1)
        .scissor_count(1);
    let raster = vk::PipelineRasterizationStateCreateInfo::default()
        .polygon_mode(vk::PolygonMode::FILL)
        .line_width(1.0)
        .cull_mode(vk::CullModeFlags::NONE)
        .front_face(vk::FrontFace::COUNTER_CLOCKWISE);
    let multisample = vk::PipelineMultisampleStateCreateInfo::default()
        .rasterization_samples(vk::SampleCountFlags::TYPE_1);
    let depth = vk::PipelineDepthStencilStateCreateInfo::default()
        .depth_test_enable(false)
        .depth_write_enable(false)
        .depth_compare_op(vk::CompareOp::ALWAYS);
    let blend_attach = vk::PipelineColorBlendAttachmentState::default()
        .color_write_mask(vk::ColorComponentFlags::RGBA)
        .blend_enable(false);
    let blend = vk::PipelineColorBlendStateCreateInfo::default()
        .attachments(std::slice::from_ref(&blend_attach));
    let dyn_states = [vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR];
    let dynamic = vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dyn_states);

    let info = vk::GraphicsPipelineCreateInfo::default()
        .stages(&stages)
        .vertex_input_state(&vert_input)
        .input_assembly_state(&input_assembly)
        .viewport_state(&viewport_state)
        .rasterization_state(&raster)
        .multisample_state(&multisample)
        .depth_stencil_state(&depth)
        .color_blend_state(&blend)
        .dynamic_state(&dynamic)
        .layout(layout)
        .render_pass(render_pass)
        .subpass(0);
    let pipeline = crate::vulkan::pipeline_cache::create_graphics_pipeline(device, &info)
        .map_err(|e| format!("create reflection composite pso: {e}"))?;
    Ok(pipeline)
}

impl ReflectionCompositeResources {
    // Build every composite resource. `views` bundles the per-frame scene
    // (`hdr_resolve_views`) and the unified G-buffer pre-pass's per-frame
    // `normal_depth_views` + `roughness_views`; these feed the composite's static
    // bindings while the reflection binding is re-pointed per encode. `blur_scale`
    // is the per-axis blur divisor.
    pub(in crate::vulkan) fn new(
        ctx: &GpuUploadContext,
        width: u32,
        height: u32,
        frames: usize,
        blur_scale: u32,
        views: &CompositeInputViews,
        hot_reload: bool,
    ) -> Result<Self, String> {
        let device = ctx.device;
        let blur_scale = blur_scale.max(1);
        let render_pass = create_composite_render_pass(device)?;

        // Blur set 0: reflection + roughness. Composite set 0: reflection + scene +
        // gbuffer normal+depth + roughness + blur.
        let sampler_binding = |b: u32| {
            (
                b,
                vk::DescriptorType::COMBINED_IMAGE_SAMPLER,
                vk::ShaderStageFlags::FRAGMENT,
            )
        };
        let blur_set_layout =
            create_descriptor_set_layout(device, &[sampler_binding(0), sampler_binding(1)])?;
        let composite_set_layout = create_descriptor_set_layout(
            device,
            &[
                sampler_binding(0),
                sampler_binding(1),
                sampler_binding(2),
                sampler_binding(3),
                sampler_binding(4),
            ],
        )?;

        let make_layout = |set_layout: vk::DescriptorSetLayout, name: &str| -> Result<_, String> {
            let layouts = [set_layout];
            device
                .create_pipeline_layout(
                    &vk::PipelineLayoutCreateInfo::default().set_layouts(&layouts),
                )
                .map_err(|e| format!("{name}: {e}"))
        };
        let blur_pipeline_layout = make_layout(blur_set_layout.handle(), "reflection blur layout")?;
        let composite_pipeline_layout =
            make_layout(composite_set_layout.handle(), "reflection composite layout")?;

        let shaders = compile_reflection_composite_shaders(hot_reload)?;
        let blur_pso = create_composite_pipeline(
            device,
            render_pass.handle(),
            blur_pipeline_layout.handle(),
            &shaders.vs,
            &shaders.blur_fs,
        )?;
        let composite_pso = create_composite_pipeline(
            device,
            render_pass.handle(),
            composite_pipeline_layout.handle(),
            &shaders.vs,
            &shaders.composite_fs,
        )?;

        // Pool: per-frame blur sets (2 samplers) + composite sets (5 samplers).
        let f = frames as u32;
        let pool_sizes = [vk::DescriptorPoolSize::default()
            .ty(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
            .descriptor_count(f * 7)];
        let descriptor_pool = device
            .create_descriptor_pool(
                &vk::DescriptorPoolCreateInfo::default()
                    .pool_sizes(&pool_sizes)
                    .max_sets(f * 2),
            )
            .map_err(|e| format!("reflection composite descriptor pool: {e}"))?;
        let blur_layouts: Vec<_> = (0..frames).map(|_| blur_set_layout.handle()).collect();
        let blur_sets = alloc_descriptor_sets(device, descriptor_pool.handle(), &blur_layouts)?;
        let composite_layouts: Vec<_> =
            (0..frames).map(|_| composite_set_layout.handle()).collect();
        let composite_sets =
            alloc_descriptor_sets(device, descriptor_pool.handle(), &composite_layouts)?;

        let sampler = create_sampler_linear_clamp(device)?;

        let mut me = Self {
            output: GpuImage::null(),
            output_framebuffer: OwnedFramebuffer::null(),
            blur: GpuImage::null(),
            blur_framebuffer: OwnedFramebuffer::null(),
            blur_extent: vk::Extent2D::default(),
            render_pass,
            _blur_set_layout: blur_set_layout,
            _composite_set_layout: composite_set_layout,
            blur_pipeline_layout,
            composite_pipeline_layout,
            blur_pso,
            composite_pso,
            _descriptor_pool: descriptor_pool,
            blur_sets,
            composite_sets,
            sampler,
            blur_scale,
        };
        me.build_targets(ctx, width, height)?;
        me.wire_sets(device, views);
        Ok(me)
    }

    // Allocate / re-allocate the resolution-dependent output + blur targets and
    // their framebuffers at the given extent.
    fn build_targets(
        &mut self,
        ctx: &GpuUploadContext,
        width: u32,
        height: u32,
    ) -> Result<(), String> {
        let device = ctx.device;
        let w = width.max(1);
        let h = height.max(1);
        let bw = (w / self.blur_scale).max(1);
        let bh = (h / self.blur_scale).max(1);
        self.output = create_target(ctx, w, h)?;
        self.blur = create_target(ctx, bw, bh)?;
        self.blur_extent = vk::Extent2D {
            width: bw,
            height: bh,
        };

        let make_fb = |view: vk::ImageView, fw: u32, fh: u32| -> Result<OwnedFramebuffer, String> {
            device
                .create_framebuffer(
                    &vk::FramebufferCreateInfo::default()
                        .render_pass(self.render_pass.handle())
                        .attachments(std::slice::from_ref(&view))
                        .width(fw)
                        .height(fh)
                        .layers(1),
                )
                .map_err(|e| format!("reflection composite framebuffer: {e}"))
        };
        self.output_framebuffer = make_fb(self.output.view, w, h)?;
        self.blur_framebuffer = make_fb(self.blur.view, bw, bh)?;
        Ok(())
    }

    // Wire the per-frame static bindings: blur set binding 1 = roughness; composite
    // set bindings 1..4 = scene / normal+depth / roughness / blur. Binding 0 (the
    // reflection target) is left at a valid placeholder and re-pointed per encode.
    // Single-entry G-buffer slices are shared across frames (the legacy pre-pass
    // produced one view); per-frame slices index by frame.
    fn wire_sets(&self, device: &VkDevice, views: &CompositeInputViews) {
        let &CompositeInputViews {
            hdr_resolve_views,
            normal_depth_views,
            roughness_views,
        } = views;
        let img = |view: vk::ImageView| {
            vk::DescriptorImageInfo::default()
                .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                .image_view(view)
                .sampler(self.sampler.handle())
        };
        let write = |set: vk::DescriptorSet, binding: u32, info: &vk::DescriptorImageInfo| {
            let w = vk::WriteDescriptorSet::default()
                .dst_set(set)
                .dst_binding(binding)
                .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                .image_info(std::slice::from_ref(info));
            // SAFETY: `writes` and the buffer/image infos it borrows are live for the call, and
            // every set and resource it names belongs to this device.
            unsafe { device.update_descriptor_sets(std::slice::from_ref(&w), &[]) };
        };
        let pick = |views: &[vk::ImageView], i: usize| views[i % views.len().max(1)];
        let blur_info = img(self.blur.view);
        for i in 0..self.blur_sets.len() {
            let rough = img(pick(roughness_views, i));
            let placeholder = img(pick(hdr_resolve_views, i));
            // Blur set: 0 = reflection placeholder, 1 = roughness.
            write(self.blur_sets[i], 0, &placeholder);
            write(self.blur_sets[i], 1, &rough);
            // Composite set: 0 = reflection placeholder, 1 = scene, 2 = normal+depth,
            // 3 = roughness, 4 = blur.
            let scene = img(pick(hdr_resolve_views, i));
            let nd = img(pick(normal_depth_views, i));
            write(self.composite_sets[i], 0, &placeholder);
            write(self.composite_sets[i], 1, &scene);
            write(self.composite_sets[i], 2, &nd);
            write(self.composite_sets[i], 3, &rough);
            write(self.composite_sets[i], 4, &blur_info);
        }
    }

    fn destroy_targets(&mut self, _device: &VkDevice) {
        self.output_framebuffer = OwnedFramebuffer::null();
        self.blur_framebuffer = OwnedFramebuffer::null();
        self.output = GpuImage::null();
        self.blur = GpuImage::null();
    }

    // Rebuild the resolution-dependent targets at a new extent and re-wire the
    // per-frame static bindings (the scene / G-buffer / blur views all moved). The
    // caller has already idled the device.
    pub(in crate::vulkan) fn rebuild(
        &mut self,
        ctx: &GpuUploadContext,
        width: u32,
        height: u32,
        views: &CompositeInputViews,
    ) -> Result<(), String> {
        self.destroy_targets(ctx.device);
        self.build_targets(ctx, width, height)?;
        self.wire_sets(ctx.device, views);
        Ok(())
    }

    // Swap freshly-built pipelines into the live resources after a hot-reload.
    pub(in crate::vulkan) fn swap_pipelines(&mut self, rebuilt: RebuiltReflectionComposite) {
        self.blur_pso = rebuilt.blur;
        self.composite_pso = rebuilt.composite;
    }

    // Destroy every composite resource. The caller has already idled the device.
    pub(in crate::vulkan) fn destroy(&mut self, device: &VkDevice) {
        self.destroy_targets(device);
    }
}

impl VkContext {
    // Blur the reflection target by surface roughness and composite it over the base
    // HDR scene into `reflection_composite.output`. `reflection_view` is the resolve
    // target the SSR / RT pass just wrote (radiance + weight), in
    // SHADER_READ_ONLY_OPTIMAL after its render pass. Encoded inline at the tail of
    // `encode_ssr_resolve` / `encode_rt_reflections`. No-op when the composite is
    // absent (no reflection path active).
    pub(in crate::vulkan) fn encode_reflection_composite(
        &self,
        cmd: vk::CommandBuffer,
        reflection_view: vk::ImageView,
        frame_idx: usize,
    ) {
        let Some(rc) = &self.reflection_composite else {
            return;
        };
        let device = &self.device;

        // Re-point binding 0 (reflection) of this frame's blur + composite sets at
        // the resolve that just ran. This frame's sets are fence-gated (the previous
        // submission for this slot completed at the top of the frame), so the write
        // is safe; the SSR and RT paths are mutually exclusive, so only one feeds a
        // given frame.
        let refl = vk::DescriptorImageInfo::default()
            .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
            .image_view(reflection_view)
            .sampler(rc.sampler.handle());
        let repoint = [
            vk::WriteDescriptorSet::default()
                .dst_set(rc.blur_sets[frame_idx])
                .dst_binding(0)
                .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                .image_info(std::slice::from_ref(&refl)),
            vk::WriteDescriptorSet::default()
                .dst_set(rc.composite_sets[frame_idx])
                .dst_binding(0)
                .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                .image_info(std::slice::from_ref(&refl)),
        ];
        // SAFETY: `writes` and the buffer/image infos it borrows are live for the call, and every
        // set and resource it names belongs to this device.
        unsafe { device.update_descriptor_sets(&repoint, &[]) };

        // Pass 1: roughness blur into the reduced-resolution blur target.
        self.begin_fullscreen_pass_sized(
            cmd,
            rc.render_pass.handle(),
            rc.blur_framebuffer.handle(),
            rc.blur_extent,
        );
        // SAFETY: `cmd` is a command buffer in the recording state, and every handle and slice
        // these commands name is live for the call.
        unsafe {
            device.cmd_bind_pipeline(cmd, vk::PipelineBindPoint::GRAPHICS, rc.blur_pso.handle());
            device.cmd_bind_descriptor_sets(
                cmd,
                vk::PipelineBindPoint::GRAPHICS,
                rc.blur_pipeline_layout.handle(),
                0,
                std::slice::from_ref(&rc.blur_sets[frame_idx]),
                &[],
            );
            device.cmd_draw(cmd, 3, 1, 0, 0);
        }
        self.end_fullscreen_pass(cmd);

        // Pass 2: lerp sharp vs upsampled blur by roughness, composite over scene.
        self.begin_fullscreen_pass(cmd, rc.render_pass.handle(), rc.output_framebuffer.handle());
        // SAFETY: `cmd` is a command buffer in the recording state, and every handle and slice
        // these commands name is live for the call.
        unsafe {
            device.cmd_bind_pipeline(
                cmd,
                vk::PipelineBindPoint::GRAPHICS,
                rc.composite_pso.handle(),
            );
            device.cmd_bind_descriptor_sets(
                cmd,
                vk::PipelineBindPoint::GRAPHICS,
                rc.composite_pipeline_layout.handle(),
                0,
                std::slice::from_ref(&rc.composite_sets[frame_idx]),
                &[],
            );
            device.cmd_draw(cmd, 3, 1, 0, 0);
        }
        self.end_fullscreen_pass(cmd);
    }
}

#[cfg(test)]
mod tests {
    // The composite vert + blur + composite fragments compile to SPIR-V. Guards the
    // GLSL so a shader error fails a test instead of only an init failure on the GPU
    // host. The composite passes carry no push constant / UBO, so there is no
    // CPU<->GPU layout to assert.
    #[test]
    fn reflection_composite_shaders_compile() {
        if !crate::slangc_gate::slangc_available() {
            return;
        }
        let shaders = super::compile_reflection_composite_shaders(false)
            .expect("reflection composite shaders compile");
        assert!(super::is_spirv(&shaders.vs));
        assert!(super::is_spirv(&shaders.blur_fs));
        assert!(super::is_spirv(&shaders.composite_fs));
    }
}