Skip to main content

egui_pop_viewport/
display.rs

1//! The display transform: the last step from the source's pixels to the
2//! window, where the application plugs in its colour management.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! - A [`DisplayTarget`] is an encoding a surface expects: primaries,
8//!   transfer, the luminance of SDR white, the headroom above it, the
9//!   surface format. A window's surface has one ([`set_target`],
10//!   [`target`]; sRGB until said otherwise, and the GPU path records what
11//!   eframe configured when it is installed).
12//! - The application may **want** another for a window ([`want`]): Display
13//!   P3, HDR with PQ or HLG. The viewport then draws for what the surface
14//!   can carry and says why when that is less ([`resolve`],
15//!   [`Resolution`]): an application declaring a P3 or HDR target gets
16//!   faithful output where the platform allows it, and a correct sRGB
17//!   fallback with the reason otherwise.
18//! - A [`DisplayTransform`] (the application's, [`LinearSrgb`] by
19//!   default) turns scene pixels into a [`Stage`] for a target: a 3×3
20//!   matrix from the working space to the target's primaries (computed
21//!   from their chromaticities, [`Primaries::conversion`]), a clamp, and
22//!   the target's transfer (sRGB, 2.2, extended linear or extended sRGB,
23//!   SMPTE ST 2084 PQ, BT.2100 HLG). The GPU path runs the stage in its
24//!   shader; the CPU path ([`apply_cpu`]) runs the same arithmetic
25//!   ([`Stage::encode`]) and writes 8-bit sRGB textures, so it always
26//!   draws sRGB.
27//! - A source that does its own transform on the CPU delivers display
28//!   pixels (`Pixels::Display` of the tile source) and skips this.
29//!
30//! ```
31//! use egui_pop_viewport::display::{DisplayTarget, DisplayTransform, LinearSrgb, Transfer};
32//!
33//! let stage = LinearSrgb.stage(&DisplayTarget::srgb());
34//! // Linear 0.5 is sRGB-encoded 188.
35//! assert_eq!(stage.encode_8bit([0.5, 0.5, 0.5]), [188, 188, 188]);
36//! // SDR white at 203 nits is 58 % of the PQ signal (BT.2408).
37//! assert!((Transfer::Pq.encode_at(1.0, 203.0) - 0.5807).abs() < 1e-3);
38//! ```
39
40use egui::{Color32, Context, ViewportId};
41use egui_pop_core::state::Slot;
42
43/// The primaries (and white) of an encoding.
44#[derive(Clone, Copy, Debug, PartialEq)]
45pub enum Primaries {
46    /// BT.709 / sRGB.
47    Srgb,
48    DisplayP3,
49    /// BT.2020 (and BT.2100).
50    Bt2020,
51    /// Chromaticities `[x, y]` of red, green, blue and white.
52    Custom {
53        r: [f64; 2],
54        g: [f64; 2],
55        b: [f64; 2],
56        w: [f64; 2],
57    },
58}
59
60/// The D65 white point.
61pub const D65: [f64; 2] = [0.3127, 0.3290];
62
63type M3 = [[f64; 3]; 3];
64
65fn mul(a: &M3, b: &M3) -> M3 {
66    let mut out = [[0.0; 3]; 3];
67    for (i, row) in out.iter_mut().enumerate() {
68        for (j, v) in row.iter_mut().enumerate() {
69            *v = (0..3).map(|k| a[i][k] * b[k][j]).sum();
70        }
71    }
72    out
73}
74
75fn inverse(m: &M3) -> M3 {
76    let [[a, b, c], [d, e, f], [g, h, i]] = *m;
77    let co = [
78        e * i - f * h,
79        -(d * i - f * g),
80        d * h - e * g,
81        -(b * i - c * h),
82        a * i - c * g,
83        -(a * h - b * g),
84        b * f - c * e,
85        -(a * f - c * d),
86        a * e - b * d,
87    ];
88    let det = a * co[0] + b * co[1] + c * co[2];
89    // The adjugate is the transposed cofactor matrix.
90    [
91        [co[0] / det, co[3] / det, co[6] / det],
92        [co[1] / det, co[4] / det, co[7] / det],
93        [co[2] / det, co[5] / det, co[8] / det],
94    ]
95}
96
97fn xyz(c: [f64; 2]) -> [f64; 3] {
98    [c[0] / c[1], 1.0, (1.0 - c[0] - c[1]) / c[1]]
99}
100
101impl Primaries {
102    /// Red, green, blue and white chromaticities `[x, y]`.
103    pub fn chromaticities(&self) -> [[f64; 2]; 4] {
104        match *self {
105            Primaries::Srgb => [[0.64, 0.33], [0.30, 0.60], [0.15, 0.06], D65],
106            Primaries::DisplayP3 => [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], D65],
107            Primaries::Bt2020 => [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046], D65],
108            Primaries::Custom { r, g, b, w } => [r, g, b, w],
109        }
110    }
111
112    /// Linear RGB in these primaries to CIE XYZ (white at `Y = 1`).
113    pub fn to_xyz(&self) -> [[f64; 3]; 3] {
114        let [r, g, b, w] = self.chromaticities();
115        let (r, g, b) = (xyz(r), xyz(g), xyz(b));
116        let p = [[r[0], g[0], b[0]], [r[1], g[1], b[1]], [r[2], g[2], b[2]]];
117        let white = xyz(w);
118        let inv = inverse(&p);
119        let s: [f64; 3] = [0, 1, 2].map(|i| (0..3).map(|k| inv[i][k] * white[k]).sum());
120        [0, 1, 2].map(|i| [0, 1, 2].map(|j| p[i][j] * s[j]))
121    }
122
123    /// The matrix from linear RGB in `from` to linear RGB in `to` (no
124    /// chromatic adaptation: the named primaries share D65).
125    pub fn conversion(from: Primaries, to: Primaries) -> [[f32; 3]; 3] {
126        if from == to {
127            return IDENTITY;
128        }
129        let m = mul(&inverse(&to.to_xyz()), &from.to_xyz());
130        m.map(|row| row.map(|v| v as f32))
131    }
132
133    /// How wide the gamut is, to compare the named ones (sRGB 0, Display
134    /// P3 1, BT.2020 2); custom primaries count as BT.2020.
135    pub fn rank(&self) -> u8 {
136        match self {
137            Primaries::Srgb => 0,
138            Primaries::DisplayP3 => 1,
139            Primaries::Bt2020 | Primaries::Custom { .. } => 2,
140        }
141    }
142
143    pub fn name(&self) -> &'static str {
144        match self {
145            Primaries::Srgb => "sRGB",
146            Primaries::DisplayP3 => "Display P3",
147            Primaries::Bt2020 => "BT.2020",
148            Primaries::Custom { .. } => "custom primaries",
149        }
150    }
151}
152
153/// The transfer the shader applies before writing.
154#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155pub enum Transfer {
156    /// The sRGB piecewise curve.
157    SrgbPiecewise,
158    /// A pure 2.2 power.
159    Gamma22,
160    /// Linear, extended range (scRGB): negatives carry the gamut, values
161    /// above 1.0 the headroom.
162    ExtLinear,
163    /// The sRGB curve continued past 1.0 and mirrored below 0.0 (the
164    /// extended sRGB colour spaces).
165    ExtSrgb,
166    /// SMPTE ST 2084 (PQ): absolute luminance, 1.0 the signal of 10 000
167    /// nits.
168    Pq,
169    /// BT.2100 hybrid log-gamma, with SDR white at 75 % of the signal
170    /// (BT.2408).
171    Hlg,
172}
173
174/// PQ constants (SMPTE ST 2084).
175const PQ_M1: f32 = 2610.0 / 16384.0;
176const PQ_M2: f32 = 2523.0 / 4096.0 * 128.0;
177const PQ_C1: f32 = 3424.0 / 4096.0;
178const PQ_C2: f32 = 2413.0 / 4096.0 * 32.0;
179const PQ_C3: f32 = 2392.0 / 4096.0 * 32.0;
180
181/// HLG constants (BT.2100).
182const HLG_A: f32 = 0.178_832_77;
183const HLG_B: f32 = 1.0 - 4.0 * HLG_A;
184const HLG_C: f32 = 0.559_910_7;
185
186/// The HLG scene light SDR white maps to: the signal 0.75 (BT.2408).
187pub const HLG_WHITE: f32 = 0.264_962_56;
188
189/// The luminance of SDR white BT.2408 recommends for HDR (nits).
190pub const HDR_REFERENCE_WHITE: f32 = 203.0;
191
192fn srgb_encode(v: f32) -> f32 {
193    if v <= 0.003_130_8 {
194        v * 12.92
195    } else {
196        1.055 * v.powf(1.0 / 2.4) - 0.055
197    }
198}
199
200fn srgb_decode(v: f32) -> f32 {
201    if v <= 0.040_45 {
202        v / 12.92
203    } else {
204        ((v + 0.055) / 1.055).powf(2.4)
205    }
206}
207
208/// The PQ signal of an absolute luminance in nits.
209pub fn pq_encode(nits: f32) -> f32 {
210    let y = (nits / 10_000.0).clamp(0.0, 1.0).powf(PQ_M1);
211    ((PQ_C1 + PQ_C2 * y) / (1.0 + PQ_C3 * y)).powf(PQ_M2)
212}
213
214/// The luminance in nits of a PQ signal.
215pub fn pq_decode(signal: f32) -> f32 {
216    let e = signal.clamp(0.0, 1.0).powf(1.0 / PQ_M2);
217    let y = ((e - PQ_C1).max(0.0) / (PQ_C2 - PQ_C3 * e)).powf(1.0 / PQ_M1);
218    y * 10_000.0
219}
220
221/// The HLG signal of normalised scene light (0..1, the BT.2100 OETF).
222pub fn hlg_oetf(e: f32) -> f32 {
223    let e = e.clamp(0.0, 1.0);
224    if e <= 1.0 / 12.0 {
225        (3.0 * e).sqrt()
226    } else {
227        HLG_A * (12.0 * e - HLG_B).ln() + HLG_C
228    }
229}
230
231/// The normalised scene light of an HLG signal (the inverse OETF).
232pub fn hlg_inverse_oetf(signal: f32) -> f32 {
233    let s = signal.clamp(0.0, 1.0);
234    if s <= 0.5 {
235        s * s / 3.0
236    } else {
237        (((s - HLG_C) / HLG_A).exp() + HLG_B) / 12.0
238    }
239}
240
241impl Transfer {
242    /// Encodes a linear value (1.0 is SDR white), SDR white at
243    /// [`HDR_REFERENCE_WHITE`] nits for PQ.
244    pub fn encode(self, v: f32) -> f32 {
245        self.encode_at(v, HDR_REFERENCE_WHITE)
246    }
247
248    /// Encodes a linear value, SDR white at `white_nits` (used by PQ
249    /// only, which is absolute).
250    pub fn encode_at(self, v: f32, white_nits: f32) -> f32 {
251        match self {
252            Transfer::ExtLinear => v,
253            Transfer::Gamma22 => v.max(0.0).powf(1.0 / 2.2),
254            Transfer::SrgbPiecewise => srgb_encode(v.max(0.0)),
255            Transfer::ExtSrgb => v.signum() * srgb_encode(v.abs()),
256            Transfer::Pq => pq_encode(v.max(0.0) * white_nits),
257            Transfer::Hlg => hlg_oetf(v.max(0.0) * HLG_WHITE),
258        }
259    }
260
261    /// Decodes a signal back to linear (1.0 is SDR white), SDR white at
262    /// [`HDR_REFERENCE_WHITE`] nits for PQ.
263    pub fn decode(self, v: f32) -> f32 {
264        self.decode_at(v, HDR_REFERENCE_WHITE)
265    }
266
267    /// Decodes a signal back to linear, SDR white at `white_nits`.
268    pub fn decode_at(self, v: f32, white_nits: f32) -> f32 {
269        match self {
270            Transfer::ExtLinear => v,
271            Transfer::Gamma22 => v.max(0.0).powf(2.2),
272            Transfer::SrgbPiecewise => srgb_decode(v.max(0.0)),
273            Transfer::ExtSrgb => v.signum() * srgb_decode(v.abs()),
274            Transfer::Pq => pq_decode(v) / white_nits,
275            Transfer::Hlg => hlg_inverse_oetf(v) / HLG_WHITE,
276        }
277    }
278
279    /// Whether values above SDR white are carried.
280    pub fn is_hdr(self) -> bool {
281        matches!(
282            self,
283            Transfer::ExtLinear | Transfer::ExtSrgb | Transfer::Pq | Transfer::Hlg
284        )
285    }
286
287    /// Whether negatives are carried (any gamut through any primaries).
288    pub fn is_extended(self) -> bool {
289        matches!(self, Transfer::ExtLinear | Transfer::ExtSrgb)
290    }
291
292    /// The highest headroom the transfer carries (relative to SDR white).
293    pub fn max_headroom(self, white_nits: f32) -> f32 {
294        match self {
295            Transfer::SrgbPiecewise | Transfer::Gamma22 => 1.0,
296            Transfer::ExtLinear | Transfer::ExtSrgb => f32::MAX,
297            Transfer::Pq => 10_000.0 / white_nits.max(1.0),
298            Transfer::Hlg => 1.0 / HLG_WHITE,
299        }
300    }
301
302    /// The code the shader uses.
303    pub fn code(self) -> u32 {
304        match self {
305            Transfer::SrgbPiecewise => 0,
306            Transfer::Gamma22 => 1,
307            Transfer::ExtLinear => 2,
308            Transfer::Pq => 3,
309            Transfer::Hlg => 4,
310            Transfer::ExtSrgb => 5,
311        }
312    }
313
314    pub fn name(self) -> &'static str {
315        match self {
316            Transfer::SrgbPiecewise => "sRGB",
317            Transfer::Gamma22 => "gamma 2.2",
318            Transfer::ExtLinear => "extended linear",
319            Transfer::ExtSrgb => "extended sRGB",
320            Transfer::Pq => "PQ",
321            Transfer::Hlg => "HLG",
322        }
323    }
324}
325
326/// The surface's pixel format, as configured.
327#[derive(Clone, Copy, Debug, PartialEq, Eq)]
328pub enum SurfaceFormat {
329    /// 8 bits, the hardware encodes sRGB on write.
330    Rgba8UnormSrgb,
331    /// 8 bits, written as given (the shader encodes).
332    Rgba8Unorm,
333    /// 10 bits per channel.
334    Rgb10a2Unorm,
335    /// Half floats (scRGB, extended sRGB or HDR).
336    Rgba16Float,
337    /// Anything else.
338    Other,
339}
340
341impl SurfaceFormat {
342    /// Whether the format holds values outside 0..1.
343    pub fn is_float(self) -> bool {
344        self == SurfaceFormat::Rgba16Float
345    }
346
347    /// Bits per colour channel (0 when unknown).
348    pub fn bits(self) -> u8 {
349        match self {
350            SurfaceFormat::Rgba8UnormSrgb | SurfaceFormat::Rgba8Unorm => 8,
351            SurfaceFormat::Rgb10a2Unorm => 10,
352            SurfaceFormat::Rgba16Float => 16,
353            SurfaceFormat::Other => 0,
354        }
355    }
356}
357
358/// The colour space a surface is configured with: how the compositor
359/// reads what is written (the colour spaces wgpu configures).
360#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
361pub enum ColorSpace {
362    Srgb,
363    /// scRGB: linear, sRGB primaries, extended range.
364    ExtendedSrgbLinear,
365    /// sRGB-encoded, extended range.
366    ExtendedSrgb,
367    DisplayP3,
368    /// Display P3, sRGB-encoded, extended range.
369    ExtendedDisplayP3,
370    /// HDR10: BT.2020 primaries, PQ.
371    Bt2100Pq,
372    /// BT.2020 primaries, HLG.
373    Bt2100Hlg,
374}
375
376impl ColorSpace {
377    pub const ALL: [ColorSpace; 7] = [
378        ColorSpace::Srgb,
379        ColorSpace::ExtendedSrgbLinear,
380        ColorSpace::ExtendedSrgb,
381        ColorSpace::DisplayP3,
382        ColorSpace::ExtendedDisplayP3,
383        ColorSpace::Bt2100Pq,
384        ColorSpace::Bt2100Hlg,
385    ];
386
387    /// Its primaries and transfer.
388    pub fn encoding(self) -> (Primaries, Transfer) {
389        match self {
390            ColorSpace::Srgb => (Primaries::Srgb, Transfer::SrgbPiecewise),
391            ColorSpace::ExtendedSrgbLinear => (Primaries::Srgb, Transfer::ExtLinear),
392            ColorSpace::ExtendedSrgb => (Primaries::Srgb, Transfer::ExtSrgb),
393            ColorSpace::DisplayP3 => (Primaries::DisplayP3, Transfer::SrgbPiecewise),
394            ColorSpace::ExtendedDisplayP3 => (Primaries::DisplayP3, Transfer::ExtSrgb),
395            ColorSpace::Bt2100Pq => (Primaries::Bt2020, Transfer::Pq),
396            ColorSpace::Bt2100Hlg => (Primaries::Bt2020, Transfer::Hlg),
397        }
398    }
399
400    /// Whether egui's renderer draws the interface faithfully on it:
401    /// egui writes sRGB-encoded values to every surface that is not an
402    /// `*Srgb` format, which only the sRGB and extended sRGB colour
403    /// spaces read as meant.
404    pub fn egui_draws_faithfully(self) -> bool {
405        matches!(self, ColorSpace::Srgb | ColorSpace::ExtendedSrgb)
406    }
407
408    /// The formats that carry it: half floats for the extended ones, at
409    /// least 10 bits for PQ and HLG.
410    pub fn needs(self) -> &'static [SurfaceFormat] {
411        match self {
412            ColorSpace::Srgb | ColorSpace::DisplayP3 => &[
413                SurfaceFormat::Rgba8Unorm,
414                SurfaceFormat::Rgba8UnormSrgb,
415                SurfaceFormat::Rgb10a2Unorm,
416                SurfaceFormat::Rgba16Float,
417            ],
418            ColorSpace::ExtendedSrgbLinear
419            | ColorSpace::ExtendedSrgb
420            | ColorSpace::ExtendedDisplayP3 => &[SurfaceFormat::Rgba16Float],
421            ColorSpace::Bt2100Pq | ColorSpace::Bt2100Hlg => {
422                &[SurfaceFormat::Rgb10a2Unorm, SurfaceFormat::Rgba16Float]
423            }
424        }
425    }
426}
427
428/// Where the target's description comes from.
429#[derive(Clone, Copy, Debug, PartialEq, Eq)]
430pub enum TargetSource {
431    /// Nothing declared: sRGB assumed.
432    Assumed,
433    /// Declared by the driver's window system integration (the surface
434    /// configured through wgpu).
435    Wsi,
436    /// Declared by the application itself: through a compositor
437    /// protocol (Wayland's `wp_color_management_v1`, any primaries and
438    /// transfer the protocol names, no surface colour space needed), or
439    /// on a surface it configured itself.
440    Tagged,
441    /// Read from the operating system.
442    Os,
443}
444
445/// What a window's surface expects.
446#[derive(Clone, Copy, Debug, PartialEq)]
447pub struct DisplayTarget {
448    /// Primaries and white of the encoding the surface declares (not the
449    /// monitor's).
450    pub primaries: Primaries,
451    pub transfer: Transfer,
452    /// Nits the encoding's reference white maps to.
453    pub sdr_white_nits: f32,
454    /// Highest value the target may carry, relative to SDR white (1.0
455    /// for SDR).
456    pub headroom: f32,
457    pub surface_format: SurfaceFormat,
458    pub source: TargetSource,
459}
460
461impl Default for DisplayTarget {
462    fn default() -> Self {
463        DisplayTarget::srgb()
464    }
465}
466
467/// Why a target is not drawn as wanted.
468#[derive(Clone, Debug, PartialEq, Eq)]
469pub enum Fallback {
470    /// Nobody configured the surface for it (its source is `Assumed`).
471    NotConfigured,
472    /// No surface colour space has these primaries and this transfer
473    /// (nor the compositor protocol, for a tagged target).
474    NoColorSpace,
475    /// The format cannot carry the transfer (8 bits for PQ, unsigned
476    /// values for an extended range).
477    Format(SurfaceFormat),
478    /// Headroom above SDR white on an SDR transfer.
479    HeadroomOnSdr,
480    /// The surface carries less than wanted (its encoding, and what is
481    /// missing).
482    Surface { surface: String, missing: String },
483    /// As `Surface`, and the image could not get a surface of its own
484    /// (why: no colour management on the compositor, an X11 window...).
485    Unavailable {
486        surface: String,
487        missing: String,
488        why: String,
489    },
490    /// The CPU path draws 8-bit sRGB textures.
491    CpuPath,
492    /// The application's hook chose so.
493    Hook,
494}
495
496impl std::fmt::Display for Fallback {
497    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
498        match self {
499            Fallback::NotConfigured => {
500                f.write_str("the window's surface is not configured for it (nothing declared it)")
501            }
502            Fallback::NoColorSpace => {
503                f.write_str("no surface colour space or compositor encoding has these primaries and this transfer")
504            }
505            Fallback::Format(format) => write!(f, "a {format:?} surface cannot carry it"),
506            Fallback::HeadroomOnSdr => {
507                f.write_str("headroom above SDR white needs an HDR transfer")
508            }
509            Fallback::Surface { surface, missing } => {
510                write!(f, "the surface is {surface}: {missing} cannot be shown")
511            }
512            Fallback::Unavailable {
513                surface,
514                missing,
515                why,
516            } => write!(
517                f,
518                "the surface is {surface}: {missing} cannot be shown ({why})"
519            ),
520            Fallback::CpuPath => f.write_str(
521                "the CPU path draws 8-bit sRGB textures (the GPU path draws wide gamut and HDR)",
522            ),
523            Fallback::Hook => f.write_str("the application's hook chose this target"),
524        }
525    }
526}
527
528impl DisplayTarget {
529    /// sRGB, SDR, 8 bits: what every surface can show.
530    pub fn srgb() -> DisplayTarget {
531        DisplayTarget {
532            primaries: Primaries::Srgb,
533            transfer: Transfer::SrgbPiecewise,
534            sdr_white_nits: 80.0,
535            headroom: 1.0,
536            surface_format: SurfaceFormat::Rgba8UnormSrgb,
537            source: TargetSource::Assumed,
538        }
539    }
540
541    /// Display P3, SDR (what an application wanting the P3 gamut asks
542    /// for).
543    pub fn display_p3() -> DisplayTarget {
544        DisplayTarget {
545            primaries: Primaries::DisplayP3,
546            surface_format: SurfaceFormat::Rgba8Unorm,
547            ..DisplayTarget::srgb()
548        }
549    }
550
551    /// HDR10: BT.2020 primaries, PQ, SDR white at 203 nits, `headroom`
552    /// times brighter at most.
553    pub fn hdr_pq(headroom: f32) -> DisplayTarget {
554        DisplayTarget {
555            primaries: Primaries::Bt2020,
556            transfer: Transfer::Pq,
557            sdr_white_nits: HDR_REFERENCE_WHITE,
558            headroom,
559            surface_format: SurfaceFormat::Rgb10a2Unorm,
560            source: TargetSource::Assumed,
561        }
562    }
563
564    /// BT.2100 HLG, SDR white at 75 % of the signal.
565    pub fn hdr_hlg() -> DisplayTarget {
566        DisplayTarget {
567            transfer: Transfer::Hlg,
568            headroom: 1.0 / HLG_WHITE,
569            ..DisplayTarget::hdr_pq(1.0)
570        }
571    }
572
573    /// The encoding of a surface colour space on a format, as declared
574    /// by `source`; `headroom` is kept within what the transfer carries.
575    pub fn for_color_space(
576        color_space: ColorSpace,
577        format: SurfaceFormat,
578        headroom: f32,
579        source: TargetSource,
580    ) -> DisplayTarget {
581        let (primaries, transfer) = color_space.encoding();
582        let sdr_white_nits = match transfer {
583            Transfer::Pq | Transfer::Hlg => HDR_REFERENCE_WHITE,
584            _ => 80.0,
585        };
586        let headroom = if transfer.is_hdr() {
587            headroom.clamp(1.0, transfer.max_headroom(sdr_white_nits))
588        } else {
589            1.0
590        };
591        DisplayTarget {
592            primaries,
593            transfer,
594            sdr_white_nits,
595            headroom,
596            surface_format: format,
597            source,
598        }
599    }
600
601    /// Who declared it.
602    pub fn with_source(mut self, source: TargetSource) -> DisplayTarget {
603        self.source = source;
604        self
605    }
606
607    /// The surface colour space this encoding is, if any (a 2.2 power
608    /// counts as sRGB).
609    pub fn color_space(&self) -> Option<ColorSpace> {
610        ColorSpace::ALL.into_iter().find(|c| {
611            let (p, t) = c.encoding();
612            p == self.primaries
613                && (t == self.transfer
614                    || (t == Transfer::SrgbPiecewise && self.transfer == Transfer::Gamma22))
615        })
616    }
617
618    /// Why the viewport cannot draw this encoding faithfully, if it
619    /// cannot: it must be a colour space a surface can be configured
620    /// with, on a format that carries it, declared by whoever configured
621    /// the surface (an `Assumed` target is sRGB). A `Tagged` target needs
622    /// no colour space: the compositor protocol names its primaries and
623    /// transfer ([`DisplayTarget::untaggable`]).
624    pub fn unsupported(&self) -> Option<Fallback> {
625        let srgb = self.primaries == Primaries::Srgb
626            && matches!(self.transfer, Transfer::SrgbPiecewise | Transfer::Gamma22);
627        if self.headroom > 1.0 && !self.transfer.is_hdr() {
628            return Some(Fallback::HeadroomOnSdr);
629        }
630        if srgb {
631            return None;
632        }
633        if self.source == TargetSource::Tagged {
634            let tag = self.untaggable()?;
635            // A surface the application configured in a colour space.
636            return match self.color_space() {
637                Some(space) if space.needs().contains(&self.surface_format) => None,
638                _ => Some(tag),
639            };
640        }
641        let Some(space) = self.color_space() else {
642            return Some(Fallback::NoColorSpace);
643        };
644        if !space.needs().contains(&self.surface_format) {
645            return Some(Fallback::Format(self.surface_format));
646        }
647        if self.source == TargetSource::Assumed {
648            return Some(Fallback::NotConfigured);
649        }
650        None
651    }
652
653    /// Why a surface tagged through the compositor protocol cannot carry
654    /// this encoding, if it cannot: the protocol names the sRGB, Display
655    /// P3 and BT.2020 primaries (not custom ones) and every transfer but
656    /// extended sRGB; the format must carry the transfer (half floats for
657    /// extended linear, at least 10 bits for PQ and HLG).
658    pub fn untaggable(&self) -> Option<Fallback> {
659        if matches!(self.primaries, Primaries::Custom { .. }) || self.transfer == Transfer::ExtSrgb
660        {
661            return Some(Fallback::NoColorSpace);
662        }
663        let carries = match self.transfer {
664            Transfer::ExtLinear | Transfer::ExtSrgb => self.surface_format.is_float(),
665            Transfer::Pq | Transfer::Hlg => self.surface_format.bits() >= 10,
666            Transfer::SrgbPiecewise | Transfer::Gamma22 => {
667                self.surface_format != SurfaceFormat::Other
668            }
669        };
670        (!carries).then_some(Fallback::Format(self.surface_format))
671    }
672
673    /// Whether the viewport draws this target faithfully. The stage
674    /// encodes every transfer and primaries (CPU and GPU), so this says
675    /// whether the encoding is one a surface can be configured with, on
676    /// a format that carries it, declared by whoever configured it
677    /// ([`DisplayTarget::unsupported`] says why not). Others are drawn
678    /// as sRGB ([`DisplayTarget::effective`]).
679    pub fn is_supported(&self) -> bool {
680        self.unsupported().is_none()
681    }
682
683    /// The target actually drawn: this one when supported, else sRGB.
684    pub fn effective(&self) -> DisplayTarget {
685        if self.is_supported() {
686            *self
687        } else {
688            DisplayTarget {
689                surface_format: self.surface_format,
690                source: self.source,
691                ..DisplayTarget::srgb()
692            }
693        }
694    }
695
696    /// The bounds after the matrix: `[0, 1]` for SDR, `[0, headroom]`
697    /// for PQ and HLG, `[-headroom, headroom]` for the extended ones
698    /// (negatives carry colours outside the primaries).
699    pub fn range(&self) -> [f32; 2] {
700        let h = self.headroom.max(1.0);
701        match self.transfer {
702            Transfer::SrgbPiecewise | Transfer::Gamma22 => [0.0, 1.0],
703            Transfer::Pq | Transfer::Hlg => [0.0, h],
704            Transfer::ExtLinear | Transfer::ExtSrgb => [-h, h],
705        }
706    }
707
708    /// A short description ("Display P3 primaries, sRGB transfer, SDR").
709    pub fn describe(&self) -> String {
710        let range = if self.transfer.is_hdr() {
711            format!("headroom {:.1}", self.headroom)
712        } else {
713            "SDR".into()
714        };
715        format!(
716            "{} primaries, {} transfer, {range}",
717            self.primaries.name(),
718            self.transfer.name()
719        )
720    }
721
722    /// What this target carries less than `wanted` (a wider gamut, more
723    /// headroom), if anything.
724    pub fn missing(&self, wanted: &DisplayTarget) -> Option<String> {
725        let gamut = if self.transfer.is_extended() {
726            u8::MAX
727        } else {
728            self.primaries.rank()
729        };
730        let mut missing = Vec::new();
731        if wanted.primaries.rank() > gamut {
732            missing.push(format!("the {} gamut", wanted.primaries.name()));
733        }
734        let wanted_headroom = if wanted.transfer.is_hdr() {
735            wanted.headroom
736        } else {
737            1.0
738        };
739        let headroom = if self.transfer.is_hdr() {
740            self.headroom
741        } else {
742            1.0
743        };
744        if wanted_headroom > headroom + 1e-3 {
745            missing.push(format!("headroom {wanted_headroom:.1} (HDR)"));
746        }
747        (!missing.is_empty()).then(|| missing.join(" and "))
748    }
749}
750
751/// What a window draws for, and why when less than wanted.
752#[derive(Clone, Debug, PartialEq)]
753pub struct Resolution {
754    /// What the application wants for the window (sRGB unless said).
755    pub wanted: DisplayTarget,
756    /// What the window's surface expects.
757    pub surface: DisplayTarget,
758    /// What is drawn: the stage encodes for it.
759    pub drawn: DisplayTarget,
760    /// Why `drawn` carries less than `wanted`, or why the surface's
761    /// encoding is not drawn.
762    pub fallback: Option<Fallback>,
763}
764
765impl Resolution {
766    /// Whether the window shows what was wanted.
767    pub fn faithful(&self) -> bool {
768        self.fallback.is_none()
769    }
770
771    /// The reason, in words.
772    pub fn reason(&self) -> Option<String> {
773        self.fallback.as_ref().map(ToString::to_string)
774    }
775}
776
777/// What the viewport draws for, given what is wanted, what the surface
778/// expects and whether the GPU path runs: the surface's encoding when it
779/// is supported (the stage converts the wanted content into it), sRGB
780/// otherwise; the fallback says what is lost.
781///
782/// ```
783/// use egui_pop_viewport::display::{self, ColorSpace, DisplayTarget, SurfaceFormat, TargetSource};
784///
785/// // eframe today: an 8-bit sRGB surface; P3 is drawn as sRGB, with the reason.
786/// let r = display::resolve(&DisplayTarget::display_p3(), &DisplayTarget::srgb(), true);
787/// assert_eq!(r.drawn.color_space(), Some(ColorSpace::Srgb));
788/// assert!(r.reason().unwrap().contains("Display P3"));
789///
790/// // A surface configured as extended sRGB on half floats carries P3.
791/// let ext = DisplayTarget::for_color_space(
792///     ColorSpace::ExtendedSrgb, SurfaceFormat::Rgba16Float, 4.0, TargetSource::Wsi);
793/// assert!(display::resolve(&DisplayTarget::display_p3(), &ext, true).faithful());
794/// ```
795pub fn resolve(wanted: &DisplayTarget, surface: &DisplayTarget, gpu: bool) -> Resolution {
796    let srgb = DisplayTarget {
797        surface_format: surface.surface_format,
798        source: surface.source,
799        ..DisplayTarget::srgb()
800    };
801    let (drawn, fallback) = match surface.unsupported() {
802        Some(f) => (srgb, Some(f)),
803        None if !gpu && surface.color_space() != Some(ColorSpace::Srgb) => {
804            // sRGB textures on any surface egui draws faithfully; what
805            // they lose is said only when it was wanted.
806            let lost = srgb.missing(wanted).map(|_| Fallback::CpuPath);
807            (srgb, lost)
808        }
809        None => {
810            let lost = surface.missing(wanted).map(|missing| Fallback::Surface {
811                surface: surface.describe(),
812                missing,
813            });
814            (*surface, lost)
815        }
816    };
817    Resolution {
818        wanted: *wanted,
819        surface: *surface,
820        drawn,
821        fallback,
822    }
823}
824
825/// What a window's surface expects, per window.
826const TARGET: Slot<DisplayTarget> = Slot::new("viewport.display.target");
827/// What the application wants for a window, per window.
828const WANTED: Slot<DisplayTarget> = Slot::new("viewport.display.wanted");
829/// What every window's surface expects unless set per window.
830const DEFAULT_TARGET: Slot<DisplayTarget> = Slot::new("viewport.display.default_target");
831/// What a window's image is drawn into, per window.
832const IMAGE: Slot<ImageSurface> = Slot::new("viewport.display.image");
833
834/// What the surface of the window being drawn expects: what was set for
835/// it, else what the GPU path found when installed, else sRGB.
836pub fn target(ctx: &Context) -> DisplayTarget {
837    target_of(ctx, ctx.viewport_id())
838}
839
840/// What a window's image is drawn into: the image's own surface when it
841/// has one ([`set_image_surface`]), else the window's surface.
842pub fn target_of(ctx: &Context, viewport: ViewportId) -> DisplayTarget {
843    IMAGE
844        .keyed(viewport)
845        .get(ctx)
846        .and_then(|i| i.target)
847        .or_else(|| TARGET.keyed(viewport).get(ctx))
848        .or_else(|| DEFAULT_TARGET.get(ctx))
849        .unwrap_or_default()
850}
851
852/// The image's own surface in a window, as the image surface layer
853/// decided it (`image_surface`, Wayland).
854#[derive(Clone, Debug, Default, PartialEq)]
855pub struct ImageSurface {
856    /// What the image's surface expects, when the image has one (it then
857    /// overrides the window's surface for the image).
858    pub target: Option<DisplayTarget>,
859    /// Why the image has no surface of its own, or one carrying less than
860    /// wanted.
861    pub why: Option<String>,
862}
863
864/// Sets what a window's image is drawn into when it has a surface of
865/// its own, and why not (or why less than wanted); viewports in that
866/// window follow on the next frame.
867pub fn set_image_surface(ctx: &Context, viewport: ViewportId, image: ImageSurface) {
868    let slot = IMAGE.keyed(viewport);
869    let changed = slot.get(ctx).as_ref() != Some(&image);
870    slot.set(ctx, image);
871    if changed {
872        ctx.request_repaint_of(viewport);
873    }
874}
875
876/// What was set with [`set_image_surface`] for a window.
877pub fn image_surface_of(ctx: &Context, viewport: ViewportId) -> Option<ImageSurface> {
878    IMAGE.keyed(viewport).get(ctx)
879}
880
881/// Sets what a window's surface expects (for example when its surface
882/// or monitor changes, or when the application configured the surface
883/// itself). Viewports in that window follow on the next frame and signal
884/// it.
885pub fn set_target(ctx: &Context, viewport: ViewportId, target: DisplayTarget) {
886    TARGET.keyed(viewport).set(ctx, target);
887    ctx.request_repaint_of(viewport);
888}
889
890/// Sets what every window's surface expects unless set per window (the
891/// GPU path calls it with what eframe configured).
892pub fn set_default_target(ctx: &Context, target: DisplayTarget) {
893    DEFAULT_TARGET.set(ctx, target);
894    ctx.request_repaint();
895}
896
897/// What the application wants for the window being drawn (sRGB until
898/// said).
899pub fn wanted(ctx: &Context) -> DisplayTarget {
900    wanted_of(ctx, ctx.viewport_id())
901}
902
903/// What the application wants for a window (sRGB until said).
904pub fn wanted_of(ctx: &Context, viewport: ViewportId) -> DisplayTarget {
905    WANTED.keyed(viewport).get_or_default(ctx)
906}
907
908/// Declares what the application wants for a window: Display P3, HDR.
909/// The viewport draws it when the surface carries it, and says why not
910/// otherwise ([`Resolution::fallback`]).
911pub fn want(ctx: &Context, viewport: ViewportId, wanted: DisplayTarget) {
912    WANTED.keyed(viewport).set(ctx, wanted);
913    ctx.request_repaint_of(viewport);
914}
915
916/// What the window being drawn draws for: what is wanted against what
917/// its surface expects, on the GPU path when it is installed (as a
918/// viewport resolves it, before its `before_display` hook).
919pub fn resolution(ctx: &Context) -> Resolution {
920    let mut r = resolve(&wanted(ctx), &target(ctx), crate::tiles::device(ctx).gpu);
921    let why = image_surface_of(ctx, ctx.viewport_id()).and_then(|i| i.why);
922    if let (Some(why), Some(Fallback::Surface { surface, missing })) = (why, r.fallback.clone()) {
923        r.fallback = Some(Fallback::Unavailable {
924            surface,
925            missing,
926            why,
927        });
928    }
929    r
930}
931
932/// The arithmetic of a display transform for one target, as the shader
933/// runs it: `encode(clamp(matrix × rgb))`.
934#[derive(Clone, Copy, Debug, PartialEq)]
935pub struct Stage {
936    /// Working space to the target's primaries, by rows.
937    pub matrix: [[f32; 3]; 3],
938    /// Lower and upper bound after the matrix (`[0, 1]` for SDR).
939    pub clamp: [f32; 2],
940    pub transfer: Transfer,
941    /// Nits SDR white maps to (PQ, which is absolute, uses it).
942    pub white_nits: f32,
943}
944
945impl Stage {
946    /// Linear pixels in `working` primaries to `target`: the matrix
947    /// between the primaries, the target's range and transfer.
948    pub fn convert(working: Primaries, target: &DisplayTarget) -> Stage {
949        Stage {
950            matrix: Primaries::conversion(working, target.primaries),
951            clamp: target.range(),
952            transfer: target.transfer,
953            white_nits: target.sdr_white_nits,
954        }
955    }
956
957    /// This stage after `pre` (a matrix applied to the pixels first).
958    pub fn after(mut self, pre: [[f32; 3]; 3]) -> Stage {
959        let m = self.matrix;
960        self.matrix =
961            [0, 1, 2].map(|i| [0, 1, 2].map(|j| (0..3).map(|k| m[i][k] * pre[k][j]).sum()));
962        self
963    }
964
965    /// One pixel, encoded (0..1 for SDR; the extended transfers go
966    /// beyond).
967    pub fn encode(&self, rgb: [f32; 3]) -> [f32; 3] {
968        let m = &self.matrix;
969        [0, 1, 2].map(|i| {
970            let v = m[i][0] * rgb[0] + m[i][1] * rgb[1] + m[i][2] * rgb[2];
971            self.transfer
972                .encode_at(v.clamp(self.clamp[0], self.clamp[1]), self.white_nits)
973        })
974    }
975
976    /// One pixel, encoded in 8 bits.
977    pub fn encode_8bit(&self, rgb: [f32; 3]) -> [u8; 3] {
978        self.encode(rgb)
979            .map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
980    }
981}
982
983/// The identity matrix.
984pub const IDENTITY: [[f32; 3]; 3] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
985
986/// The application's colour management at the end of the viewport.
987pub trait DisplayTransform: Send + Sync + std::fmt::Debug {
988    /// The stage for a target (the GPU path runs it in its shader).
989    fn stage(&self, target: &DisplayTarget) -> Stage;
990
991    /// Scene pixels (RGBA floats) to display colours, on the CPU. By
992    /// default the stage's arithmetic; override for a LUT or anything
993    /// the stage cannot express (then deliver display pixels from the
994    /// source, as the GPU path only runs stages).
995    fn apply(&self, target: &DisplayTarget, scene: &[f32], out: &mut [Color32]) {
996        let stage = self.stage(target);
997        for (px, o) in scene.chunks_exact(4).zip(out.iter_mut()) {
998            let [r, g, b] = stage.encode_8bit([px[0], px[1], px[2]]);
999            let a = (px[3].clamp(0.0, 1.0) * 255.0).round() as u8;
1000            *o = Color32::from_rgba_unmultiplied(r, g, b, a);
1001        }
1002    }
1003
1004    /// Scene pixels (RGBA floats) to encoded floats for a target, on the
1005    /// CPU (an export, a surface of the application's own): the stage's
1006    /// arithmetic, alpha kept.
1007    fn apply_f32(&self, target: &DisplayTarget, scene: &[f32], out: &mut [f32]) {
1008        let stage = self.stage(target);
1009        for (px, o) in scene.chunks_exact(4).zip(out.chunks_exact_mut(4)) {
1010            let [r, g, b] = stage.encode([px[0], px[1], px[2]]);
1011            o.copy_from_slice(&[r, g, b, px[3]]);
1012        }
1013    }
1014
1015    /// Bumped when the transform changes (pixels transformed on the CPU
1016    /// are then redone).
1017    fn revision(&self) -> u64 {
1018        0
1019    }
1020}
1021
1022/// Scene pixels already in linear sRGB primaries: converted to the
1023/// target's primaries, clamped and encoded.
1024#[derive(Clone, Copy, Debug, Default)]
1025pub struct LinearSrgb;
1026
1027impl DisplayTransform for LinearSrgb {
1028    fn stage(&self, target: &DisplayTarget) -> Stage {
1029        Stage::convert(Primaries::Srgb, &target.effective())
1030    }
1031}
1032
1033/// Scene pixels in linear RGB of other primaries (a wide working space:
1034/// linear BT.2020, custom primaries): converted to the target's
1035/// primaries, clamped and encoded.
1036#[derive(Clone, Copy, Debug)]
1037pub struct Linear(pub Primaries);
1038
1039impl DisplayTransform for Linear {
1040    fn stage(&self, target: &DisplayTarget) -> Stage {
1041        Stage::convert(self.0, &target.effective())
1042    }
1043}
1044
1045/// Scene pixels through a matrix of the application's to linear sRGB,
1046/// then to the target's primaries, clamped and encoded.
1047#[derive(Clone, Copy, Debug)]
1048pub struct Matrix(pub [[f32; 3]; 3]);
1049
1050impl DisplayTransform for Matrix {
1051    fn stage(&self, target: &DisplayTarget) -> Stage {
1052        Stage::convert(Primaries::Srgb, &target.effective()).after(self.0)
1053    }
1054}
1055
1056/// The CPU path: scene pixels through a transform for a target.
1057pub fn apply_cpu(
1058    transform: &dyn DisplayTransform,
1059    target: &DisplayTarget,
1060    scene: &[f32],
1061    out: &mut [Color32],
1062) {
1063    transform.apply(&target.effective(), scene, out);
1064}
1065
1066#[cfg(test)]
1067mod tests {
1068    use super::*;
1069
1070    fn close(a: f32, b: f32, eps: f32) -> bool {
1071        (a - b).abs() <= eps
1072    }
1073
1074    fn configured(space: ColorSpace, format: SurfaceFormat, headroom: f32) -> DisplayTarget {
1075        DisplayTarget::for_color_space(space, format, headroom, TargetSource::Wsi)
1076    }
1077
1078    #[test]
1079    fn srgb_encoding_matches_the_standard_curve() {
1080        let s = LinearSrgb.stage(&DisplayTarget::srgb());
1081        assert_eq!(s.encode_8bit([0.0, 1.0, 0.002]), [0, 255, 7]);
1082        assert_eq!(s.encode_8bit([0.215_861, 0.5, 2.0]), [128, 188, 255]);
1083    }
1084
1085    #[test]
1086    fn pq_matches_the_reference_values() {
1087        // SMPTE ST 2084 / BT.2100 reference points (nits to signal).
1088        for (nits, signal) in [
1089            (0.0, 0.000_000_7),
1090            (100.0, 0.508_078),
1091            (203.0, 0.580_690),
1092            (1000.0, 0.751_827),
1093            (4000.0, 0.902_572),
1094            (10_000.0, 1.0),
1095        ] {
1096            assert!(
1097                close(pq_encode(nits), signal, 2e-5),
1098                "{nits}: {}",
1099                pq_encode(nits)
1100            );
1101        }
1102        assert!(close(pq_decode(0.508_078), 100.0, 0.01));
1103        assert!(close(pq_decode(0.751_827), 1000.0, 0.1));
1104    }
1105
1106    #[test]
1107    fn pq_round_trips() {
1108        for i in 0..=200 {
1109            let v = i as f32 / 20.0; // 0..10 times SDR white
1110            let e = Transfer::Pq.encode_at(v, 203.0);
1111            let back = Transfer::Pq.decode_at(e, 203.0);
1112            assert!(close(back, v, 1e-3 * v.max(1.0)), "{v} -> {e} -> {back}");
1113        }
1114    }
1115
1116    #[test]
1117    fn hlg_matches_the_reference_values() {
1118        assert!(close(hlg_oetf(0.0), 0.0, 1e-7));
1119        assert!(close(hlg_oetf(1.0 / 12.0), 0.5, 1e-6));
1120        assert!(close(hlg_oetf(1.0), 1.0, 1e-6));
1121        // SDR white at 75 % of the signal (BT.2408).
1122        assert!(close(Transfer::Hlg.encode(1.0), 0.75, 1e-5));
1123        assert!(close(hlg_inverse_oetf(0.75), HLG_WHITE, 1e-6));
1124        // Both branches meet at 1/12.
1125        assert!(close(hlg_inverse_oetf(0.5), 1.0 / 12.0, 1e-6));
1126    }
1127
1128    #[test]
1129    fn hlg_round_trips() {
1130        for i in 0..=100 {
1131            let e = i as f32 / 100.0;
1132            let back = hlg_oetf(hlg_inverse_oetf(e));
1133            assert!(close(back, e, 1e-5), "{e} -> {back}");
1134        }
1135        let max = Transfer::Hlg.max_headroom(203.0);
1136        for i in 0..=40 {
1137            let v = i as f32 / 40.0 * max;
1138            let back = Transfer::Hlg.decode(Transfer::Hlg.encode(v));
1139            assert!(close(back, v, 1e-4 * v.max(1.0)), "{v} -> {back}");
1140        }
1141    }
1142
1143    #[test]
1144    fn extended_srgb_mirrors_negatives_and_continues_past_white() {
1145        let t = Transfer::ExtSrgb;
1146        assert!(close(t.encode(-0.5), -t.encode(0.5), 1e-7));
1147        assert!(t.encode(4.0) > 1.0);
1148        for v in [-2.0, -0.2, 0.001, 0.5, 1.0, 3.0] {
1149            assert!(close(t.decode(t.encode(v)), v, 1e-5), "{v}");
1150        }
1151    }
1152
1153    #[test]
1154    #[allow(
1155        clippy::needless_range_loop,
1156        reason = "the test walks the rows of two matrices side by side"
1157    )]
1158    fn primaries_convert_as_published() {
1159        // Linear sRGB to Display P3 and to BT.2020 (BT.2087), by rows.
1160        let p3 = Primaries::conversion(Primaries::Srgb, Primaries::DisplayP3);
1161        let want_p3 = [
1162            [0.822_462, 0.177_538, 0.0],
1163            [0.033_194, 0.966_806, 0.0],
1164            [0.017_083, 0.072_397, 0.910_520],
1165        ];
1166        let bt2020 = Primaries::conversion(Primaries::Srgb, Primaries::Bt2020);
1167        let want_2020 = [
1168            [0.627_404, 0.329_283, 0.043_313],
1169            [0.069_097, 0.919_540, 0.011_362],
1170            [0.016_391, 0.088_013, 0.895_595],
1171        ];
1172        for (m, w) in [(p3, want_p3), (bt2020, want_2020)] {
1173            for i in 0..3 {
1174                for j in 0..3 {
1175                    assert!(close(m[i][j], w[i][j], 2e-4), "{m:?}");
1176                }
1177            }
1178        }
1179        // White stays white; there and back is the identity.
1180        let back = Primaries::conversion(Primaries::Bt2020, Primaries::Srgb);
1181        for i in 0..3 {
1182            let row: f32 = bt2020[i].iter().sum();
1183            assert!(close(row, 1.0, 1e-5));
1184            for j in 0..3 {
1185                let v: f32 = (0..3).map(|k| back[i][k] * bt2020[k][j]).sum();
1186                assert!(close(v, if i == j { 1.0 } else { 0.0 }, 1e-5));
1187            }
1188        }
1189    }
1190
1191    #[test]
1192    fn unsupported_targets_draw_as_srgb() {
1193        let hdr = DisplayTarget {
1194            primaries: Primaries::Bt2020,
1195            transfer: Transfer::Pq,
1196            sdr_white_nits: 203.0,
1197            headroom: 4.0,
1198            surface_format: SurfaceFormat::Rgba16Float,
1199            source: TargetSource::Assumed,
1200        };
1201        assert_eq!(hdr.unsupported(), Some(Fallback::NotConfigured));
1202        assert_eq!(hdr.effective().primaries, Primaries::Srgb);
1203        assert_eq!(LinearSrgb.stage(&hdr).clamp, [0.0, 1.0]);
1204        // PQ on 8 bits, P3 with a PQ curve: no surface carries them.
1205        let tagged = hdr.with_source(TargetSource::Tagged);
1206        assert!(tagged.is_supported());
1207        let eight = DisplayTarget {
1208            surface_format: SurfaceFormat::Rgba8Unorm,
1209            ..tagged
1210        };
1211        assert_eq!(
1212            eight.unsupported(),
1213            Some(Fallback::Format(SurfaceFormat::Rgba8Unorm))
1214        );
1215        // No wgpu colour space is Display P3 with PQ.
1216        let odd = DisplayTarget {
1217            primaries: Primaries::DisplayP3,
1218            ..tagged.with_source(TargetSource::Wsi)
1219        };
1220        assert_eq!(odd.unsupported(), Some(Fallback::NoColorSpace));
1221    }
1222
1223    #[test]
1224    fn tagged_targets_need_no_surface_colour_space() {
1225        // BT.2020 with a 2.2 power: no wgpu colour space, a protocol
1226        // encoding (bt2020 + gamma22).
1227        let rec2020 = DisplayTarget {
1228            primaries: Primaries::Bt2020,
1229            transfer: Transfer::Gamma22,
1230            surface_format: SurfaceFormat::Rgb10a2Unorm,
1231            ..DisplayTarget::srgb()
1232        };
1233        assert_eq!(rec2020.color_space(), None);
1234        assert_eq!(rec2020.unsupported(), Some(Fallback::NoColorSpace));
1235        assert_eq!(rec2020.effective().primaries, Primaries::Srgb);
1236        let tagged = rec2020.with_source(TargetSource::Tagged);
1237        assert!(tagged.is_supported());
1238        assert_eq!(tagged.effective(), tagged);
1239        // The stage encodes a 2.2 power into BT.2020: sRGB white stays
1240        // white, pure sRGB red is inside BT.2020.
1241        let s = LinearSrgb.stage(&tagged);
1242        assert_eq!(s.transfer, Transfer::Gamma22);
1243        for v in s.encode([1.0, 1.0, 1.0]) {
1244            assert!(close(v, 1.0, 1e-5), "{v}");
1245        }
1246        let red = s.encode([1.0, 0.0, 0.0]);
1247        assert!(red[0] < 1.0 && red[1] > 0.0 && red[2] > 0.0, "{red:?}");
1248        // Eight bits carry an SDR transfer.
1249        let eight = DisplayTarget {
1250            surface_format: SurfaceFormat::Rgba8Unorm,
1251            ..tagged
1252        };
1253        assert!(eight.is_supported());
1254        // Display P3 with PQ is a protocol encoding, on 10 bits.
1255        let p3_pq = DisplayTarget {
1256            primaries: Primaries::DisplayP3,
1257            transfer: Transfer::Pq,
1258            sdr_white_nits: HDR_REFERENCE_WHITE,
1259            headroom: 4.0,
1260            ..tagged
1261        };
1262        assert!(p3_pq.is_supported());
1263        assert_eq!(
1264            DisplayTarget {
1265                surface_format: SurfaceFormat::Rgba8Unorm,
1266                ..p3_pq
1267            }
1268            .unsupported(),
1269            Some(Fallback::Format(SurfaceFormat::Rgba8Unorm))
1270        );
1271        // Not tagged: custom primaries, extended sRGB, extended linear
1272        // on 10 bits.
1273        let custom = DisplayTarget {
1274            primaries: Primaries::Custom {
1275                r: [0.7, 0.3],
1276                g: [0.2, 0.7],
1277                b: [0.15, 0.05],
1278                w: D65,
1279            },
1280            ..tagged
1281        };
1282        assert_eq!(custom.unsupported(), Some(Fallback::NoColorSpace));
1283        let ext = DisplayTarget {
1284            transfer: Transfer::ExtSrgb,
1285            ..tagged
1286        };
1287        assert_eq!(ext.unsupported(), Some(Fallback::NoColorSpace));
1288        let linear = DisplayTarget {
1289            transfer: Transfer::ExtLinear,
1290            ..tagged
1291        };
1292        assert_eq!(
1293            linear.unsupported(),
1294            Some(Fallback::Format(SurfaceFormat::Rgb10a2Unorm))
1295        );
1296        // Wanted BT.2020 on a tagged BT.2020 surface: faithful on the
1297        // GPU path.
1298        assert!(resolve(&rec2020, &tagged, true).faithful());
1299        assert_eq!(
1300            resolve(&rec2020, &tagged, false).fallback,
1301            Some(Fallback::CpuPath)
1302        );
1303    }
1304
1305    #[test]
1306    fn configured_surfaces_are_drawn_faithfully() {
1307        let pq = configured(ColorSpace::Bt2100Pq, SurfaceFormat::Rgb10a2Unorm, 5.0);
1308        assert!(pq.is_supported());
1309        let s = LinearSrgb.stage(&pq);
1310        assert_eq!(s.transfer, Transfer::Pq);
1311        assert_eq!(s.clamp, [0.0, 5.0]);
1312        // sRGB white is BT.2020 white, at 203 nits.
1313        for v in s.encode([1.0, 1.0, 1.0]) {
1314            assert!(close(v, 0.580_69, 1e-4), "{v}");
1315        }
1316        // scRGB carries P3 red as a negative green and blue.
1317        let sc = configured(
1318            ColorSpace::ExtendedSrgbLinear,
1319            SurfaceFormat::Rgba16Float,
1320            4.0,
1321        );
1322        let red = Linear(Primaries::DisplayP3)
1323            .stage(&sc)
1324            .encode([1.0, 0.0, 0.0]);
1325        assert!(red[0] > 1.0 && red[1] < 0.0 && red[2] < 0.0, "{red:?}");
1326    }
1327
1328    #[test]
1329    fn resolution_falls_back_with_a_reason() {
1330        let p3 = DisplayTarget::display_p3();
1331        let hdr = DisplayTarget::hdr_pq(4.0);
1332        // An 8-bit sRGB surface (eframe's): sRGB drawn, the reason given.
1333        let r = resolve(&p3, &DisplayTarget::srgb(), true);
1334        assert_eq!(r.drawn.color_space(), Some(ColorSpace::Srgb));
1335        assert!(matches!(r.fallback, Some(Fallback::Surface { .. })));
1336        let reason = resolve(&hdr, &DisplayTarget::srgb(), true)
1337            .reason()
1338            .unwrap();
1339        assert!(
1340            reason.contains("BT.2020") && reason.contains("headroom 4.0"),
1341            "{reason}"
1342        );
1343        // sRGB wanted on sRGB: faithful.
1344        assert!(resolve(&DisplayTarget::srgb(), &DisplayTarget::srgb(), false).faithful());
1345        // Extended sRGB carries P3 and HDR on the GPU path, not on the CPU.
1346        let ext = configured(ColorSpace::ExtendedSrgb, SurfaceFormat::Rgba16Float, 4.0);
1347        assert!(resolve(&p3, &ext, true).faithful());
1348        assert!(resolve(&hdr, &ext, true).faithful());
1349        let cpu = resolve(&p3, &ext, false);
1350        assert_eq!(cpu.fallback, Some(Fallback::CpuPath));
1351        assert_eq!(cpu.drawn.primaries, Primaries::Srgb);
1352        assert!(resolve(&DisplayTarget::srgb(), &ext, false).faithful());
1353        // HDR10 carries P3 and its headroom.
1354        let pq = configured(ColorSpace::Bt2100Pq, SurfaceFormat::Rgb10a2Unorm, 10.0);
1355        assert!(resolve(&hdr, &pq, true).faithful());
1356        // Less headroom than wanted is said.
1357        let dim = configured(ColorSpace::ExtendedSrgb, SurfaceFormat::Rgba16Float, 2.0);
1358        assert!(
1359            resolve(&hdr, &dim, true)
1360                .reason()
1361                .unwrap()
1362                .contains("headroom")
1363        );
1364    }
1365
1366    #[test]
1367    fn the_cpu_path_runs_the_stage() {
1368        let m = Matrix([[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]);
1369        let mut out = [Color32::BLACK; 1];
1370        apply_cpu(&m, &DisplayTarget::srgb(), &[1.0, 0.0, 0.0, 1.0], &mut out);
1371        assert_eq!(out[0], Color32::from_rgb(0, 255, 0));
1372        let mut f = [0.0; 4];
1373        let pq = configured(ColorSpace::Bt2100Pq, SurfaceFormat::Rgba16Float, 4.0);
1374        LinearSrgb.apply_f32(&pq, &[1.0, 1.0, 1.0, 0.5], &mut f);
1375        assert!(close(f[0], 0.580_69, 1e-4) && f[3] == 0.5, "{f:?}");
1376    }
1377}