kiss3d 0.43.0

Keep it simple, stupid, 2D and 3D graphics engine for Rust.
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
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
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
//! HDR finishing for the rasterization pipeline: floating-point film, ACES /
//! Reinhard tonemapping and Kawase dual-filter bloom.
//!
//! The rasterizer renders the scene into a linear `Rgba16Float` HDR texture (so
//! emissive values and bright highlights survive `> 1.0`). This module owns that
//! HDR target plus a bloom mip chain, and resolves everything into the final LDR
//! swapchain / offscreen texture in a single tonemap+composite pass.
//!
//! Pipeline order (see `window/rendering.rs`):
//!   1. the scene is rasterized into the (optionally multisampled) HDR target;
//!   2. MSAA is resolved into a single-sample HDR texture;
//!   3. bloom extracts/blurs bright pixels through the mip chain;
//!   4. the tonemap pass composites bloom, applies exposure + the tonemap
//!      operator + gamma, and writes LDR.
//!
//! Existing [`PostProcessingEffect`](crate::post_processing::PostProcessingEffect)s
//! run **after** tonemapping (on the resolved LDR image), so they are unaffected
//! by the HDR change.

use crate::context::Context;
use bytemuck::{Pod, Zeroable};

/// The floating-point format used for the HDR scene target and bloom chain.
pub const HDR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;

/// Weighted-blended OIT accumulation target (premultiplied weighted color + weight).
pub const OIT_ACCUM_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
/// Weighted-blended OIT revealage target (product of `1 - alpha`).
pub const OIT_REVEAL_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R16Float;

/// Number of mip levels in the bloom chain (each half the previous resolution).
const BLOOM_MIPS: u32 = 5;

/// Tonemapping operator applied during the HDR resolve pass.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum Tonemap {
    /// No tonemapping; the HDR color is simply clamped to `[0, 1]` (then gamma
    /// encoded). The old, pre-HDR rasterizer look.
    None,
    /// ACES filmic tonemapping. Cinematic, but desaturates saturated colors and
    /// skews some hues — included mostly for comparison. Matches the path tracer.
    Aces,
    /// Reinhard tonemapping (`x / (1 + x)`).
    Reinhard,
    /// AgX neutral filmic tonemapping. Graceful highlight roll-off without ACES's
    /// hue skews; mild, even desaturation toward white at the top.
    AgX,
    /// Khronos PBR Neutral tonemapping (the default). Preserves the saturation of
    /// in-gamut colors and only desaturates true highlights — the least "washed
    /// out", which best matches kiss3d's display-referred colors.
    #[default]
    Neutral,
    /// Tony McMapface (Tomasz Stachowiak), sampled from its baked 3D LUT. A
    /// perceptual, hue-preserving display transform; the LUT is CC0.
    TonyMcMapface,
}

impl Tonemap {
    /// Operator code passed to the tonemap shaders (raster + path tracer).
    pub(crate) fn as_u32(self) -> u32 {
        match self {
            Tonemap::None => 0,
            Tonemap::Aces => 1,
            Tonemap::Reinhard => 2,
            Tonemap::AgX => 3,
            Tonemap::Neutral => 4,
            Tonemap::TonyMcMapface => 5,
        }
    }
}

/// User-facing HDR finishing settings (exposure, tonemap operator, bloom knobs).
#[derive(Copy, Clone, Debug)]
pub struct HdrSettings {
    /// Linear exposure multiplier applied before tonemapping. `1.0` is neutral.
    pub exposure: f32,
    /// Tonemapping operator.
    pub tonemap: Tonemap,
    /// Whether bloom is applied. Off by default.
    pub bloom_enabled: bool,
    /// Brightness threshold above which pixels contribute to bloom.
    pub bloom_threshold: f32,
    /// Soft-knee width around the threshold for a smooth bloom roll-off.
    pub bloom_knee: f32,
    /// Additive intensity of the bloom contribution.
    pub bloom_intensity: f32,
}

impl Default for HdrSettings {
    fn default() -> Self {
        HdrSettings {
            exposure: 1.0,
            tonemap: Tonemap::default(),
            // Bloom is subtle/off by default so neutral settings match the old look.
            bloom_enabled: false,
            bloom_threshold: 1.0,
            bloom_knee: 0.5,
            bloom_intensity: 0.04,
        }
    }
}

#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
struct QuadVertex {
    position: [f32; 2],
}

#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
struct BloomUniforms {
    src_texel: [f32; 2],
    threshold: f32,
    knee: f32,
}

#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
struct TonemapUniforms {
    exposure: f32,
    operator: u32,
    bloom_intensity: f32,
    _pad: f32,
}

/// A single mip level of the bloom chain.
struct BloomMip {
    // The texture is kept alive alongside its view.
    _texture: wgpu::Texture,
    view: wgpu::TextureView,
    width: u32,
    height: u32,
}

/// The set of GPU textures (re)created together when the size or sample count
/// changes.
struct HdrTargets {
    scene_texture: wgpu::Texture,
    scene_view: wgpu::TextureView,
    scene_msaa_texture: Option<wgpu::Texture>,
    scene_msaa_view: Option<wgpu::TextureView>,
    bloom_mips: Vec<BloomMip>,
    // Weighted-blended OIT targets (single-sample): premultiplied weighted color
    // accumulator and revealage. The transparent geometry pass renders into these;
    // `composite_oit` blends the result over the opaque HDR scene.
    oit_accum_texture: wgpu::Texture,
    oit_accum_view: wgpu::TextureView,
    oit_reveal_texture: wgpu::Texture,
    oit_reveal_view: wgpu::TextureView,
}

/// Owns the HDR scene target, bloom chain and resolve pipelines for the
/// rasterizer. One instance lives on each [`Window`](crate::window::Window).
pub struct HdrPipeline {
    settings: HdrSettings,

    // Render-target size and sample count the GPU resources were built for.
    width: u32,
    height: u32,
    sample_count: u32,

    // HDR scene target. When multisampled, `scene_msaa` is the MSAA attachment
    // and `scene` is its single-sample resolve destination; otherwise only
    // `scene` exists and is rendered into directly.
    // Single-sample HDR scene texture, kept alive alongside its view.
    _scene_texture: wgpu::Texture,
    scene_view: wgpu::TextureView,
    // MSAA HDR attachment, kept alive alongside its view.
    _scene_msaa_texture: Option<wgpu::Texture>,
    scene_msaa_view: Option<wgpu::TextureView>,

    // Bloom mip chain (single-sample HDR), smallest first index is mip 0 = half res.
    bloom_mips: Vec<BloomMip>,

    // Weighted-blended OIT targets + composite pipeline.
    _oit_accum_texture: wgpu::Texture,
    oit_accum_view: wgpu::TextureView,
    _oit_reveal_texture: wgpu::Texture,
    oit_reveal_view: wgpu::TextureView,
    oit_layout: wgpu::BindGroupLayout,
    oit_composite_pipeline: wgpu::RenderPipeline,

    sampler: wgpu::Sampler,

    // Bloom pipelines (prefilter / downsample / upsample) and tonemap pipeline.
    bloom_layout: wgpu::BindGroupLayout,
    prefilter_pipeline: wgpu::RenderPipeline,
    downsample_pipeline: wgpu::RenderPipeline,
    upsample_pipeline: wgpu::RenderPipeline,
    tonemap_layout: wgpu::BindGroupLayout,
    tonemap_pipeline: wgpu::RenderPipeline,

    // Tony McMapface 48³ display-transform LUT (sampled by the tonemap pass).
    _tony_lut_texture: wgpu::Texture,
    tony_lut_view: wgpu::TextureView,
    tony_sampler: wgpu::Sampler,

    vertex_buffer: wgpu::Buffer,
    bloom_uniform: wgpu::Buffer,
    tonemap_uniform: wgpu::Buffer,
}

impl HdrPipeline {
    /// Creates the HDR pipeline for the given size, sample count and output
    /// (LDR) format.
    pub fn new(
        width: u32,
        height: u32,
        sample_count: u32,
        output_format: wgpu::TextureFormat,
    ) -> Self {
        let ctxt = Context::get();

        let sampler = ctxt.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("hdr_sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
            ..Default::default()
        });

        // Bloom bind group: source texture + sampler + uniforms.
        let bloom_layout = ctxt.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("hdr_bloom_layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });

        let bloom_shader = ctxt.create_shader_module(
            Some("hdr_bloom_shader"),
            include_str!("../builtin/hdr_bloom.wgsl"),
        );

        let vertex_layout = wgpu::VertexBufferLayout {
            array_stride: std::mem::size_of::<QuadVertex>() as wgpu::BufferAddress,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &[wgpu::VertexAttribute {
                offset: 0,
                shader_location: 0,
                format: wgpu::VertexFormat::Float32x2,
            }],
        };

        let bloom_pipeline_layout = ctxt.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("hdr_bloom_pipeline_layout"),
            bind_group_layouts: &[Some(&bloom_layout)],
            immediate_size: 0,
        });

        let make_bloom_pipeline = |label: &str, fs_entry: &str, blend: Option<wgpu::BlendState>| {
            ctxt.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some(label),
                layout: Some(&bloom_pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &bloom_shader,
                    entry_point: Some("vs_main"),
                    buffers: std::slice::from_ref(&vertex_layout),
                    compilation_options: Default::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &bloom_shader,
                    entry_point: Some(fs_entry),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: HDR_FORMAT,
                        blend,
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                    compilation_options: Default::default(),
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleStrip,
                    strip_index_format: None,
                    front_face: wgpu::FrontFace::Ccw,
                    cull_mode: None,
                    polygon_mode: wgpu::PolygonMode::Fill,
                    unclipped_depth: false,
                    conservative: false,
                },
                depth_stencil: None,
                multisample: wgpu::MultisampleState {
                    count: 1,
                    mask: !0,
                    alpha_to_coverage_enabled: false,
                },
                multiview_mask: None,
                cache: None,
            })
        };

        let prefilter_pipeline = make_bloom_pipeline("hdr_bloom_prefilter", "fs_prefilter", None);
        let downsample_pipeline =
            make_bloom_pipeline("hdr_bloom_downsample", "fs_downsample", None);
        // The upsample pass additively blends into the larger mip.
        let upsample_pipeline = make_bloom_pipeline(
            "hdr_bloom_upsample",
            "fs_upsample",
            Some(wgpu::BlendState {
                color: wgpu::BlendComponent {
                    src_factor: wgpu::BlendFactor::One,
                    dst_factor: wgpu::BlendFactor::One,
                    operation: wgpu::BlendOperation::Add,
                },
                alpha: wgpu::BlendComponent::REPLACE,
            }),
        );

        // Tonemap bind group: scene texture + sampler, bloom texture + sampler, uniforms.
        let tonemap_layout = ctxt.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("hdr_tonemap_layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 4,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                // Tony McMapface 3D LUT + its sampler (shared `tonemap_ops.wgsl`
                // declares these at bindings 6 & 7).
                wgpu::BindGroupLayoutEntry {
                    binding: 6,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D3,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 7,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });

        // Tony McMapface display-transform LUT: a 48³ Rgba16Float 3D texture decoded
        // (offline) from the CC0 baked LUT. Sampled with the `x/(x+1)` encoding.
        let tony_lut = Self::create_tony_lut(&ctxt);
        let tony_lut_view = tony_lut.create_view(&wgpu::TextureViewDescriptor {
            dimension: Some(wgpu::TextureViewDimension::D3),
            ..Default::default()
        });
        let tony_sampler = ctxt.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("hdr_tony_sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
            ..Default::default()
        });

        let tonemap_shader = ctxt.create_shader_module(
            Some("hdr_tonemap_shader"),
            concat!(
                include_str!("../builtin/tonemap_ops.wgsl"),
                include_str!("../builtin/hdr_tonemap.wgsl"),
            ),
        );

        let tonemap_pipeline_layout =
            ctxt.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("hdr_tonemap_pipeline_layout"),
                bind_group_layouts: &[Some(&tonemap_layout)],
                immediate_size: 0,
            });

        let tonemap_pipeline = ctxt.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("hdr_tonemap_pipeline"),
            layout: Some(&tonemap_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &tonemap_shader,
                entry_point: Some("vs_main"),
                buffers: std::slice::from_ref(&vertex_layout),
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &tonemap_shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: output_format,
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleStrip,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                polygon_mode: wgpu::PolygonMode::Fill,
                unclipped_depth: false,
                conservative: false,
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState {
                count: 1,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            multiview_mask: None,
            cache: None,
        });

        // OIT composite: reads the accum + revealage targets and blends the resolved
        // transparent color over the opaque HDR scene (SrcAlpha / OneMinusSrcAlpha,
        // with the fragment's alpha = 1 - revealage).
        let oit_layout = ctxt.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("hdr_oit_layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
            ],
        });
        let oit_shader = ctxt.create_shader_module(
            Some("hdr_oit_shader"),
            include_str!("../builtin/hdr_oit.wgsl"),
        );
        let oit_pipeline_layout = ctxt.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("hdr_oit_pipeline_layout"),
            bind_group_layouts: &[Some(&oit_layout)],
            immediate_size: 0,
        });
        let oit_composite_pipeline = ctxt.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("hdr_oit_composite_pipeline"),
            layout: Some(&oit_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &oit_shader,
                entry_point: Some("vs_main"),
                buffers: std::slice::from_ref(&vertex_layout),
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &oit_shader,
                entry_point: Some("fs_composite"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: HDR_FORMAT,
                    blend: Some(wgpu::BlendState {
                        color: wgpu::BlendComponent {
                            src_factor: wgpu::BlendFactor::SrcAlpha,
                            dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                            operation: wgpu::BlendOperation::Add,
                        },
                        alpha: wgpu::BlendComponent::REPLACE,
                    }),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleStrip,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                polygon_mode: wgpu::PolygonMode::Fill,
                unclipped_depth: false,
                conservative: false,
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState {
                count: 1,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            multiview_mask: None,
            cache: None,
        });

        let vertices = [
            QuadVertex {
                position: [-1.0, -1.0],
            },
            QuadVertex {
                position: [1.0, -1.0],
            },
            QuadVertex {
                position: [-1.0, 1.0],
            },
            QuadVertex {
                position: [1.0, 1.0],
            },
        ];
        let vertex_buffer = ctxt.create_buffer_init(
            Some("hdr_vertex_buffer"),
            bytemuck::cast_slice(&vertices),
            wgpu::BufferUsages::VERTEX,
        );

        let bloom_uniform = ctxt.create_buffer_simple(
            Some("hdr_bloom_uniform"),
            std::mem::size_of::<BloomUniforms>() as u64,
            wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
        );
        let tonemap_uniform = ctxt.create_buffer_simple(
            Some("hdr_tonemap_uniform"),
            std::mem::size_of::<TonemapUniforms>() as u64,
            wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
        );

        let targets = Self::create_targets(width, height, sample_count);

        HdrPipeline {
            settings: HdrSettings::default(),
            width,
            height,
            sample_count,
            _scene_texture: targets.scene_texture,
            scene_view: targets.scene_view,
            _scene_msaa_texture: targets.scene_msaa_texture,
            scene_msaa_view: targets.scene_msaa_view,
            bloom_mips: targets.bloom_mips,
            _oit_accum_texture: targets.oit_accum_texture,
            oit_accum_view: targets.oit_accum_view,
            _oit_reveal_texture: targets.oit_reveal_texture,
            oit_reveal_view: targets.oit_reveal_view,
            oit_layout,
            oit_composite_pipeline,
            sampler,
            bloom_layout,
            prefilter_pipeline,
            downsample_pipeline,
            upsample_pipeline,
            tonemap_layout,
            tonemap_pipeline,
            _tony_lut_texture: tony_lut,
            tony_lut_view,
            tony_sampler,
            vertex_buffer,
            bloom_uniform,
            tonemap_uniform,
        }
    }

    /// Uploads the embedded Tony McMapface LUT (48³ `Rgba16Float`, decoded offline
    /// from the CC0 baked LUT) as a 3D texture. Shared with the path tracer's
    /// tonemap pass so both sample the identical LUT.
    pub(crate) fn create_tony_lut(ctxt: &Context) -> wgpu::Texture {
        const DIM: u32 = 48;
        let data: &[u8] = include_bytes!("../builtin/tony_mc_mapface.bin");
        let tex = ctxt.create_texture(&wgpu::TextureDescriptor {
            label: Some("hdr_tony_lut"),
            size: wgpu::Extent3d {
                width: DIM,
                height: DIM,
                depth_or_array_layers: DIM,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D3,
            format: wgpu::TextureFormat::Rgba16Float,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        ctxt.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &tex,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            data,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(DIM * 8), // 4 channels * 2 bytes (f16)
                rows_per_image: Some(DIM),
            },
            wgpu::Extent3d {
                width: DIM,
                height: DIM,
                depth_or_array_layers: DIM,
            },
        );
        tex
    }

    /// (Re)creates the HDR scene target and bloom chain textures.
    fn create_targets(width: u32, height: u32, sample_count: u32) -> HdrTargets {
        let ctxt = Context::get();
        let width = width.max(1);
        let height = height.max(1);
        let sample_count = sample_count.max(1);

        // Single-sample HDR scene texture (sampled by bloom + tonemap). When MSAA
        // is active this is the resolve destination.
        let scene_texture = ctxt.create_texture(&wgpu::TextureDescriptor {
            label: Some("hdr_scene_texture"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: HDR_FORMAT,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let scene_view = scene_texture.create_view(&wgpu::TextureViewDescriptor::default());

        // Multisampled HDR attachment, resolved into `scene_texture`.
        let (scene_msaa_texture, scene_msaa_view) = if sample_count > 1 {
            let msaa = ctxt.create_texture(&wgpu::TextureDescriptor {
                label: Some("hdr_scene_msaa_texture"),
                size: wgpu::Extent3d {
                    width,
                    height,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count,
                dimension: wgpu::TextureDimension::D2,
                format: HDR_FORMAT,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                view_formats: &[],
            });
            let view = msaa.create_view(&wgpu::TextureViewDescriptor::default());
            (Some(msaa), Some(view))
        } else {
            (None, None)
        };

        // Bloom mip chain: each level is half the previous resolution.
        let mut bloom_mips = Vec::with_capacity(BLOOM_MIPS as usize);
        let mut mw = width;
        let mut mh = height;
        for i in 0..BLOOM_MIPS {
            mw = (mw / 2).max(1);
            mh = (mh / 2).max(1);
            let tex = ctxt.create_texture(&wgpu::TextureDescriptor {
                label: Some("hdr_bloom_mip"),
                size: wgpu::Extent3d {
                    width: mw,
                    height: mh,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: HDR_FORMAT,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::TEXTURE_BINDING,
                view_formats: &[],
            });
            let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
            bloom_mips.push(BloomMip {
                _texture: tex,
                view,
                width: mw,
                height: mh,
            });
            let _ = i;
        }

        // Weighted-blended OIT targets (single-sample, full resolution).
        let make_oit = |label: &str, format: wgpu::TextureFormat| {
            let tex = ctxt.create_texture(&wgpu::TextureDescriptor {
                label: Some(label),
                size: wgpu::Extent3d {
                    width,
                    height,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::TEXTURE_BINDING,
                view_formats: &[],
            });
            let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
            (tex, view)
        };
        let (oit_accum_texture, oit_accum_view) = make_oit("hdr_oit_accum", OIT_ACCUM_FORMAT);
        let (oit_reveal_texture, oit_reveal_view) = make_oit("hdr_oit_reveal", OIT_REVEAL_FORMAT);

        HdrTargets {
            scene_texture,
            scene_view,
            scene_msaa_texture,
            scene_msaa_view,
            bloom_mips,
            oit_accum_texture,
            oit_accum_view,
            oit_reveal_texture,
            oit_reveal_view,
        }
    }

    /// Resizes the HDR resources if the size or sample count changed.
    pub fn resize(&mut self, width: u32, height: u32, sample_count: u32) {
        let width = width.max(1);
        let height = height.max(1);
        let sample_count = sample_count.max(1);
        if self.width == width && self.height == height && self.sample_count == sample_count {
            return;
        }
        let targets = Self::create_targets(width, height, sample_count);
        self._scene_texture = targets.scene_texture;
        self.scene_view = targets.scene_view;
        self._scene_msaa_texture = targets.scene_msaa_texture;
        self.scene_msaa_view = targets.scene_msaa_view;
        self.bloom_mips = targets.bloom_mips;
        self._oit_accum_texture = targets.oit_accum_texture;
        self.oit_accum_view = targets.oit_accum_view;
        self._oit_reveal_texture = targets.oit_reveal_texture;
        self.oit_reveal_view = targets.oit_reveal_view;
        self.width = width;
        self.height = height;
        self.sample_count = sample_count;
    }

    /// The view the scene must be rendered into (the MSAA attachment when MSAA
    /// is active, the single-sample HDR texture otherwise).
    pub fn scene_render_view(&self) -> &wgpu::TextureView {
        self.scene_msaa_view.as_ref().unwrap_or(&self.scene_view)
    }

    /// The MSAA resolve target (the single-sample HDR texture), or `None` when
    /// MSAA is disabled.
    pub fn scene_resolve_view(&self) -> Option<&wgpu::TextureView> {
        if self.scene_msaa_view.is_some() {
            Some(&self.scene_view)
        } else {
            None
        }
    }

    /// The weighted-blended OIT accumulation target (transparent geometry pass,
    /// color attachment 0). Clear to transparent black before rendering.
    pub fn oit_accum_view(&self) -> &wgpu::TextureView {
        &self.oit_accum_view
    }

    /// The weighted-blended OIT revealage target (transparent geometry pass, color
    /// attachment 1). Clear to white (1.0) before rendering.
    pub fn oit_reveal_view(&self) -> &wgpu::TextureView {
        &self.oit_reveal_view
    }

    /// Composites the transparent OIT result over the opaque HDR scene. Run after
    /// the transparent geometry pass and before [`resolve`](Self::resolve).
    pub fn composite_oit(&self, encoder: &mut wgpu::CommandEncoder) {
        let ctxt = Context::get();
        let bind_group = ctxt.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("hdr_oit_composite_bind_group"),
            layout: &self.oit_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&self.oit_accum_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(&self.oit_reveal_view),
                },
            ],
        });
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("hdr_oit_composite_pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                // Blend over the (single-sample) opaque HDR scene.
                view: &self.scene_view,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Load,
                    store: wgpu::StoreOp::Store,
                },
                depth_slice: None,
            })],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        pass.set_pipeline(&self.oit_composite_pipeline);
        pass.set_bind_group(0, &bind_group, &[]);
        pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
        pass.draw(0..4, 0..1);
    }

    /// Mutable access to the HDR finishing settings.
    pub fn settings_mut(&mut self) -> &mut HdrSettings {
        &mut self.settings
    }

    /// The current HDR finishing settings.
    pub fn settings(&self) -> &HdrSettings {
        &self.settings
    }

    fn bloom_bind_group(
        &self,
        ctxt: &Context,
        src: &wgpu::TextureView,
        src_w: u32,
        src_h: u32,
    ) -> wgpu::BindGroup {
        ctxt.write_buffer(
            &self.bloom_uniform,
            0,
            bytemuck::bytes_of(&BloomUniforms {
                src_texel: [1.0 / src_w.max(1) as f32, 1.0 / src_h.max(1) as f32],
                threshold: self.settings.bloom_threshold,
                knee: self.settings.bloom_knee,
            }),
        );
        ctxt.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("hdr_bloom_bind_group"),
            layout: &self.bloom_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(src),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: self.bloom_uniform.as_entire_binding(),
                },
            ],
        })
    }

    /// Runs the bloom prefilter + downsample + upsample chain. The final blurred
    /// result lands in `bloom_mips[0]` (half resolution), which the tonemap pass
    /// samples.
    fn run_bloom(&self, encoder: &mut wgpu::CommandEncoder) {
        let ctxt = Context::get();

        // Prefilter the full-res scene into the first (half-res) mip.
        {
            let bg = self.bloom_bind_group(&ctxt, &self.scene_view, self.width, self.height);
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("hdr_bloom_prefilter_pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &self.bloom_mips[0].view,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                        store: wgpu::StoreOp::Store,
                    },
                    depth_slice: None,
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            pass.set_pipeline(&self.prefilter_pipeline);
            pass.set_bind_group(0, &bg, &[]);
            pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
            pass.draw(0..4, 0..1);
        }

        // Downsample down the chain: mip[i] -> mip[i+1].
        for i in 0..self.bloom_mips.len() - 1 {
            let src = &self.bloom_mips[i];
            let dst = &self.bloom_mips[i + 1];
            let bg = self.bloom_bind_group(&ctxt, &src.view, src.width, src.height);
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("hdr_bloom_downsample_pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &dst.view,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                        store: wgpu::StoreOp::Store,
                    },
                    depth_slice: None,
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            pass.set_pipeline(&self.downsample_pipeline);
            pass.set_bind_group(0, &bg, &[]);
            pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
            pass.draw(0..4, 0..1);
        }

        // Upsample back up the chain, additively blending: mip[i+1] -> mip[i].
        for i in (0..self.bloom_mips.len() - 1).rev() {
            let src = &self.bloom_mips[i + 1];
            let dst = &self.bloom_mips[i];
            let bg = self.bloom_bind_group(&ctxt, &src.view, src.width, src.height);
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("hdr_bloom_upsample_pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &dst.view,
                    resolve_target: None,
                    // Load: the upsample pipeline additively blends onto existing content.
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Load,
                        store: wgpu::StoreOp::Store,
                    },
                    depth_slice: None,
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            pass.set_pipeline(&self.upsample_pipeline);
            pass.set_bind_group(0, &bg, &[]);
            pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
            pass.draw(0..4, 0..1);
        }
    }

    /// Runs the full HDR resolve: optional bloom, then the tonemap+composite pass
    /// that writes the LDR result into `output_view`.
    ///
    /// The scene must already have been rendered into `scene_render_view` (and,
    /// if MSAA is active, resolved into the single-sample scene texture by the
    /// scene render pass's `resolve_target`).
    pub fn resolve(&self, encoder: &mut wgpu::CommandEncoder, output_view: &wgpu::TextureView) {
        let ctxt = Context::get();

        let bloom_enabled = self.settings.bloom_enabled && self.settings.bloom_intensity > 0.0;
        if bloom_enabled {
            self.run_bloom(encoder);
        }

        ctxt.write_buffer(
            &self.tonemap_uniform,
            0,
            bytemuck::bytes_of(&TonemapUniforms {
                exposure: self.settings.exposure,
                operator: self.settings.tonemap.as_u32(),
                bloom_intensity: if bloom_enabled {
                    self.settings.bloom_intensity
                } else {
                    0.0
                },
                _pad: 0.0,
            }),
        );

        // When bloom is disabled, sample the (black) first mip so the bind group
        // is always complete; its zero intensity makes the contribution vanish.
        let bloom_view = &self.bloom_mips[0].view;

        let bind_group = ctxt.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("hdr_tonemap_bind_group"),
            layout: &self.tonemap_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&self.scene_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(bloom_view),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 4,
                    resource: self.tonemap_uniform.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 6,
                    resource: wgpu::BindingResource::TextureView(&self.tony_lut_view),
                },
                wgpu::BindGroupEntry {
                    binding: 7,
                    resource: wgpu::BindingResource::Sampler(&self.tony_sampler),
                },
            ],
        });

        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("hdr_tonemap_pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: output_view,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                    store: wgpu::StoreOp::Store,
                },
                depth_slice: None,
            })],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        pass.set_pipeline(&self.tonemap_pipeline);
        pass.set_bind_group(0, &bind_group, &[]);
        pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
        pass.draw(0..4, 0..1);
    }
}