concinnity-device 0.19.119

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
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
//! Projected (deferred) decals for the Vulkan backend. Each decal is drawn
//! as a unit cube (positions in `[-0.5, 0.5]^3`) transformed by its world
//! model matrix and the camera VP; the fragment shader samples the main
//! pass's depth attachment to reconstruct the world-space sample point at
//! each pixel and tests it against the decal's local bounding box,
//! stamping the texture onto whatever fills the box.
//!
//! Runs after the main HDR resolve and before SSR resolve / TAA, so
//! decals are reflected and tracked by the temporal history just like
//! the rest of the scene. Mirrors `src/directx/decal.rs` and
//! `src/metal/decal.rs`.

use ash::vk;
use concinnity_core::gfx::frustum::Frustum;
use concinnity_core::render::decal::DecalRecord;
use concinnity_core::render::error::{RenderError, RenderResult};
use concinnity_core::transform::mat4_inverse;
use std::cell::Cell;
// `DecalView` (per-frame, 144 bytes) is the layout struct shared with the other
// backends; the per-decal `DecalParams` (160 bytes, inside the 256-byte stride
// slot) rides the set's slots. Both mirror `shaders/decal.hlsl`.
use concinnity_core::render::uniforms::DecalView;

use super::allocator::{DeviceAllocator, PooledBuffer};
use super::context::VkContext;
use super::descriptor_layout::{Binding, PoolSizes};
use super::pipeline_desc::{Blend, GraphicsPipelineDesc, Raster};
use super::resources::{alloc_descriptor_sets, create_descriptor_set_layout, source_set_bindings};
use super::set_writes::SetWrites;
use super::texture::GpuImage;
use crate::vulkan::builtin_shaders::CompileProgram;
use crate::vulkan::owned::{
    OwnedDescriptorPool, OwnedFramebuffer, OwnedPipeline, OwnedPipelineLayout, OwnedRenderPass,
    OwnedSetLayout, VkDevice,
};

// Cap on the number of active decals: the descriptor pool reserves a
// fixed block of `MAX_DECALS` per-decal albedo sets at init, so runtime
// adds past this many return an error.
pub(in crate::vulkan) const MAX_DECALS: usize = 256;

// Eight unit-cube corners in [-0.5, 0.5]^3. Matches the DirectX / Metal
// vertex lists.
const CUBE_VERTS: [f32; 24] = [
    -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5,
    0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5,
];

// 36 indices forming 12 triangles wound CCW outward. Matches the
// DirectX / Metal index list so the rasterized cube exactly mirrors the
// reference.
const CUBE_INDICES: [u16; 36] = [
    // -Z face                +Z face
    0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, // -Y                     +Y
    0, 1, 5, 0, 5, 4, 3, 6, 2, 3, 7, 6, // -X                     +X
    0, 4, 7, 0, 7, 3, 1, 2, 6, 1, 6, 5,
];

// Stride for the per-decal params uniform buffer ring. Vulkan's
// `minUniformBufferOffsetAlignment` is at most 256 bytes on every
// desktop GPU we target (spec-guaranteed upper bound), so a constant
// 256 byte stride keeps each dynamic-offset slot naturally aligned
// without querying the device.
const PARAMS_STRIDE: u64 = 256;

// Owned by `VkContext` exactly once: the decal pipeline + its dependent
// resources. The decal slot table lives on `VkContext` itself (mirroring the
// DirectX / Metal layout).
//
// Decal-pass descriptor sets follow a two-set layout:
//   * **set 0** (per-frame, FRAMES sets):
//       - binding 0: UNIFORM_BUFFER, `DecalView` (per-frame)
//       - binding 1: UNIFORM_BUFFER_DYNAMIC, `DecalParams` ring (per-frame,
//         MAX_DECALS slots; dynamic offset picks the per-decal slot)
//       - binding 2: SAMPLED_IMAGE, main depth view, read by texel (per-frame
//         so a future-frame depth swap doesn't break a binding allocated
//         from a sibling frame slot)
//   * **set 1** (per-decal, MAX_DECALS sets):
//       - binding 0: SAMPLED_IMAGE, decal albedo
//       - binding 1: SAMPLER, the albedo's sampler
pub(in crate::vulkan) struct DecalResources {
    pub(in crate::vulkan) render_pass: OwnedRenderPass,
    pub(in crate::vulkan) pipeline: OwnedPipeline,
    pub(in crate::vulkan) pipeline_layout: OwnedPipelineLayout,
    pub(in crate::vulkan) _view_set_layout: OwnedSetLayout,
    pub(in crate::vulkan) _albedo_set_layout: OwnedSetLayout,
    pub(in crate::vulkan) _descriptor_pool: OwnedDescriptorPool,

    // Unit-cube vertex + index buffers (shared across frames).
    pub(in crate::vulkan) vertex_buffer: PooledBuffer,
    pub(in crate::vulkan) index_buffer: PooledBuffer,

    // Per-frame view UBO (DecalView, 144 bytes). Persistently mapped.
    pub(in crate::vulkan) view_ubos: Vec<PooledBuffer>,

    // Per-frame per-decal params ring (PARAMS_STRIDE * MAX_DECALS bytes).
    // Persistently mapped; bound as UNIFORM_BUFFER_DYNAMIC with a
    // per-draw offset of `decal_id * PARAMS_STRIDE`.
    pub(in crate::vulkan) params_ubos: Vec<PooledBuffer>,

    // Per-frame view sets (binding 0 view UBO, 1 params dynamic, 2 depth).
    pub(in crate::vulkan) view_sets: Vec<vk::DescriptorSet>,
    // Per-decal albedo sets (binding 0 albedo, 1 its sampler). Indexed by
    // `decal_id`; tombstoned slots keep their last write, but the
    // executor only binds the set for visible records.
    pub(in crate::vulkan) albedo_sets: Vec<vk::DescriptorSet>,

    // One framebuffer per frame-in-flight slot, each binding its frame
    // slot's `hdr_resolve_images[i].view` as the sole color attachment.
    pub(in crate::vulkan) framebuffers: Vec<OwnedFramebuffer>,

    // Last-uploaded texture-pool slot per decal id. Used by
    // `rewrite_texture_slot` to detect which decal albedo sets need
    // re-writing when a streamed texture pool entry swaps.
    pub(in crate::vulkan) decal_texture_slots: Cell<[usize; MAX_DECALS]>,
}

// Vulkan handles needed to create the decal pass's GPU resources
// (buffers, one-shot transfer submits). Borrowed for the duration of
// `DecalResources::new`.
#[derive(Clone, Copy)]
pub(in crate::vulkan) struct DecalDeviceContext<'a> {
    pub(in crate::vulkan) alloc: &'a DeviceAllocator,
    pub(in crate::vulkan) device: &'a VkDevice,
    pub(in crate::vulkan) command_pool: vk::CommandPool,
    pub(in crate::vulkan) queue: vk::Queue,
}

// Render-target inputs the decal pass writes into / samples from: the
// resolved HDR color attachment (format + per-frame views), the main
// depth views, the albedo sampler, and the framebuffer extent.
#[derive(Clone, Copy)]
pub(in crate::vulkan) struct DecalPassTargets<'a> {
    pub(in crate::vulkan) hdr_format: vk::Format,
    pub(in crate::vulkan) hdr_resolve_views: &'a [vk::ImageView],
    pub(in crate::vulkan) depth_views: &'a [vk::ImageView],
    pub(in crate::vulkan) sampler: vk::Sampler,
    pub(in crate::vulkan) extent: vk::Extent2D,
}

impl DecalResources {
    // Build the decal pipeline + its dependent resources. Called
    // unconditionally from `VkContext::new` so runtime `add_decal`
    // works from a world that started empty; the cost is one pipeline
    // + small buffers.
    pub(in crate::vulkan) fn new(
        ctx: DecalDeviceContext,
        targets: DecalPassTargets,
        frames: usize,
        msaa: bool,
        hot_reload: bool,
    ) -> RenderResult<Self> {
        let DecalDeviceContext {
            alloc,
            device,
            command_pool,
            queue,
        } = ctx;
        let DecalPassTargets {
            hdr_format,
            hdr_resolve_views,
            depth_views,
            sampler,
            extent,
        } = targets;
        let render_pass = create_decal_render_pass(device, hdr_format)?;
        let view_set_layout = create_descriptor_set_layout(device, &view_set_bindings())?;
        let albedo_set_layout = create_descriptor_set_layout(device, &source_set_bindings(1))?;
        let pipeline_layout = create_decal_pipeline_layout(
            device,
            view_set_layout.handle(),
            albedo_set_layout.handle(),
        )?;

        let (vert_spv, frag_spv) = compile_decal_shaders(hot_reload, msaa)?;
        let pipeline = create_decal_pipeline(
            device,
            render_pass.handle(),
            pipeline_layout.handle(),
            &vert_spv,
            &frag_spv,
        )?;

        // Unit-cube vertex + index buffers (single device-local upload).
        let vertex_buffer = upload_static_buffer(
            alloc,
            device,
            command_pool,
            queue,
            bytemuck_cast(&CUBE_VERTS),
            vk::BufferUsageFlags::VERTEX_BUFFER,
        )?;
        let index_buffer = upload_static_buffer(
            alloc,
            device,
            command_pool,
            queue,
            bytemuck_cast(&CUBE_INDICES),
            vk::BufferUsageFlags::INDEX_BUFFER,
        )?;

        // Per-frame view UBOs (HOST_VISIBLE | HOST_COHERENT, persistently
        // mapped).
        let mut view_ubos = Vec::with_capacity(frames);
        for _ in 0..frames {
            view_ubos.push(alloc.create_buffer(
                std::mem::size_of::<DecalView>() as u64,
                vk::BufferUsageFlags::UNIFORM_BUFFER,
                vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
            )?);
        }

        // Per-frame per-decal params ring.
        let params_total = PARAMS_STRIDE * MAX_DECALS as u64;
        let mut params_ubos = Vec::with_capacity(frames);
        for _ in 0..frames {
            params_ubos.push(alloc.create_buffer(
                params_total,
                vk::BufferUsageFlags::UNIFORM_BUFFER,
                vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
            )?);
        }

        let descriptor_pool = create_decal_descriptor_pool(device, frames)?;

        // Per-frame view sets (one per frame slot).
        let view_layouts: Vec<_> = (0..frames).map(|_| view_set_layout.handle()).collect();
        let view_sets = alloc_descriptor_sets(device, descriptor_pool.handle(), &view_layouts)?;
        for (i, &set) in view_sets.iter().enumerate() {
            // The dynamic params binding windows one PARAMS_STRIDE slot at the
            // offset given at bind time.
            SetWrites::new(set)
                .uniform_buffer(
                    0,
                    view_ubos[i].buffer(),
                    std::mem::size_of::<DecalView>() as u64,
                )
                .buffer(
                    1,
                    vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC,
                    params_ubos[i].buffer(),
                    0,
                    PARAMS_STRIDE,
                )
                .sampled_image(2, depth_views[i.min(depth_views.len().saturating_sub(1))])
                .apply(device);
        }

        // Per-decal albedo sets (MAX_DECALS sets, pre-allocated).
        let albedo_layouts: Vec<_> = (0..MAX_DECALS)
            .map(|_| albedo_set_layout.handle())
            .collect();
        let albedo_sets = alloc_descriptor_sets(device, descriptor_pool.handle(), &albedo_layouts)?;
        // The sampler never changes, so it is written once here; a decal's
        // albedo image is written when the decal takes the slot.
        for &set in &albedo_sets {
            SetWrites::new(set).sampler(1, sampler).apply(device);
        }

        // Per-frame framebuffers (one per frame slot binding that slot's
        // hdr_resolve view as the color attachment).
        let mut framebuffers = Vec::with_capacity(frames);
        for &view in hdr_resolve_views.iter().take(frames) {
            let attachments = [view];
            let fb_info = vk::FramebufferCreateInfo::default()
                .render_pass(render_pass.handle())
                .attachments(&attachments)
                .width(extent.width.max(1))
                .height(extent.height.max(1))
                .layers(1);
            let fb = device
                .create_framebuffer(&fb_info)
                .map_err(|e| super::error::map_vk_result(e, "decal framebuffer"))?;
            framebuffers.push(fb);
        }

        Ok(Self {
            render_pass,
            pipeline,
            pipeline_layout,
            _view_set_layout: view_set_layout,
            _albedo_set_layout: albedo_set_layout,
            _descriptor_pool: descriptor_pool,
            vertex_buffer,
            index_buffer,
            view_ubos,
            params_ubos,
            view_sets,
            albedo_sets,
            framebuffers,
            decal_texture_slots: Cell::new([usize::MAX; MAX_DECALS]),
        })
    }

    // Rebuild the framebuffers + re-point the per-frame view set's depth
    // binding after a swapchain resize. Called from
    // `VkContext::rebuild_swapchain`; same pattern as `SsrResources` /
    // `SsaoResources`. The pipeline, layouts, buffers, and
    // per-decal albedo sets all survive.
    pub(in crate::vulkan) fn rebuild(
        &mut self,
        device: &VkDevice,
        hdr_resolve_views: &[vk::ImageView],
        depth_views: &[vk::ImageView],
        extent: vk::Extent2D,
    ) -> RenderResult<()> {
        self.framebuffers.clear();
        for &view in hdr_resolve_views.iter().take(self.view_ubos.len()) {
            let attachments = [view];
            let fb_info = vk::FramebufferCreateInfo::default()
                .render_pass(self.render_pass.handle())
                .attachments(&attachments)
                .width(extent.width.max(1))
                .height(extent.height.max(1))
                .layers(1);
            let fb = device
                .create_framebuffer(&fb_info)
                .map_err(|e| super::error::map_vk_result(e, "decal framebuffer (rebuild)"))?;
            self.framebuffers.push(fb);
        }
        // Re-point each per-frame view set's depth binding (binding 2)
        // at the rebuilt depth view.
        for (i, &set) in self.view_sets.iter().enumerate() {
            SetWrites::new(set)
                .sampled_image(2, depth_views[i.min(depth_views.len().saturating_sub(1))])
                .apply(device);
        }
        Ok(())
    }

    // Destroy every GPU resource. Called from `VkContext::destroy` after
    // `wait_idle`; the pooled buffers retire through the allocator as their
    // fields clear.
    pub(in crate::vulkan) fn destroy(&mut self, _device: &VkDevice) {
        self.framebuffers.clear();
        self.view_ubos.clear();
        self.params_ubos.clear();
        self.vertex_buffer = PooledBuffer::null();
        self.index_buffer = PooledBuffer::null();
    }
}

// Render pass / pipeline construction

fn create_decal_render_pass(
    device: &VkDevice,
    format: vk::Format,
) -> RenderResult<OwnedRenderPass> {
    // One color attachment: the resolved HDR scene. The main pass left
    // it in SHADER_READ_ONLY_OPTIMAL; we want it in COLOR_ATTACHMENT
    // during the subpass, then SHADER_READ_ONLY_OPTIMAL again on exit so
    // SSR / TAA / bloom / composite can sample it. The subpass
    // dependencies + (initial=SHADER_READ_ONLY, final=SHADER_READ_ONLY)
    // do the round-trip transition without an explicit barrier from the
    // caller.
    let attachment = vk::AttachmentDescription::default()
        .format(format)
        .samples(vk::SampleCountFlags::TYPE_1)
        .load_op(vk::AttachmentLoadOp::LOAD)
        .store_op(vk::AttachmentStoreOp::STORE)
        .stencil_load_op(vk::AttachmentLoadOp::DONT_CARE)
        .stencil_store_op(vk::AttachmentStoreOp::DONT_CARE)
        .initial_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
        .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));
    // Entry: anyone sampling the resolved HDR (e.g. the main pass's resolve
    // attachment writer, which finished with this image in
    // SHADER_READ_ONLY) must complete before the decal subpass starts
    // writing it.
    let dep_in = 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::SHADER_READ | vk::AccessFlags::COLOR_ATTACHMENT_WRITE)
        .dst_stage_mask(vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT)
        .dst_access_mask(
            vk::AccessFlags::COLOR_ATTACHMENT_WRITE | vk::AccessFlags::COLOR_ATTACHMENT_READ,
        );
    // Exit: any subsequent SSR / TAA / bloom / composite pass reading the
    // resolved HDR must wait for our writes to complete and become
    // available + visible to the fragment shader.
    let dep_out = vk::SubpassDependency::default()
        .src_subpass(0)
        .dst_subpass(vk::SUBPASS_EXTERNAL)
        .src_stage_mask(vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT)
        .src_access_mask(vk::AccessFlags::COLOR_ATTACHMENT_WRITE)
        .dst_stage_mask(vk::PipelineStageFlags::FRAGMENT_SHADER)
        .dst_access_mask(vk::AccessFlags::SHADER_READ);
    let deps = [dep_in, dep_out];
    let info = vk::RenderPassCreateInfo::default()
        .attachments(std::slice::from_ref(&attachment))
        .subpasses(std::slice::from_ref(&subpass))
        .dependencies(&deps);
    device
        .create_render_pass(&info)
        .map_err(|e| super::error::map_vk_result(e, "decal render pass"))
}

// Set 0, per frame: the view UBO, the per-decal params dynamic UBO and the
// main depth.
fn view_set_bindings() -> [Binding; 3] {
    use vk::DescriptorType as T;
    let vert_frag = vk::ShaderStageFlags::VERTEX | vk::ShaderStageFlags::FRAGMENT;
    [
        (0, T::UNIFORM_BUFFER, vert_frag),
        (1, T::UNIFORM_BUFFER_DYNAMIC, vert_frag),
        (2, T::SAMPLED_IMAGE, vk::ShaderStageFlags::FRAGMENT),
    ]
}

fn create_decal_pipeline_layout(
    device: &VkDevice,
    view_set_layout: vk::DescriptorSetLayout,
    albedo_set_layout: vk::DescriptorSetLayout,
) -> RenderResult<OwnedPipelineLayout> {
    let set_layouts = [view_set_layout, albedo_set_layout];
    let info = vk::PipelineLayoutCreateInfo::default().set_layouts(&set_layouts);
    device
        .create_pipeline_layout(&info)
        .map_err(|e| super::error::map_vk_result(e, "decal pipeline layout"))
}

fn create_decal_descriptor_pool(
    device: &VkDevice,
    frames: usize,
) -> RenderResult<OwnedDescriptorPool> {
    let frames = frames as u32;
    let max_decals = MAX_DECALS as u32;
    let sizes = PoolSizes::default()
        .sets(&view_set_bindings(), frames)
        .sets(&source_set_bindings(1), max_decals)
        .build();
    let info = vk::DescriptorPoolCreateInfo::default()
        .max_sets(frames + max_decals)
        .pool_sizes(&sizes);
    device
        .create_descriptor_pool(&info)
        .map_err(|e| super::error::map_vk_result(e, "decal descriptor pool"))
}

fn compile_decal_shaders(hot_reload: bool, msaa: bool) -> RenderResult<(Vec<u8>, Vec<u8>)> {
    let vert = super::builtin_shaders::DECAL_VERT.compile(hot_reload)?;
    let frag = super::builtin_shaders::DECAL_FRAG
        .at(msaa)
        .compile(hot_reload)?;
    Ok((vert, frag))
}

// Rebuild the decal graphics pipeline against the existing render pass +
// layout. Used by the Vulkan shader hot-reload path. The caller is
// responsible for destroying the previous pipeline only after this call
// succeeds.
pub(in crate::vulkan) fn rebuild_decal_pipeline(
    device: &VkDevice,
    decals: &DecalResources,
    msaa: bool,
    hot_reload: bool,
) -> RenderResult<OwnedPipeline> {
    let (vert_spv, frag_spv) = compile_decal_shaders(hot_reload, msaa)?;
    create_decal_pipeline(
        device,
        decals.render_pass.handle(),
        decals.pipeline_layout.handle(),
        &vert_spv,
        &frag_spv,
    )
}

// A unit cube with front faces culled, so the back faces still rasterize when
// the camera is inside the decal volume, alpha-blended into the SINGLE-SAMPLE
// resolved HDR regardless of the main pass's MSAA. Mirrors DirectX / Metal.
fn create_decal_pipeline(
    device: &VkDevice,
    render_pass: vk::RenderPass,
    layout: vk::PipelineLayout,
    vert_spv: &[u8],
    frag_spv: &[u8],
) -> RenderResult<OwnedPipeline> {
    let bindings = [vk::VertexInputBindingDescription::default()
        .binding(0)
        .stride(12) // vec3 position
        .input_rate(vk::VertexInputRate::VERTEX)];
    let attrs = [vk::VertexInputAttributeDescription::default()
        .location(0)
        .binding(0)
        .format(vk::Format::R32G32B32_SFLOAT)
        .offset(0)];
    GraphicsPipelineDesc {
        raster: Raster {
            cull: vk::CullModeFlags::FRONT,
            ..Raster::default()
        },
        vertex_bindings: &bindings,
        vertex_attributes: &attrs,
        ..GraphicsPipelineDesc::fullscreen(
            vert_spv,
            frag_spv,
            layout,
            render_pass,
            &[Blend::AlphaOver],
        )
    }
    .build(device, "decal")
}

// Helpers for upload + casting

fn upload_static_buffer(
    alloc: &DeviceAllocator,
    device: &VkDevice,
    command_pool: vk::CommandPool,
    queue: vk::Queue,
    data: &[u8],
    usage: vk::BufferUsageFlags,
) -> RenderResult<PooledBuffer> {
    let size = data.len() as vk::DeviceSize;
    let staging = alloc.create_buffer(
        size,
        vk::BufferUsageFlags::TRANSFER_SRC,
        vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
    )?;
    staging.write_bytes(0, data);
    let buf = alloc.create_buffer(
        size,
        usage | vk::BufferUsageFlags::TRANSFER_DST,
        vk::MemoryPropertyFlags::DEVICE_LOCAL,
    )?;
    super::texture::one_shot_submit(device, command_pool, queue, |cmd| {
        let region = vk::BufferCopy::default().size(size);
        // 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_copy_buffer(
                cmd,
                staging.buffer(),
                buf.buffer(),
                std::slice::from_ref(&region),
            )
        };
    })?;
    Ok(buf)
}

fn bytemuck_cast<T: bytemuck::NoUninit>(s: &[T]) -> &[u8] {
    bytemuck::cast_slice(s)
}

// Encoder

impl VkContext {
    // Encode the projected-decal pass. Called between the main HDR
    // resolve and the SSR resolve so a decal is reflected by SSR and
    // tracked by TAA's history buffer like the rest of the scene.
    //
    // `vp` is the same jittered view-projection the main pass
    // rasterized with; the inverse drives the world-space reconstruction
    // in the fragment shader.
    pub(in crate::vulkan) fn encode_decals(
        &self,
        cmd: vk::CommandBuffer,
        frame_idx: usize,
        vp: [[f32; 4]; 4],
        frustum: &Frustum,
    ) {
        let decals = match &self.decal.resources {
            Some(s) => s,
            None => return,
        };
        // Frustum-cull first so a frame where every live decal lands
        // off-screen skips the pass, including the depth-transition
        // barriers. Peeking answers that without testing any decal twice.
        let mut visible = self.decal.set.visible(frustum).peekable();
        if visible.peek().is_none() {
            return;
        }

        let device = &self.hw.device;
        let extent = self.targets.render_extent;

        // Upload this frame's view UBO.
        let inv_vp = mat4_inverse(vp);
        let viewport_pix = [extent.width as f32, extent.height as f32];
        let view_uni = DecalView {
            vp,
            inv_vp,
            viewport: viewport_pix,
            _pad: [0.0; 2],
        };
        decals.view_ubos[frame_idx].write_val(0, &view_uni);

        // Main depth is already in SHADER_READ_ONLY for the fragment's sample:
        // the graph declares this pass's depth read and the executor emits the
        // transition ahead of this command buffer.
        let rp_begin = vk::RenderPassBeginInfo::default()
            .render_pass(decals.render_pass.handle())
            .framebuffer(decals.framebuffers[frame_idx].handle())
            .render_area(vk::Rect2D::default().extent(extent));

        // Negative-height viewport matches the main pass so the
        // rasterized pixel grid lines up with the depth attachment we're
        // sampling. Without this, the cube would be drawn Y-flipped
        // relative to the scene depth.
        let vp_state = vk::Viewport {
            x: 0.0,
            y: extent.height as f32,
            width: extent.width as f32,
            height: -(extent.height as f32),
            min_depth: 0.0,
            max_depth: 1.0,
        };
        let scissor = vk::Rect2D::default().extent(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_begin_render_pass(cmd, &rp_begin, vk::SubpassContents::INLINE);
            device.cmd_set_viewport(cmd, 0, std::slice::from_ref(&vp_state));
            device.cmd_set_scissor(cmd, 0, std::slice::from_ref(&scissor));
            device.cmd_bind_pipeline(
                cmd,
                vk::PipelineBindPoint::GRAPHICS,
                decals.pipeline.handle(),
            );
            device.cmd_bind_vertex_buffers(cmd, 0, &[decals.vertex_buffer.buffer()], &[0]);
            device.cmd_bind_index_buffer(
                cmd,
                decals.index_buffer.buffer(),
                0,
                vk::IndexType::UINT16,
            );
        }

        for decal in visible {
            // This frame's ring slot keeps what an earlier frame wrote, so a
            // decal whose record has not changed since is already uploaded.
            if decal.take_upload(frame_idx) {
                decals.params_ubos[frame_idx]
                    .write_val(decal.id * PARAMS_STRIDE as usize, decal.params);
            }
            let dynamic_offset = (decal.id as u64 * PARAMS_STRIDE) as u32;
            // 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_descriptor_sets(
                    cmd,
                    vk::PipelineBindPoint::GRAPHICS,
                    decals.pipeline_layout.handle(),
                    0,
                    std::slice::from_ref(&decals.view_sets[frame_idx]),
                    std::slice::from_ref(&dynamic_offset),
                );
                device.cmd_bind_descriptor_sets(
                    cmd,
                    vk::PipelineBindPoint::GRAPHICS,
                    decals.pipeline_layout.handle(),
                    1,
                    std::slice::from_ref(&decals.albedo_sets[decal.id]),
                    &[],
                );
                device.cmd_draw_indexed(cmd, 36, 1, 0, 0, 0);
            }
            self.inc_draw_calls(1);
        }

        // 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_end_render_pass(cmd);
        }
    }
}

// Runtime mutation (RenderBackend::add_decal / remove_decal)

impl VkContext {
    // Append a runtime decal. Writes the per-decal albedo descriptor
    // into the reserved slot for `id`; the encoder reads it next frame.
    // Reuses tombstoned slots from a prior `remove_decal` before growing
    // the vec.
    pub(crate) fn add_decal(&mut self, record: DecalRecord) -> RenderResult<usize> {
        let last_tex = self.scene.textures.len().saturating_sub(1);
        let tex_idx = record.texture_slot.min(last_tex);

        let id = self.decal.set.insert(record).map_err(|_| {
            RenderError::Other(format!("add_decal: MAX_DECALS ({MAX_DECALS}) exceeded"))
        })?;

        // Write the albedo descriptor for this slot. The texture pool
        // entry is referenced live; a future eviction routes through
        // `rewrite_texture_slot` to re-point.
        let decals = self.decal.resources.as_ref().ok_or_else(|| {
            RenderError::Other("add_decal: decal pipeline unavailable".to_string())
        })?;
        write_albedo_image(
            &self.hw.device,
            decals.albedo_sets[id],
            self.scene.textures[tex_idx].view,
        );
        let mut slots = decals.decal_texture_slots.get();
        slots[id] = tex_idx;
        decals.decal_texture_slots.set(slots);
        Ok(id)
    }

    // Tombstone a runtime decal slot. The id becomes invalid; the next
    // `add_decal` may reuse it. Reached only through the bin's `cn debug`
    // runtime-mutation path (dead in the FFI lib, live in the bin).
    pub(crate) fn remove_decal(&mut self, decal_id: usize) -> RenderResult<()> {
        self.decal
            .set
            .remove(decal_id)
            .map_err(|e| RenderError::Other(format!("remove_decal: id {decal_id} {e}")))?;
        if let Some(decals) = &self.decal.resources {
            let mut slots = decals.decal_texture_slots.get();
            slots[decal_id] = usize::MAX;
            decals.decal_texture_slots.set(slots);
        }
        Ok(())
    }

    // Re-point every decal albedo set that pointed at texture-pool slot
    // `slot` to the new `GpuImage` at that slot. Called from the
    // streaming-texture path when an evicted slot is replaced. Walks
    // `decal.resources.decal_texture_slots` so a world with no decals pays
    // nothing.
    // Whether any live decal's albedo set samples texture-pool `slot`. The
    // streaming fast path checks this: decal sets are single-copy and bound
    // whenever the decal pass runs, so a swap of a slot they sample must
    // drain the device before rewriting.
    pub(in crate::vulkan) fn decal_samples_slot(&self, slot: usize) -> bool {
        match &self.decal.resources {
            Some(s) => s.decal_texture_slots.get().contains(&slot),
            None => false,
        }
    }

    pub(in crate::vulkan) fn rewrite_decal_albedo_slot(&self, slot: usize) {
        let decals = match &self.decal.resources {
            Some(s) => s,
            None => return,
        };
        let slots = decals.decal_texture_slots.get();
        let last_tex = self.scene.textures.len().saturating_sub(1);
        for (id, &tex_slot) in slots.iter().enumerate() {
            if tex_slot == slot {
                let view = self.scene.textures[tex_slot.min(last_tex)].view;
                write_albedo_image(&self.hw.device, decals.albedo_sets[id], view);
            }
        }
    }
}

// Point a decal's albedo set at `view`. Its sampler was written with the set.
fn write_albedo_image(device: &VkDevice, set: vk::DescriptorSet, view: vk::ImageView) {
    SetWrites::new(set).sampled_image(0, view).apply(device);
}

// Wire authored decals into the runtime state at init.

impl VkContext {
    // Push every world-authored `DecalRecord` through `add_decal` so its
    // albedo descriptor lands in the reserved slot. Called once from
    // `VkContext::new` after `decal.resources` is built.
    pub(in crate::vulkan) fn upload_initial_decals(
        &mut self,
        records: Vec<DecalRecord>,
    ) -> RenderResult<()> {
        if records.len() > MAX_DECALS {
            return Err(RenderError::Other(format!(
                "decals: {} authored decals exceed MAX_DECALS ({})",
                records.len(),
                MAX_DECALS
            )));
        }
        for rec in records {
            self.add_decal(rec)?;
        }
        Ok(())
    }
}

// Re-export GpuImage so the textures module compiles cleanly when the
// decal module is the only consumer of a few of its helpers.
type _Marker = GpuImage;