concinnity-device 0.19.24

GPU backends (Metal, Vulkan, DirectX) behind a device facade for Concinnity
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
// src/vulkan/post/bloom.rs
//
// Bloom for the Vulkan backend. Co-locates the bloom GLSL sources, the
// prefilter / downsample / upsample pipeline builders, the bloom mip-chain
// target allocator (per frame slot), the framebuffer + descriptor wiring, and
// the per-frame `encode_bloom` encoder. Mirrors src/metal/post/bloom.rs.

use ash::vk;

use crate::vulkan::owned::{OwnedFramebuffer, OwnedPipeline, VkDevice};

use super::super::allocator::DeviceAllocator;
use super::super::context::*;
use super::super::pipeline::spv_module;
use super::super::resources::alloc_descriptor_sets;
use super::super::texture::*;
use crate::vulkan::slang_builtins::SlangCompile;

// Upper bound on `bloom_mip_count` (which clamps to 4..=6). The bloom
// descriptor pool is sized for this many mips per frame so a resize that
// changes the octave count never has to resize the pool.
pub(in crate::vulkan) const MAX_BLOOM_MIPS: u32 = 6;

//  Bloom shaders

// SPIR-V for the bloom chain: the shared fullscreen-triangle vertex shader
// plus the prefilter / downsample / upsample fragment shaders.
pub(in crate::vulkan) struct BloomShaders {
    pub vert: Vec<u8>,
    pub prefilter: Vec<u8>,
    pub downsample: Vec<u8>,
    pub upsample: Vec<u8>,
}

pub(in crate::vulkan) fn compile_bloom_shaders(hot_reload: bool) -> Result<BloomShaders, String> {
    use super::super::{builtins, slang_builtins};
    let ctx = builtins::Ctx::plain(hot_reload);
    Ok(BloomShaders {
        vert: slang_builtins::FULLSCREEN_VERT.compile(&ctx)?,
        prefilter: slang_builtins::BLOOM_PREFILTER.compile(&ctx)?,
        downsample: slang_builtins::BLOOM_DOWNSAMPLE.compile(&ctx)?,
        upsample: slang_builtins::BLOOM_UPSAMPLE.compile(&ctx)?,
    })
}

//  Pipeline builder

// Build a bloom-chain pipeline: a vertex-buffer-less fullscreen triangle into
// a single-sample HDR mip, no depth. With `additive` set the colour blend is
// `dst + src`, used by the upsample pass to accumulate onto the downsampled
// mip already in the target.
pub(in crate::vulkan) fn create_bloom_pipeline(
    device: &VkDevice,
    render_pass: vk::RenderPass,
    layout: vk::PipelineLayout,
    vert_spv: &[u8],
    frag_spv: &[u8],
    additive: bool,
) -> 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)
        .primitive_restart_enable(false);
    let viewport_state = vk::PipelineViewportStateCreateInfo::default()
        .viewport_count(1)
        .scissor_count(1);
    let raster = vk::PipelineRasterizationStateCreateInfo::default()
        .depth_clamp_enable(false)
        .rasterizer_discard_enable(false)
        .polygon_mode(vk::PolygonMode::FILL)
        .line_width(1.0)
        .cull_mode(vk::CullModeFlags::NONE)
        .front_face(vk::FrontFace::COUNTER_CLOCKWISE)
        .depth_bias_enable(false);
    let multisample = vk::PipelineMultisampleStateCreateInfo::default()
        .sample_shading_enable(false)
        .rasterization_samples(vk::SampleCountFlags::TYPE_1);
    let depth_stencil = vk::PipelineDepthStencilStateCreateInfo::default()
        .depth_test_enable(false)
        .depth_write_enable(false)
        .depth_compare_op(vk::CompareOp::ALWAYS);

    let color_blend_attach = if additive {
        vk::PipelineColorBlendAttachmentState::default()
            .color_write_mask(vk::ColorComponentFlags::RGBA)
            .blend_enable(true)
            .src_color_blend_factor(vk::BlendFactor::ONE)
            .dst_color_blend_factor(vk::BlendFactor::ONE)
            .color_blend_op(vk::BlendOp::ADD)
            .src_alpha_blend_factor(vk::BlendFactor::ONE)
            .dst_alpha_blend_factor(vk::BlendFactor::ONE)
            .alpha_blend_op(vk::BlendOp::ADD)
    } else {
        vk::PipelineColorBlendAttachmentState::default()
            .color_write_mask(vk::ColorComponentFlags::RGBA)
            .blend_enable(false)
    };

    let color_blend = vk::PipelineColorBlendStateCreateInfo::default()
        .logic_op_enable(false)
        .attachments(std::slice::from_ref(&color_blend_attach));

    let dynamic_states = [vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR];
    let dynamic = vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dynamic_states);

    let pipeline_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_stencil)
        .color_blend_state(&color_blend)
        .dynamic_state(&dynamic)
        .layout(layout)
        .render_pass(render_pass)
        .subpass(0);

    let pipeline = crate::vulkan::pipeline_cache::create_graphics_pipeline(device, &pipeline_info)
        .map_err(|e| format!("create bloom pipeline: {e}"))?;

    Ok(pipeline)
}

//  Target builder

// Number of mip levels in the bloom chain for an HDR target of the given
// resolution. Clamped to 4..=6: enough octaves for a wide soft glow without
// spending a dozen render passes on sub-pixel mips. Mirrors `bloom_mip_count`
// in metal/texture.rs.
pub(in crate::vulkan) fn bloom_mip_count(width: u32, height: u32) -> u32 {
    let min_dim = width.min(height).max(1);
    // mip 0 is already half-res, so subtract one octave before clamping.
    let levels = (min_dim as f32).log2().floor() as i32 - 1;
    levels.clamp(4, 6) as u32
}

// The shared Vulkan device + one-shot upload context threaded through the
// bloom target allocators. Bundles the instance/device borrows with the
// physical device, command pool, and queue used to create images and submit
// the one-shot layout transitions.
pub(in crate::vulkan) struct BloomDeviceContext<'a> {
    pub alloc: &'a DeviceAllocator,
    pub device: &'a VkDevice,
    pub command_pool: vk::CommandPool,
    pub queue: vk::Queue,
}

// Create the bloom mip chain for an HDR target of `width`x`height`. `mips[i]`
// has resolution `(width >> (i+1), height >> (i+1))`, floored at one texel;
// `mips[0]` is half-res. Each mip is a single-sample colour image usable as
// both a render target and a sampled texture, and is pre-transitioned to
// `SHADER_READ_ONLY_OPTIMAL` so the composite pass can bind it even when
// bloom is disabled and the bloom passes never run.
pub(in crate::vulkan) fn create_bloom_mips(
    ctx: &BloomDeviceContext,
    width: u32,
    height: u32,
    format: vk::Format,
    mip0_override: Option<(vk::Image, vk::ImageView)>,
) -> Result<(Vec<GpuImage>, Vec<vk::Extent2D>), String> {
    let &BloomDeviceContext {
        alloc,
        device,
        command_pool,
        queue,
    } = ctx;
    let full_w = width.max(1);
    let full_h = height.max(1);
    let count = bloom_mip_count(full_w, full_h);

    let mut mips = Vec::with_capacity(count as usize);
    let mut extents = Vec::with_capacity(count as usize);
    for i in 0..count {
        let mw = (full_w >> (i + 1)).max(1);
        let mh = (full_h >> (i + 1)).max(1);
        let gpu_image = if i == 0
            && let Some((image, view)) = mip0_override
        {
            // Pooled `bloom_top`: the transient pool owns image + view + memory.
            // Wrap it borrowed so the chain indexes it uniformly; the prefilter
            // re-establishes its layout from UNDEFINED each frame, so no
            // pre-transition is done here.
            GpuImage::borrowed(image, view)
        } else {
            let pooled = create_image(
                alloc,
                &ImageSpec {
                    width: mw,
                    height: mh,
                    format,
                    tiling: vk::ImageTiling::OPTIMAL,
                    usage: vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::SAMPLED,
                    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, format, vk::ImageAspectFlags::COLOR)?;
            GpuImage::from_pooled(pooled, view)
        };
        mips.push(gpu_image);
        extents.push(vk::Extent2D {
            width: mw,
            height: mh,
        });
    }
    Ok((mips, extents))
}

// Create the per-frame-slot bloom mip chains. Returns one chain per slot
// plus the shared mip extents (the same across all slots).
// `bloom_top` is the per-frame pooled mip 0 (one `(image, view)` per frame in
// flight) when bloom is enabled, else empty (mip 0 is committed like the rest).
pub(in crate::vulkan) fn create_bloom_chain(
    ctx: &BloomDeviceContext,
    extent: vk::Extent2D,
    frames: usize,
    bloom_top: &[(vk::Image, vk::ImageView)],
) -> Result<(Vec<Vec<GpuImage>>, Vec<vk::Extent2D>), String> {
    let mut mips = Vec::with_capacity(frames);
    let mut extents = Vec::new();
    for f in 0..frames {
        let (m, e) = create_bloom_mips(
            ctx,
            extent.width,
            extent.height,
            HDR_FORMAT,
            bloom_top.get(f).copied(),
        )?;
        if extents.is_empty() {
            extents = e;
        }
        mips.push(m);
    }
    Ok((mips, extents))
}

// The bloom write and blend framebuffer sets, each indexed [frame][mip].
type BloomFramebuffers = (Vec<Vec<OwnedFramebuffer>>, Vec<Vec<OwnedFramebuffer>>);

// Build the bloom write + blend framebuffers for every frame slot. The write
// set has one framebuffer per mip; the blend set omits the smallest mip,
// which is never upsampled into.
pub(in crate::vulkan) fn create_bloom_framebuffers(
    device: &VkDevice,
    write_pass: vk::RenderPass,
    blend_pass: vk::RenderPass,
    bloom_mips: &[Vec<GpuImage>],
    extents: &[vk::Extent2D],
) -> Result<BloomFramebuffers, String> {
    let make_fb = |rp: vk::RenderPass, view: vk::ImageView, ext: vk::Extent2D| {
        let fb_info = vk::FramebufferCreateInfo::default()
            .render_pass(rp)
            .attachments(std::slice::from_ref(&view))
            .width(ext.width)
            .height(ext.height)
            .layers(1);
        device
            .create_framebuffer(&fb_info)
            .map_err(|e| format!("bloom framebuffer: {e}"))
    };
    let mut write = Vec::with_capacity(bloom_mips.len());
    let mut blend = Vec::with_capacity(bloom_mips.len());
    for mips in bloom_mips {
        let mut w = Vec::with_capacity(mips.len());
        let mut b = Vec::with_capacity(mips.len().saturating_sub(1));
        for (i, mip) in mips.iter().enumerate() {
            w.push(make_fb(write_pass, mip.view, extents[i])?);
            if i + 1 < mips.len() {
                b.push(make_fb(blend_pass, mip.view, extents[i])?);
            }
        }
        write.push(w);
        blend.push(b);
    }
    Ok((write, blend))
}

// Re-point bloom input set 0's binding 0 at `view`. Used when TAA is enabled
// so the bloom prefilter thresholds the post-TAA scene image instead of the
// raw HDR resolve.
pub(in crate::vulkan) fn rebind_bloom_input0(
    device: &VkDevice,
    set: vk::DescriptorSet,
    view: vk::ImageView,
    sampler: vk::Sampler,
) {
    let img_info = vk::DescriptorImageInfo::default()
        .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
        .image_view(view)
        .sampler(sampler);
    let write = vk::WriteDescriptorSet::default()
        .dst_set(set)
        .dst_binding(0)
        .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
        .image_info(std::slice::from_ref(&img_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(&write), &[]) };
}

// Allocate + wire the bloom input descriptor sets. Per frame slot there is
// one set per distinct input image: set 0 binds that slot's HDR resolve
// image, set `1 + m` binds bloom mip `m`.
pub(in crate::vulkan) fn alloc_bloom_input_sets(
    device: &VkDevice,
    pool: vk::DescriptorPool,
    layout: vk::DescriptorSetLayout,
    sampler: vk::Sampler,
    hdr_resolve_images: &[GpuImage],
    bloom_mips: &[Vec<GpuImage>],
) -> Result<Vec<Vec<vk::DescriptorSet>>, String> {
    let mut out = Vec::with_capacity(bloom_mips.len());
    for (frame, mips) in bloom_mips.iter().enumerate() {
        let layouts: Vec<_> = (0..mips.len() + 1).map(|_| layout).collect();
        let sets = alloc_descriptor_sets(device, pool, &layouts)?;
        for (idx, &set) in sets.iter().enumerate() {
            let view = if idx == 0 {
                hdr_resolve_images[frame].view
            } else {
                mips[idx - 1].view
            };
            let img_info = vk::DescriptorImageInfo::default()
                .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                .image_view(view)
                .sampler(sampler);
            let write = vk::WriteDescriptorSet::default()
                .dst_set(set)
                .dst_binding(0)
                .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                .image_info(std::slice::from_ref(&img_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(&write), &[]) };
        }
        out.push(sets);
    }
    Ok(out)
}

//  Per-frame encoder

// The bloom chain orchestration lives once in `gfx::fullscreen`; this impl binds
// + draws each sub-pass in Vulkan. `Args` is the frame-in-flight index selecting
// the per-frame framebuffers + descriptor sets (the scene input is pre-wired into
// `bloom.input_sets[frame_idx][0]`, so prefilter needs no extra argument).
impl crate::gfx::fullscreen::BloomEncoder for VkContext {
    type Rec = vk::CommandBuffer;
    type Args = usize;

    fn bloom_mip_count(&self) -> usize {
        self.bloom.mip_extents.len()
    }

    // All three bloom pipelines share one layout, so the tunables pushed here
    // survive the pipeline switches and the render-pass boundaries between the
    // sub-passes; the rest of the render-pass state is set per sub-pass.
    fn begin_bloom(&self, cmd: &Self::Rec, _frame_idx: &Self::Args) {
        // SAFETY: `cmd` is a command buffer in the recording state, and every handle and slice
        // these commands name is live for the call.
        unsafe {
            self.device.cmd_push_constants(
                *cmd,
                self.bloom.pipeline_layout.handle(),
                vk::ShaderStageFlags::FRAGMENT,
                0,
                bytemuck::bytes_of(&self.post_process),
            );
        }
    }

    // Prefilter: HDR resolve (input set 0) -> mip 0 (soft-knee + Karis).
    fn bloom_prefilter(&self, cmd: &Self::Rec, frame_idx: &Self::Args) {
        let f = *frame_idx;
        self.bloom_run_pass(
            *cmd,
            self.bloom.write_pass.handle(),
            self.bloom.write_framebuffers[f][0].handle(),
            self.bloom.mip_extents[0],
            &self.bloom.pipeline_prefilter,
            self.bloom.input_sets[f][0],
        );
    }

    // Downsample: mip dst-1 -> mip dst. Input set for mip m is `m`.
    fn bloom_downsample(&self, cmd: &Self::Rec, frame_idx: &Self::Args, dst: usize) {
        let f = *frame_idx;
        self.bloom_run_pass(
            *cmd,
            self.bloom.write_pass.handle(),
            self.bloom.write_framebuffers[f][dst].handle(),
            self.bloom.mip_extents[dst],
            &self.bloom.pipeline_downsample,
            self.bloom.input_sets[f][dst],
        );
    }

    // Upsample: mip dst+1 -> mip dst, additively blended. Input set is `dst + 2`.
    fn bloom_upsample(&self, cmd: &Self::Rec, frame_idx: &Self::Args, dst: usize) {
        let f = *frame_idx;
        self.bloom_run_pass(
            *cmd,
            self.bloom.blend_pass.handle(),
            self.bloom.blend_framebuffers[f][dst].handle(),
            self.bloom.mip_extents[dst],
            &self.bloom.pipeline_upsample,
            self.bloom.input_sets[f][dst + 2],
        );
    }
}

impl VkContext {
    // Encode the bloom prefilter, downsample, and additive upsample passes for
    // frame slot `frame_idx` via the shared `gfx::fullscreen` driver. On return
    // `bloom.mips[frame_idx][0]` holds the accumulated bloom the composite pass
    // samples. Called only when `post_process.bloom_intensity > 0`.
    pub(in crate::vulkan) fn encode_bloom(&self, cmd: vk::CommandBuffer, frame_idx: usize) {
        crate::gfx::fullscreen::encode_bloom_chain(self, &cmd, frame_idx);
    }

    // One fullscreen-triangle bloom sub-pass: render into `framebuffer` (sized
    // `ext`) sampling `input_set`, with `pipeline` bound inside `render_pass`.
    fn bloom_run_pass(
        &self,
        cmd: vk::CommandBuffer,
        render_pass: vk::RenderPass,
        framebuffer: vk::Framebuffer,
        ext: vk::Extent2D,
        pipeline: &OwnedPipeline,
        input_set: vk::DescriptorSet,
    ) {
        let device = &self.device;
        let rp_begin = vk::RenderPassBeginInfo::default()
            .render_pass(render_pass)
            .framebuffer(framebuffer)
            .render_area(vk::Rect2D::default().extent(ext));
        let vp = vk::Viewport {
            x: 0.0,
            y: 0.0,
            width: ext.width as f32,
            height: ext.height as f32,
            min_depth: 0.0,
            max_depth: 1.0,
        };
        let scissor = vk::Rect2D::default().extent(ext);
        // 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_begin_render_pass(cmd, &rp_begin, vk::SubpassContents::INLINE);
            device.cmd_set_viewport(cmd, 0, std::slice::from_ref(&vp));
            device.cmd_set_scissor(cmd, 0, std::slice::from_ref(&scissor));
            device.cmd_bind_pipeline(cmd, vk::PipelineBindPoint::GRAPHICS, pipeline.handle());
            device.cmd_bind_descriptor_sets(
                cmd,
                vk::PipelineBindPoint::GRAPHICS,
                self.bloom.pipeline_layout.handle(),
                0,
                std::slice::from_ref(&input_set),
                &[],
            );
            device.cmd_draw(cmd, 3, 1, 0, 0);
            device.cmd_end_render_pass(cmd);
        }
    }
}