sinomo-ui-render-wgpu 0.4.1

wgpu renderer boundary for SUI scene frames.
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
use crate::WgpuRenderer;
use crate::diagnostics::RendererFrameStats;
use crate::resources::OffscreenTarget;
use bytemuck::Pod;
use bytemuck::Zeroable;
use sui_core::Color;
use sui_core::Error;
use sui_core::Result;
use sui_core::WindowId;
use sui_scene::SceneFrame;
use sui_scene::TextSubpixelOrder;
use web_time::Instant;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RendererCapabilities {
    pub supports_color_management: bool,
    pub supports_offscreen_surfaces: bool,
}

impl Default for RendererCapabilities {
    fn default() -> Self {
        Self {
            supports_color_management: true,
            supports_offscreen_surfaces: true,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DisplayColorPrimaries {
    #[default]
    Srgb,
    DisplayP3,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DynamicRangeMode {
    #[default]
    StandardDynamicRange,
    HighDynamicRange,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DisplayTransferFunction {
    #[default]
    Srgb,
    LinearExtended,
    Pq,
    Hlg,
}

#[derive(Debug, Clone, PartialEq)]
pub struct DisplayCapabilities {
    /// Whether the display shows colors beyond sRGB.
    pub supports_wide_gamut: bool,
    pub supports_hdr: bool,
    /// The primaries to encode output for this display in. A display
    /// presenting HDR as scRGB prefers sRGB primaries even when it shows
    /// wider colors, which scRGB carries as values beyond sRGB's range; see
    /// [`OutputStrategy::gamut`] for the colors an output shows.
    pub preferred_primaries: DisplayColorPrimaries,
    pub preferred_dynamic_range: DynamicRangeMode,
    pub max_luminance_nits: Option<f32>,
    pub sdr_white_nits: Option<f32>,
    pub max_content_headroom: Option<f32>,
    pub native_hdr_presentation_supported: bool,
    /// The subpixel order the system antialiases text for on this display, or
    /// `None` when it uses grayscale antialiasing or does not say. Windows that
    /// follow the system's text smoothing render LCD text in this order.
    pub text_subpixel_order: TextSubpixelOrder,
    pub notes: String,
}

impl DisplayCapabilities {
    /// An sRGB display that shows SDR only.
    pub fn sdr() -> Self {
        Self {
            notes: "Simulated SDR display".to_string(),
            ..Self::default()
        }
    }

    /// A Display P3 display that shows SDR only.
    pub fn wide_gamut() -> Self {
        Self {
            supports_wide_gamut: true,
            preferred_primaries: DisplayColorPrimaries::DisplayP3,
            notes: "Simulated wide-gamut SDR display".to_string(),
            ..Self::default()
        }
    }

    /// A wide-gamut display presenting HDR natively as scRGB, as Windows HDR
    /// displays do, `peak_nits` bright with SDR white at `sdr_white_nits`.
    pub fn hdr(peak_nits: f32, sdr_white_nits: f32) -> Self {
        Self {
            supports_wide_gamut: true,
            supports_hdr: true,
            preferred_primaries: DisplayColorPrimaries::Srgb,
            preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
            max_luminance_nits: Some(peak_nits),
            sdr_white_nits: Some(sdr_white_nits),
            max_content_headroom: None,
            native_hdr_presentation_supported: true,
            notes: "Simulated HDR display".to_string(),
            ..Self::default()
        }
    }
}

/// Output settings for a window rendered without a surface: it renders as if
/// presenting to a display with these capabilities, so diagnostics and
/// final-output captures follow the same strategy a real surface would.
#[derive(Debug, Clone, Default)]
pub(crate) struct OffscreenOutput {
    pub(crate) display_capabilities: DisplayCapabilities,
    pub(crate) color_management: ColorManagementMode,
}

impl OffscreenOutput {
    /// The formats surfaces commonly offer: 8-bit sRGB and 16-bit float.
    const SURFACE_FORMATS: [wgpu::TextureFormat; 2] = [
        wgpu::TextureFormat::Bgra8UnormSrgb,
        wgpu::TextureFormat::Rgba16Float,
    ];

    pub(crate) fn output_strategy(&self) -> OutputStrategy {
        select_output_strategy(
            &Self::SURFACE_FORMATS,
            self.display_capabilities.clone(),
            self.color_management,
        )
    }
}

impl Default for DisplayCapabilities {
    fn default() -> Self {
        Self {
            supports_wide_gamut: false,
            supports_hdr: false,
            preferred_primaries: DisplayColorPrimaries::Srgb,
            preferred_dynamic_range: DynamicRangeMode::StandardDynamicRange,
            max_luminance_nits: None,
            sdr_white_nits: None,
            max_content_headroom: None,
            native_hdr_presentation_supported: false,
            text_subpixel_order: TextSubpixelOrder::None,
            notes: "Default SDR capability profile".to_string(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RequestedOutputColorPrimaries {
    #[default]
    Automatic,
    Srgb,
    DisplayP3,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RequestedDynamicRangeMode {
    #[default]
    Automatic,
    StandardDynamicRange,
    HighDynamicRange,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RequestedColorManagementMode {
    #[default]
    Automatic,
    ForceSdr,
    PreferWideGamut,
    PreferHdr,
}

/// How extended-range colors fit an SDR output. Colors within SDR range
/// pass through unchanged in every mode, so SDR content looks as authored.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RequestedToneMappingMode {
    /// `Clamp` on SDR outputs; native HDR outputs present extended range.
    #[default]
    Automatic,
    /// Clip highlights while keeping their hue: the brightest channel lands
    /// at SDR white and the others keep their ratio to it.
    Clamp,
    /// Clip highlights like `Clamp`, then turn the energy above SDR white
    /// toward white along a Reinhard curve, so brighter highlights still read
    /// brighter.
    Reinhard,
}

/// Fit a linear color to the SDR range as `mode` does on an SDR output. The
/// same function runs on the GPU; this is it for inspection and tests.
pub fn fit_to_sdr(color: [f32; 3], mode: RequestedToneMappingMode) -> [f32; 3] {
    SdrFit::for_tone_mapping(mode).apply(color)
}

/// How a pipeline fits colors to its target (see `shaders/sdr_fit.wgsl`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub(crate) enum SdrFit {
    /// Keep extended range: float targets and native HDR output.
    None,
    #[default]
    Clip,
    RollOff,
}

impl SdrFit {
    pub(crate) const fn for_tone_mapping(mode: RequestedToneMappingMode) -> Self {
        match mode {
            RequestedToneMappingMode::Automatic | RequestedToneMappingMode::Clamp => Self::Clip,
            RequestedToneMappingMode::Reinhard => Self::RollOff,
        }
    }

    /// The fit an output transform applies for `strategy`.
    pub(crate) const fn for_output(
        strategy: OutputStrategy,
        mode: RequestedToneMappingMode,
    ) -> Self {
        match strategy {
            OutputStrategy::HdrNativeSurface { .. } => Self::None,
            _ => Self::for_tone_mapping(mode),
        }
    }

    pub(crate) const fn shader_value(self) -> u32 {
        match self {
            Self::None => 0,
            Self::Clip => 1,
            Self::RollOff => 2,
        }
    }

    pub(crate) fn apply(self, color: [f32; 3]) -> [f32; 3] {
        let peak = color[0].max(color[1]).max(color[2]);
        if self == Self::None || peak <= 1.0 {
            return color;
        }
        let hue = color.map(|channel| channel / peak);
        match self {
            Self::RollOff => {
                let toward_white = 1.0 - 1.0 / peak;
                hue.map(|channel| channel + (1.0 - channel) * toward_white)
            }
            _ => hue,
        }
    }
}

/// Whether draws into `format` keep extended-range values, so they need no
/// fit before the output transform.
pub(crate) fn target_keeps_extended_range(format: wgpu::TextureFormat) -> bool {
    matches!(
        format,
        wgpu::TextureFormat::Rgba16Float | wgpu::TextureFormat::Rgba32Float
    )
}

pub const DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS: f32 = 203.0;
pub(crate) const SCRGB_REFERENCE_WHITE_NITS: f32 = 80.0;

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ColorManagementMode {
    pub mode: RequestedColorManagementMode,
    pub output_primaries: RequestedOutputColorPrimaries,
    pub dynamic_range: RequestedDynamicRangeMode,
    pub tone_mapping: RequestedToneMappingMode,
    pub sdr_content_brightness_nits: f32,
}

impl Default for ColorManagementMode {
    fn default() -> Self {
        Self {
            mode: RequestedColorManagementMode::Automatic,
            output_primaries: RequestedOutputColorPrimaries::Automatic,
            dynamic_range: RequestedDynamicRangeMode::Automatic,
            tone_mapping: RequestedToneMappingMode::Automatic,
            sdr_content_brightness_nits: DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputStrategy {
    SdrSurface {
        format: wgpu::TextureFormat,
    },
    WideGamutSurface {
        format: wgpu::TextureFormat,
        primaries: DisplayColorPrimaries,
    },
    HdrNativeSurface {
        format: wgpu::TextureFormat,
        primaries: DisplayColorPrimaries,
        transfer: DisplayTransferFunction,
    },
    /// Debug/offscreen-only path for inspecting HDR scene values on SDR outputs.
    ///
    /// Normal presentation should choose native HDR when the environment can present
    /// HDR end-to-end; otherwise it should render SDR instead of tone mapping HDR.
    HdrIntermediateThenToneMap {
        intermediate_format: wgpu::TextureFormat,
        surface_format: wgpu::TextureFormat,
        primaries: DisplayColorPrimaries,
    },
}

impl OutputStrategy {
    pub const fn surface_format(self) -> wgpu::TextureFormat {
        match self {
            Self::SdrSurface { format }
            | Self::WideGamutSurface { format, .. }
            | Self::HdrNativeSurface { format, .. } => format,
            Self::HdrIntermediateThenToneMap { surface_format, .. } => surface_format,
        }
    }

    /// The colors this output shows on a display with `capabilities`.
    ///
    /// Outputs clip colors to their primaries, except native HDR, which
    /// keeps extended range: colors beyond its primaries reach the display,
    /// which shows as many as it can.
    pub fn gamut(self, capabilities: &DisplayCapabilities) -> OutputGamut {
        let clipped_to = |primaries| match primaries {
            DisplayColorPrimaries::Srgb => OutputGamut::Srgb,
            DisplayColorPrimaries::DisplayP3 => OutputGamut::DisplayP3,
        };
        match self {
            Self::SdrSurface { .. } => OutputGamut::Srgb,
            Self::WideGamutSurface { primaries, .. }
            | Self::HdrIntermediateThenToneMap { primaries, .. } => clipped_to(primaries),
            Self::HdrNativeSurface { primaries, .. } => {
                if capabilities.supports_wide_gamut {
                    OutputGamut::Display
                } else {
                    clipped_to(primaries)
                }
            }
        }
    }
}

/// The colors an output shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OutputGamut {
    /// sRGB colors; others are clipped to sRGB.
    #[default]
    Srgb,
    /// Display P3 colors; others are clipped to Display P3.
    DisplayP3,
    /// The display's own gamut: colors beyond sRGB reach the display
    /// unclipped, and it shows as many as it can, as with native HDR output
    /// (scRGB) on a wide-gamut display.
    Display,
}

impl OutputGamut {
    /// Whether colors beyond sRGB reach the display.
    pub const fn is_wide(self) -> bool {
        !matches!(self, Self::Srgb)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DebugCaptureStage {
    HdrIntermediate,
    #[default]
    FinalComposed,
}

impl DebugCaptureStage {
    pub const fn is_hdr_capable(self) -> bool {
        matches!(self, Self::HdrIntermediate)
    }

    pub const fn uses_hdr_intermediate(self) -> bool {
        matches!(self, Self::HdrIntermediate)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DebugSdrVisualization {
    #[default]
    ToneMappedColor,
    LuminanceHeatmap,
    HeadroomHeatmap,
    ClipMask,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DebugCaptureEncoding {
    Exr,
    #[default]
    Png,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DebugCaptureRequest {
    pub stage: DebugCaptureStage,
    pub encoding: DebugCaptureEncoding,
    pub sdr_visualization: DebugSdrVisualization,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
pub(crate) struct OutputTransformUniform {
    pub(crate) tone_mapping_mode: u32,
    pub(crate) encode_srgb: u32,
    pub(crate) output_primaries: u32,
    pub(crate) _padding0: u32,
    pub(crate) sdr_content_scale: f32,
    pub(crate) _padding1: [u32; 3],
}

pub(crate) struct CachedOutputTransform {
    pub(crate) source_view: wgpu::TextureView,
    pub(crate) uniform: OutputTransformUniform,
    pub(crate) buffer: wgpu::Buffer,
    pub(crate) bind_group: wgpu::BindGroup,
}

impl OutputTransformUniform {
    pub(crate) const fn new(
        tone_mapping_mode: u32,
        encode_srgb: bool,
        output_primaries: DisplayColorPrimaries,
        sdr_content_scale: f32,
    ) -> Self {
        Self {
            tone_mapping_mode,
            encode_srgb: encode_srgb as u32,
            output_primaries: match output_primaries {
                DisplayColorPrimaries::Srgb => 0,
                DisplayColorPrimaries::DisplayP3 => 1,
            },
            _padding0: 0,
            sdr_content_scale,
            _padding1: [0; 3],
        }
    }
}
impl WgpuRenderer {
    pub(crate) fn render_debug_capture_stage(
        &mut self,
        frame: &SceneFrame,
        size: (u32, u32),
        request: DebugCaptureRequest,
    ) -> Result<RendererFrameStats> {
        match request.stage {
            DebugCaptureStage::HdrIntermediate => self.render_offscreen(frame, size),
            DebugCaptureStage::FinalComposed
                if request.encoding == DebugCaptureEncoding::Png
                    && request.sdr_visualization == DebugSdrVisualization::ToneMappedColor =>
            {
                self.render_offscreen(frame, size)
            }
            DebugCaptureStage::FinalComposed => self.render_final_composed_offscreen(frame, size),
        }
    }

    pub(crate) fn render_final_composed_offscreen(
        &mut self,
        frame: &SceneFrame,
        size: (u32, u32),
    ) -> Result<RendererFrameStats> {
        self.ensure_shared(None)?;

        let Some(strategy) = self.window_output_strategy(frame.window_id) else {
            return self.render_offscreen(frame, size);
        };
        let color_management = self.window_color_management(frame.window_id);
        let requested_tone_mapping = color_management.tone_mapping;
        let sdr_content_brightness_nits = color_management.sdr_content_brightness_nits;
        let display_sdr_white_nits = self
            .window_display_capabilities(frame.window_id)
            .and_then(|capabilities| capabilities.sdr_white_nits);
        let final_format = strategy.surface_format();
        let final_view = self.ensure_offscreen_target(frame.window_id, size, final_format)?;
        let prepared = self.prepare_scene_submission(frame)?;

        if output_transform_requires_intermediate(strategy) {
            let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
            let intermediate_format = self
                .intermediate_targets
                .get(&frame.window_id)
                .map(|target| target.format)
                .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
            let mut encoder = self.frame_encoder();
            let mut frame_stats = self.encode_prepared_scene(
                prepared,
                intermediate_format,
                &intermediate_view,
                &mut encoder,
            )?;
            self.encode_output_transform_pass(
                frame.window_id,
                &intermediate_view,
                &final_view,
                final_format,
                strategy,
                requested_tone_mapping,
                sdr_content_brightness_nits,
                display_sdr_white_nits,
                &mut frame_stats,
                &mut encoder,
            )?;
            self.submit_frame_encoder(encoder, &mut frame_stats);
            Ok(frame_stats)
        } else {
            self.shared
                .as_mut()
                .expect("renderer shared state initialized")
                .sdr_fit = SdrFit::for_tone_mapping(requested_tone_mapping);
            self.submit_prepared_scene(prepared, final_format, &final_view)
        }
    }

    pub(crate) fn render_offscreen(
        &mut self,
        frame: &SceneFrame,
        size: (u32, u32),
    ) -> Result<RendererFrameStats> {
        self.ensure_shared(None)?;

        let final_format = wgpu::TextureFormat::Bgra8UnormSrgb;
        let target_started = self.runtime_diagnostics_enabled.then(Instant::now);
        let final_view = self.ensure_offscreen_target(frame.window_id, size, final_format)?;
        let mut target_us =
            target_started.map_or(0, |started| started.elapsed().as_micros() as u64);
        let prepared = self.prepare_scene_submission(frame)?;
        let target_started = self.runtime_diagnostics_enabled.then(Instant::now);
        let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
        let intermediate_format = self
            .intermediate_targets
            .get(&frame.window_id)
            .map(|target| target.format)
            .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
        target_us += target_started.map_or(0, |started| started.elapsed().as_micros() as u64);
        let mut encoder = self.frame_encoder();
        let mut frame_stats = self.encode_prepared_scene(
            prepared,
            intermediate_format,
            &intermediate_view,
            &mut encoder,
        )?;
        self.encode_output_transform_pass(
            frame.window_id,
            &intermediate_view,
            &final_view,
            final_format,
            OutputStrategy::SdrSurface {
                format: final_format,
            },
            // Fit highlights as the window's own SDR output would.
            self.window_color_management(frame.window_id).tone_mapping,
            ColorManagementMode::default().sdr_content_brightness_nits,
            None,
            &mut frame_stats,
            &mut encoder,
        )?;
        self.submit_frame_encoder(encoder, &mut frame_stats);
        frame_stats.target_prepare_time_us = target_us;
        Ok(frame_stats)
    }

    pub(crate) fn ensure_offscreen_target(
        &mut self,
        window_id: WindowId,
        size: (u32, u32),
        format: wgpu::TextureFormat,
    ) -> Result<wgpu::TextureView> {
        let recreate = self
            .offscreen_targets
            .get(&window_id)
            .is_none_or(|target| target.size != size || target.format != format);
        if recreate {
            let shared = self
                .shared
                .as_ref()
                .expect("renderer shared state initialized");
            let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
                label: Some("SUI offscreen frame"),
                size: wgpu::Extent3d {
                    width: size.0,
                    height: size.1,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
                view_formats: &[],
            });
            self.offscreen_targets.insert(
                window_id,
                OffscreenTarget {
                    view: texture.create_view(&wgpu::TextureViewDescriptor::default()),
                    texture,
                    format,
                    size,
                },
            );
        }
        self.offscreen_targets
            .get(&window_id)
            .map(|target| target.view.clone())
            .ok_or_else(|| Error::new(format!("missing target for window {}", window_id.get())))
    }

    pub(crate) fn ensure_intermediate_target(
        &mut self,
        window_id: WindowId,
        size: (u32, u32),
    ) -> Result<wgpu::TextureView> {
        let format = wgpu::TextureFormat::Rgba16Float;
        let recreate = self
            .intermediate_targets
            .get(&window_id)
            .is_none_or(|target| target.size != size || target.format != format);
        if recreate {
            let shared = self
                .shared
                .as_ref()
                .expect("renderer shared state initialized");
            let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
                label: Some("SUI HDR intermediate frame"),
                size: wgpu::Extent3d {
                    width: size.0,
                    height: size.1,
                    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
                    | wgpu::TextureUsages::COPY_SRC,
                view_formats: &[],
            });
            self.intermediate_targets.insert(
                window_id,
                OffscreenTarget {
                    view: texture.create_view(&wgpu::TextureViewDescriptor::default()),
                    texture,
                    format,
                    size,
                },
            );
        }
        self.intermediate_targets
            .get(&window_id)
            .map(|target| target.view.clone())
            .ok_or_else(|| Error::new(format!("missing target for window {}", window_id.get())))
    }

    #[cfg(test)]
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn submit_output_transform_pass(
        &mut self,
        window_id: WindowId,
        source: &wgpu::TextureView,
        destination: &wgpu::TextureView,
        format: wgpu::TextureFormat,
        strategy: OutputStrategy,
        tone: RequestedToneMappingMode,
        brightness: f32,
        white: Option<f32>,
        stats: &mut RendererFrameStats,
    ) -> Result<()> {
        let mut encoder = self.frame_encoder();
        self.encode_output_transform_pass(
            window_id,
            source,
            destination,
            format,
            strategy,
            tone,
            brightness,
            white,
            stats,
            &mut encoder,
        )?;
        self.submit_frame_encoder(encoder, stats);
        Ok(())
    }

    pub(crate) fn encode_output_transform_pass(
        &mut self,
        window_id: WindowId,
        source_view: &wgpu::TextureView,
        destination_view: &wgpu::TextureView,
        destination_format: wgpu::TextureFormat,
        strategy: OutputStrategy,
        requested_tone_mapping: RequestedToneMappingMode,
        sdr_content_brightness_nits: f32,
        display_sdr_white_nits: Option<f32>,
        frame_stats: &mut RendererFrameStats,
        encoder: &mut wgpu::CommandEncoder,
    ) -> Result<()> {
        let prepare_started = self.runtime_diagnostics_enabled.then(Instant::now);
        let resolved_tone_mapping =
            SdrFit::for_output(strategy, requested_tone_mapping).shader_value();
        let shared = self
            .shared
            .as_mut()
            .expect("renderer shared state initialized");
        let sdr_content_scale = crate::output::output_sdr_content_scale(
            strategy,
            sdr_content_brightness_nits,
            display_sdr_white_nits,
        );
        let encode_srgb = matches!(
            destination_format,
            wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm
        ) || matches!(
            strategy,
            OutputStrategy::HdrNativeSurface {
                transfer: DisplayTransferFunction::Srgb,
                ..
            }
        );
        let uniform = OutputTransformUniform::new(
            resolved_tone_mapping,
            encode_srgb,
            crate::output::output_primaries(strategy),
            sdr_content_scale,
        );
        let cache = &mut self.frame_resources.output_transforms;
        let recreate = cache
            .get(&window_id)
            .is_none_or(|cached| cached.source_view != *source_view);
        if recreate {
            let uniform_buffer = shared.device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("SUI output transform uniform"),
                size: std::mem::size_of::<OutputTransformUniform>() as u64,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            let bind_group = shared.device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("SUI output transform bind group"),
                layout: &shared.output_transform_bind_group_layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::TextureView(source_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: uniform_buffer.as_entire_binding(),
                    },
                ],
            });
            cache.insert(
                window_id,
                CachedOutputTransform {
                    source_view: source_view.clone(),
                    uniform,
                    buffer: uniform_buffer,
                    bind_group,
                },
            );
        }
        let cached = cache
            .get_mut(&window_id)
            .expect("output transform resources allocated");
        if recreate || cached.uniform != uniform {
            self.frame_resources.uploads.write_buffer(
                &shared.device,
                &cached.buffer,
                0,
                bytemuck::bytes_of(&uniform),
            );
            cached.uniform = uniform;
        }
        let bind_group = cached.bind_group.clone();
        if let Some(started) = prepare_started {
            frame_stats.gpu_upload_time_us += started.elapsed().as_micros() as u64;
        }
        let encode_started = self.runtime_diagnostics_enabled.then(Instant::now);
        {
            let pipeline = shared.output_transform_pipeline(destination_format);
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("SUI output transform pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: destination_view,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                occlusion_query_set: None,
                timestamp_writes: None,
                multiview_mask: None,
            });
            pass.set_pipeline(pipeline);
            pass.set_bind_group(0, &bind_group, &[]);
            pass.draw(0..3, 0..1);
        }
        if let Some(started) = encode_started {
            frame_stats.pass_encode_time_us += started.elapsed().as_micros() as u64;
        }
        frame_stats.pass_count += 1;
        Ok(())
    }
}

pub(crate) fn shader_color(color: Color) -> [f32; 4] {
    let linear = color.to_linear_srgb();
    [
        linear.red,
        linear.green,
        linear.blue,
        linear.alpha.clamp(0.0, 1.0),
    ]
}

pub(crate) fn preferred_surface_format(
    formats: &[wgpu::TextureFormat],
) -> Option<wgpu::TextureFormat> {
    formats
        .iter()
        .copied()
        .find(wgpu::TextureFormat::is_srgb)
        .or_else(|| formats.first().copied())
}

pub(crate) fn preferred_hdr_surface_format(
    formats: &[wgpu::TextureFormat],
) -> Option<wgpu::TextureFormat> {
    formats
        .iter()
        .copied()
        .find(|format| matches!(format, wgpu::TextureFormat::Rgba16Float))
}

pub(crate) fn output_transform_requires_intermediate(strategy: OutputStrategy) -> bool {
    match strategy {
        OutputStrategy::HdrNativeSurface { .. }
        | OutputStrategy::HdrIntermediateThenToneMap { .. } => true,
        OutputStrategy::WideGamutSurface { format, primaries } => {
            !format.is_srgb() || !matches!(primaries, DisplayColorPrimaries::Srgb)
        }
        OutputStrategy::SdrSurface { format } => !format.is_srgb(),
    }
}

/// LCD coverage is tied to the final RGB channels. A gamut conversion or HDR
/// presentation/tone map after blending cannot preserve that interpretation.
pub(crate) fn output_allows_lcd(strategy: OutputStrategy) -> bool {
    matches!(
        strategy,
        OutputStrategy::SdrSurface { .. }
            | OutputStrategy::WideGamutSurface {
                primaries: DisplayColorPrimaries::Srgb,
                ..
            }
    )
}

pub(crate) fn output_primaries(strategy: OutputStrategy) -> DisplayColorPrimaries {
    match strategy {
        OutputStrategy::SdrSurface { .. } => DisplayColorPrimaries::Srgb,
        OutputStrategy::WideGamutSurface { primaries, .. }
        | OutputStrategy::HdrNativeSurface { primaries, .. }
        | OutputStrategy::HdrIntermediateThenToneMap { primaries, .. } => primaries,
    }
}

pub(crate) fn output_sdr_content_scale(
    strategy: OutputStrategy,
    brightness_nits: f32,
    _display_sdr_white_nits: Option<f32>,
) -> f32 {
    let sanitized = if brightness_nits.is_finite() && brightness_nits > 0.0 {
        brightness_nits
    } else {
        DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS
    };

    match strategy {
        // Native HDR is presented as linear scRGB: 1.0 is the 80 nit scRGB
        // reference, so SDR reference white must be lifted to the requested
        // SDR-content brightness before presentation.
        OutputStrategy::HdrNativeSurface { .. } => sanitized / SCRGB_REFERENCE_WHITE_NITS,
        OutputStrategy::SdrSurface { .. }
        | OutputStrategy::WideGamutSurface { .. }
        | OutputStrategy::HdrIntermediateThenToneMap { .. } => 1.0,
    }
}

#[cfg(test)]
pub(crate) fn apply_output_transform_for_testing(
    color: [f32; 4],
    strategy: OutputStrategy,
    mode: RequestedToneMappingMode,
    sdr_content_brightness_nits: f32,
    display_sdr_white_nits: Option<f32>,
) -> [f32; 4] {
    let scale = output_sdr_content_scale(
        strategy,
        sdr_content_brightness_nits,
        display_sdr_white_nits,
    );
    let scaled = [
        color[0] * scale,
        color[1] * scale,
        color[2] * scale,
        color[3],
    ];

    let fit = SdrFit::for_output(strategy, mode);
    let mut output = linear_srgb_to_output_primaries([scaled[0], scaled[1], scaled[2]], strategy);
    if fit != SdrFit::None {
        output = output.map(|channel| channel.max(0.0));
    }
    let [red, green, blue] = fit.apply(output);
    [red, green, blue, scaled[3].clamp(0.0, 1.0)]
}

#[cfg(test)]
pub(crate) fn linear_srgb_to_output_primaries(
    color: [f32; 3],
    strategy: OutputStrategy,
) -> [f32; 3] {
    match output_primaries(strategy) {
        DisplayColorPrimaries::Srgb => color,
        DisplayColorPrimaries::DisplayP3 => [
            (0.822_461_96 * color[0]) + (0.177_538_02 * color[1]),
            (0.033_194_2 * color[0]) + (0.966_805_76 * color[1]),
            (0.017_082_63 * color[0]) + (0.072_397_43 * color[1]) + (0.910_519_96 * color[2]),
        ],
    }
}

pub(crate) fn requested_output_primaries(
    capabilities: DisplayCapabilities,
    requested: ColorManagementMode,
) -> DisplayColorPrimaries {
    match requested.output_primaries {
        RequestedOutputColorPrimaries::Automatic => {
            if capabilities.supports_wide_gamut {
                capabilities.preferred_primaries
            } else {
                DisplayColorPrimaries::Srgb
            }
        }
        RequestedOutputColorPrimaries::Srgb => DisplayColorPrimaries::Srgb,
        RequestedOutputColorPrimaries::DisplayP3 => {
            if capabilities.supports_wide_gamut {
                DisplayColorPrimaries::DisplayP3
            } else {
                DisplayColorPrimaries::Srgb
            }
        }
    }
}

pub(crate) fn select_output_strategy(
    formats: &[wgpu::TextureFormat],
    capabilities: DisplayCapabilities,
    requested: ColorManagementMode,
) -> OutputStrategy {
    let sdr_format =
        preferred_surface_format(formats).unwrap_or(wgpu::TextureFormat::Bgra8UnormSrgb);
    let primaries = requested_output_primaries(capabilities.clone(), requested);
    let native_hdr_format = preferred_hdr_surface_format(formats);
    let native_hdr_available =
        capabilities.native_hdr_presentation_supported && native_hdr_format.is_some();

    if matches!(requested.mode, RequestedColorManagementMode::ForceSdr) {
        return OutputStrategy::SdrSurface { format: sdr_format };
    }

    let wants_hdr = match requested.dynamic_range {
        RequestedDynamicRangeMode::HighDynamicRange => true,
        RequestedDynamicRangeMode::StandardDynamicRange => false,
        RequestedDynamicRangeMode::Automatic => match requested.mode {
            RequestedColorManagementMode::PreferHdr => true,
            RequestedColorManagementMode::Automatic => {
                native_hdr_available
                    || capabilities.supports_hdr
                    || matches!(
                        capabilities.preferred_dynamic_range,
                        DynamicRangeMode::HighDynamicRange
                    )
            }
            RequestedColorManagementMode::ForceSdr
            | RequestedColorManagementMode::PreferWideGamut => false,
        },
    };
    let wants_wide_gamut = match requested.output_primaries {
        RequestedOutputColorPrimaries::DisplayP3 => true,
        RequestedOutputColorPrimaries::Srgb => false,
        RequestedOutputColorPrimaries::Automatic => match requested.mode {
            RequestedColorManagementMode::PreferWideGamut
            | RequestedColorManagementMode::PreferHdr => true,
            RequestedColorManagementMode::Automatic => capabilities.supports_wide_gamut,
            RequestedColorManagementMode::ForceSdr => false,
        },
    };

    if wants_hdr {
        if native_hdr_available && let Some(format) = native_hdr_format {
            let uses_linear_sc_rgb = capabilities.native_hdr_presentation_supported
                && matches!(
                    capabilities.preferred_primaries,
                    DisplayColorPrimaries::Srgb
                );
            let transfer = if uses_linear_sc_rgb {
                DisplayTransferFunction::LinearExtended
            } else {
                DisplayTransferFunction::Srgb
            };
            return OutputStrategy::HdrNativeSurface {
                format,
                primaries: DisplayColorPrimaries::Srgb,
                transfer,
            };
        }

        // If HDR cannot be presented end-to-end, normal presentation stays SDR.
        // HdrIntermediateThenToneMap is reserved for debug captures and explicit
        // diagnostics where seeing HDR scene values on an SDR display is useful.
        return OutputStrategy::SdrSurface { format: sdr_format };
    }

    if wants_wide_gamut && capabilities.supports_wide_gamut {
        return OutputStrategy::WideGamutSurface {
            format: sdr_format,
            primaries,
        };
    }

    OutputStrategy::SdrSurface { format: sdr_format }
}