Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

HyperGlass on an HDR desktop: the half-float screen is tone mapped, not given up

gelenmedya0bd22ce29eb4
diff --git a/crates/rf-win/src/glass/capture.rs b/crates/rf-win/src/glass/capture.rs
index 3d5d4ea6..4342247a 100644
--- a/crates/rf-win/src/glass/capture.rs
+++ b/crates/rf-win/src/glass/capture.rs
@@ -14,7 +14,7 @@ use std::ffi::c_void;
use crossbeam_channel::Receiver;
use windows::Win32::Foundation::{E_ACCESSDENIED, HANDLE, LUID, RECT};
use windows::Win32::Graphics::Direct3D11::{D3D11_TEXTURE2D_DESC, ID3D11Texture2D};
-use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_MODE_ROTATION_IDENTITY, DXGI_MODE_ROTATION_UNSPECIFIED};
+use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_MODE_ROTATION_IDENTITY, DXGI_MODE_ROTATION_UNSPECIFIED};
use windows::Win32::Graphics::Dxgi::{
CreateDXGIFactory1, DXGI_ERROR_ACCESS_LOST, DXGI_ERROR_DEVICE_HUNG, DXGI_ERROR_DEVICE_REMOVED, DXGI_ERROR_DEVICE_RESET,
DXGI_ERROR_DRIVER_INTERNAL_ERROR, DXGI_ERROR_NOT_FOUND, DXGI_ERROR_WAIT_TIMEOUT, DXGI_OUTDUPL_FRAME_INFO, DXGI_OUTDUPL_MOVE_RECT, IDXGIAdapter1, IDXGIFactory1,
@@ -84,6 +84,60 @@ fn input_desktop_is_ours() -> bool {
}
}
+/// The monitor's "SDR content brightness" over 80 nits (scRGB 1.0), what SDR white is on an HDR desktop: Windows keeps it per display
+/// path (`DISPLAYCONFIG_SDR_WHITE_LEVEL`, in thousandths of 80 nits). 2.5 (200 nits, near Windows' default) when it cannot be read.
+fn sdr_white_level(out: &IDXGIOutput) -> f32 {
+ use windows::Win32::Devices::Display::{
+ DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL, DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_HEADER, DISPLAYCONFIG_MODE_INFO,
+ DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SDR_WHITE_LEVEL, DISPLAYCONFIG_SOURCE_DEVICE_NAME, DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes,
+ QDC_ONLY_ACTIVE_PATHS, QueryDisplayConfig,
+ };
+ const FALLBACK: f32 = 2.5;
+ // SAFETY: plain queries into buffers sized by the system; every struct carries its own size.
+ unsafe {
+ let Ok(desc) = out.GetDesc() else { return FALLBACK };
+ let device = String::from_utf16_lossy(&desc.DeviceName);
+ let device = device.trim_end_matches('\0');
+ let (mut np, mut nm) = (0u32, 0u32);
+ if GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut np, &mut nm).is_err() {
+ return FALLBACK;
+ }
+ let mut paths = vec![DISPLAYCONFIG_PATH_INFO::default(); np as usize];
+ let mut modes = vec![DISPLAYCONFIG_MODE_INFO::default(); nm as usize];
+ if QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &mut np, paths.as_mut_ptr(), &mut nm, modes.as_mut_ptr(), None).is_err() {
+ return FALLBACK;
+ }
+ for p in paths.iter().take(np as usize) {
+ let mut name = DISPLAYCONFIG_SOURCE_DEVICE_NAME::default();
+ name.header = DISPLAYCONFIG_DEVICE_INFO_HEADER {
+ r#type: DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME,
+ size: size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as u32,
+ adapterId: p.sourceInfo.adapterId,
+ id: p.sourceInfo.id,
+ };
+ if DisplayConfigGetDeviceInfo(&mut name.header) != 0 {
+ continue;
+ }
+ let gdi = String::from_utf16_lossy(&name.viewGdiDeviceName);
+ if !gdi.trim_end_matches('\0').eq_ignore_ascii_case(device) {
+ continue;
+ }
+ let mut white = DISPLAYCONFIG_SDR_WHITE_LEVEL::default();
+ white.header = DISPLAYCONFIG_DEVICE_INFO_HEADER {
+ r#type: DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL,
+ size: size_of::<DISPLAYCONFIG_SDR_WHITE_LEVEL>() as u32,
+ adapterId: p.targetInfo.adapterId,
+ id: p.targetInfo.id,
+ };
+ if DisplayConfigGetDeviceInfo(&mut white.header) == 0 && white.SDRWhiteLevel >= 1000 {
+ return white.SDRWhiteLevel as f32 / 1000.0;
+ }
+ return FALLBACK;
+ }
+ FALLBACK
+ }
+}
+
/// DuplicateOutput1 asking for BGRA only (an HDR display then hands back an 8 bit tone-mapped picture), else the plain DuplicateOutput.
unsafe fn duplicate(g: &Gpu, out: &IDXGIOutput) -> R<IDXGIOutputDuplication> {
if let Ok(o5) = out.cast::<IDXGIOutput5>()
@@ -480,21 +534,36 @@ impl DupMonitor {
// the first picture of a monitor, or of a duplication made anew, says nothing about what changed
let whole = !self.has_image || self.fresh;
if want {
- match (res.take().and_then(|x| x.cast::<ID3D11Texture2D>().ok()), &self.mirror) {
- (Some(tex), Some(m)) => {
+ match (res.take().and_then(|x| x.cast::<ID3D11Texture2D>().ok()), self.mirror.as_ref().map(|m| (m.w, m.h, m.hdr.is_some()))) {
+ (Some(tex), Some((mw, mh, mirror_hdr))) => {
let mut td = D3D11_TEXTURE2D_DESC::default();
tex.GetDesc(&mut td);
- if td.Format != DXGI_FORMAT_B8G8R8A8_UNORM || (td.Width, td.Height) != (m.w, m.h) {
+ // An HDR desktop hands over half floats (linear scRGB) even when 8 bits were asked for; the mirror then holds
+ // them as they are and the crop pass tone maps (until 1.0.7 the glass gave up on such a desktop and fell
+ // back).
+ let hdr = td.Format == DXGI_FORMAT_R16G16B16A16_FLOAT;
+ if !(hdr || td.Format == DXGI_FORMAT_B8G8R8A8_UNORM) || (td.Width, td.Height) != (mw, mh) {
bad = Some(format!(
- "the duplicated frame is {}x{} {:?}, not {}x{} B8G8R8A8 (HDR or wide colour is not handled)",
- td.Width, td.Height, td.Format, m.w, m.h
+ "the duplicated frame is {}x{} {:?}, not {}x{} B8G8R8A8 or FP16",
+ td.Width, td.Height, td.Format, mw, mh
));
} else {
- // The whole frame, not only the parts under the windows: a window dragged onto another part of an idle
- // desktop gets no new frame, so the mirror must already hold everything.
- g.ctx.CopyResource(&m.tex, &tex);
- image = true;
- self.has_image = true;
+ if hdr != mirror_hdr {
+ let made = if hdr { Source::new_hdr(g, mw, mh, sdr_white_level(&self.output)) } else { Source::new(g, mw, mh, None) };
+ match made {
+ Ok(m) => self.mirror = Some(m),
+ Err(e) => bad = Some(format!("the mirror for this desktop's colour format could not be made: {e}")),
+ }
+ }
+ if bad.is_none()
+ && let Some(m) = &self.mirror
+ {
+ // The whole frame, not only the parts under the windows: a window dragged onto another part of an idle
+ // desktop gets no new frame, so the mirror must already hold everything.
+ g.ctx.CopyResource(&m.tex, &tex);
+ image = true;
+ self.has_image = true;
+ }
}
}
// frames that arrive but never become a picture would leave the window "starting" for ever
diff --git a/crates/rf-win/src/glass/glass.hlsl b/crates/rf-win/src/glass/glass.hlsl
index 8af52a35..57beae10 100644
--- a/crates/rf-win/src/glass/glass.hlsl
+++ b/crates/rf-win/src/glass/glass.hlsl
@@ -113,7 +113,17 @@ float4 VSMain(uint id : SV_VertexID) : SV_Position
// Pass 1: copy the window rectangle (plus margin) out of the source. The clamp sampler repeats the edge pixels where the region sticks out.
float4 PSCrop(float4 pos : SV_Position) : SV_Target
{
- return tA.SampleLevel(sLin, (uReg.xy + pos.xy) / uReg.zw, 0);
+ float4 c = tA.SampleLevel(sLin, (uReg.xy + pos.xy) / uReg.zw, 0);
+ // An HDR desktop (uOpt.z = 1): half floats, linear scRGB where 1.0 is 80 nits. SDR white (uOpt.w, the monitor's "SDR content
+ // brightness" over 80 nits) becomes 1, brighter is clipped, and the result is sRGB encoded: the picture an 8 bit desktop holds.
+ if (uOpt.z > 0.5)
+ {
+ float3 l = saturate(c.rgb / max(uOpt.w, 0.01));
+ float3 lo = l * 12.92;
+ float3 hi = 1.055 * pow(l, 1.0 / 2.4) - 0.055;
+ c = float4(lerp(hi, lo, step(l, 0.0031308)), 1.0);
+ }
+ return c;
}
// Pass 2: 13 tap downsample (Jimenez, "Next generation post processing in Call of Duty: Advanced Warfare"), one level of the chain.
diff --git a/crates/rf-win/src/glass/gpu.rs b/crates/rf-win/src/glass/gpu.rs
index cab38100..88d3bcde 100644
--- a/crates/rf-win/src/glass/gpu.rs
+++ b/crates/rf-win/src/glass/gpu.rs
@@ -14,7 +14,7 @@ use windows::Win32::Graphics::Direct3D::{
D3D_FEATURE_LEVEL_11_1, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, D3D_SRV_DIMENSION_TEXTURE2D, ID3DBlob,
};
use windows::Win32::Graphics::Direct3D11::*;
-use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_SAMPLE_DESC};
+use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_SAMPLE_DESC};
use windows::Win32::Graphics::Dxgi::IDXGIAdapter;
use windows::core::{Interface, PCSTR};
@@ -636,6 +636,9 @@ pub(super) struct Source {
pub srv: ID3D11ShaderResourceView,
pub w: u32,
pub h: u32,
+ /// An HDR desktop's picture (half floats, linear scRGB): the SDR white level over 80 nits, which the crop pass divides by before
+ /// it encodes sRGB. `None`: an 8 bit sRGB picture.
+ pub hdr: Option<f32>,
}
impl Source {
@@ -645,7 +648,28 @@ impl Source {
g.ctx.UpdateSubresource(&tex, 0, None, d.as_ptr() as *const c_void, w * 4, 0);
}
let srv = srv_mip(g, &tex, DXGI_FORMAT_B8G8R8A8_UNORM, 0, 1)?;
- Ok(Source { tex, srv, w, h })
+ Ok(Source { tex, srv, w, h, hdr: None })
+ }
+
+ /// A mirror for an HDR desktop: the duplicated frames are copied in as they come (FP16), and the crop pass tone maps them.
+ pub(super) unsafe fn new_hdr(g: &Gpu, w: u32, h: u32, sdr_white: f32) -> R<Source> {
+ let tex = tex2d(g, w, h, 1, DXGI_FORMAT_R16G16B16A16_FLOAT, D3D11_BIND_SHADER_RESOURCE.0 as u32)?;
+ let srv = srv_mip(g, &tex, DXGI_FORMAT_R16G16B16A16_FLOAT, 0, 1)?;
+ Ok(Source { tex, srv, w, h, hdr: Some(sdr_white) })
+ }
+}
+
+/// The crop pass's word for a source: `opt[2]` 1 for an HDR picture, `opt[3]` its SDR white level over 80 nits.
+fn mark_source(opt: &mut [f32; 4], src: &Source) {
+ match src.hdr {
+ Some(white) => {
+ opt[2] = 1.0;
+ opt[3] = white;
+ }
+ None => {
+ opt[2] = 0.0;
+ opt[3] = 1.0;
+ }
}
}
@@ -835,6 +859,7 @@ pub(super) fn other_monitor_crop(origin: (i32, i32), pad: u32, region: (u32, u32
/// are those pictures with their top left minus this monitor's, desktop px.
pub(super) unsafe fn prep_with(r: &Renderer, region: &Region, src: &Source, extra: &[(&Source, (i32, i32))], geo: &Geometry, look: &Look, check: bool) -> Prepared {
let mut cb = make_cb(geo, look, (src.w, src.h), region, check);
+ mark_source(&mut cb.opt, src);
r.pass(&r.ps_crop, &region.rtv[0], region.w, region.h, &src.srv, &cb);
if !extra.is_empty() {
let c = &r.g.ctx;
@@ -842,6 +867,7 @@ pub(super) unsafe fn prep_with(r: &Renderer, region: &Region, src: &Source, extr
let Some((reg, [x0, y0, x1, y1])) = other_monitor_crop(geo.origin, region.pad, (region.w, region.h), *delta, (other.w, other.h)) else { continue };
let mut ocb = cb;
ocb.reg = [reg[0], reg[1], other.w as f32, other.h as f32];
+ mark_source(&mut ocb.opt, other);
c.RSSetState(&r.scissor);
c.RSSetScissorRects(Some(&[RECT { left: x0 as i32, top: y0 as i32, right: x1 as i32, bottom: y1 as i32 }]));
r.pass(&r.ps_crop, &region.rtv[0], region.w, region.h, &other.srv, &ocb);
diff --git a/crates/rf-win/src/glass/tests.rs b/crates/rf-win/src/glass/tests.rs
index 2dad380b..3d91c3fd 100644
--- a/crates/rf-win/src/glass/tests.rs
+++ b/crates/rf-win/src/glass/tests.rs
@@ -329,6 +329,53 @@ fn backdrop_luma_is_the_brightness_under_the_glass() {
});
}
+/// A half float, for the HDR test below (normal numbers only, rounded toward zero: enough for these values).
+fn half(v: f32) -> u16 {
+ if v == 0.0 {
+ return 0;
+ }
+ let b = v.to_bits();
+ let sign = ((b >> 16) & 0x8000) as u16;
+ let exp = ((b >> 23) & 0xff) as i32 - 127 + 15;
+ let man = ((b >> 13) & 0x3ff) as u16;
+ sign | ((exp.clamp(1, 30) as u16) << 10) | man
+}
+
+/// An HDR desktop (half floats, linear scRGB, 1.0 = 80 nits) is read as the picture an 8 bit desktop would show: its SDR white level is
+/// white, black stays black, a mid grey stays mid grey, and what is brighter than SDR white is clipped to white (until 1.0.7 the
+/// glass gave up on an HDR desktop and fell back).
+#[test]
+fn an_hdr_backdrop_reads_as_the_sdr_picture_it_shows() {
+ if !can_draw() {
+ return;
+ }
+ let (sw, sh) = (700u32, 600u32);
+ let geo = Geometry { w: 300, h: 200, origin: (100, 100), scale: 1.0, radius_px: 8.0, cut_corners: true, shape: None, shadow: None };
+ let look = Look::regular(false, &LookParams::DEFAULT);
+ with_renderer(true, |r| unsafe {
+ let region = Region::new(&r.g, geo.w, geo.h, region_pad(geo.scale)).expect("region");
+ let white_level = 2.5; // 200 nits
+ let luma_of = |linear: f32| {
+ let src = Source::new_hdr(&r.g, sw, sh, white_level).expect("hdr source");
+ let c = half(linear * white_level);
+ let one = half(1.0);
+ let px: Vec<u16> = (0..sw * sh).flat_map(|_| [c, c, c, one]).collect();
+ r.g.ctx.UpdateSubresource(&src.tex, 0, None, px.as_ptr() as *const core::ffi::c_void, sw * 8, 0);
+ prep(r, &region, &src, &geo, &look, false);
+ region.read_back(&r.g, geo.glass_rect()).expect("read back").luma.expect("a glass has texels")
+ };
+ let white = luma_of(1.0);
+ let black = luma_of(0.0);
+ // sRGB 128 is 0.2158 linear
+ let grey = luma_of(0.2158);
+ let brighter = luma_of(3.0);
+ assert!(white > 0.97, "SDR white of an HDR desktop: {white}");
+ assert!(black < 0.03, "black of an HDR desktop: {black}");
+ assert!((grey - 128.0 / 255.0).abs() < 0.03, "mid grey of an HDR desktop: {grey}");
+ assert!(brighter > 0.97, "brighter than SDR white is clipped: {brighter}");
+ });
+}
+
/// The value the app reads: unknown until the engine has measured, only for a window the app still holds, gone with the glass.
#[test]
fn the_brightness_is_unknown_until_measured_and_goes_with_the_glass() {