Skip to main content

sui_render_wgpu/
output.rs

1use crate::WgpuRenderer;
2use crate::diagnostics::RendererFrameStats;
3use crate::resources::OffscreenTarget;
4use bytemuck::Pod;
5use bytemuck::Zeroable;
6use sui_core::Color;
7use sui_core::Error;
8use sui_core::Result;
9use sui_core::WindowId;
10use sui_scene::SceneFrame;
11use web_time::Instant;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct RendererCapabilities {
15    pub supports_color_management: bool,
16    pub supports_offscreen_surfaces: bool,
17}
18
19impl Default for RendererCapabilities {
20    fn default() -> Self {
21        Self {
22            supports_color_management: true,
23            supports_offscreen_surfaces: true,
24        }
25    }
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
29pub enum DisplayColorPrimaries {
30    #[default]
31    Srgb,
32    DisplayP3,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum DynamicRangeMode {
37    #[default]
38    StandardDynamicRange,
39    HighDynamicRange,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43pub enum DisplayTransferFunction {
44    #[default]
45    Srgb,
46    LinearExtended,
47    Pq,
48    Hlg,
49}
50
51#[derive(Debug, Clone, PartialEq)]
52pub struct DisplayCapabilities {
53    pub supports_wide_gamut: bool,
54    pub supports_hdr: bool,
55    pub preferred_primaries: DisplayColorPrimaries,
56    pub preferred_dynamic_range: DynamicRangeMode,
57    pub max_luminance_nits: Option<f32>,
58    pub sdr_white_nits: Option<f32>,
59    pub max_content_headroom: Option<f32>,
60    pub native_hdr_presentation_supported: bool,
61    pub notes: String,
62}
63
64impl Default for DisplayCapabilities {
65    fn default() -> Self {
66        Self {
67            supports_wide_gamut: false,
68            supports_hdr: false,
69            preferred_primaries: DisplayColorPrimaries::Srgb,
70            preferred_dynamic_range: DynamicRangeMode::StandardDynamicRange,
71            max_luminance_nits: None,
72            sdr_white_nits: None,
73            max_content_headroom: None,
74            native_hdr_presentation_supported: false,
75            notes: "Default SDR capability profile".to_string(),
76        }
77    }
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
81pub enum RequestedOutputColorPrimaries {
82    #[default]
83    Automatic,
84    Srgb,
85    DisplayP3,
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
89pub enum RequestedDynamicRangeMode {
90    #[default]
91    Automatic,
92    StandardDynamicRange,
93    HighDynamicRange,
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
97pub enum RequestedColorManagementMode {
98    #[default]
99    Automatic,
100    ForceSdr,
101    PreferWideGamut,
102    PreferHdr,
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
106pub enum RequestedToneMappingMode {
107    #[default]
108    Automatic,
109    Clamp,
110    Reinhard,
111}
112
113pub const DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS: f32 = 203.0;
114pub(crate) const SCRGB_REFERENCE_WHITE_NITS: f32 = 80.0;
115
116#[derive(Debug, Clone, Copy, PartialEq)]
117pub struct ColorManagementMode {
118    pub mode: RequestedColorManagementMode,
119    pub output_primaries: RequestedOutputColorPrimaries,
120    pub dynamic_range: RequestedDynamicRangeMode,
121    pub tone_mapping: RequestedToneMappingMode,
122    pub sdr_content_brightness_nits: f32,
123}
124
125impl Default for ColorManagementMode {
126    fn default() -> Self {
127        Self {
128            mode: RequestedColorManagementMode::Automatic,
129            output_primaries: RequestedOutputColorPrimaries::Automatic,
130            dynamic_range: RequestedDynamicRangeMode::Automatic,
131            tone_mapping: RequestedToneMappingMode::Automatic,
132            sdr_content_brightness_nits: DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS,
133        }
134    }
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub enum OutputStrategy {
139    SdrSurface {
140        format: wgpu::TextureFormat,
141    },
142    WideGamutSurface {
143        format: wgpu::TextureFormat,
144        primaries: DisplayColorPrimaries,
145    },
146    HdrNativeSurface {
147        format: wgpu::TextureFormat,
148        primaries: DisplayColorPrimaries,
149        transfer: DisplayTransferFunction,
150    },
151    /// Debug/offscreen-only path for inspecting HDR scene values on SDR outputs.
152    ///
153    /// Normal presentation should choose native HDR when the environment can present
154    /// HDR end-to-end; otherwise it should render SDR instead of tone mapping HDR.
155    HdrIntermediateThenToneMap {
156        intermediate_format: wgpu::TextureFormat,
157        surface_format: wgpu::TextureFormat,
158        primaries: DisplayColorPrimaries,
159    },
160}
161
162impl OutputStrategy {
163    pub const fn surface_format(self) -> wgpu::TextureFormat {
164        match self {
165            Self::SdrSurface { format }
166            | Self::WideGamutSurface { format, .. }
167            | Self::HdrNativeSurface { format, .. } => format,
168            Self::HdrIntermediateThenToneMap { surface_format, .. } => surface_format,
169        }
170    }
171}
172
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
174pub enum DebugCaptureStage {
175    HdrIntermediate,
176    #[default]
177    FinalComposed,
178}
179
180impl DebugCaptureStage {
181    pub const fn is_hdr_capable(self) -> bool {
182        matches!(self, Self::HdrIntermediate)
183    }
184
185    pub const fn uses_hdr_intermediate(self) -> bool {
186        matches!(self, Self::HdrIntermediate)
187    }
188}
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
191pub enum DebugSdrVisualization {
192    #[default]
193    ToneMappedColor,
194    LuminanceHeatmap,
195    HeadroomHeatmap,
196    ClipMask,
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
200pub enum DebugCaptureEncoding {
201    Exr,
202    #[default]
203    Png,
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
207pub struct DebugCaptureRequest {
208    pub stage: DebugCaptureStage,
209    pub encoding: DebugCaptureEncoding,
210    pub sdr_visualization: DebugSdrVisualization,
211}
212
213#[repr(C)]
214#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
215pub(crate) struct OutputTransformUniform {
216    pub(crate) tone_mapping_mode: u32,
217    pub(crate) encode_srgb: u32,
218    pub(crate) output_primaries: u32,
219    pub(crate) _padding0: u32,
220    pub(crate) sdr_content_scale: f32,
221    pub(crate) _padding1: [u32; 3],
222}
223
224pub(crate) struct CachedOutputTransform {
225    pub(crate) source_view: wgpu::TextureView,
226    pub(crate) uniform: OutputTransformUniform,
227    pub(crate) buffer: wgpu::Buffer,
228    pub(crate) bind_group: wgpu::BindGroup,
229}
230
231impl OutputTransformUniform {
232    pub(crate) const fn new(
233        tone_mapping_mode: u32,
234        encode_srgb: bool,
235        output_primaries: DisplayColorPrimaries,
236        sdr_content_scale: f32,
237    ) -> Self {
238        Self {
239            tone_mapping_mode,
240            encode_srgb: encode_srgb as u32,
241            output_primaries: match output_primaries {
242                DisplayColorPrimaries::Srgb => 0,
243                DisplayColorPrimaries::DisplayP3 => 1,
244            },
245            _padding0: 0,
246            sdr_content_scale,
247            _padding1: [0; 3],
248        }
249    }
250}
251impl WgpuRenderer {
252    pub(crate) fn render_debug_capture_stage(
253        &mut self,
254        frame: &SceneFrame,
255        size: (u32, u32),
256        request: DebugCaptureRequest,
257    ) -> Result<RendererFrameStats> {
258        match request.stage {
259            DebugCaptureStage::HdrIntermediate => self.render_offscreen(frame, size),
260            DebugCaptureStage::FinalComposed
261                if request.encoding == DebugCaptureEncoding::Png
262                    && request.sdr_visualization == DebugSdrVisualization::ToneMappedColor =>
263            {
264                self.render_offscreen(frame, size)
265            }
266            DebugCaptureStage::FinalComposed => self.render_final_composed_offscreen(frame, size),
267        }
268    }
269
270    pub(crate) fn render_final_composed_offscreen(
271        &mut self,
272        frame: &SceneFrame,
273        size: (u32, u32),
274    ) -> Result<RendererFrameStats> {
275        self.ensure_shared(None)?;
276
277        let Some(surface_state) = self.surfaces.get(&frame.window_id) else {
278            return self.render_offscreen(frame, size);
279        };
280        let strategy = surface_state.output_strategy;
281        let requested_tone_mapping = surface_state.color_management.tone_mapping;
282        let sdr_content_brightness_nits =
283            surface_state.color_management.sdr_content_brightness_nits;
284        let display_sdr_white_nits = surface_state.display_capabilities.sdr_white_nits;
285        let final_format = strategy.surface_format();
286        let final_view = self.ensure_offscreen_target(frame.window_id, size, final_format)?;
287        let prepared = self.prepare_scene_submission(frame)?;
288
289        if output_transform_requires_intermediate(strategy) {
290            let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
291            let intermediate_format = self
292                .intermediate_targets
293                .get(&frame.window_id)
294                .map(|target| target.format)
295                .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
296            let mut encoder = self.frame_encoder();
297            let mut frame_stats = self.encode_prepared_scene(
298                prepared,
299                intermediate_format,
300                &intermediate_view,
301                &mut encoder,
302            )?;
303            self.encode_output_transform_pass(
304                frame.window_id,
305                &intermediate_view,
306                &final_view,
307                final_format,
308                strategy,
309                requested_tone_mapping,
310                sdr_content_brightness_nits,
311                display_sdr_white_nits,
312                &mut frame_stats,
313                &mut encoder,
314            )?;
315            self.submit_frame_encoder(encoder, &mut frame_stats);
316            Ok(frame_stats)
317        } else {
318            self.submit_prepared_scene(prepared, final_format, &final_view)
319        }
320    }
321
322    pub(crate) fn render_offscreen(
323        &mut self,
324        frame: &SceneFrame,
325        size: (u32, u32),
326    ) -> Result<RendererFrameStats> {
327        self.ensure_shared(None)?;
328
329        let final_format = wgpu::TextureFormat::Bgra8UnormSrgb;
330        let target_started = self.runtime_diagnostics_enabled.then(Instant::now);
331        let final_view = self.ensure_offscreen_target(frame.window_id, size, final_format)?;
332        let mut target_us =
333            target_started.map_or(0, |started| started.elapsed().as_micros() as u64);
334        let prepared = self.prepare_scene_submission(frame)?;
335        let target_started = self.runtime_diagnostics_enabled.then(Instant::now);
336        let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
337        let intermediate_format = self
338            .intermediate_targets
339            .get(&frame.window_id)
340            .map(|target| target.format)
341            .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
342        target_us += target_started.map_or(0, |started| started.elapsed().as_micros() as u64);
343        let mut encoder = self.frame_encoder();
344        let mut frame_stats = self.encode_prepared_scene(
345            prepared,
346            intermediate_format,
347            &intermediate_view,
348            &mut encoder,
349        )?;
350        self.encode_output_transform_pass(
351            frame.window_id,
352            &intermediate_view,
353            &final_view,
354            final_format,
355            OutputStrategy::SdrSurface {
356                format: final_format,
357            },
358            RequestedToneMappingMode::Clamp,
359            ColorManagementMode::default().sdr_content_brightness_nits,
360            None,
361            &mut frame_stats,
362            &mut encoder,
363        )?;
364        self.submit_frame_encoder(encoder, &mut frame_stats);
365        frame_stats.target_prepare_time_us = target_us;
366        Ok(frame_stats)
367    }
368
369    pub(crate) fn ensure_offscreen_target(
370        &mut self,
371        window_id: WindowId,
372        size: (u32, u32),
373        format: wgpu::TextureFormat,
374    ) -> Result<wgpu::TextureView> {
375        let recreate = self
376            .offscreen_targets
377            .get(&window_id)
378            .is_none_or(|target| target.size != size || target.format != format);
379        if recreate {
380            let shared = self
381                .shared
382                .as_ref()
383                .expect("renderer shared state initialized");
384            let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
385                label: Some("SUI offscreen frame"),
386                size: wgpu::Extent3d {
387                    width: size.0,
388                    height: size.1,
389                    depth_or_array_layers: 1,
390                },
391                mip_level_count: 1,
392                sample_count: 1,
393                dimension: wgpu::TextureDimension::D2,
394                format,
395                usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
396                view_formats: &[],
397            });
398            self.offscreen_targets.insert(
399                window_id,
400                OffscreenTarget {
401                    view: texture.create_view(&wgpu::TextureViewDescriptor::default()),
402                    texture,
403                    format,
404                    size,
405                },
406            );
407        }
408        self.offscreen_targets
409            .get(&window_id)
410            .map(|target| target.view.clone())
411            .ok_or_else(|| Error::new(format!("missing target for window {}", window_id.get())))
412    }
413
414    pub(crate) fn ensure_intermediate_target(
415        &mut self,
416        window_id: WindowId,
417        size: (u32, u32),
418    ) -> Result<wgpu::TextureView> {
419        let format = wgpu::TextureFormat::Rgba16Float;
420        let recreate = self
421            .intermediate_targets
422            .get(&window_id)
423            .is_none_or(|target| target.size != size || target.format != format);
424        if recreate {
425            let shared = self
426                .shared
427                .as_ref()
428                .expect("renderer shared state initialized");
429            let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
430                label: Some("SUI HDR intermediate frame"),
431                size: wgpu::Extent3d {
432                    width: size.0,
433                    height: size.1,
434                    depth_or_array_layers: 1,
435                },
436                mip_level_count: 1,
437                sample_count: 1,
438                dimension: wgpu::TextureDimension::D2,
439                format,
440                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
441                    | wgpu::TextureUsages::TEXTURE_BINDING
442                    | wgpu::TextureUsages::COPY_SRC,
443                view_formats: &[],
444            });
445            self.intermediate_targets.insert(
446                window_id,
447                OffscreenTarget {
448                    view: texture.create_view(&wgpu::TextureViewDescriptor::default()),
449                    texture,
450                    format,
451                    size,
452                },
453            );
454        }
455        self.intermediate_targets
456            .get(&window_id)
457            .map(|target| target.view.clone())
458            .ok_or_else(|| Error::new(format!("missing target for window {}", window_id.get())))
459    }
460
461    #[cfg(test)]
462    #[allow(clippy::too_many_arguments)]
463    pub(crate) fn submit_output_transform_pass(
464        &mut self,
465        window_id: WindowId,
466        source: &wgpu::TextureView,
467        destination: &wgpu::TextureView,
468        format: wgpu::TextureFormat,
469        strategy: OutputStrategy,
470        tone: RequestedToneMappingMode,
471        brightness: f32,
472        white: Option<f32>,
473        stats: &mut RendererFrameStats,
474    ) -> Result<()> {
475        let mut encoder = self.frame_encoder();
476        self.encode_output_transform_pass(
477            window_id,
478            source,
479            destination,
480            format,
481            strategy,
482            tone,
483            brightness,
484            white,
485            stats,
486            &mut encoder,
487        )?;
488        self.submit_frame_encoder(encoder, stats);
489        Ok(())
490    }
491
492    pub(crate) fn encode_output_transform_pass(
493        &mut self,
494        window_id: WindowId,
495        source_view: &wgpu::TextureView,
496        destination_view: &wgpu::TextureView,
497        destination_format: wgpu::TextureFormat,
498        strategy: OutputStrategy,
499        requested_tone_mapping: RequestedToneMappingMode,
500        sdr_content_brightness_nits: f32,
501        display_sdr_white_nits: Option<f32>,
502        frame_stats: &mut RendererFrameStats,
503        encoder: &mut wgpu::CommandEncoder,
504    ) -> Result<()> {
505        let prepare_started = self.runtime_diagnostics_enabled.then(Instant::now);
506        let resolved_tone_mapping = match strategy {
507            OutputStrategy::HdrNativeSurface { .. } => 0,
508            _ => match requested_tone_mapping {
509                RequestedToneMappingMode::Automatic => 1,
510                RequestedToneMappingMode::Clamp => 1,
511                RequestedToneMappingMode::Reinhard => 2,
512            },
513        };
514        let shared = self
515            .shared
516            .as_mut()
517            .expect("renderer shared state initialized");
518        let sdr_content_scale = crate::output::output_sdr_content_scale(
519            strategy,
520            sdr_content_brightness_nits,
521            display_sdr_white_nits,
522        );
523        let encode_srgb = matches!(
524            destination_format,
525            wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm
526        ) || matches!(
527            strategy,
528            OutputStrategy::HdrNativeSurface {
529                transfer: DisplayTransferFunction::Srgb,
530                ..
531            }
532        );
533        let uniform = OutputTransformUniform::new(
534            resolved_tone_mapping,
535            encode_srgb,
536            crate::output::output_primaries(strategy),
537            sdr_content_scale,
538        );
539        let cache = &mut self.frame_resources.output_transforms;
540        let recreate = cache
541            .get(&window_id)
542            .is_none_or(|cached| cached.source_view != *source_view);
543        if recreate {
544            let uniform_buffer = shared.device.create_buffer(&wgpu::BufferDescriptor {
545                label: Some("SUI output transform uniform"),
546                size: std::mem::size_of::<OutputTransformUniform>() as u64,
547                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
548                mapped_at_creation: false,
549            });
550            let bind_group = shared.device.create_bind_group(&wgpu::BindGroupDescriptor {
551                label: Some("SUI output transform bind group"),
552                layout: &shared.output_transform_bind_group_layout,
553                entries: &[
554                    wgpu::BindGroupEntry {
555                        binding: 0,
556                        resource: wgpu::BindingResource::TextureView(source_view),
557                    },
558                    wgpu::BindGroupEntry {
559                        binding: 1,
560                        resource: uniform_buffer.as_entire_binding(),
561                    },
562                ],
563            });
564            cache.insert(
565                window_id,
566                CachedOutputTransform {
567                    source_view: source_view.clone(),
568                    uniform,
569                    buffer: uniform_buffer,
570                    bind_group,
571                },
572            );
573        }
574        let cached = cache
575            .get_mut(&window_id)
576            .expect("output transform resources allocated");
577        if recreate || cached.uniform != uniform {
578            self.frame_resources.uploads.write_buffer(
579                &shared.device,
580                &cached.buffer,
581                0,
582                bytemuck::bytes_of(&uniform),
583            );
584            cached.uniform = uniform;
585        }
586        let bind_group = cached.bind_group.clone();
587        if let Some(started) = prepare_started {
588            frame_stats.gpu_upload_time_us += started.elapsed().as_micros() as u64;
589        }
590        let encode_started = self.runtime_diagnostics_enabled.then(Instant::now);
591        {
592            let pipeline = shared.output_transform_pipeline(destination_format);
593            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
594                label: Some("SUI output transform pass"),
595                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
596                    view: destination_view,
597                    depth_slice: None,
598                    resolve_target: None,
599                    ops: wgpu::Operations {
600                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
601                        store: wgpu::StoreOp::Store,
602                    },
603                })],
604                depth_stencil_attachment: None,
605                occlusion_query_set: None,
606                timestamp_writes: None,
607                multiview_mask: None,
608            });
609            pass.set_pipeline(pipeline);
610            pass.set_bind_group(0, &bind_group, &[]);
611            pass.draw(0..3, 0..1);
612        }
613        if let Some(started) = encode_started {
614            frame_stats.pass_encode_time_us += started.elapsed().as_micros() as u64;
615        }
616        frame_stats.pass_count += 1;
617        Ok(())
618    }
619}
620
621pub(crate) fn shader_color(color: Color) -> [f32; 4] {
622    let linear = color.to_linear_srgb();
623    [
624        linear.red,
625        linear.green,
626        linear.blue,
627        linear.alpha.clamp(0.0, 1.0),
628    ]
629}
630
631pub(crate) fn preferred_surface_format(
632    formats: &[wgpu::TextureFormat],
633) -> Option<wgpu::TextureFormat> {
634    formats
635        .iter()
636        .copied()
637        .find(wgpu::TextureFormat::is_srgb)
638        .or_else(|| formats.first().copied())
639}
640
641pub(crate) fn preferred_hdr_surface_format(
642    formats: &[wgpu::TextureFormat],
643) -> Option<wgpu::TextureFormat> {
644    formats
645        .iter()
646        .copied()
647        .find(|format| matches!(format, wgpu::TextureFormat::Rgba16Float))
648}
649
650pub(crate) fn output_transform_requires_intermediate(strategy: OutputStrategy) -> bool {
651    match strategy {
652        OutputStrategy::HdrNativeSurface { .. }
653        | OutputStrategy::HdrIntermediateThenToneMap { .. } => true,
654        OutputStrategy::WideGamutSurface { format, primaries } => {
655            !format.is_srgb() || !matches!(primaries, DisplayColorPrimaries::Srgb)
656        }
657        OutputStrategy::SdrSurface { format } => !format.is_srgb(),
658    }
659}
660
661/// LCD coverage is tied to the final RGB channels. A gamut conversion or HDR
662/// presentation/tone map after blending cannot preserve that interpretation.
663pub(crate) fn output_allows_lcd(strategy: OutputStrategy) -> bool {
664    matches!(
665        strategy,
666        OutputStrategy::SdrSurface { .. }
667            | OutputStrategy::WideGamutSurface {
668                primaries: DisplayColorPrimaries::Srgb,
669                ..
670            }
671    )
672}
673
674pub(crate) fn output_primaries(strategy: OutputStrategy) -> DisplayColorPrimaries {
675    match strategy {
676        OutputStrategy::SdrSurface { .. } => DisplayColorPrimaries::Srgb,
677        OutputStrategy::WideGamutSurface { primaries, .. }
678        | OutputStrategy::HdrNativeSurface { primaries, .. }
679        | OutputStrategy::HdrIntermediateThenToneMap { primaries, .. } => primaries,
680    }
681}
682
683pub(crate) fn output_sdr_content_scale(
684    strategy: OutputStrategy,
685    brightness_nits: f32,
686    _display_sdr_white_nits: Option<f32>,
687) -> f32 {
688    let sanitized = if brightness_nits.is_finite() && brightness_nits > 0.0 {
689        brightness_nits
690    } else {
691        DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS
692    };
693
694    match strategy {
695        // Native HDR is presented as linear scRGB: 1.0 is the 80 nit scRGB
696        // reference, so SDR reference white must be lifted to the requested
697        // SDR-content brightness before presentation.
698        OutputStrategy::HdrNativeSurface { .. } => sanitized / SCRGB_REFERENCE_WHITE_NITS,
699        OutputStrategy::SdrSurface { .. }
700        | OutputStrategy::WideGamutSurface { .. }
701        | OutputStrategy::HdrIntermediateThenToneMap { .. } => 1.0,
702    }
703}
704
705#[cfg(test)]
706pub(crate) fn apply_output_transform_for_testing(
707    color: [f32; 4],
708    strategy: OutputStrategy,
709    mode: RequestedToneMappingMode,
710    sdr_content_brightness_nits: f32,
711    display_sdr_white_nits: Option<f32>,
712) -> [f32; 4] {
713    let scale = output_sdr_content_scale(
714        strategy,
715        sdr_content_brightness_nits,
716        display_sdr_white_nits,
717    );
718    let scaled = [
719        color[0] * scale,
720        color[1] * scale,
721        color[2] * scale,
722        color[3],
723    ];
724
725    let transformed = match strategy {
726        OutputStrategy::HdrNativeSurface { .. } => [scaled[0], scaled[1], scaled[2], scaled[3]],
727        _ => match mode {
728            RequestedToneMappingMode::Automatic => match strategy {
729                OutputStrategy::SdrSurface { .. }
730                | OutputStrategy::WideGamutSurface { .. }
731                | OutputStrategy::HdrIntermediateThenToneMap { .. } => {
732                    tone_map_linear_color(scaled, RequestedToneMappingMode::Clamp)
733                }
734                OutputStrategy::HdrNativeSurface { .. } => unreachable!(),
735            },
736            RequestedToneMappingMode::Clamp => {
737                tone_map_linear_color(scaled, RequestedToneMappingMode::Clamp)
738            }
739            RequestedToneMappingMode::Reinhard => {
740                tone_map_linear_color(scaled, RequestedToneMappingMode::Reinhard)
741            }
742        },
743    };
744
745    let [red, green, blue] =
746        linear_srgb_to_output_primaries([transformed[0], transformed[1], transformed[2]], strategy);
747    [red, green, blue, transformed[3]]
748}
749
750#[cfg(test)]
751pub(crate) fn linear_srgb_to_output_primaries(
752    color: [f32; 3],
753    strategy: OutputStrategy,
754) -> [f32; 3] {
755    match output_primaries(strategy) {
756        DisplayColorPrimaries::Srgb => color,
757        DisplayColorPrimaries::DisplayP3 => [
758            (0.822_461_96 * color[0]) + (0.177_538_02 * color[1]),
759            (0.033_194_2 * color[0]) + (0.966_805_76 * color[1]),
760            (0.017_082_63 * color[0]) + (0.072_397_43 * color[1]) + (0.910_519_96 * color[2]),
761        ],
762    }
763}
764
765#[cfg(test)]
766pub(crate) fn tone_map_linear_color(color: [f32; 4], mode: RequestedToneMappingMode) -> [f32; 4] {
767    let transform = |channel: f32| match mode {
768        RequestedToneMappingMode::Automatic | RequestedToneMappingMode::Clamp => {
769            channel.clamp(0.0, 1.0)
770        }
771        RequestedToneMappingMode::Reinhard => {
772            let channel = channel.max(0.0);
773            channel / (1.0 + channel)
774        }
775    };
776
777    [
778        transform(color[0]),
779        transform(color[1]),
780        transform(color[2]),
781        color[3].clamp(0.0, 1.0),
782    ]
783}
784
785pub(crate) fn requested_output_primaries(
786    capabilities: DisplayCapabilities,
787    requested: ColorManagementMode,
788) -> DisplayColorPrimaries {
789    match requested.output_primaries {
790        RequestedOutputColorPrimaries::Automatic => {
791            if capabilities.supports_wide_gamut {
792                capabilities.preferred_primaries
793            } else {
794                DisplayColorPrimaries::Srgb
795            }
796        }
797        RequestedOutputColorPrimaries::Srgb => DisplayColorPrimaries::Srgb,
798        RequestedOutputColorPrimaries::DisplayP3 => {
799            if capabilities.supports_wide_gamut {
800                DisplayColorPrimaries::DisplayP3
801            } else {
802                DisplayColorPrimaries::Srgb
803            }
804        }
805    }
806}
807
808pub(crate) fn select_output_strategy(
809    formats: &[wgpu::TextureFormat],
810    capabilities: DisplayCapabilities,
811    requested: ColorManagementMode,
812) -> OutputStrategy {
813    let sdr_format =
814        preferred_surface_format(formats).unwrap_or(wgpu::TextureFormat::Bgra8UnormSrgb);
815    let primaries = requested_output_primaries(capabilities.clone(), requested);
816    let native_hdr_format = preferred_hdr_surface_format(formats);
817    let native_hdr_available =
818        capabilities.native_hdr_presentation_supported && native_hdr_format.is_some();
819
820    if matches!(requested.mode, RequestedColorManagementMode::ForceSdr) {
821        return OutputStrategy::SdrSurface { format: sdr_format };
822    }
823
824    let wants_hdr = match requested.dynamic_range {
825        RequestedDynamicRangeMode::HighDynamicRange => true,
826        RequestedDynamicRangeMode::StandardDynamicRange => false,
827        RequestedDynamicRangeMode::Automatic => match requested.mode {
828            RequestedColorManagementMode::PreferHdr => true,
829            RequestedColorManagementMode::Automatic => {
830                native_hdr_available
831                    || capabilities.supports_hdr
832                    || matches!(
833                        capabilities.preferred_dynamic_range,
834                        DynamicRangeMode::HighDynamicRange
835                    )
836            }
837            RequestedColorManagementMode::ForceSdr
838            | RequestedColorManagementMode::PreferWideGamut => false,
839        },
840    };
841    let wants_wide_gamut = match requested.output_primaries {
842        RequestedOutputColorPrimaries::DisplayP3 => true,
843        RequestedOutputColorPrimaries::Srgb => false,
844        RequestedOutputColorPrimaries::Automatic => match requested.mode {
845            RequestedColorManagementMode::PreferWideGamut
846            | RequestedColorManagementMode::PreferHdr => true,
847            RequestedColorManagementMode::Automatic => capabilities.supports_wide_gamut,
848            RequestedColorManagementMode::ForceSdr => false,
849        },
850    };
851
852    if wants_hdr {
853        if native_hdr_available && let Some(format) = native_hdr_format {
854            let uses_linear_sc_rgb = capabilities.native_hdr_presentation_supported
855                && matches!(
856                    capabilities.preferred_primaries,
857                    DisplayColorPrimaries::Srgb
858                );
859            let transfer = if uses_linear_sc_rgb {
860                DisplayTransferFunction::LinearExtended
861            } else {
862                DisplayTransferFunction::Srgb
863            };
864            return OutputStrategy::HdrNativeSurface {
865                format,
866                primaries: DisplayColorPrimaries::Srgb,
867                transfer,
868            };
869        }
870
871        // If HDR cannot be presented end-to-end, normal presentation stays SDR.
872        // HdrIntermediateThenToneMap is reserved for debug captures and explicit
873        // diagnostics where seeing HDR scene values on an SDR display is useful.
874        return OutputStrategy::SdrSurface { format: sdr_format };
875    }
876
877    if wants_wide_gamut && capabilities.supports_wide_gamut {
878        return OutputStrategy::WideGamutSurface {
879            format: sdr_format,
880            primaries,
881        };
882    }
883
884    OutputStrategy::SdrSurface { format: sdr_format }
885}