Add surface color-space selection (HDR output): Vulkan, DX12, Metal, WebGPU (#9658)

This commit is contained in:
Stuart Parmenter authored and GitHub committed 2026-06-26 03:52:05 +00:00
1 parent 87bfa5ebb2
commit 3fb225a9c6
36 files changed
+2344 -208

No files matched your search

+31
View File
@@ -112,6 +112,37 @@ Zero-size buffer bindings are still not permitted. `BufferBinding` now implement
By @beholdnec in [#8505](https://github.com/gfx-rs/wgpu/pull/8505).
#### Surface color space selection (HDR output)
Surfaces can now be configured with an explicit color space, enabling HDR and wide-gamut output where the platform supports it. `SurfaceConfiguration` has a new `color_space` field, and `SurfaceCapabilities` reports the supported color spaces for every supported format in a new `format_capabilities` field ([#2920](https://github.com/gfx-rs/wgpu/issues/2920)). `SurfaceColorSpace::is_hdr()` classifies a color space (the extended-range and PQ/HLG spaces are HDR) so you can branch after picking one.
The new `SurfaceColorSpace::Auto` default reproduces wgpu's historical behavior (extended linear scRGB for `Rgba16Float` where supported, sRGB otherwise; never a wide-gamut or HDR color space), so to migrate, add the field:
```diff
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
+ color_space: wgpu::SurfaceColorSpace::Auto,
..
};
```
Support by backend:
- **Vulkan**: reports and honors `SurfaceColorSpace::Bt2100Pq` (HDR10: BT.2020 + ST 2084 PQ), `SurfaceColorSpace::Bt2100Hlg` (BT.2100 HLG), `SurfaceColorSpace::DisplayP3`, `SurfaceColorSpace::ExtendedSrgb` (extended-range nonlinear sRGB, via `VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT`), `SurfaceColorSpace::ExtendedSrgbLinear` (scRGB), and `SurfaceColorSpace::Srgb`, as exposed by the driver via `VK_EXT_swapchain_colorspace`.
- **DX12**: reports and honors `Bt2100Pq` (HDR10) on `Rgb10a2Unorm`, applied with `IDXGISwapChain3::SetColorSpace1`; `Rgba16Float` keeps its scRGB (`ExtendedSrgbLinear`) interpretation. These are advertised regardless of whether the display is currently in HDR mode — Windows always composites in scRGB and tone-maps as needed, so the live HDR state is a query concern, not a configuration gate. `ExtendedSrgb` is not supported, as DXGI has no encoded-extended-sRGB swapchain color space (only G10 linear scRGB).
- **Metal**: reports and honors `DisplayP3` on every format, `ExtendedSrgb` (extended-range nonlinear sRGB, via `kCGColorSpaceExtendedSRGB`), `ExtendedDisplayP3` (extended-range nonlinear Display-P3, via `kCGColorSpaceExtendedDisplayP3`), and `ExtendedSrgbLinear` (EDR) on `Rgba16Float`, and `Bt2100Pq`/`Bt2100Hlg` on `Rgba16Float`/`Rgb10a2Unorm` (macOS 11+/iOS 14+), by setting the `CAMetalLayer` color space.
- **Browser WebGPU**: reports and honors `DisplayP3` (canvas `colorSpace`), `ExtendedSrgb` (sRGB-encoded extended range), and `ExtendedDisplayP3` (Display-P3-encoded extended range, via the `"display-p3"` canvas plus extended tone mapping) on `Rgba16Float`, via the W3C HDR-canvas `toneMapping: { mode: "extended" }` (Chrome 129+); these extended spaces are advertised whenever the fp16 canvas is configurable, independent of the display's current dynamic range. `ExtendedSrgbLinear` is native-only and not advertised here, since WebGPU exposes no linear-transfer canvas color space. `Bt2100Pq`/`Bt2100Hlg` are unsupported (browsers expose no PQ/HLG canvas signaling). `Auto` keeps the browser defaults even for fp16, matching historical behavior. `Rgba16Float` is only advertised in `get_capabilities` when the browser can actually configure an fp16 canvas (probed empirically, so it self-corrects when e.g. Firefox adds support), and a `configure` that the browser rejects or that requests an unsupported color space reports the surface as lost from `get_current_texture` instead of panicking (there is no `catch_unwind` on wasm).
- **GLES**: sRGB only.
Selecting a color space a surface doesn't support fails validation with `ConfigureSurfaceError::UnsupportedColorSpace`. Formats that a driver exposes exclusively in explicit-opt-in color spaces (e.g. HDR10-only) are listed in `format_capabilities` but excluded from the legacy `formats` list.
For `wgpu-hal` users: `hal::SurfaceConfiguration` gained a `color_space` field (never `Auto`), and `hal::SurfaceCapabilities::formats` is now `Vec<SurfaceFormatCapabilities>` instead of `Vec<TextureFormat>`.
A new standalone example, `examples/standalone/03_hdr_surface`, prints a surface's (format, color space) capabilities and renders an HDR luminance test pattern through the most capable color space available.
By @stuartparmenter in [#9658](https://github.com/gfx-rs/wgpu/pull/9658).
### Added/New Features
#### General
Generated
+39
View File
@@ -2722,6 +2722,18 @@ dependencies = [
"objc2 0.6.4",
]
[[package]]
name = "objc2-core-graphics"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"
dependencies = [
"dispatch2",
"objc2 0.6.4",
"objc2-core-foundation",
"objc2-io-surface",
]
[[package]]
name = "objc2-core-image"
version = "0.2.2"
@@ -2776,6 +2788,17 @@ dependencies = [
"objc2-core-foundation",
]
[[package]]
name = "objc2-io-surface"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"
dependencies = [
"bitflags 2.13.0",
"objc2 0.6.4",
"objc2-core-foundation",
]
[[package]]
name = "objc2-link-presentation"
version = "0.2.2"
@@ -2834,6 +2857,7 @@ dependencies = [
"bitflags 2.13.0",
"objc2 0.6.4",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-foundation 0.3.2",
"objc2-metal 0.3.2",
]
@@ -4754,6 +4778,20 @@ dependencies = [
"winit",
]
[[package]]
name = "wgpu-example-03-hdr-surface"
version = "0.0.0"
dependencies = [
"console_error_panic_hook",
"env_logger",
"pollster",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"wgpu",
"winit",
]
[[package]]
name = "wgpu-example-custom-backend"
version = "0.0.0"
@@ -4826,6 +4864,7 @@ dependencies = [
"ndk-sys",
"objc2 0.6.4",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-foundation 0.3.2",
"objc2-metal 0.3.2",
"objc2-quartz-core 0.3.2",
+5
View File
@@ -218,6 +218,10 @@ objc2-core-foundation = { version = "0.3.2", default-features = false, features
"std",
"CFCGTypes",
] }
objc2-core-graphics = { version = "0.3.2", default-features = false, features = [
"std",
"CGColorSpace",
] }
objc2-foundation = { version = "0.3.2", default-features = false, features = [
"std",
"NSError",
@@ -265,6 +269,7 @@ objc2-metal = { version = "0.3.2", default-features = false, features = [
objc2-quartz-core = { version = "0.3.2", default-features = false, features = [
"std",
"objc2-core-foundation",
"objc2-core-graphics",
"CALayer",
"CAMetalLayer",
"objc2-metal",
+1
View File
@@ -87,6 +87,7 @@ impl GPUCanvasContext {
let conf = wgpu_types::SurfaceConfiguration {
usage: configuration.usage.into(),
format,
color_space: wgpu_types::SurfaceColorSpace::Srgb,
width: *self.width.borrow(),
height: *self.height.borrow(),
present_mode: configuration
+1
View File
@@ -17,6 +17,7 @@ be cloned out of the repository to serve as a starting point for your own projec
| --- | Introductory Examples | --- |
| [1. hello compute](standalone/01_hello_compute/) | Simplest example and shows how to run a compute shader on a given set of input data and get the results back. | Native-Only |
| [2. hello window](standalone/02_hello_window/) | Shows how to create a window and render into it. | Native-Only |
| [3. hdr surface](standalone/03_hdr_surface/) | Prints a surface's (format, color space) capabilities and renders an HDR luminance test pattern. | All |
| --- | Special Examples | --- |
| [custom backend](standalone/custom_backend/) | Shows how to implement and use custom wgpu context | All |
@@ -127,6 +127,7 @@ impl State {
let surface_config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
color_space: wgpu::SurfaceColorSpace::Auto,
width,
height,
present_mode: wgpu::PresentMode::AutoVsync,
@@ -124,6 +124,7 @@ impl State {
let surface_config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
color_space: wgpu::SurfaceColorSpace::Auto,
width,
height,
present_mode: wgpu::PresentMode::AutoVsync,
+1
View File
@@ -700,6 +700,7 @@ impl<E: Example + wgpu::WasmNotSendSync> From<ExampleTestParams<E>>
&wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format,
color_space: wgpu::SurfaceColorSpace::Auto,
width: params.width,
height: params.height,
desired_maximum_frame_latency: 2,
@@ -61,6 +61,7 @@ impl State {
let surface_config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: self.surface_format,
color_space: wgpu::SurfaceColorSpace::Auto,
// Request compatibility with the sRGB-format texture view we‘re going to create later.
view_formats: vec![self.surface_format.add_srgb_suffix()],
alpha_mode: wgpu::CompositeAlphaMode::Auto,
@@ -0,0 +1,26 @@
[package]
name = "wgpu-example-03-hdr-surface"
edition = "2021"
rust-version = "1.87"
publish = false
[dependencies]
wgpu = "29.0.0"
winit = { version = "0.30.8", features = ["android-native-activity"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
env_logger = "0.11"
pollster = "0.4"
[target.'cfg(target_arch = "wasm32")'.dependencies]
console_error_panic_hook = "0.1.5"
wasm-bindgen = "0.2.108"
wasm-bindgen-futures = "0.4.58"
web-sys = { version = "0.3.85", features = [
"console",
"Document",
"Element",
"HtmlCanvasElement",
"Location",
"Window",
] }
@@ -0,0 +1,515 @@
//! HDR surface test.
//!
//! Prints the surface's supported (format, color space) combinations, then
//! configures the surface with the most capable color space available
//! (HDR10 > extended linear scRGB > encoded extended-range sRGB > sRGB) and
//! renders a luminance test pattern:
//!
//! * Top row: grayscale patches at 50 / 100 / 203 / 400 / 1000 / 10000 nits.
//! On an SDR output everything from 100 nits up clips to the same white;
//! on a working HDR output each patch is visibly brighter than the last.
//! * Middle row: red / green / blue / cyan / magenta / yellow at 203 nits.
//! These are BT.709 primaries, so they should look *the same* in every mode;
//! if they look oversaturated in HDR10 the gamut conversion is wrong.
//! * Bottom row: logarithmic luminance gradient from 1 to 10000 nits.
//!
//! Pass a mode as the first argument —
//! `hdr10|hlg|scrgb|extended-srgb|extended-display-p3|srgb` (e.g. `cargo run --
//! hdr10`; on the web: a `?mode=` query parameter) — to force a particular color
//! space instead of auto-picking.
//! Set `WGPU_BACKEND=vulkan` to force the backend.
use std::sync::Arc;
use winit::{
application::ApplicationHandler,
event::WindowEvent,
event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy},
window::{Window, WindowId},
};
/// Print to stdout on native, the developer console on the web.
fn report(msg: impl std::fmt::Display) {
#[cfg(not(target_arch = "wasm32"))]
println!("{msg}");
#[cfg(target_arch = "wasm32")]
web_sys::console::log_1(&msg.to_string().into());
}
/// The forced mode, from the first positional CLI argument on native (e.g.
/// `cargo run -- hdr10`) or the `?mode=` query parameter on the web.
fn forced_mode() -> Option<String> {
#[cfg(not(target_arch = "wasm32"))]
{
std::env::args().nth(1)
}
#[cfg(target_arch = "wasm32")]
{
let search = web_sys::window()?.location().search().ok()?;
search
.strip_prefix('?')?
.split('&')
.find_map(|pair| pair.strip_prefix("mode="))
.map(str::to_owned)
}
}
/// Run a future to completion concurrently: on a worker thread on native, or in
/// the browser's event loop on the web (where blocking is not allowed).
#[cfg(not(target_arch = "wasm32"))]
fn spawn(future: impl core::future::Future<Output = ()> + Send + 'static) {
std::thread::spawn(move || pollster::block_on(future));
}
/// Run a future to completion concurrently: on a worker thread on native, or in
/// the browser's event loop on the web (where blocking is not allowed).
#[cfg(target_arch = "wasm32")]
fn spawn(future: impl core::future::Future<Output = ()> + 'static) {
wasm_bindgen_futures::spawn_local(future);
}
struct ModeChoice {
format: wgpu::TextureFormat,
color_space: wgpu::SurfaceColorSpace,
shader_mode: u32,
}
/// Pick the most capable (format, color space) combination the surface
/// supports, preferring HDR10, then extended linear scRGB, then encoded
/// extended-range sRGB, then sRGB.
fn pick_mode(caps: &wgpu::SurfaceCapabilities, forced: Option<&str>) -> ModeChoice {
use wgpu::{SurfaceColorSpace as Cs, SurfaceColorSpaces as Csf};
// (color space, flag, shader mode, preferred formats in order)
const PREFERENCES: &[(Cs, Csf, u32, &[wgpu::TextureFormat])] = &[
(
Cs::Bt2100Pq,
Csf::BT2100_PQ,
2,
&[
wgpu::TextureFormat::Rgb10a2Unorm,
wgpu::TextureFormat::Rgba16Float,
],
),
(
Cs::Bt2100Hlg,
Csf::BT2100_HLG,
3,
&[
wgpu::TextureFormat::Rgb10a2Unorm,
wgpu::TextureFormat::Rgba16Float,
],
),
(
Cs::ExtendedSrgbLinear,
Csf::EXTENDED_SRGB_LINEAR,
1,
&[wgpu::TextureFormat::Rgba16Float],
),
(
Cs::ExtendedSrgb,
Csf::EXTENDED_SRGB,
4,
&[wgpu::TextureFormat::Rgba16Float],
),
(
Cs::ExtendedDisplayP3,
Csf::EXTENDED_DISPLAY_P3,
5,
&[wgpu::TextureFormat::Rgba16Float],
),
];
// `ExtendedDisplayP3` is reachable only via an explicit `extended-display-p3`
// request, not auto-picked: it needs gamut conversion and the BT.709 test
// pattern looks the same as `ExtendedSrgb`, so auto-pick keeps the simpler
// BT.709 HDR path.
let allowed = |cs: Cs| match forced {
None => cs == Cs::Bt2100Pq || cs == Cs::ExtendedSrgbLinear || cs == Cs::ExtendedSrgb,
Some("hdr10") => cs == Cs::Bt2100Pq,
Some("hlg") => cs == Cs::Bt2100Hlg,
Some("scrgb") => cs == Cs::ExtendedSrgbLinear,
Some("extended-srgb") => cs == Cs::ExtendedSrgb,
Some("extended-display-p3") => cs == Cs::ExtendedDisplayP3,
Some("srgb") => false,
Some(other) => {
panic!("unknown mode {other:?} (use hdr10|hlg|scrgb|extended-srgb|extended-display-p3|srgb)")
}
};
for &(cs, flag, shader_mode, preferred_formats) in PREFERENCES {
if !allowed(cs) {
continue;
}
// Try the preferred formats first, then anything else that
// supports this color space.
let preferred = preferred_formats
.iter()
.copied()
.filter(|&f| caps.color_spaces(f).contains(flag));
let any = caps
.format_capabilities
.iter()
.filter(|fc| fc.color_spaces.contains(flag))
.map(|fc| fc.format);
if let Some(format) = preferred.chain(any).next() {
return ModeChoice {
format,
color_space: cs,
shader_mode,
};
}
}
// SDR fallback.
let format = caps.formats[0];
ModeChoice {
format,
color_space: wgpu::SurfaceColorSpace::Auto,
shader_mode: 0,
}
}
struct State {
window: Arc<Window>,
device: wgpu::Device,
queue: wgpu::Queue,
surface: wgpu::Surface<'static>,
config: wgpu::SurfaceConfiguration,
pipeline: wgpu::RenderPipeline,
bind_group: wgpu::BindGroup,
}
impl State {
async fn new(
window: Arc<Window>,
instance: wgpu::Instance,
surface: wgpu::Surface<'static>,
) -> State {
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
compatible_surface: Some(&surface),
..Default::default()
})
.await
.unwrap();
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor::default())
.await
.unwrap();
let info = adapter.get_info();
report(format_args!("Adapter: {} ({:?})", info.name, info.backend));
let caps = surface.get_capabilities(&adapter);
report("Surface formats and color spaces:");
for fc in &caps.format_capabilities {
report(format_args!(" {:?}: {:?}", fc.format, fc.color_spaces));
}
// Spell out the HDR / wide-gamut spaces each format offers beyond the
// universally-supported SDR `Srgb`/`DisplayP3`, i.e. exactly what an
// app must see advertised here before it can request HDR output. On the
// web this is the key signal: an fp16 (`Rgba16Float`) canvas
// should advertise `ExtendedSrgb` / `ExtendedDisplayP3` whenever it is
// configurable, regardless of whether the display is *currently* in HDR
// mode (that state lives in the display info below, not here).
let sdr = wgpu::SurfaceColorSpaces::SRGB | wgpu::SurfaceColorSpaces::DISPLAY_P3;
report("HDR / wide-gamut color spaces (beyond SDR sRGB / Display-P3):");
for fc in &caps.format_capabilities {
let hdr = fc.color_spaces.difference(sdr);
report(format_args!(
" {:?}: {}",
fc.format,
if hdr.is_empty() {
"none (SDR only)".to_owned()
} else {
format!("{hdr:?}")
}
));
}
let forced = forced_mode();
if let Some(mode) = forced.as_deref() {
report(format_args!(
"Forced mode requested (CLI arg / ?mode=): {mode:?}"
));
}
let choice = pick_mode(&caps, forced.as_deref());
// Make the SDR fallback explicit: landing on the `Auto` path after a
// (non-`srgb`) mode was requested means the requested color space was
// **not** advertised by `color_spaces()`, the situation this example
// makes visible. On web + `Rgba16Float` the extended spaces should be
// advertised regardless of display HDR state, so seeing this there
// means the capability query is under-reporting.
if matches!(choice.color_space, wgpu::SurfaceColorSpace::Auto)
&& forced.as_deref().is_some_and(|m| m != "srgb")
{
report(
" -> requested color space is NOT advertised by the surface; \
falling back to SDR (Auto).",
);
}
// `pick_mode` already chose in one pass; `is_hdr()` on the result is the
// whole capability branch — an HDR space is the one whose highlights can
// go brighter than SDR reference white.
let dynamic_range = if choice.color_space.is_hdr() {
"HDR"
} else {
"SDR"
};
report(format_args!(
"Configuring surface with {:?} + {:?} ({dynamic_range})",
choice.format, choice.color_space,
));
window.set_title(&format!(
"wgpu HDR test — {:?} + {:?}",
choice.format, choice.color_space
));
let size = window.inner_size();
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: choice.format,
color_space: choice.color_space,
width: size.width.max(1),
height: size.height.max(1),
present_mode: wgpu::PresentMode::AutoVsync,
desired_maximum_frame_latency: 2,
alpha_mode: wgpu::CompositeAlphaMode::Auto,
view_formats: vec![],
};
surface.configure(&device, &config);
let shader = device.create_shader_module(wgpu::include_wgsl!("shader.wgsl"));
// mode, encode_srgb
let params: [u32; 2] = [
choice.shader_mode,
u32::from(choice.shader_mode == 0 && !choice.format.is_srgb()),
];
let params_buffer = wgpu::util::DeviceExt::create_buffer_init(
&device,
&wgpu::util::BufferInitDescriptor {
label: Some("params"),
contents: params.map(u32::to_ne_bytes).as_flattened(),
usage: wgpu::BufferUsages::UNIFORM,
},
);
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None,
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: params_buffer.as_entire_binding(),
}],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("hdr test pattern"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(choice.format.into())],
}),
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
multiview_mask: None,
cache: None,
});
State {
window,
device,
queue,
surface,
config,
pipeline,
bind_group,
}
}
fn resize(&mut self, size: winit::dpi::PhysicalSize<u32>) {
self.config.width = size.width.max(1);
self.config.height = size.height.max(1);
self.surface.configure(&self.device, &self.config);
}
fn render(&mut self) {
let surface_texture = match self.surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(t)
| wgpu::CurrentSurfaceTexture::Suboptimal(t) => t,
wgpu::CurrentSurfaceTexture::Outdated => {
self.surface.configure(&self.device, &self.config);
return;
}
_ => return,
};
let view = surface_texture.texture.create_view(&Default::default());
let mut encoder = self.device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &self.bind_group, &[]);
pass.draw(0..3, 0..1);
}
self.queue.submit([encoder.finish()]);
self.window.pre_present_notify();
self.queue.present(surface_texture);
}
}
/// Events delivered to the winit loop from outside a `WindowEvent`.
enum UserEvent {
/// The async setup finished; carries the initialized `State`. Boxed to keep
/// the event small (`State` is large).
Initialized(Box<State>),
}
struct App {
/// Taken on the first `resumed` call so initialization happens once.
proxy: Option<EventLoopProxy<UserEvent>>,
state: Option<State>,
}
impl ApplicationHandler<UserEvent> for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let Some(proxy) = self.proxy.take() else {
return;
};
#[cfg_attr(
not(target_arch = "wasm32"),
expect(unused_mut, reason = "wasm32 re-assigns to specify canvas")
)]
let mut attributes = Window::default_attributes().with_title("wgpu HDR test");
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
use winit::platform::web::WindowAttributesExtWebSys;
let canvas = web_sys::window()
.unwrap()
.document()
.unwrap()
.get_element_by_id("canvas")
.expect("the page must have a <canvas id=\"canvas\">")
.dyn_into::<web_sys::HtmlCanvasElement>()
.unwrap();
attributes = attributes.with_canvas(Some(canvas));
}
let window = Arc::new(event_loop.create_window(attributes).unwrap());
// Create the surface here, on the main thread: winit only hands out the
// raw window handle from the thread that owns the window (on Windows,
// `window_handle()` errors with `Unavailable` anywhere else).
//
// `InstanceDescriptor::new_without_display_handle_from_env` honors
// `WGPU_BACKEND` (e.g. `vulkan`, `dx12`) so each backend's color-space
// path can be exercised separately.
let instance =
wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
let surface = instance.create_surface(window.clone()).unwrap();
// The async tail (adapter, device, pipeline) runs off the main thread
// (native) or in the browser event loop (web); the finished `State`
// arrives back on the main thread via `user_event`.
spawn(async move {
let state = State::new(window, instance, surface).await;
let _ = proxy.send_event(UserEvent::Initialized(Box::new(state)));
});
}
fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: UserEvent) {
match event {
UserEvent::Initialized(state) => {
let state = *state;
state.window.request_redraw();
self.state = Some(state);
}
}
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
let Some(state) = self.state.as_mut() else {
return;
};
match event {
WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::Resized(size) => {
state.resize(size);
state.window.request_redraw();
}
// The test pattern is static, so we render on demand (startup, OS
// expose, resize) rather than spinning a continuous redraw loop.
WindowEvent::RedrawRequested => state.render(),
_ => {}
}
}
}
fn main() {
#[cfg(not(target_arch = "wasm32"))]
env_logger::init();
#[cfg(target_arch = "wasm32")]
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
let event_loop = EventLoop::<UserEvent>::with_user_event().build().unwrap();
event_loop.set_control_flow(ControlFlow::Wait);
let app = App {
proxy: Some(event_loop.create_proxy()),
state: None,
};
#[cfg(not(target_arch = "wasm32"))]
{
let mut app = app;
event_loop.run_app(&mut app).unwrap();
}
#[cfg(target_arch = "wasm32")]
{
use winit::platform::web::EventLoopExtWebSys;
event_loop.spawn_app(app);
}
}
@@ -0,0 +1,160 @@
struct Params {
// 0 = sRGB SDR, 1 = extended linear scRGB, 2 = HDR10 PQ, 3 = HLG,
// 4 = encoded extended-range sRGB, 5 = encoded extended-range Display-P3
mode: u32,
// 1 if the shader must apply the sRGB OETF itself (non-sRGB SDR format)
encode_srgb: u32,
}
@group(0) @binding(0) var<uniform> params: Params;
struct VertexOutput {
@builtin(position) position: vec4f,
@location(0) uv: vec2f,
}
@vertex
fn vs_main(@builtin(vertex_index) vi: u32) -> VertexOutput {
// Fullscreen triangle. Constructed in a single expression: a local
// `var out: VertexOutput` would hit the same naga ArrayStride/Offset
// issue described above (structs get explicit member offsets).
let x = f32(i32(vi & 1u) * 4 - 1);
let y = f32(i32(vi >> 1u) * 4 - 1);
return VertexOutput(vec4f(x, y, 0.0, 1.0), vec2f(x, -y) * 0.5 + 0.5);
}
// Note: indexed lookups are written as if-chains rather than local
// `array<...>` values, because naga's SPIR-V backend decorates array types
// with ArrayStride, which is invalid on function-local variables
// (VUID-StandaloneSpirv-None-10684; see
// https://github.com/gfx-rs/wgpu/issues/7696).
fn staircase_nits(i: u32) -> f32 {
if i == 0u { return 50.0; }
if i == 1u { return 100.0; }
if i == 2u { return 203.0; }
if i == 3u { return 400.0; }
if i == 4u { return 1000.0; }
return 10000.0;
}
fn primary_secondary(i: u32) -> vec3f {
if i == 0u { return vec3f(1.0, 0.0, 0.0); }
if i == 1u { return vec3f(0.0, 1.0, 0.0); }
if i == 2u { return vec3f(0.0, 0.0, 1.0); }
if i == 3u { return vec3f(0.0, 1.0, 1.0); }
if i == 4u { return vec3f(1.0, 0.0, 1.0); }
return vec3f(1.0, 1.0, 0.0);
}
// The test pattern, in linear BT.709 with absolute luminance in nits.
fn pattern_nits(uv: vec2f) -> vec3f {
let i = min(u32(uv.x * 6.0), 5u);
if uv.y < 0.3333 {
// Grayscale staircase.
return vec3f(staircase_nits(i));
} else if uv.y < 0.6667 {
// BT.709 primaries and secondaries at 203 nits.
return primary_secondary(i) * 203.0;
} else {
// Log gradient, 1 nit -> 10000 nits.
return vec3f(pow(10.0, uv.x * 4.0));
}
}
// Standard sRGB OETF, valid for inputs in [0, 1]. `pow` is undefined for
// negative inputs, so callers must clamp first (the SDR path does).
fn srgb_oetf(c: vec3f) -> vec3f {
let lo = c * 12.92;
let hi = 1.055 * pow(c, vec3f(1.0 / 2.4)) - 0.055;
return select(hi, lo, c <= vec3f(0.0031308));
}
// Extended sRGB OETF: the sRGB transfer function continued beyond [0, 1] with
// odd (point) symmetry through the origin, so values >1.0 (brighter than SDR
// reference white) and <0.0 (out-of-gamut) are encoded rather than clamped.
// This is what the `ExtendedSrgb` color space (browser HDR canvas, Vulkan
// EXTENDED_SRGB_NONLINEAR, Metal ExtendedSRGB) expects on the wire.
fn srgb_oetf_extended(c: vec3f) -> vec3f {
let s = sign(c);
let a = abs(c);
let lo = a * 12.92;
let hi = 1.055 * pow(a, vec3f(1.0 / 2.4)) - 0.055;
return s * select(hi, lo, a <= vec3f(0.0031308));
}
// SMPTE ST 2084 (PQ) OETF; input is luminance normalized to 10000 nits.
fn pq_oetf(y: vec3f) -> vec3f {
let m1 = 0.1593017578125;
let m2 = 78.84375;
let c1 = 0.8359375;
let c2 = 18.8515625;
let c3 = 18.6875;
let yp = pow(max(y, vec3f(0.0)), vec3f(m1));
return pow((c1 + c2 * yp) / (1.0 + c3 * yp), vec3f(m2));
}
// BT.2100 HLG OETF; input is scene luminance normalized to 1000-nit peak.
fn hlg_oetf(y: vec3f) -> vec3f {
let a = 0.17883277;
let b = 0.28466892;
let c = 0.55991073;
let lo = sqrt(3.0 * y);
let hi = a * log(12.0 * y - b) + c;
return select(hi, lo, y <= vec3f(1.0 / 12.0));
}
const BT709_TO_BT2020 = mat3x3f(
vec3f(0.627402, 0.069095, 0.016394),
vec3f(0.329292, 0.919544, 0.088028),
vec3f(0.043306, 0.011360, 0.895578),
);
// Linear BT.709 (sRGB) -> linear Display-P3, both D65. Column-major.
const BT709_TO_DISPLAYP3 = mat3x3f(
vec3f(0.8224621, 0.0331942, 0.0170826),
vec3f(0.1775380, 0.9668058, 0.0723974),
vec3f(0.0000000, 0.0000000, 0.9105199),
);
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4f {
let nits = pattern_nits(in.uv);
var out: vec3f;
switch params.mode {
case 1u: {
// Extended linear scRGB: BT.709 primaries, linear, 1.0 = 80 nits.
out = nits / 80.0;
}
case 4u: {
// Encoded extended-range sRGB: BT.709 primaries, the sRGB OETF
// extended beyond [0, 1]. Same normalization as scRGB
// (1.0 = 80 nits), but sRGB-encoded rather than linear.
out = srgb_oetf_extended(nits / 80.0);
}
case 5u: {
// Encoded extended-range Display-P3: convert BT.709 -> P3 primaries
// (linear), normalize like scRGB (1.0 = 80 nits), then apply the
// extended sRGB OETF. The BT.709 test primaries look identical, just
// carried in the wider P3 container.
out = srgb_oetf_extended((BT709_TO_DISPLAYP3 * nits) / 80.0);
}
case 2u: {
// HDR10: BT.2020 primaries, PQ-encoded absolute luminance.
out = pq_oetf(BT709_TO_BT2020 * (nits / 10000.0));
}
case 3u: {
// HLG: BT.2020 primaries, 1000-nit nominal peak.
out = hlg_oetf(BT709_TO_BT2020 * (min(nits, vec3f(1000.0)) / 1000.0));
}
default: {
// SDR sRGB: clip at 100 nits.
out = clamp(nits / 100.0, vec3f(0.0), vec3f(1.0));
if params.encode_srgb == 1u {
out = srgb_oetf(out);
}
}
}
return vec4f(out, 1.0);
}
@@ -0,0 +1,32 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>wgpu HDR surface test</title>
<style>
html,
body {
margin: 0;
height: 100%;
background: #111;
}
canvas {
display: block;
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<!-- The example looks the canvas up by this id. -->
<canvas id="canvas"></canvas>
<script type="module">
// Open the developer console to see the reported surface
// capabilities. Add ?mode=extended-srgb|extended-display-p3|srgb to
// force a color space; on the web the HDR modes are extended-srgb and
// extended-display-p3 (scrgb/hdr10/hlg are native-only).
import init from "./hdr_surface.js";
init();
</script>
</body>
</html>
+3
View File
@@ -27,6 +27,9 @@ Fo = "Fo"
# Abbreviation of Structured Exception Handling
SEH = "SEH"
# Content Light Level (HDR mastering metadata, e.g. MaxCLL)
CLL = "CLL"
# Usernames
Healthire = "Healthire"
REASY = "REASY"
+17 -3
View File
@@ -31,7 +31,7 @@ use crate::{
use wgt::{BufferAddress, TextureFormat};
use super::UserClosures;
use super::{surface_config, UserClosures};
impl Global {
pub fn adapter_is_surface_supported(
@@ -53,12 +53,26 @@ impl Global {
self.fetch_adapter_and_surface::<_, _>(surface_id, adapter_id, |adapter, surface| {
let mut hal_caps = surface.get_capabilities(adapter)?;
hal_caps.formats.sort_by_key(|f| !f.is_srgb());
hal_caps.formats.sort_by_key(|fc| !fc.format.is_srgb());
let usages = conv::map_texture_usage_from_hal(hal_caps.usage);
// `SurfaceCapabilities::formats` lists only the formats a
// color-space-unaware application can configure via
// `SurfaceColorSpace::Auto`, i.e. those for which `Auto` resolves to a
// concrete color space. (The full `format_capabilities` still reports
// every color space, including HDR ones, for explicit opt-in.)
Ok(wgt::SurfaceCapabilities {
formats: hal_caps.formats,
formats: hal_caps
.formats
.iter()
.filter(|fc| {
surface_config::resolve_auto_color_space(fc.format, fc.color_spaces)
.is_some()
})
.map(|fc| fc.format)
.collect(),
format_capabilities: hal_caps.formats,
present_modes: hal_caps.present_modes,
alpha_modes: hal_caps.composite_alpha_modes,
usages,
+1
View File
@@ -26,6 +26,7 @@ mod life;
pub mod queue;
pub mod ray_tracing;
pub mod resource;
mod surface_config;
#[cfg(any(feature = "trace", feature = "replay"))]
pub mod trace;
pub use {life::WaitIdleError, resource::Device};
+5 -116
View File
@@ -60,8 +60,8 @@ use crate::{
};
use super::{
queue::Queue, DeviceDescriptor, DeviceError, DeviceLostClosure, UserClosures,
ENTRYPOINT_FAILURE_ERROR, ZERO_BUFFER_SIZE,
queue::Queue, surface_config::validate_surface_configuration, DeviceDescriptor, DeviceError,
DeviceLostClosure, UserClosures, ENTRYPOINT_FAILURE_ERROR, ZERO_BUFFER_SIZE,
};
#[cfg(supports_64bit_atomics)]
@@ -5132,118 +5132,6 @@ impl Device {
use present::ConfigureSurfaceError as E;
profiling::scope!("surface_configure");
fn validate_surface_configuration(
config: &mut hal::SurfaceConfiguration,
caps: &hal::SurfaceCapabilities,
max_texture_dimension_2d: u32,
) -> Result<(), E> {
let width = config.extent.width;
let height = config.extent.height;
if width > max_texture_dimension_2d || height > max_texture_dimension_2d {
return Err(E::TooLarge {
width,
height,
max_texture_dimension_2d,
});
}
if !caps.present_modes.contains(&config.present_mode) {
// Automatic present mode checks.
//
// The "Automatic" modes are never supported by the backends.
let fallbacks = match config.present_mode {
wgt::PresentMode::AutoVsync => {
&[wgt::PresentMode::FifoRelaxed, wgt::PresentMode::Fifo][..]
}
// Always end in FIFO to make sure it's always supported
wgt::PresentMode::AutoNoVsync => &[
wgt::PresentMode::Immediate,
wgt::PresentMode::Mailbox,
wgt::PresentMode::Fifo,
][..],
_ => {
return Err(E::UnsupportedPresentMode {
requested: config.present_mode,
available: caps.present_modes.clone(),
});
}
};
let new_mode = fallbacks
.iter()
.copied()
.find(|fallback| caps.present_modes.contains(fallback))
.unwrap_or_else(|| {
unreachable!(
"Fallback system failed to choose present mode. \
This is a bug. Mode: {:?}, Options: {:?}",
config.present_mode, &caps.present_modes
);
});
api_log!(
"Automatically choosing presentation mode by rule {:?}. Chose {new_mode:?}",
config.present_mode
);
config.present_mode = new_mode;
}
if !caps.formats.contains(&config.format) {
return Err(E::UnsupportedFormat {
requested: config.format,
available: caps.formats.clone(),
});
}
if !caps
.composite_alpha_modes
.contains(&config.composite_alpha_mode)
{
let new_alpha_mode = 'alpha: {
// Automatic alpha mode checks.
let fallbacks = match config.composite_alpha_mode {
wgt::CompositeAlphaMode::Auto => &[
wgt::CompositeAlphaMode::Opaque,
wgt::CompositeAlphaMode::Inherit,
][..],
_ => {
return Err(E::UnsupportedAlphaMode {
requested: config.composite_alpha_mode,
available: caps.composite_alpha_modes.clone(),
});
}
};
for &fallback in fallbacks {
if caps.composite_alpha_modes.contains(&fallback) {
break 'alpha fallback;
}
}
unreachable!(
"Fallback system failed to choose alpha mode. This is a bug. \
AlphaMode: {:?}, Options: {:?}",
config.composite_alpha_mode, &caps.composite_alpha_modes
);
};
api_log!(
"Automatically choosing alpha mode by rule {:?}. Chose {new_alpha_mode:?}",
config.composite_alpha_mode
);
config.composite_alpha_mode = new_alpha_mode;
}
if !caps.usage.contains(config.usage) {
return Err(E::UnsupportedUsage {
requested: config.usage,
available: caps.usage,
});
}
if width == 0 || height == 0 {
return Err(E::ZeroArea);
}
Ok(())
}
log::debug!("configuring surface with {config:?}");
let error = 'error: {
@@ -5264,10 +5152,10 @@ impl Device {
if *format == config.format {
continue;
}
if !caps.formats.contains(&config.format) {
if !caps.formats.iter().any(|fc| fc.format == config.format) {
break 'error E::UnsupportedFormat {
requested: config.format,
available: caps.formats,
available: caps.texture_formats().collect(),
};
}
if config.format.remove_srgb_suffix() != format.remove_srgb_suffix() {
@@ -5293,6 +5181,7 @@ impl Device {
present_mode: config.present_mode,
composite_alpha_mode: config.alpha_mode,
format: config.format,
color_space: config.color_space,
extent: wgt::Extent3d {
width: config.width,
height: config.height,
+376
View File
@@ -0,0 +1,376 @@
//! Validation of a surface configuration against its capabilities, including
//! resolving `SurfaceColorSpace::Auto` (and present/alpha `Auto`) to concrete
//! values. Split out of the very large `resource.rs`.
use crate::{api_log, present};
use wgt::TextureFormat;
/// The concrete color space [`SurfaceColorSpace::Auto`] resolves to for `format`,
/// given the color spaces a surface supports for it, or `None` if `Auto` cannot
/// be satisfied.
///
/// Reproduces wgpu's historical behavior: extended linear scRGB for fp16 formats
/// when supported, sRGB otherwise. `Auto` never resolves to a wide-gamut or HDR
/// color space (DisplayP3, ExtendedSrgb, ExtendedDisplayP3, Bt2100Pq, Bt2100Hlg),
/// because those change how the application must encode its output, so they must
/// be requested explicitly.
///
/// This is the single source of truth shared by [`validate_surface_configuration`]
/// and the `get_capabilities` `formats` filter, so a format is listed in
/// [`SurfaceCapabilities::formats`] exactly when `Auto` resolves for it.
///
/// [`SurfaceColorSpace::Auto`]: wgt::SurfaceColorSpace::Auto
/// [`SurfaceCapabilities::formats`]: wgt::SurfaceCapabilities::formats
pub(crate) fn resolve_auto_color_space(
format: TextureFormat,
color_spaces: wgt::SurfaceColorSpaces,
) -> Option<wgt::SurfaceColorSpace> {
let fallbacks: &[_] = if format == TextureFormat::Rgba16Float {
&[
wgt::SurfaceColorSpace::ExtendedSrgbLinear,
wgt::SurfaceColorSpace::Srgb,
]
} else {
&[wgt::SurfaceColorSpace::Srgb]
};
fallbacks
.iter()
.copied()
.find(|fallback| color_spaces.contains(fallback.to_color_spaces().unwrap()))
}
/// Validate `config` against `caps`, resolving the `Auto` values in
/// `config` to concrete ones.
pub(crate) fn validate_surface_configuration(
config: &mut hal::SurfaceConfiguration,
caps: &hal::SurfaceCapabilities,
max_texture_dimension_2d: u32,
) -> Result<(), present::ConfigureSurfaceError> {
use present::ConfigureSurfaceError as E;
let width = config.extent.width;
let height = config.extent.height;
if width > max_texture_dimension_2d || height > max_texture_dimension_2d {
return Err(E::TooLarge {
width,
height,
max_texture_dimension_2d,
});
}
if !caps.present_modes.contains(&config.present_mode) {
// Automatic present mode checks.
//
// The "Automatic" modes are never supported by the backends.
let fallbacks = match config.present_mode {
wgt::PresentMode::AutoVsync => {
&[wgt::PresentMode::FifoRelaxed, wgt::PresentMode::Fifo][..]
}
// Always end in FIFO to make sure it's always supported
wgt::PresentMode::AutoNoVsync => &[
wgt::PresentMode::Immediate,
wgt::PresentMode::Mailbox,
wgt::PresentMode::Fifo,
][..],
_ => {
return Err(E::UnsupportedPresentMode {
requested: config.present_mode,
available: caps.present_modes.clone(),
});
}
};
let new_mode = fallbacks
.iter()
.copied()
.find(|fallback| caps.present_modes.contains(fallback))
.unwrap_or_else(|| {
unreachable!(
"Fallback system failed to choose present mode. \
This is a bug. Mode: {:?}, Options: {:?}",
config.present_mode, &caps.present_modes
);
});
api_log!(
"Automatically choosing presentation mode by rule {:?}. Chose {new_mode:?}",
config.present_mode
);
config.present_mode = new_mode;
}
let Some(format_caps) = caps.formats.iter().find(|fc| fc.format == config.format) else {
return Err(E::UnsupportedFormat {
requested: config.format,
available: caps.texture_formats().collect(),
});
};
if config.color_space == wgt::SurfaceColorSpace::Auto {
let Some(new_color_space) =
resolve_auto_color_space(config.format, format_caps.color_spaces)
else {
// The format is only available in color spaces that must be
// explicitly requested (e.g. HDR10-only on some drivers when the OS
// is in HDR mode).
return Err(E::UnsupportedColorSpace {
requested: config.color_space,
format: config.format,
available: format_caps.color_spaces,
});
};
api_log!(
"Automatically choosing color space by rule {:?}. Chose {new_color_space:?}",
config.color_space
);
config.color_space = new_color_space;
}
if !format_caps
.color_spaces
.contains(config.color_space.to_color_spaces().unwrap())
{
return Err(E::UnsupportedColorSpace {
requested: config.color_space,
format: config.format,
available: format_caps.color_spaces,
});
}
if !caps
.composite_alpha_modes
.contains(&config.composite_alpha_mode)
{
let new_alpha_mode = 'alpha: {
// Automatic alpha mode checks.
let fallbacks = match config.composite_alpha_mode {
wgt::CompositeAlphaMode::Auto => &[
wgt::CompositeAlphaMode::Opaque,
wgt::CompositeAlphaMode::Inherit,
][..],
_ => {
return Err(E::UnsupportedAlphaMode {
requested: config.composite_alpha_mode,
available: caps.composite_alpha_modes.clone(),
});
}
};
for &fallback in fallbacks {
if caps.composite_alpha_modes.contains(&fallback) {
break 'alpha fallback;
}
}
unreachable!(
"Fallback system failed to choose alpha mode. This is a bug. \
AlphaMode: {:?}, Options: {:?}",
config.composite_alpha_mode, &caps.composite_alpha_modes
);
};
api_log!(
"Automatically choosing alpha mode by rule {:?}. Chose {new_alpha_mode:?}",
config.composite_alpha_mode
);
config.composite_alpha_mode = new_alpha_mode;
}
if !caps.usage.contains(config.usage) {
return Err(E::UnsupportedUsage {
requested: config.usage,
available: caps.usage,
});
}
if width == 0 || height == 0 {
return Err(E::ZeroArea);
}
Ok(())
}
#[cfg(test)]
mod surface_configuration_tests {
use alloc::{vec, vec::Vec};
use super::validate_surface_configuration;
use crate::present::ConfigureSurfaceError;
fn caps(formats: Vec<wgt::SurfaceFormatCapabilities>) -> hal::SurfaceCapabilities {
hal::SurfaceCapabilities {
formats,
maximum_frame_latency: 1..=3,
current_extent: None,
usage: wgt::TextureUses::COLOR_TARGET,
present_modes: vec![wgt::PresentMode::Fifo],
composite_alpha_modes: vec![wgt::CompositeAlphaMode::Opaque],
}
}
fn config(
format: wgt::TextureFormat,
color_space: wgt::SurfaceColorSpace,
) -> hal::SurfaceConfiguration {
hal::SurfaceConfiguration {
maximum_frame_latency: 2,
present_mode: wgt::PresentMode::Fifo,
composite_alpha_mode: wgt::CompositeAlphaMode::Opaque,
format,
color_space,
extent: wgt::Extent3d {
width: 100,
height: 100,
depth_or_array_layers: 1,
},
usage: wgt::TextureUses::COLOR_TARGET,
view_formats: Vec::new(),
}
}
fn format_caps(
format: wgt::TextureFormat,
color_spaces: wgt::SurfaceColorSpaces,
) -> wgt::SurfaceFormatCapabilities {
wgt::SurfaceFormatCapabilities {
format,
color_spaces,
}
}
/// `Auto` resolves to extended linear scRGB for fp16 when supported,
/// reproducing the historical hardcoded behavior.
#[test]
fn auto_resolves_fp16_to_extended_srgb_linear() {
let caps = caps(vec![format_caps(
wgt::TextureFormat::Rgba16Float,
wgt::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR | wgt::SurfaceColorSpaces::BT2100_PQ,
)]);
let mut config = config(
wgt::TextureFormat::Rgba16Float,
wgt::SurfaceColorSpace::Auto,
);
validate_surface_configuration(&mut config, &caps, 4096).unwrap();
assert_eq!(
config.color_space,
wgt::SurfaceColorSpace::ExtendedSrgbLinear
);
}
/// `Auto` never resolves to the encoded extended-range sRGB color space,
/// even for fp16 formats: it prefers extended *linear* sRGB and falls back
/// to plain sRGB, but `ExtendedSrgb` must be requested explicitly.
#[test]
fn auto_never_resolves_to_extended_srgb() {
let caps = caps(vec![format_caps(
wgt::TextureFormat::Rgba16Float,
wgt::SurfaceColorSpaces::SRGB | wgt::SurfaceColorSpaces::EXTENDED_SRGB,
)]);
let mut config = config(
wgt::TextureFormat::Rgba16Float,
wgt::SurfaceColorSpace::Auto,
);
validate_surface_configuration(&mut config, &caps, 4096).unwrap();
assert_eq!(config.color_space, wgt::SurfaceColorSpace::Srgb);
}
/// `Auto` resolves fp16 to sRGB when extended linear is unavailable
/// (e.g. the GLES backend).
#[test]
fn auto_resolves_fp16_to_srgb_without_extended() {
let caps = caps(vec![format_caps(
wgt::TextureFormat::Rgba16Float,
wgt::SurfaceColorSpaces::SRGB,
)]);
let mut config = config(
wgt::TextureFormat::Rgba16Float,
wgt::SurfaceColorSpace::Auto,
);
validate_surface_configuration(&mut config, &caps, 4096).unwrap();
assert_eq!(config.color_space, wgt::SurfaceColorSpace::Srgb);
}
/// `Auto` never resolves to an HDR color space, even if it is the only
/// one supported for the format: HDR output changes how the application
/// must encode its colors, so it must be requested explicitly.
#[test]
fn auto_refuses_hdr_only_formats() {
let caps = caps(vec![format_caps(
wgt::TextureFormat::Rgb10a2Unorm,
wgt::SurfaceColorSpaces::BT2100_PQ,
)]);
let mut config = config(
wgt::TextureFormat::Rgb10a2Unorm,
wgt::SurfaceColorSpace::Auto,
);
let err = validate_surface_configuration(&mut config, &caps, 4096).unwrap_err();
assert!(matches!(
err,
ConfigureSurfaceError::UnsupportedColorSpace { .. }
));
}
/// `Auto` prefers sRGB for non-fp16 formats even when HDR spaces are
/// also supported.
#[test]
fn auto_prefers_srgb_for_non_fp16() {
let caps = caps(vec![format_caps(
wgt::TextureFormat::Rgb10a2Unorm,
wgt::SurfaceColorSpaces::SRGB | wgt::SurfaceColorSpaces::BT2100_PQ,
)]);
let mut config = config(
wgt::TextureFormat::Rgb10a2Unorm,
wgt::SurfaceColorSpace::Auto,
);
validate_surface_configuration(&mut config, &caps, 4096).unwrap();
assert_eq!(config.color_space, wgt::SurfaceColorSpace::Srgb);
}
/// A non-fp16 format that reports *both* sRGB and extended-linear sRGB still
/// resolves `Auto` deterministically to `Srgb`: the extended-linear fallback
/// is gated on `Rgba16Float`, so there is never ambiguity about which color
/// space `Auto` picks even when a format advertises both.
#[test]
fn auto_non_fp16_with_srgb_and_extended_linear_resolves_to_srgb() {
let caps = caps(vec![format_caps(
wgt::TextureFormat::Rgb10a2Unorm,
wgt::SurfaceColorSpaces::SRGB | wgt::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR,
)]);
let mut config = config(
wgt::TextureFormat::Rgb10a2Unorm,
wgt::SurfaceColorSpace::Auto,
);
validate_surface_configuration(&mut config, &caps, 4096).unwrap();
assert_eq!(config.color_space, wgt::SurfaceColorSpace::Srgb);
}
/// Explicitly requested color spaces are honored when supported.
#[test]
fn explicit_hdr10_is_honored() {
let caps = caps(vec![format_caps(
wgt::TextureFormat::Rgb10a2Unorm,
wgt::SurfaceColorSpaces::SRGB | wgt::SurfaceColorSpaces::BT2100_PQ,
)]);
let mut config = config(
wgt::TextureFormat::Rgb10a2Unorm,
wgt::SurfaceColorSpace::Bt2100Pq,
);
validate_surface_configuration(&mut config, &caps, 4096).unwrap();
assert_eq!(config.color_space, wgt::SurfaceColorSpace::Bt2100Pq);
}
/// Explicitly requesting an unsupported color space fails validation.
#[test]
fn explicit_unsupported_color_space_errors() {
let caps = caps(vec![format_caps(
wgt::TextureFormat::Bgra8UnormSrgb,
wgt::SurfaceColorSpaces::SRGB,
)]);
let mut config = config(
wgt::TextureFormat::Bgra8UnormSrgb,
wgt::SurfaceColorSpace::Bt2100Pq,
);
let err = validate_surface_configuration(&mut config, &caps, 4096).unwrap_err();
assert!(matches!(
err,
ConfigureSurfaceError::UnsupportedColorSpace {
requested: wgt::SurfaceColorSpace::Bt2100Pq,
..
}
));
}
}
+7
View File
@@ -98,6 +98,12 @@ pub enum ConfigureSurfaceError {
requested: wgt::TextureFormat,
available: Vec<wgt::TextureFormat>,
},
#[error("Requested color space {requested:?} is not in the list of color spaces supported for format {format:?}: {available:?}")]
UnsupportedColorSpace {
requested: wgt::SurfaceColorSpace,
format: wgt::TextureFormat,
available: wgt::SurfaceColorSpaces,
},
#[error("Requested present mode {requested:?} is not in the list of supported present modes: {available:?}")]
UnsupportedPresentMode {
requested: wgt::PresentMode,
@@ -138,6 +144,7 @@ impl WebGpuError for ConfigureSurfaceError {
| Self::TooLarge { .. }
| Self::UnsupportedQueueFamily
| Self::UnsupportedFormat { .. }
| Self::UnsupportedColorSpace { .. }
| Self::UnsupportedPresentMode { .. }
| Self::UnsupportedAlphaMode { .. }
| Self::UnsupportedUsage { .. } => ErrorType::Validation,
+3 -1
View File
@@ -76,9 +76,9 @@ metal = [
"dep:arrayvec",
"dep:block2",
"dep:bytemuck",
"dep:libc",
"dep:objc2",
"dep:objc2-core-foundation",
"dep:objc2-core-graphics",
"dep:objc2-foundation",
"dep:objc2-metal",
"dep:objc2-quartz-core",
@@ -151,6 +151,7 @@ dx12 = [
"windows/Win32_Graphics_Direct3D12",
"windows/Win32_Graphics_DirectComposition",
"windows/Win32_Graphics_Dxgi_Common",
"windows/Win32_Graphics_Gdi",
"windows/Win32_Security",
"windows/Win32_System_Diagnostics_Debug",
"windows/Win32_System_Kernel",
@@ -288,6 +289,7 @@ block2 = { workspace = true, optional = true }
bytemuck = { workspace = true, optional = true }
objc2 = { workspace = true, optional = true }
objc2-core-foundation = { workspace = true, optional = true }
objc2-core-graphics = { workspace = true, optional = true }
objc2-foundation = { workspace = true, optional = true }
objc2-metal = { workspace = true, optional = true }
objc2-quartz-core = { workspace = true, optional = true }
+1
View File
@@ -150,6 +150,7 @@ impl<A: hal::Api> Example<A> {
present_mode: wgpu_types::PresentMode::Fifo,
composite_alpha_mode: wgpu_types::CompositeAlphaMode::Opaque,
format: wgpu_types::TextureFormat::Bgra8UnormSrgb,
color_space: wgpu_types::SurfaceColorSpace::Srgb,
extent: wgpu_types::Extent3d {
width: window_size.0,
height: window_size.1,
@@ -294,11 +294,12 @@ impl<A: hal::Api> Example<A> {
dbg!(&surface_caps.formats);
let surface_format = if surface_caps
.formats
.contains(&wgpu_types::TextureFormat::Rgba8Unorm)
.iter()
.any(|fc| fc.format == wgpu_types::TextureFormat::Rgba8Unorm)
{
wgpu_types::TextureFormat::Rgba8Unorm
} else {
*surface_caps.formats.first().unwrap()
surface_caps.formats.first().unwrap().format
};
let surface_config = hal::SurfaceConfiguration {
maximum_frame_latency: DESIRED_MAX_LATENCY
@@ -307,6 +308,7 @@ impl<A: hal::Api> Example<A> {
present_mode: wgpu_types::PresentMode::Fifo,
composite_alpha_mode: wgpu_types::CompositeAlphaMode::Opaque,
format: surface_format,
color_space: wgpu_types::SurfaceColorSpace::Srgb,
extent: wgpu_types::Extent3d {
width: window_size.0,
height: window_size.1,
+29 -2
View File
@@ -1318,14 +1318,41 @@ impl crate::Adapter for super::Adapter {
}
Some(crate::SurfaceCapabilities {
formats: vec![
// `Surface::configure` applies the requested color space with
// `IDXGISwapChain3::SetColorSpace1`. fp16 buffers keep DXGI's
// scRGB interpretation (`DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709`)
// and `Rgb10a2Unorm` additionally supports BT.2100 PQ (HDR10).
//
// These color spaces are advertised unconditionally, not gated on
// whether the output is currently in HDR mode: Windows always
// composites in scRGB and tone-maps PQ down to an SDR output, so the
// color space is configurable regardless, and `CheckColorSpaceSupport`
// returning false does not mean it won't present. Whether HDR is
// actually *visible* is a separate, live question (the upcoming
// display-HDR query, #9739), not a configuration gate. Display-P3 and
// HLG are never reported: DXGI has no RGB HLG swapchain color space,
// and P3 isn't a DXGI swapchain color space.
formats: [
wgt::TextureFormat::Bgra8UnormSrgb,
wgt::TextureFormat::Bgra8Unorm,
wgt::TextureFormat::Rgba8UnormSrgb,
wgt::TextureFormat::Rgba8Unorm,
wgt::TextureFormat::Rgb10a2Unorm,
wgt::TextureFormat::Rgba16Float,
],
]
.map(|format| wgt::SurfaceFormatCapabilities {
format,
color_spaces: match format {
wgt::TextureFormat::Rgba16Float => {
wgt::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR
}
wgt::TextureFormat::Rgb10a2Unorm => {
wgt::SurfaceColorSpaces::SRGB | wgt::SurfaceColorSpaces::BT2100_PQ
}
_ => wgt::SurfaceColorSpaces::SRGB,
},
})
.to_vec(),
// See https://learn.microsoft.com/en-us/windows/win32/api/dxgi/nf-dxgi-idxgidevice1-setmaximumframelatency
maximum_frame_latency: 1..=16,
current_extent,
+35
View File
@@ -1440,6 +1440,24 @@ impl SwapChain {
}
}
fn map_surface_color_space(
color_space: wgt::SurfaceColorSpace,
) -> Dxgi::Common::DXGI_COLOR_SPACE_TYPE {
use wgt::SurfaceColorSpace as Scs;
match color_space {
Scs::Srgb => Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709,
Scs::ExtendedSrgbLinear => Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709,
Scs::Bt2100Pq => Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020,
Scs::Auto
| Scs::DisplayP3
| Scs::Bt2100Hlg
| Scs::ExtendedSrgb
| Scs::ExtendedDisplayP3 => {
unreachable!("`{color_space:?}` is never reported in the DX12 surface capabilities")
}
}
}
impl crate::Surface for Surface {
type A = Api;
@@ -1615,6 +1633,23 @@ impl crate::Surface for Surface {
}
};
// Apply the color space unconditionally (even for sRGB) so that
// reconfiguring away from HDR10 resets the swapchain's state.
//
// We deliberately skip `CheckColorSpaceSupport`: a color space reporting as
// unsupported is not a failure. Windows composites in scRGB and tone-maps
// the color space down to the output, so `SetColorSpace1` still presents
// correctly even when the check returns false (as the MS docs note). This
// lets an app configure e.g. BT.2100 PQ on an SDR output and let the
// compositor map it.
let color_space = map_surface_color_space(config.color_space);
// SAFETY: `swap_chain` is a live `IDXGISwapChain3`; `color_space` is a
// valid `DXGI_COLOR_SPACE_TYPE`.
unsafe { swap_chain.SetColorSpace1(color_space) }.map_err(|err| {
log::error!("SetColorSpace1 failed: {err}");
crate::SurfaceError::Other("IDXGISwapChain3::SetColorSpace1")
})?;
match self.target {
SurfaceTarget::WndHandle(wnd_handle) => {
// Disable automatic Alt+Enter handling by DXGI.
+11 -5
View File
@@ -1339,16 +1339,22 @@ impl crate::Adapter for super::Adapter {
}
if surface.presentable {
// There is no extended-range or wide-gamut path in the GLES
// backend; everything is presented as sRGB.
let format_caps = |format: wgt::TextureFormat| wgt::SurfaceFormatCapabilities {
format,
color_spaces: wgt::SurfaceColorSpaces::SRGB,
};
let mut formats = vec![
wgt::TextureFormat::Rgba8Unorm,
format_caps(wgt::TextureFormat::Rgba8Unorm),
#[cfg(native)]
wgt::TextureFormat::Bgra8Unorm,
format_caps(wgt::TextureFormat::Bgra8Unorm),
];
if surface.supports_srgb() {
formats.extend([
wgt::TextureFormat::Rgba8UnormSrgb,
format_caps(wgt::TextureFormat::Rgba8UnormSrgb),
#[cfg(native)]
wgt::TextureFormat::Bgra8UnormSrgb,
format_caps(wgt::TextureFormat::Bgra8UnormSrgb),
])
}
if self
@@ -1356,7 +1362,7 @@ impl crate::Adapter for super::Adapter {
.private_caps
.contains(super::PrivateCapabilities::COLOR_BUFFER_HALF_FLOAT)
{
formats.push(wgt::TextureFormat::Rgba16Float)
formats.push(format_caps(wgt::TextureFormat::Rgba16Float))
}
Some(crate::SurfaceCapabilities {
+19 -3
View File
@@ -2103,10 +2103,12 @@ pub struct ExposedAdapter<A: Api> {
/// Fetch this with [Adapter::surface_capabilities].
#[derive(Debug, Clone)]
pub struct SurfaceCapabilities {
/// List of supported texture formats.
/// List of supported texture formats together with the color spaces
/// supported for each format.
///
/// Must be at least one.
pub formats: Vec<wgt::TextureFormat>,
/// Must be at least one. At most one entry per format, each with a
/// non-empty set of color spaces.
pub formats: Vec<wgt::SurfaceFormatCapabilities>,
/// Range for the number of queued frames.
///
@@ -2136,6 +2138,14 @@ pub struct SurfaceCapabilities {
pub composite_alpha_modes: Vec<wgt::CompositeAlphaMode>,
}
impl SurfaceCapabilities {
/// Returns the supported texture formats, dropping the per-format color-space
/// information carried in [`Self::formats`].
pub fn texture_formats(&self) -> impl Iterator<Item = wgt::TextureFormat> + '_ {
self.formats.iter().map(|fc| fc.format)
}
}
#[derive(Debug)]
pub struct AcquiredSurfaceTexture<A: Api> {
pub texture: A::SurfaceTexture,
@@ -2698,6 +2708,12 @@ pub struct SurfaceConfiguration {
pub composite_alpha_mode: wgt::CompositeAlphaMode,
/// Format of the surface textures.
pub format: wgt::TextureFormat,
/// Color space in which the presentation engine interprets the surface
/// textures. Never [`wgt::SurfaceColorSpace::Auto`]; `wgpu-core` resolves
/// `Auto` to a concrete color space before configuring the surface, and
/// the (format, color space) pair must be listed in
/// `SurfaceCapabilities::formats`.
pub color_space: wgt::SurfaceColorSpace,
/// Requested texture extent. Must be in
/// `SurfaceCapabilities::extents` range.
pub extent: wgt::Extent3d,
+35 -4
View File
@@ -410,17 +410,48 @@ impl crate::Adapter for super::Adapter {
&self,
surface: &super::Surface,
) -> Option<crate::SurfaceCapabilities> {
// `CAMetalLayer` color-matches layer contents to whatever display the
// window is on, with the compositor tone-mapping where needed, so
// Display-P3 and HDR (PQ/HLG) color spaces work regardless of the
// physical display's gamut and are not gated on it here.
let format_caps = |format: wgt::TextureFormat| {
let mut color_spaces =
wgt::SurfaceColorSpaces::SRGB | wgt::SurfaceColorSpaces::DISPLAY_P3;
if format == wgt::TextureFormat::Rgba16Float {
// `Rgba16Float` enables Metal's extended dynamic range, in both
// linear (scRGB) and encoded (extended nonlinear sRGB) form,
// for the BT.709 and Display-P3 gamuts.
color_spaces |= wgt::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR
| wgt::SurfaceColorSpaces::EXTENDED_SRGB
| wgt::SurfaceColorSpaces::EXTENDED_DISPLAY_P3;
}
// PQ/HLG only on the >=10-bit formats: 8-bit PQ would result in unusable
// banding. The ITUR_2100 color space constants require
// macOS 11.0/iOS 14.0.
if matches!(
format,
wgt::TextureFormat::Rgba16Float | wgt::TextureFormat::Rgb10a2Unorm
) && available!(macos = 11.0, ios = 14.0, tvos = 14.0, visionos = 1.0)
{
color_spaces |=
wgt::SurfaceColorSpaces::BT2100_PQ | wgt::SurfaceColorSpaces::BT2100_HLG;
}
wgt::SurfaceFormatCapabilities {
format,
color_spaces,
}
};
let mut formats = vec![
wgt::TextureFormat::Bgra8Unorm,
wgt::TextureFormat::Bgra8UnormSrgb,
wgt::TextureFormat::Rgba16Float,
format_caps(wgt::TextureFormat::Bgra8Unorm),
format_caps(wgt::TextureFormat::Bgra8UnormSrgb),
format_caps(wgt::TextureFormat::Rgba16Float),
];
if self
.shared
.private_texture_format_caps
.format_rgb10a2_unorm_all
{
formats.push(wgt::TextureFormat::Rgb10a2Unorm);
formats.push(format_caps(wgt::TextureFormat::Rgb10a2Unorm));
}
Some(crate::SurfaceCapabilities {
+63 -29
View File
@@ -6,7 +6,8 @@ use objc2::{
runtime::ProtocolObject,
ClassType, Message,
};
use objc2_core_foundation::CGSize;
use objc2_core_foundation::{CFString, CGSize};
use objc2_core_graphics::CGColorSpace;
use objc2_foundation::NSObjectProtocol;
use objc2_metal::MTLTextureType;
use objc2_quartz_core::{CAMetalDrawable, CAMetalLayer};
@@ -14,6 +15,23 @@ use parking_lot::{Mutex, RwLock};
use super::OsFeatures;
/// Walks up from `start` to the `NSWindow` hosting this layer: the first ancestor
/// layer with a delegate is the backing `NSView`, and we return its `window`.
/// `None` if no ancestor has a delegate.
#[cfg(target_os = "macos")]
fn hosting_window(
start: Retained<objc2_quartz_core::CALayer>,
) -> Option<Retained<objc2::runtime::NSObject>> {
let mut current = Some(start);
while let Some(layer) = current {
if let Some(delegate) = layer.delegate() {
return unsafe { objc2::msg_send![&*delegate, window] };
}
current = layer.superlayer();
}
None
}
impl super::Surface {
pub fn new(layer: Retained<CAMetalLayer>) -> Self {
Self {
@@ -89,13 +107,47 @@ impl crate::Surface for super::Surface {
render_layer.setDevice(Some(device_raw));
render_layer.setPixelFormat(caps.map_format(config.format));
render_layer.setFramebufferOnly(framebuffer_only);
// opt-in to Metal EDR
// EDR potentially more power used in display and more bandwidth, memory footprint.
let wants_edr = config.format == wgt::TextureFormat::Rgba16Float;
// Opt into Metal EDR for the HDR color spaces (more display power, memory,
// and bandwidth). The HDR spaces are exactly those `is_hdr()` classifies.
let wants_edr = config.color_space.is_hdr();
if wants_edr != render_layer.wantsExtendedDynamicRangeContent() {
render_layer.setWantsExtendedDynamicRangeContent(wants_edr);
}
let colorspace_name: Option<&'static CFString> = match config.color_space {
wgt::SurfaceColorSpace::Auto => {
unreachable!("wgpu-core resolves `Auto` before configuring the surface")
}
// Reset to the layer's default, which treats contents as sRGB.
wgt::SurfaceColorSpace::Srgb => None,
wgt::SurfaceColorSpace::ExtendedSrgbLinear => {
Some(unsafe { objc2_core_graphics::kCGColorSpaceExtendedLinearSRGB })
}
wgt::SurfaceColorSpace::ExtendedSrgb => {
Some(unsafe { objc2_core_graphics::kCGColorSpaceExtendedSRGB })
}
wgt::SurfaceColorSpace::ExtendedDisplayP3 => {
Some(unsafe { objc2_core_graphics::kCGColorSpaceExtendedDisplayP3 })
}
wgt::SurfaceColorSpace::DisplayP3 => {
Some(unsafe { objc2_core_graphics::kCGColorSpaceDisplayP3 })
}
wgt::SurfaceColorSpace::Bt2100Pq | wgt::SurfaceColorSpace::Bt2100Hlg => {
// The ITUR_2100 color space constants require macOS 11.0/iOS 14.0;
// `surface_capabilities` only reports BT.2100 PQ/HLG on those OS versions.
if !available!(macos = 11.0, ios = 14.0, tvos = 14.0, visionos = 1.0) {
unreachable!("BT.2100 PQ/HLG color spaces are only reported on macOS 11.0+/iOS 14.0+/tvOS 14.0+");
}
Some(if config.color_space == wgt::SurfaceColorSpace::Bt2100Pq {
unsafe { objc2_core_graphics::kCGColorSpaceITUR_2100_PQ }
} else {
unsafe { objc2_core_graphics::kCGColorSpaceITUR_2100_HLG }
})
}
};
let colorspace = colorspace_name.and_then(|name| CGColorSpace::with_name(Some(name)));
render_layer.setColorspace(colorspace.as_deref());
// this gets ignored on iOS for certain OS/device combinations (iphone5s iOS 10.3)
render_layer.setMaximumDrawableCount(config.maximum_frame_latency as usize + 1);
render_layer.setDrawableSize(drawable_size);
@@ -128,33 +180,15 @@ impl crate::Surface for super::Surface {
// for vsync. Check the window's occlusion state and skip acquisition if
// the window is not visible - this avoids a 1-second hang in nextDrawable().
use objc2::rc::Retained;
use objc2::runtime::NSObject;
use objc2_quartz_core::CALayer;
// The CAMetalLayer is typically a sublayer, so we need to traverse up
// to find the root layer whose delegate is the NSView.
let mut current_layer: Option<Retained<CALayer>> =
Some(Retained::into_super(render_layer.clone()));
while let Some(layer) = current_layer {
if let Some(delegate) = layer.delegate() {
// Found a layer with a delegate - this should be the NSView
let window: Option<Retained<NSObject>> =
unsafe { objc2::msg_send![&*delegate, window] };
if let Some(window) = window {
const NS_WINDOW_OCCLUSION_STATE_VISIBLE: usize = 1 << 1;
let occlusion_state: usize =
unsafe { objc2::msg_send![&*window, occlusionState] };
let is_visible = (occlusion_state & NS_WINDOW_OCCLUSION_STATE_VISIBLE) != 0;
if !is_visible {
return Err(crate::SurfaceError::Occluded);
}
}
break;
// The CAMetalLayer is typically a sublayer; find the hosting window
// and skip acquisition while it is occluded.
if let Some(window) = hosting_window(Retained::into_super(render_layer.clone())) {
const NS_WINDOW_OCCLUSION_STATE_VISIBLE: usize = 1 << 1;
let occlusion_state: usize = unsafe { objc2::msg_send![&*window, occlusionState] };
if occlusion_state & NS_WINDOW_OCCLUSION_STATE_VISIBLE == 0 {
return Err(crate::SurfaceError::Occluded);
}
current_layer = layer.superlayer();
}
}
+96 -19
View File
@@ -158,31 +158,57 @@ impl super::PrivateCapabilities {
}
}
pub fn map_vk_surface_formats(sf: vk::SurfaceFormatKHR) -> Option<wgt::TextureFormat> {
pub fn map_vk_surface_formats(
sf: vk::SurfaceFormatKHR,
) -> Option<(wgt::TextureFormat, wgt::SurfaceColorSpace)> {
use ash::vk::Format as F;
use wgt::TextureFormat as Tf;
// List we care about pulled from https://vulkan.gpuinfo.org/listsurfaceformats.php.
// Device::create_swapchain() hardcodes linear scRGB for fp16, non-linear sRGB otherwise.
Some(match sf.color_space {
vk::ColorSpaceKHR::SRGB_NONLINEAR => match sf.format {
F::B8G8R8A8_UNORM => Tf::Bgra8Unorm,
F::B8G8R8A8_SRGB => Tf::Bgra8UnormSrgb,
F::R8G8B8A8_SNORM => Tf::Rgba8Snorm,
F::R8G8B8A8_UNORM => Tf::Rgba8Unorm,
F::R8G8B8A8_SRGB => Tf::Rgba8UnormSrgb,
F::R16G16B16A16_SNORM => Tf::Rgba16Snorm,
F::R16G16B16A16_UNORM => Tf::Rgba16Unorm,
F::A2B10G10R10_UNORM_PACK32 => Tf::Rgb10a2Unorm,
_ => return None,
},
vk::ColorSpaceKHR::EXTENDED_SRGB_LINEAR_EXT => match sf.format {
F::R16G16B16A16_SFLOAT => Tf::Rgba16Float,
_ => return None,
},
// Format list we care about pulled from https://vulkan.gpuinfo.org/listsurfaceformats.php.
let format = match sf.format {
F::B8G8R8A8_UNORM => Tf::Bgra8Unorm,
F::B8G8R8A8_SRGB => Tf::Bgra8UnormSrgb,
F::R8G8B8A8_SNORM => Tf::Rgba8Snorm,
F::R8G8B8A8_UNORM => Tf::Rgba8Unorm,
F::R8G8B8A8_SRGB => Tf::Rgba8UnormSrgb,
F::R16G16B16A16_SNORM => Tf::Rgba16Snorm,
F::R16G16B16A16_UNORM => Tf::Rgba16Unorm,
F::R16G16B16A16_SFLOAT => Tf::Rgba16Float,
F::A2B10G10R10_UNORM_PACK32 => Tf::Rgb10a2Unorm,
_ => return None,
};
let color_space = map_vk_color_space(sf.color_space)?;
Some((format, color_space))
}
pub fn map_vk_color_space(color_space: vk::ColorSpaceKHR) -> Option<wgt::SurfaceColorSpace> {
use wgt::SurfaceColorSpace as Scs;
Some(match color_space {
vk::ColorSpaceKHR::SRGB_NONLINEAR => Scs::Srgb,
vk::ColorSpaceKHR::EXTENDED_SRGB_LINEAR_EXT => Scs::ExtendedSrgbLinear,
vk::ColorSpaceKHR::EXTENDED_SRGB_NONLINEAR_EXT => Scs::ExtendedSrgb,
vk::ColorSpaceKHR::DISPLAY_P3_NONLINEAR_EXT => Scs::DisplayP3,
vk::ColorSpaceKHR::HDR10_ST2084_EXT => Scs::Bt2100Pq,
vk::ColorSpaceKHR::HDR10_HLG_EXT => Scs::Bt2100Hlg,
_ => return None,
})
}
pub fn map_surface_color_space(color_space: wgt::SurfaceColorSpace) -> vk::ColorSpaceKHR {
use wgt::SurfaceColorSpace as Scs;
match color_space {
Scs::Auto => unreachable!("wgpu-core resolves `Auto` before configuring the surface"),
Scs::Srgb => vk::ColorSpaceKHR::SRGB_NONLINEAR,
Scs::ExtendedSrgbLinear => vk::ColorSpaceKHR::EXTENDED_SRGB_LINEAR_EXT,
Scs::ExtendedSrgb => vk::ColorSpaceKHR::EXTENDED_SRGB_NONLINEAR_EXT,
Scs::DisplayP3 => vk::ColorSpaceKHR::DISPLAY_P3_NONLINEAR_EXT,
Scs::Bt2100Pq => vk::ColorSpaceKHR::HDR10_ST2084_EXT,
Scs::Bt2100Hlg => vk::ColorSpaceKHR::HDR10_HLG_EXT,
Scs::ExtendedDisplayP3 => {
unreachable!("`ExtendedDisplayP3` is never reported in the Vulkan surface capabilities")
}
}
}
impl crate::Attachment<'_, super::TextureView> {
pub(super) fn make_attachment_key(&self, ops: crate::AttachmentOps) -> super::AttachmentKey {
super::AttachmentKey {
@@ -1057,3 +1083,54 @@ pub fn map_acceleration_structure_usage_to_barrier(
(stages, access)
}
#[cfg(test)]
mod tests {
use super::*;
/// `map_vk_color_space` and `map_surface_color_space` must stay mutually
/// inverse so that a color space reported in the surface capabilities is
/// exactly what the swapchain is created with.
#[test]
fn color_space_round_trip() {
for vk_color_space in [
vk::ColorSpaceKHR::SRGB_NONLINEAR,
vk::ColorSpaceKHR::EXTENDED_SRGB_LINEAR_EXT,
vk::ColorSpaceKHR::EXTENDED_SRGB_NONLINEAR_EXT,
vk::ColorSpaceKHR::DISPLAY_P3_NONLINEAR_EXT,
vk::ColorSpaceKHR::HDR10_ST2084_EXT,
vk::ColorSpaceKHR::HDR10_HLG_EXT,
] {
let mapped = map_vk_color_space(vk_color_space).unwrap();
assert_eq!(map_surface_color_space(mapped), vk_color_space);
}
}
#[test]
fn unknown_color_spaces_are_dropped() {
for vk_color_space in [
vk::ColorSpaceKHR::BT2020_LINEAR_EXT,
vk::ColorSpaceKHR::DOLBYVISION_EXT,
vk::ColorSpaceKHR::PASS_THROUGH_EXT,
vk::ColorSpaceKHR::ADOBERGB_NONLINEAR_EXT,
] {
assert!(map_vk_color_space(vk_color_space).is_none());
assert!(map_vk_surface_formats(vk::SurfaceFormatKHR {
format: vk::Format::B8G8R8A8_UNORM,
color_space: vk_color_space,
})
.is_none());
}
}
#[test]
fn hdr10_surface_format_maps() {
let (format, color_space) = map_vk_surface_formats(vk::SurfaceFormatKHR {
format: vk::Format::A2B10G10R10_UNORM_PACK32,
color_space: vk::ColorSpaceKHR::HDR10_ST2084_EXT,
})
.unwrap();
assert_eq!(format, wgt::TextureFormat::Rgb10a2Unorm);
assert_eq!(color_space, wgt::SurfaceColorSpace::Bt2100Pq);
}
}
+15 -9
View File
@@ -132,10 +132,22 @@ impl Surface for NativeSurface {
}
};
let formats = raw_surface_formats
// Group the driver's (format, color space) pairs into one entry per
// format, preserving the driver's format order.
let mut formats: Vec<wgt::SurfaceFormatCapabilities> = Vec::new();
for (format, color_space) in raw_surface_formats
.into_iter()
.filter_map(conv::map_vk_surface_formats)
.collect();
{
let color_spaces = color_space.to_color_spaces().unwrap();
match formats.iter_mut().find(|fc| fc.format == format) {
Some(fc) => fc.color_spaces |= color_spaces,
None => formats.push(wgt::SurfaceFormatCapabilities {
format,
color_spaces,
}),
}
}
Some(crate::SurfaceCapabilities {
formats,
// TODO: Right now we're always truncating the swap chain
@@ -167,13 +179,7 @@ impl Surface for NativeSurface {
.map(|osc| osc.as_any().downcast_ref::<NativeSwapchain>().unwrap().raw)
.unwrap_or(vk::SwapchainKHR::null());
let color_space = if config.format == wgt::TextureFormat::Rgba16Float {
// Enable wide color gamut mode
// Vulkan swapchain for Android only supports DISPLAY_P3_NONLINEAR_EXT and EXTENDED_SRGB_LINEAR_EXT
vk::ColorSpaceKHR::EXTENDED_SRGB_LINEAR_EXT
} else {
vk::ColorSpaceKHR::SRGB_NONLINEAR
};
let color_space = conv::map_surface_color_space(config.color_space);
let original_format = device.shared.private_caps.map_texture_format(config.format);
let mut raw_flags = vk::SwapchainCreateFlagsKHR::empty();
+16
View File
@@ -0,0 +1,16 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 460 452" width="460" height="452" font-family="sans-serif"><title>CIE 1931 chromaticity diagram with sRGB, Display-P3 and BT.2020 gamut triangles</title><desc>The red, green and blue primaries of sRGB/BT.709, Display-P3 and BT.2020 plotted as nested triangles inside the CIE 1931 spectral locus, sharing the D65 white point. A wider triangle can express more colors.</desc>
<style>.ax{stroke:#888;stroke-width:1;fill:none}.lbl{fill:#888;font-size:13px}.tick{fill:#888;font-size:10px}.gname{font-size:13px;font-weight:bold}</style>
<line class="ax" x1="58.0" y1="410.0" x2="440.0" y2="410.0"/><line class="ax" x1="58.0" y1="410.0" x2="58.0" y2="30.0"/>
<line class="ax" x1="58.0" y1="410.0" x2="58.0" y2="414.0"/><text class="tick" x="58.0" y="425.0" text-anchor="middle">0</text><line class="ax" x1="159.9" y1="410.0" x2="159.9" y2="414.0"/><text class="tick" x="159.9" y="425.0" text-anchor="middle">0.2</text><line class="ax" x1="261.7" y1="410.0" x2="261.7" y2="414.0"/><text class="tick" x="261.7" y="425.0" text-anchor="middle">0.4</text><line class="ax" x1="363.6" y1="410.0" x2="363.6" y2="414.0"/><text class="tick" x="363.6" y="425.0" text-anchor="middle">0.6</text><line class="ax" x1="54.0" y1="410.0" x2="58.0" y2="410.0"/><text class="tick" x="51.0" y="413.0" text-anchor="end">0</text><line class="ax" x1="54.0" y1="320.6" x2="58.0" y2="320.6"/><text class="tick" x="51.0" y="323.6" text-anchor="end">0.2</text><line class="ax" x1="54.0" y1="231.2" x2="58.0" y2="231.2"/><text class="tick" x="51.0" y="234.2" text-anchor="end">0.4</text><line class="ax" x1="54.0" y1="141.8" x2="58.0" y2="141.8"/><text class="tick" x="51.0" y="144.8" text-anchor="end">0.6</text><line class="ax" x1="54.0" y1="52.4" x2="58.0" y2="52.4"/><text class="tick" x="51.0" y="55.4" text-anchor="end">0.8</text>
<text class="lbl" x="249" y="440.0" text-anchor="middle">CIE x</text>
<text class="lbl" x="20" y="220" text-anchor="middle" transform="rotate(-90 20 220)">CIE y</text>
<polygon points="146.7,407.8 146.5,407.8 146.3,407.9 145.9,407.9 145.3,407.7 144.0,406.9 141.7,405.1 137.8,402.1 131.3,396.7 121.2,384.2 104.5,350.7 81.1,278.1 62.2,169.3 65.1,74.6 95.8,37.2 136.8,49.7 174.9,72.8 211.6,100.5 248.0,130.8 284.2,162.0 319.0,192.5 351.0,220.4 377.4,243.5 397.1,260.7 410.2,272.2 418.6,279.5 424.2,284.4 427.8,287.5 429.8,289.3 430.8,290.2 431.5,290.8 432.2,291.4" fill="#9999991f" stroke="#9a9a9a" stroke-width="1"/>
<polygon points="418.6,279.5 144.6,53.7 124.7,389.4" fill="#5b7bff14" stroke="#6f8cff" stroke-width="1.6" stroke-dasharray="5 3"/>
<polygon points="404.3,266.9 193.0,101.5 134.4,383.2" fill="#23a86620" stroke="#23a866" stroke-width="1.6" stroke-dasharray="2 2"/>
<polygon points="384.0,262.5 210.8,141.8 134.4,383.2" fill="#ff444418" stroke="#ee5555" stroke-width="1.8"/>
<circle cx="217.3" cy="262.9" r="3.2" fill="#888"/>
<text class="tick" x="224.3" y="265.9" fill="#aaa">D65</text>
<text class="gname" x="225" y="230" fill="#ee5555">sRGB / BT.709</text>
<text class="gname" x="210.8" y="88.1" fill="#23a866">Display-P3</text>
<text class="gname" x="147.1" y="45.6" fill="#6f8cff">BT.2020</text>
</svg>

After

Width:  |  Height:  |  Size: 3.1 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 540 170" width="540" height="170" font-family="sans-serif"><title>SDR vs HDR value range number line</title><desc>A number line: 0.0 black, 0 to 1 is the SDR range, 1.0 is SDR reference white, values above 1.0 are HDR headroom up to the display's peak.</desc><style>.t{font-size:12px;fill:#888}.tb{font-size:12px;fill:#888;font-weight:bold}.cap{font-size:11px;fill:#888}.ax{stroke:#888;stroke-width:1.5}</style><!-- SDR band 0..1 : x 50..300 ; HDR band 1..peak : x 300..500 --><defs><linearGradient id="sdr" x1="0" x2="1"><stop offset="0" stop-color="#111"/><stop offset="1" stop-color="#dddddd"/></linearGradient><linearGradient id="hdr" x1="0" x2="1"><stop offset="0" stop-color="#dddddd"/><stop offset="1" stop-color="#ffffff"/></linearGradient></defs><!-- SDR band --><rect x="50" y="50" width="250" height="34" fill="url(#sdr)" stroke="#888" stroke-width="1"/><!-- HDR band (outlined, brighter-than-white headroom) --><rect x="300" y="50" width="200" height="34" fill="url(#hdr)" stroke="#888" stroke-width="1" stroke-dasharray="5 3"/><!-- baseline + ticks --><line class="ax" x1="50" y1="96" x2="500" y2="96"/><g><line class="ax" x1="50" y1="90" x2="50" y2="102"/><line class="ax" x1="300" y1="88" x2="300" y2="104"/><line class="ax" x1="500" y1="90" x2="500" y2="102"/></g><text class="t" x="50" y="120" text-anchor="middle">0.0</text><text class="tb" x="300" y="120" text-anchor="middle">1.0</text><text class="t" x="500" y="120" text-anchor="middle">peak</text><!-- region labels --><text class="t" x="175" y="40" text-anchor="middle">SDR range</text><text class="t" x="400" y="40" text-anchor="middle">HDR headroom (&gt; 1.0)</text><!-- callouts --><text class="t" x="50" y="137" text-anchor="middle">black</text><text class="t" x="300" y="137" text-anchor="middle">SDR reference white</text><text class="t" x="500" y="137" text-anchor="middle">display peak</text><text class="cap" x="50" y="160">SDR clamps at 1.0. HDR drives values above 1.0, up to the display's headroom.</text></svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

+408
View File
@@ -1,3 +1,9 @@
//! Surface presentation configuration: present modes, alpha compositing, and
//! color-space types (HDR and wide-gamut output).
//!
//! This module is re-exported flatly from `wgpu-types`; the user-facing color
//! space and HDR primer lives in the `wgpu` crate's top-level docs.
use alloc::{vec, vec::Vec};
use crate::{link_to_wgpu_docs, link_to_wgpu_item, TextureFormat, TextureUsages};
@@ -131,13 +137,387 @@ pub enum CompositeAlphaMode {
Inherit = 4,
}
/// The color space in which the presentation engine interprets the values
/// written to a surface texture.
///
/// A color space defines the *primaries*, *white point*, and *transfer
/// function* of the output signal (see the Terminology section below),
/// following the same convention as [CSS predefined color spaces] and
/// [`VkColorSpaceKHR`].
/// It does **not** change the texel format of the surface; it changes how the
/// compositor / display pipeline interprets those texels.
///
/// Support is queried via [`SurfaceCapabilities`], which reports a set of
/// [`SurfaceColorSpaces`] for every supported texture format. Selecting a
/// color space other than [`Srgb`](Self::Srgb) is how an application opts a
/// surface into high-dynamic-range (HDR) or wide-color-gamut output on
/// platforms that support it.
///
/// New to HDR? The `wgpu` crate's top-level docs include a [color space and HDR
/// primer] covering the concepts and the steps to get HDR output on screen.
///
/// # Terminology
///
/// Each variant is described by four properties:
///
/// * **Primaries** (the *gamut*): the chromaticities of the red, green, and
/// blue that color values address, and so the range of colors that can be
/// expressed. [BT.709] (the sRGB / HDTV primaries) is the standard-gamut set;
/// [Display P3] and [BT.2020] are progressively wider.
/// * **White point**: the chromaticity produced by equal red, green, and blue.
/// Every color space here uses [D65], the standard daylight white.
/// * **Transfer function** (the *OETF*): how stored values map to light, such
/// as the [sRGB] transfer function, a linear transfer, or an HDR transfer
/// function like [PQ] or [HLG]. Your shader applies this encoding transfer
/// function; the display applies the inverse (the *EOTF*). Except for writes
/// to an `*Srgb` texture format (where the hardware applies the sRGB encoding
/// for you), wgpu does **not** encode for you: the values your shader writes
/// to the surface texture must already be in whatever encoding the chosen
/// color space expects (linear for a linear transfer). The [HDR surface
/// example] shows the encoder each variant expects.
/// * **Dynamic range**: standard dynamic range (SDR), where `1.0` is reference
/// (SDR) white and values outside 0.0..=1.0 are clamped, or high dynamic
/// range (HDR), where `(1.0, 1.0, 1.0)` is SDR reference white and values
/// above `1.0` drive brighter-than-SDR output on HDR displays.
///
#[doc = include_str!("color_gamuts.svg")]
///
/// *The primaries of each color space form a triangle on the CIE 1931
/// chromaticity diagram; colors inside it are expressible, colors outside are
/// not. [`Srgb`](Self::Srgb) uses the [BT.709] gamut;
/// [`DisplayP3`](Self::DisplayP3) and [`Bt2100Pq`](Self::Bt2100Pq)'s [BT.2020]
/// are progressively wider. All share the [D65] white point.*
///
#[doc = include_str!("sdr_hdr_range.svg")]
///
/// *`0.0` is black and `1.0` is SDR reference white. [`Srgb`](Self::Srgb) and
/// [`DisplayP3`](Self::DisplayP3) clamp above `1.0`; the extended-range and HDR
/// color spaces drive values above `1.0` as brighter-than-SDR output, up to the
/// display's headroom.*
///
/// # Extended-range variants: linear vs encoded
///
/// The extended-range color spaces come in two forms that share a range but
/// differ in transfer: [`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear) carries
/// a **linear** signal, while [`ExtendedSrgb`](Self::ExtendedSrgb) and
/// [`ExtendedDisplayP3`](Self::ExtendedDisplayP3) carry the **sRGB-encoded**
/// (gamma) signal: the sRGB transfer function is applied as usual and then
/// continued to values above `1.0` (brighter than SDR white) and below `0.0`
/// (colors outside the base gamut). Pick by whether the values your shader
/// writes to the surface texture are linear or encoded; confusing the two is the
/// most common HDR setup mistake.
///
/// # Web (WebGPU) backend
///
/// Browsers do not expose these named color spaces directly. A WebGPU canvas is
/// configured with a [`colorSpace`] (only `"srgb"` or `"display-p3"`) plus a
/// separate [`toneMapping`] mode (`"standard"` or `"extended"`), so on the web
/// wgpu offers only the combinations that pair can produce: [`Srgb`](Self::Srgb)
/// and [`DisplayP3`](Self::DisplayP3) with standard tone mapping, plus their
/// extended-range HDR forms [`ExtendedSrgb`](Self::ExtendedSrgb) and
/// [`ExtendedDisplayP3`](Self::ExtendedDisplayP3) with extended tone mapping.
/// There is no linear-transfer canvas color space, so
/// [`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear) (scRGB) is native-only, and
/// [`Bt2100Pq`](Self::Bt2100Pq) and [`Bt2100Hlg`](Self::Bt2100Hlg) are
/// unavailable (browsers expose no PQ or HLG canvas signaling).
///
/// [CSS predefined color spaces]: https://www.w3.org/TR/css-color-4/#predefined
/// [`VkColorSpaceKHR`]: https://registry.khronos.org/vulkan/specs/latest/man/html/VkColorSpaceKHR.html
///
/// [BT.709]: https://www.itu.int/rec/R-REC-BT.709
/// [BT.2020]: https://www.itu.int/rec/R-REC-BT.2020
/// [Display P3]: https://en.wikipedia.org/wiki/DCI-P3#Display_P3
/// [D65]: https://en.wikipedia.org/wiki/Standard_illuminant#D65_values
/// [sRGB]: https://registry.color.org/rgb-registry/srgb
/// [PQ]: https://en.wikipedia.org/wiki/Perceptual_quantizer
/// [HLG]: https://www.itu.int/rec/R-REC-BT.2100
/// [HDR surface example]: https://github.com/gfx-rs/wgpu/tree/trunk/examples/standalone/03_hdr_surface
///
/// [`colorSpace`]: https://www.w3.org/TR/webgpu/#dom-gpucanvasconfiguration-colorspace
/// [`toneMapping`]: https://www.w3.org/TR/webgpu/#gpucanvastonemappingmode
#[doc = link_to_wgpu_docs!(["color space and HDR primer"]: "index.html#surface-color-spaces-and-hdr-output")]
#[repr(C)]
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum SurfaceColorSpace {
/// Let the backend choose a color space, reproducing wgpu's historical
/// behavior:
///
/// * [`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear) if the format is
/// [`TextureFormat::Rgba16Float`] and the surface supports it for that
/// format,
/// * otherwise [`Srgb`](Self::Srgb), if the surface supports it for the
/// format.
///
/// Apart from the linear [`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear)
/// above (which fp16 surfaces have historically used and which needs no
/// extra encoding), `Auto` never resolves to a wide-gamut or HDR color
/// space, since those would change how the application must encode its
/// output. If a format is only available in such color spaces (which some
/// drivers report when the OS is in HDR mode), configuring it with `Auto`
/// fails validation; such formats are listed in
/// [`SurfaceCapabilities::format_capabilities`] but excluded from
/// [`SurfaceCapabilities::formats`].
///
/// On the browser WebGPU backend, `Auto` always keeps the canvas
/// defaults (sRGB with standard tone mapping), even for
/// [`TextureFormat::Rgba16Float`]; request
/// [`ExtendedSrgb`](Self::ExtendedSrgb) explicitly for HDR canvas output
/// ([`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear) is native-only).
#[default]
Auto = 0,
/// The sRGB color space: BT.709 primaries, D65 white point, sRGB transfer
/// function, standard dynamic range.
///
/// Values outside of 0.0..=1.0 (after format encoding) are clamped by
/// the display pipeline.
///
/// This is what every backend produces today for non-`Rgba16Float`
/// formats and is supported everywhere.
///
/// Note that the transfer function is applied by the *format*, not this
/// color space choice: an `*Srgb` format applies sRGB encoding on write,
/// while writes to a non-`*Srgb` format are interpreted as already
/// sRGB-encoded.
Srgb = 1,
/// Extended linear sRGB, also known as [scRGB] (the **linear** encoding of
/// IEC 61966-2-2): BT.709 primaries, D65 white point, **linear** transfer
/// function, extended dynamic range. Typically used with
/// [`TextureFormat::Rgba16Float`].
///
/// The linear counterpart to the sRGB-encoded
/// [`ExtendedSrgb`](Self::ExtendedSrgb) (IEC 61966-2-2 defines both); pick
/// this one if the values your shader writes to the surface texture are
/// **linear**.
///
/// This corresponds to Vulkan's `VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT`,
/// Metal's extended dynamic range (EDR), and DXGI's
/// `DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709`.
///
/// * **Supported on**: native only (Vulkan, Metal, DX12). Not available on
/// the browser WebGPU backend, which cannot express a linear-transfer
/// canvas color space; use [`ExtendedSrgb`](Self::ExtendedSrgb) for HDR
/// canvas output on the web.
/// * **Also known as**: scRGB.
///
/// [scRGB]: https://en.wikipedia.org/wiki/ScRGB
ExtendedSrgbLinear = 2,
/// The [Display P3] color space: P3 primaries, D65 white point, sRGB
/// transfer function, standard dynamic range.
///
/// A wide-gamut SDR color space covering roughly 25% more area than sRGB in
/// the CIE chromaticity diagram. It uses the wide P3 primaries of theatrical
/// DCI-P3, but with the D65 white point and the sRGB transfer function (not
/// DCI's white point and 2.6 gamma).
///
/// Like [`Srgb`](Self::Srgb), this is standard dynamic range (values outside
/// 0.0..=1.0 are clamped). For wide-gamut HDR that keeps the P3 primaries
/// but extends the range, use [`ExtendedDisplayP3`](Self::ExtendedDisplayP3).
///
/// * **Supported on**: Vulkan (where the driver exposes it), Metal, and the
/// browser WebGPU backend (canvas color space `"display-p3"`). Not
/// reported on DX12.
///
/// [Display P3]: https://en.wikipedia.org/wiki/DCI-P3#Display_P3
DisplayP3 = 3,
/// BT.2100 perceptual quantization (HDR10): BT.2020/2100 primaries, D65 white
/// point, SMPTE ST 2084 perceptual quantizer ([PQ]) transfer function, high
/// dynamic range.
///
/// Texel values are interpreted as a PQ-encoded signal whose encoded range,
/// `0.0..=1.0`, maps to absolute luminance from 0 to 10,000 nits. The values
/// your shader writes to the surface texture must already be in the BT.2020
/// gamut and PQ-encoded into that `0.0..=1.0` range; the [HDR surface example]
/// shows how. The format is non-sRGB, typically
/// [`TextureFormat::Rgb10a2Unorm`].
///
/// Commonly known as **HDR10** — though that term additionally implies static
/// ST 2086 / MaxCLL mastering metadata, which wgpu does not set; this
/// configures only the PQ color space.
///
/// * **Supported on**: Vulkan (where the driver exposes it), DX12 (on
/// `Rgb10a2Unorm`), and Metal. Unavailable on the browser WebGPU backend
/// (no PQ canvas signaling).
///
/// [PQ]: https://en.wikipedia.org/wiki/Perceptual_quantizer
/// [HDR surface example]: https://github.com/gfx-rs/wgpu/tree/trunk/examples/standalone/03_hdr_surface
Bt2100Pq = 4,
/// BT.2100 hybrid log-gamma: BT.2020/2100 primaries, D65 white point, [HLG]
/// (ARIB STD-B67) transfer function, high dynamic range.
///
/// A relative-luminance HDR signal, primarily used for broadcast content. The
/// values your shader writes to the surface texture must already be in the
/// BT.2020 gamut and HLG-encoded into `0.0..=1.0`; the [HDR surface example]
/// shows how. The format is non-sRGB, typically
/// [`TextureFormat::Rgb10a2Unorm`].
///
/// Unlike [`Bt2100Pq`](Self::Bt2100Pq)'s PQ, the HLG signal is *relative*:
/// `1.0` maps to the display's nominal peak luminance rather than a fixed
/// absolute level. BT.2100 defines its reference OOTF at a nominal peak of
/// 1000 cd/m² (system gamma 1.2); the [HDR surface example] normalizes its
/// absolute-nit test pattern onto that 1000-nit nominal peak.
///
/// * **Supported on**: Vulkan (where the driver exposes it) and Metal.
/// Unavailable on DX12 and the browser WebGPU backend (no HLG canvas
/// signaling).
///
/// [HLG]: https://www.itu.int/rec/R-REC-BT.2100
/// [HDR surface example]: https://github.com/gfx-rs/wgpu/tree/trunk/examples/standalone/03_hdr_surface
Bt2100Hlg = 5,
/// Extended-range sRGB (encoded): BT.709 primaries, D65 white point, the
/// **nonlinear sRGB transfer function extended beyond 0.0..=1.0**,
/// extended dynamic range.
///
/// The sRGB-encoded sibling of
/// [`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear): the signal is
/// sRGB-*encoded* (gamma), not linear. Typically used with
/// [`TextureFormat::Rgba16Float`].
///
/// If the values your shader writes to the surface texture are **linear**,
/// you want [`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear) (scRGB) instead;
/// confusing the two is the most common HDR setup mistake. See the [HDR
/// surface example] for the encoder.
///
/// This is the "encoded extended range" sRGB used by browser WebGPU (canvas
/// color space `"srgb"` with `"extended"` tone mapping). It corresponds to
/// Vulkan's `VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT` and Metal's
/// `kCGColorSpaceExtendedSRGB`.
///
/// * **Supported on**: Vulkan (where the driver exposes it), Metal, and the
/// browser WebGPU backend. Not available on DX12, which has no
/// encoded-extended-sRGB swapchain color space.
///
/// [HDR surface example]: https://github.com/gfx-rs/wgpu/tree/trunk/examples/standalone/03_hdr_surface
ExtendedSrgb = 6,
/// Extended-range Display-P3 (encoded): P3 primaries, D65 white point, the
/// **nonlinear sRGB transfer function extended beyond 0.0..=1.0**,
/// extended dynamic range.
///
/// The wide-gamut (P3) analogue of [`ExtendedSrgb`](Self::ExtendedSrgb), and
/// the HDR counterpart to the SDR-only [`DisplayP3`](Self::DisplayP3): it
/// keeps the P3 primaries but extends the encoded range for HDR. Like
/// [`ExtendedSrgb`](Self::ExtendedSrgb) the signal is sRGB-*encoded* (gamma),
/// not linear. Typically used with [`TextureFormat::Rgba16Float`].
///
/// * **Supported on**: Metal and the browser WebGPU backend (canvas color
/// space `"display-p3"` with `"extended"` tone mapping; Metal's
/// `kCGColorSpaceExtendedDisplayP3`). Not available on Vulkan or DX12,
/// neither of which has an encoded-extended-Display-P3 swapchain color
/// space.
ExtendedDisplayP3 = 7,
}
impl SurfaceColorSpace {
/// Returns the [`SurfaceColorSpaces`] flag set holding just this color space,
/// or `None` for [`Auto`](Self::Auto) (which maps to no specific flag).
#[must_use]
pub fn to_color_spaces(self) -> Option<SurfaceColorSpaces> {
match self {
Self::Auto => None,
Self::Srgb => Some(SurfaceColorSpaces::SRGB),
Self::ExtendedSrgbLinear => Some(SurfaceColorSpaces::EXTENDED_SRGB_LINEAR),
Self::DisplayP3 => Some(SurfaceColorSpaces::DISPLAY_P3),
Self::Bt2100Pq => Some(SurfaceColorSpaces::BT2100_PQ),
Self::Bt2100Hlg => Some(SurfaceColorSpaces::BT2100_HLG),
Self::ExtendedSrgb => Some(SurfaceColorSpaces::EXTENDED_SRGB),
Self::ExtendedDisplayP3 => Some(SurfaceColorSpaces::EXTENDED_DISPLAY_P3),
}
}
/// Whether this is a high-dynamic-range color space: one that drives values
/// above SDR white (`1.0`) as brighter-than-white output.
///
/// `true` for the extended-range and PQ/HLG spaces; `false` for the SDR ones
/// ([`Srgb`](Self::Srgb) and the wide-gamut-but-SDR
/// [`DisplayP3`](Self::DisplayP3)). [`Auto`](Self::Auto) is `false`: it defers
/// to the backend and is the SDR-safe default, so check the resolved color
/// space if you need certainty.
///
/// Use this to branch after picking a color space from
/// [`SurfaceCapabilities`]: only an HDR result drives highlights above SDR
/// white (`1.0`).
#[must_use]
pub fn is_hdr(self) -> bool {
match self {
Self::ExtendedSrgbLinear
| Self::ExtendedSrgb
| Self::ExtendedDisplayP3
| Self::Bt2100Pq
| Self::Bt2100Hlg => true,
Self::Auto | Self::Srgb | Self::DisplayP3 => false,
}
}
}
bitflags::bitflags! {
/// A set of [`SurfaceColorSpace`]s supported by a surface for a particular
/// texture format.
///
/// Reported per format in [`SurfaceCapabilities::formats`] via
/// [`SurfaceFormatCapabilities`].
#[repr(transparent)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct SurfaceColorSpaces: u32 {
/// [`SurfaceColorSpace::Srgb`] is supported.
const SRGB = 1 << 0;
/// [`SurfaceColorSpace::ExtendedSrgbLinear`] is supported.
const EXTENDED_SRGB_LINEAR = 1 << 1;
/// [`SurfaceColorSpace::DisplayP3`] is supported.
const DISPLAY_P3 = 1 << 2;
/// [`SurfaceColorSpace::Bt2100Pq`] is supported.
const BT2100_PQ = 1 << 3;
/// [`SurfaceColorSpace::Bt2100Hlg`] is supported.
const BT2100_HLG = 1 << 4;
/// [`SurfaceColorSpace::ExtendedSrgb`] is supported.
const EXTENDED_SRGB = 1 << 5;
/// [`SurfaceColorSpace::ExtendedDisplayP3`] is supported.
const EXTENDED_DISPLAY_P3 = 1 << 6;
}
}
/// A texture format supported by a surface, together with the color spaces
/// in which the surface can present it.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SurfaceFormatCapabilities {
/// The texture format.
pub format: TextureFormat,
/// The set of color spaces the surface supports for this format.
///
/// This reports which color spaces the surface can be *configured* with; it
/// does not reflect whether the display is currently in HDR mode.
///
/// Guaranteed to be non-empty.
pub color_spaces: SurfaceColorSpaces,
}
/// Defines the capabilities of a given surface and adapter.
#[derive(Debug)]
pub struct SurfaceCapabilities {
/// List of supported formats to use with the given adapter. The first format in the vector is preferred.
///
/// Only contains formats that can be configured with the default
/// [`SurfaceColorSpace::Auto`]; formats available exclusively in
/// explicit-opt-in (wide-gamut / HDR) color spaces appear only in
/// [`format_capabilities`](Self::format_capabilities).
///
/// Returns an empty vector if the surface is incompatible with the adapter.
pub formats: Vec<TextureFormat>,
/// List of supported formats together with the color spaces supported for
/// each format, in the same preference order as
/// [`formats`](Self::formats), of which it is a superset.
///
/// Returns an empty vector if the surface is incompatible with the adapter.
pub format_capabilities: Vec<SurfaceFormatCapabilities>,
/// List of supported presentation modes to use with the given adapter.
///
/// Returns an empty vector if the surface is incompatible with the adapter.
@@ -152,10 +532,27 @@ pub struct SurfaceCapabilities {
pub usages: TextureUsages,
}
impl SurfaceCapabilities {
/// Returns the set of color spaces supported for the given format, or an
/// empty set if the format is not supported.
///
/// This is a convenience lookup over
/// [`format_capabilities`](Self::format_capabilities): an empty result
/// means `format` is absent from that list.
#[must_use]
pub fn color_spaces(&self, format: TextureFormat) -> SurfaceColorSpaces {
self.format_capabilities
.iter()
.filter(|fc| fc.format == format)
.fold(SurfaceColorSpaces::empty(), |acc, fc| acc | fc.color_spaces)
}
}
impl Default for SurfaceCapabilities {
fn default() -> Self {
Self {
formats: Vec::new(),
format_capabilities: Vec::new(),
present_modes: Vec::new(),
alpha_modes: vec![CompositeAlphaMode::Opaque],
usages: TextureUsages::RENDER_ATTACHMENT,
@@ -175,6 +572,16 @@ pub struct SurfaceConfiguration<V> {
/// The texture format of the swap chain. The only formats that are guaranteed are
/// [`TextureFormat::Bgra8Unorm`] and [`TextureFormat::Bgra8UnormSrgb`].
pub format: TextureFormat,
/// The color space in which the presentation engine interprets the values
/// written to the swap chain.
///
/// The supported color spaces for each format are listed in
/// [`SurfaceCapabilities::format_capabilities`].
/// [`SurfaceColorSpace::Auto`] (the default) is supported for every
/// format in [`SurfaceCapabilities::formats`]; any other value must be
/// present in the format's
/// [`color_spaces`](SurfaceFormatCapabilities::color_spaces) set.
pub color_space: SurfaceColorSpace,
/// Width of the swap chain. Must be the same size as the surface, and nonzero.
///
/// If this is not the same size as the underlying surface (e.g. if it is
@@ -248,6 +655,7 @@ impl<V: Clone> SurfaceConfiguration<V> {
SurfaceConfiguration {
usage: self.usage,
format: self.format,
color_space: self.color_space,
width: self.width,
height: self.height,
present_mode: self.present_mode,
+13
View File
@@ -58,6 +58,11 @@ impl Surface<'_> {
/// Return a default `SurfaceConfiguration` from width and height to use for the [`Surface`] with this adapter.
///
/// The returned configuration requests the surface's preferred format and
/// [`SurfaceColorSpace::Auto`], reproducing wgpu's historical SDR / standard
/// behavior. Set the `color_space` field to opt into wide-gamut or HDR
/// output; see [`SurfaceColorSpace`] for what each color space means.
///
/// Returns None if the surface isn't supported by this adapter
pub fn get_default_config(
&self,
@@ -69,6 +74,7 @@ impl Surface<'_> {
Some(SurfaceConfiguration {
usage: wgt::TextureUsages::RENDER_ATTACHMENT,
format: *caps.formats.first()?,
color_space: wgt::SurfaceColorSpace::Auto,
width,
height,
desired_maximum_frame_latency: 2,
@@ -91,6 +97,8 @@ impl Surface<'_> {
///
/// - An old [`SurfaceTexture`] is still alive referencing an old surface.
/// - Texture format requested is unsupported on the surface.
/// - The requested color space is unsupported for the requested format
/// (see [`SurfaceCapabilities::format_capabilities`]).
/// - `config.width` or `config.height` is zero.
pub fn configure(&self, device: &Device, config: &SurfaceConfiguration) {
self.inner.configure(&device.inner, config);
@@ -102,6 +110,11 @@ impl Surface<'_> {
/// Returns the current configuration of [`Surface`], if configured.
///
/// This is similar to [WebGPU `GPUcCanvasContext::getConfiguration`](https://gpuweb.github.io/gpuweb/#dom-gpucanvascontext-getconfiguration).
///
/// Note that this returns the configuration as passed to
/// [`Surface::configure`]: automatic values such as
/// [`SurfaceColorSpace::Auto`] are returned as-is, not as the concrete
/// values they resolved to.
pub fn get_configuration(&self) -> Option<SurfaceConfiguration> {
self.config.lock().clone()
}
+230 -7
View File
@@ -20,6 +20,7 @@ use core::{
future::Future,
ops::Range,
pin::Pin,
sync::atomic::{AtomicU8, Ordering},
task::{self, Poll},
};
use wgt::Backends;
@@ -1001,6 +1002,12 @@ fn future_request_device(
.map(|device| {
let queue = device.queue();
// A `GPUDevice` is the first point at which we can empirically probe
// which canvas formats this browser actually supports (see
// `probe_rgba16float_canvas_support`). Run it once here so that
// `Surface::get_capabilities` can report `Rgba16Float` truthfully.
rgba16float_probe::probe_rgba16float_canvas_support(&device);
(
WebDevice {
inner: device,
@@ -1156,6 +1163,7 @@ impl ContextWebGpu {
gpu: self.gpu.clone(),
context,
canvas,
configure_failed: Cell::new(false),
ident: crate::cmp::Identifier::create(),
}
.into())
@@ -1442,6 +1450,15 @@ pub struct WebSurface {
gpu: Option<DefinedNonNullJsValue<webgpu_sys::Gpu>>,
canvas: Canvas,
context: webgpu_sys::GpuCanvasContext,
/// Set when the most recent [`configure`](Self::configure) call failed, e.g.
/// because the browser rejected the requested canvas format. While set,
/// `get_current_texture` reports [`SurfaceStatus::Lost`] instead of letting
/// the JS exception turn into a panic — there is no `catch_unwind` on wasm,
/// so a panic would be an uncatchable abort the application cannot recover
/// from.
///
/// [`SurfaceStatus::Lost`]: crate::SurfaceStatus::Lost
configure_failed: Cell<bool>,
/// Unique identifier for this Surface.
ident: crate::cmp::Identifier,
}
@@ -3922,13 +3939,93 @@ impl Drop for WebRenderBundle {
}
}
/// Probing and caching of whether this browser can configure an `rgba16float`
/// WebGPU canvas. Only the reader functions are visible outside this module; the
/// cached state and the probe machinery are private to it.
mod rgba16float_probe {
use super::*;
/// Cached result of probing whether this browser can configure a WebGPU canvas
/// with the `rgba16float` format: [`PROBE_UNKNOWN`] until first probed,
/// otherwise [`PROBE_SUPPORTED`]/[`PROBE_UNSUPPORTED`].
///
/// Canvas-format support is process-wide and immutable at runtime, so a single
/// probe suffices. The probe (see [`probe_rgba16float_canvas_support`]) is
/// empirical (it actually calls `configure()` rather than checking a
/// browser/version), so it starts reporting supported automatically once a
/// browser (e.g. Firefox, <https://bugzilla.mozilla.org/show_bug.cgi?id=1834395>)
/// adds support, with no wgpu change required.
static RGBA16FLOAT_CANVAS_SUPPORT: AtomicU8 = AtomicU8::new(PROBE_UNKNOWN);
const PROBE_UNKNOWN: u8 = 0;
const PROBE_UNSUPPORTED: u8 = 1;
const PROBE_SUPPORTED: u8 = 2;
/// Whether `Surface::get_capabilities` should advertise `Rgba16Float`.
///
/// Optimistic (advertised) until the probe has determined it is unsupported:
/// the no-panic handling in [`WebSurface::configure`]/
/// [`WebSurface::get_current_texture`] recovers if an app selects it before a
/// device exists on a browser that rejects it.
pub(super) fn rgba16float_canvas_supported() -> bool {
RGBA16FLOAT_CANVAS_SUPPORT.load(Ordering::Relaxed) != PROBE_UNSUPPORTED
}
/// Probe (once, then cache) whether this browser can configure a `rgba16float`
/// WebGPU canvas, by actually configuring a throwaway 1x1 `OffscreenCanvas`.
///
/// Some browsers list `rgba16float` as a context format but throw from
/// `configure` (current Firefox), which on wasm would otherwise be an
/// uncatchable panic. Detecting it empirically (instead of sniffing the user
/// agent) means the result self-corrects when the browser ships support.
pub(super) fn probe_rgba16float_canvas_support(device: &webgpu_sys::GpuDevice) {
if RGBA16FLOAT_CANVAS_SUPPORT.load(Ordering::Relaxed) != PROBE_UNKNOWN {
return;
}
// If the probe can't run (e.g. no `OffscreenCanvas`), leave the support
// state unknown so we keep advertising the format optimistically.
let Some(supported) = try_configure_rgba16float_canvas(device) else {
return;
};
RGBA16FLOAT_CANVAS_SUPPORT.store(
if supported {
PROBE_SUPPORTED
} else {
PROBE_UNSUPPORTED
},
Ordering::Relaxed,
);
}
/// Returns `Some(true)`/`Some(false)` if a `rgba16float` canvas could/couldn't
/// be configured, or `None` if the probe itself couldn't be set up.
fn try_configure_rgba16float_canvas(device: &webgpu_sys::GpuDevice) -> Option<bool> {
let canvas = web_sys::OffscreenCanvas::new(1, 1).ok()?;
let context = canvas.get_context("webgpu").ok()??;
let context: webgpu_sys::GpuCanvasContext = context.unchecked_into();
let config = webgpu_sys::GpuCanvasConfiguration::new(
device,
map_texture_format(wgt::TextureFormat::Rgba16Float),
);
let supported = context.configure(&config).is_ok();
if supported {
// Leave the throwaway context unconfigured before it's dropped.
context.unconfigure();
}
Some(supported)
}
}
impl dispatch::SurfaceInterface for WebSurface {
fn get_capabilities(&self, _adapter: &dispatch::DispatchAdapter) -> wgt::SurfaceCapabilities {
let mut formats = vec![
wgt::TextureFormat::Rgba8Unorm,
wgt::TextureFormat::Bgra8Unorm,
wgt::TextureFormat::Rgba16Float,
];
// Only advertise `Rgba16Float` where the browser can actually configure
// it as a canvas (some, e.g. current Firefox, throw from `configure`).
if rgba16float_probe::rgba16float_canvas_supported() {
formats.push(wgt::TextureFormat::Rgba16Float);
}
let mut mapped_formats = formats.iter().map(|format| map_texture_format(*format));
// Preferred canvas format will only be either "rgba8unorm" or "bgra8unorm".
// https://www.w3.org/TR/webgpu/#dom-gpu-getpreferredcanvasformat
@@ -3942,6 +4039,38 @@ impl dispatch::SurfaceInterface for WebSurface {
}
wgt::SurfaceCapabilities {
format_capabilities: formats
.iter()
.map(|&format| {
// Every WebGPU implementation supports the "srgb" and
// "display-p3" canvas color spaces.
// https://gpuweb.github.io/gpuweb/#canvas-configuration
let mut color_spaces =
wgt::SurfaceColorSpaces::SRGB | wgt::SurfaceColorSpaces::DISPLAY_P3;
// An fp16 canvas with "extended" tone mapping holds
// encoded extended-range values (the nonlinear sRGB OETF,
// continued beyond [0, 1]). "extended" tone mapping is a
// configuration the canvas always accepts on an fp16 surface,
// independent of the display: an SDR display clamps the
// out-of-range values rather than rejecting the config (and
// `configure` here never gates on display HDR state either).
// So these spaces are gated on fp16-canvas support alone —
// the same condition that puts `Rgba16Float` in `formats` —
// not on whether the display is currently HDR. WebGPU has no
// linear canvas color space, so the web backend advertises
// the encoded `ExtendedSrgb` and, for the "display-p3"
// canvas, the wide-gamut `ExtendedDisplayP3` — not the
// linear `ExtendedSrgbLinear`.
if format == wgt::TextureFormat::Rgba16Float {
color_spaces |= wgt::SurfaceColorSpaces::EXTENDED_SRGB
| wgt::SurfaceColorSpaces::EXTENDED_DISPLAY_P3;
}
wgt::SurfaceFormatCapabilities {
format,
color_spaces,
}
})
.collect(),
// https://gpuweb.github.io/gpuweb/#supported-context-formats
formats,
// Doesn't really have meaning on the web.
@@ -3984,6 +4113,66 @@ impl dispatch::SurfaceInterface for WebSurface {
);
mapped.set_usage(config.usage.bits());
mapped.set_alpha_mode(alpha_mode);
match config.color_space {
// `Auto` intentionally keeps the browser defaults (colorSpace
// "srgb", standard tone mapping) even for fp16 formats, matching
// wgpu's historical behavior on the web.
wgt::SurfaceColorSpace::Auto | wgt::SurfaceColorSpace::Srgb => {}
wgt::SurfaceColorSpace::DisplayP3 => {
// The vendored bindings have no `colorSpace` setter, so set
// the dictionary member by reflection.
js_sys::Reflect::set(
&mapped,
&JsValue::from_str("colorSpace"),
&JsValue::from_str("display-p3"),
)
.expect("Setting the canvas configuration color space should never fail");
}
wgt::SurfaceColorSpace::ExtendedSrgb => {
// The canvas keeps the default "srgb" color space; "extended"
// tone mapping disables clamping to [0, 1], so an fp16 canvas
// holds sRGB-encoded extended-range values (the nonlinear sRGB
// OETF, continued beyond [0, 1]). This is the W3C HDR-canvas
// mechanism shipped in Chrome 129+.
let tone_mapping = webgpu_sys::GpuCanvasToneMapping::new();
tone_mapping.set_mode(webgpu_sys::GpuCanvasToneMappingMode::Extended);
mapped.set_tone_mapping(&tone_mapping);
}
wgt::SurfaceColorSpace::ExtendedDisplayP3 => {
// Wide-gamut HDR: the "display-p3" canvas color space combined
// with "extended" tone mapping holds Display-P3-encoded
// extended-range values. Set both dictionary members (colorSpace
// by reflection, as for `DisplayP3`).
js_sys::Reflect::set(
&mapped,
&JsValue::from_str("colorSpace"),
&JsValue::from_str("display-p3"),
)
.expect("Setting the canvas configuration color space should never fail");
let tone_mapping = webgpu_sys::GpuCanvasToneMapping::new();
tone_mapping.set_mode(webgpu_sys::GpuCanvasToneMappingMode::Extended);
mapped.set_tone_mapping(&tone_mapping);
}
cs @ (wgt::SurfaceColorSpace::ExtendedSrgbLinear
| wgt::SurfaceColorSpace::Bt2100Pq
| wgt::SurfaceColorSpace::Bt2100Hlg) => {
// Not representable on a WebGPU canvas: `ExtendedSrgbLinear`
// needs a linear-transfer canvas (WebGPU has none), and
// `Bt2100Pq`/`Bt2100Hlg` need PQ/HLG canvas signaling (browsers expose
// none). `get_capabilities` never advertises these, but an app
// may still request one without checking; record the failure and
// report the surface as lost (as for a rejected `configure`)
// rather than panicking, since there is no `catch_unwind` on
// wasm to recover an abort.
self.configure_failed.set(true);
log::error!(
"Surface color space {cs:?} is not supported on the WebGPU backend; \
the surface will report as lost. Check `get_capabilities` before \
configuring."
);
return;
}
}
let mapped_view_formats = config
.view_formats
.iter()
@@ -3994,7 +4183,28 @@ impl dispatch::SurfaceInterface for WebSurface {
})
.collect::<Vec<js_sys::JsString>>();
mapped.set_view_formats(&mapped_view_formats);
self.context.configure(&mapped).unwrap();
// `configure` can throw (e.g. the browser doesn't support the requested
// canvas format). There is no `catch_unwind` on wasm, so unwrapping here
// would be an uncatchable abort. Instead, record the failure and report
// the surface as lost from `get_current_texture`, which the application
// can already handle and recover from (e.g. by selecting a different
// format reported by `get_capabilities`).
//
// This isn't WebGPU behavior we have to support forever: some browsers
// (current Firefox) list a context format and then reject it from
// `configure`. Once they stop doing that, this handling can go away.
match self.context.configure(&mapped) {
Ok(()) => self.configure_failed.set(false),
Err(err) => {
self.configure_failed.set(true);
log::error!(
"Surface configuration failed: {err:?}. The browser may not support \
this canvas format (for example, Firefox does not yet support \
`rgba16float` canvases). The surface will report as lost until it \
is successfully reconfigured."
);
}
}
}
fn get_current_texture(
@@ -4004,7 +4214,23 @@ impl dispatch::SurfaceInterface for WebSurface {
crate::SurfaceStatus,
dispatch::DispatchSurfaceOutputDetail,
) {
let surface_texture = self.context.get_current_texture().unwrap();
let detail = WebSurfaceOutputDetail {
ident: crate::cmp::Identifier::create(),
};
// If the last `configure` failed, the context is not usable; report the
// surface as lost rather than panicking (see `configure`).
if self.configure_failed.get() {
return (None, crate::SurfaceStatus::Lost, detail.into());
}
let surface_texture = match self.context.get_current_texture() {
Ok(surface_texture) => surface_texture,
Err(err) => {
log::error!("`getCurrentTexture` failed: {err:?}");
return (None, crate::SurfaceStatus::Lost, detail.into());
}
};
let web_surface_texture = WebTexture {
inner: surface_texture,
@@ -4014,10 +4240,7 @@ impl dispatch::SurfaceInterface for WebSurface {
(
Some(web_surface_texture.into()),
crate::SurfaceStatus::Good,
WebSurfaceOutputDetail {
ident: crate::cmp::Identifier::create(),
}
.into(),
detail.into(),
)
}
}
+142 -8
View File
@@ -71,6 +71,140 @@
//! - **`wgpu_core`** --- Enabled when there is any non-webgpu backend enabled on the platform.
//! - **`naga`** --- Enabled when target `glsl` or `spirv` input is enabled, or when `wgpu_core` is enabled.
//!
//! ## Surface color spaces and HDR output
//!
//! A surface can present in different color spaces to get HDR or wide-gamut
//! output onto the screen. This is configured through
//! [`SurfaceConfiguration::color_space`], and the rest of this section is a
//! concept primer on how it works.
//!
//! ### HDR output in a nutshell
//!
//! By default a surface is standard dynamic range (SDR) with the sRGB gamut: the
//! value `1.0` is the brightest white, anything above it clips, and only colors
//! within sRGB are expressible. Other [`SurfaceColorSpace`]s opt into a **wider
//! gamut** (for example [`DisplayP3`](SurfaceColorSpace::DisplayP3), still SDR
//! but with more saturated colors than sRGB), **high dynamic range** (values
//! above `1.0` drive brighter-than-white output), or both (for example
//! [`Bt2100Pq`](SurfaceColorSpace::Bt2100Pq), aka HDR10), on platforms that
//! support it.
//!
//! Three ideas carry most of the weight:
//!
//! * **Reference white and headroom.** Brightness is measured in *nits*
//! (cd/m²). On HDR-capable monitors, SDR reference white (plain white, `(1.0, 1.0, 1.0)` in the
//! extended color spaces) sits *below* the display's peak output on purpose, so
//! highlights have room above it. That gap is the display's *headroom*.
//! * **The transfer function is a round-trip.** Your shader applies an
//! encoding transfer function (the OETF) to turn the light it computed into a
//! stored signal, and the display applies the inverse decoding transfer
//! function (the EOTF) to turn it back into light. Choosing a color space
//! chooses which transfer functions both ends use.
//! * **Who applies the encoding transfer function.** wgpu applies it for you
//! **only** when you render to an `*Srgb` texture view format, where the GPU
//! runs the sRGB OETF when a value is stored to a texture. For every other
//! color space (linear extended sRGB, encoded extended sRGB or P3, PQ, HLG)
//! **the values your shader writes to the surface texture must already be
//! encoded by you**, along with any gamut conversion; in a typical renderer
//! this happens in a final tone-mapping or post-processing pass. wgpu hands
//! the signal to the compositor unchanged; getting this wrong produces a
//! wrong image with no error.
//!
//! wgpu does **not** tonemap or gamut-map for you. It gives you the surface;
//! *choosing* and *applying* a tone curve is your application's job.
//!
//! ### The practical path
//!
//! 1. **Query capabilities.** Call `Surface::get_capabilities`. To use HDR or
//! wide-gamut output, read [`SurfaceCapabilities::format_capabilities`] (each
//! format and the [`SurfaceColorSpaces`] it supports), **not**
//! [`SurfaceCapabilities::formats`]: the latter lists only formats usable
//! with [`Auto`](SurfaceColorSpace::Auto), which never selects HDR.
//! [`SurfaceCapabilities::color_spaces`] is a convenience lookup for one
//! format.
//! 2. **Choose a format and color space.** Intersect what you want with what
//! step 1 advertises, in your own preference order (for example HDR10, then
//! linear extended sRGB, then encoded extended sRGB, then SDR
//! [`Srgb`](SurfaceColorSpace::Srgb)). Keep an SDR fallback for when nothing
//! HDR is advertised, such as when OS HDR is off.
//! 3. **Configure the surface.** Set [`SurfaceConfiguration::color_space`] and
//! `format`. [`Auto`](SurfaceColorSpace::Auto) (the default) reproduces
//! wgpu's historical behavior and never picks HDR; any other value must be in
//! that format's advertised set or configuration fails validation.
//! 4. **Encode what you write to the surface texture.** For an `*Srgb` format,
//! output linear and the hardware encodes for you. Otherwise the values your
//! shader writes to the surface texture must already carry the encoding the
//! chosen color space expects (sRGB, extended sRGB, PQ, or HLG) **and** any
//! gamut conversion (for example outputting in the BT.2020 gamut for HDR10);
//! in a typical renderer you do this in a final tone-mapping or
//! post-processing pass. See the table below.
//! 5. **Present** as usual. If OS HDR is toggled mid-run, re-query
//! `Surface::get_capabilities` and re-run the steps above.
//!
//! The standalone [HDR surface example] implements every step, including the
//! encoding transfer function for each color space.
//!
//! ### What to output from your fragment shader
//!
//! What the values your shader writes to the surface texture must contain for
//! each color space, and whether wgpu applies the transfer function for you:
//!
//! | Color space | Typical format | You write | wgpu encodes? |
//! | ----------- | -------------- | --------- | ------------- |
//! | `Srgb`, `*Srgb` format | `{Rgba,Bgra}8UnormSrgb` | linear | **yes** (hardware sRGB OETF on store) |
//! | `Srgb`, non-srgb format | `{Rgba,Bgra}8Unorm` | sRGB-encoded | no; apply the sRGB OETF yourself or use `*Srgb` instead |
//! | `ExtendedSrgbLinear` (scRGB) | `Rgba16Float` | linear, `1.0` = SDR white | no, but no encoding is necessary |
//! | `ExtendedSrgb` | `Rgba16Float` | extended sRGB-encoded | no; apply the extended sRGB OETF yourself |
//! | `DisplayP3` | `Bgra8Unorm` | sRGB-encoded, P3 primaries | no; apply the sRGB OETF (after gamut-mapping to P3) |
//! | `ExtendedDisplayP3` | `Rgba16Float` | extended sRGB-encoded, P3 primaries | no; apply the extended sRGB OETF (after gamut-mapping to P3) |
//! | `Bt2100Pq` (HDR10) | `Rgb10a2Unorm` | PQ-encoded, BT.2020 primaries | no; apply the PQ OETF (after gamut-mapping to BT.2020) |
//! | `Bt2100Hlg` | `Rgb10a2Unorm` | HLG-encoded, BT.2020 primaries | no; apply the HLG OETF (after gamut-mapping to BT.2020) |
//!
//! In short, wgpu applies the transfer function for you only when you render to
//! an `*Srgb` format. In every other case the values your shader writes to the
//! surface texture must already carry both the transfer function and any gamut
//! conversion. The [HDR surface example] implements every encoder in WGSL.
//!
//! ### Glossary
//!
//! * **Chromaticity** --- a color's hue and saturation independent of its
//! brightness, given as an `(x, y)` coordinate on the CIE 1931 diagram.
//! * **Primaries / gamut** --- the chromaticities of the red, green, and blue a
//! color space addresses, and so the range of colors it can express. [BT.709]
//! is the sRGB gamut, [Display P3] is wider, and [BT.2020] is wider still.
//! * **White point** --- the chromaticity of `R = G = B` (what "white" looks
//! like). Every color space here uses [D65], standard daylight.
//! * **Transfer function (OETF / EOTF)** --- how stored values map to light. The
//! *OETF* is the encoding transfer function your application applies; the
//! *EOTF* is the inverse decoding transfer function the display applies.
//! * **SDR / HDR** --- standard dynamic range clips at `1.0` (reference white);
//! high dynamic range lets values above `1.0` drive brighter-than-white
//! output.
//! * **Nits and reference white** --- a *nit* (cd/m²) is a unit of brightness;
//! *reference white* (also called *paper white*, especially on Windows) is the
//! brightness of SDR plain white, set below the panel's peak so highlights have
//! room above it.
//! * **Headroom (EDR)** --- how much brighter than current SDR white the display
//! can go right now, as a multiplier (`1.0` means none). A dynamic property of
//! the display.
//! * **PQ / HLG** --- the two HDR transfer functions: [PQ] (SMPTE ST 2084,
//! HDR10) encodes absolute luminance, [HLG] (BT.2100) encodes relative
//! luminance.
//! * **scRGB / extended-range sRGB** --- sRGB extended past 0.0..=1.0 for
//! HDR: [scRGB] is *linear*
//! ([`ExtendedSrgbLinear`](SurfaceColorSpace::ExtendedSrgbLinear)), while
//! [`ExtendedSrgb`](SurfaceColorSpace::ExtendedSrgb) is the same range but
//! sRGB-*encoded* (gamma), the web's HDR path.
//!
//! [HDR surface example]: https://github.com/gfx-rs/wgpu/tree/v29/examples/standalone/03_hdr_surface
//! [BT.709]: https://www.itu.int/rec/R-REC-BT.709
//! [BT.2020]: https://www.itu.int/rec/R-REC-BT.2020
//! [Display P3]: https://en.wikipedia.org/wiki/DCI-P3#Display_P3
//! [D65]: https://en.wikipedia.org/wiki/Standard_illuminant#D65_values
//! [PQ]: https://en.wikipedia.org/wiki/Perceptual_quantizer
//! [HLG]: https://www.itu.int/rec/R-REC-BT.2100
//! [scRGB]: https://en.wikipedia.org/wiki/ScRGB
//!
#![no_std]
// `-Znext-solver` requires deeper recursion limits (at least for now) to prove Send/Sync
@@ -149,14 +283,14 @@ pub use wgt::{
PresentationTimestamp, PrimitiveState, PrimitiveTopology, QueryType, RenderBundleDepthStencil,
RequestAdapterError, SamplerBindingType, SamplerBorderColor, ShaderLocation, ShaderModel,
ShaderRuntimeChecks, ShaderStages, StencilFaceState, StencilOperation, StencilState,
StorageTextureAccess, SurfaceCapabilities, SurfaceStatus, TexelCopyBufferLayout, TextureAspect,
TextureChannel, TextureDimension, TextureFormat, TextureFormatFeatureFlags,
TextureFormatFeatures, TextureSampleType, TextureTransition, TextureUsages, TextureUses,
TextureViewDimension, Trace, VertexAttribute, VertexFormat, VertexStepMode, WasmNotSend,
WasmNotSendSync, WasmNotSync, WriteOnly, WriteOnlyIter, COPY_BUFFER_ALIGNMENT,
COPY_BYTES_PER_ROW_ALIGNMENT, IMMEDIATE_DATA_ALIGNMENT, MAP_ALIGNMENT,
MAXIMUM_SUBGROUP_MAX_SIZE, MINIMUM_SUBGROUP_MIN_SIZE, QUERY_RESOLVE_BUFFER_ALIGNMENT,
QUERY_SET_MAX_QUERIES, QUERY_SIZE, VERTEX_ALIGNMENT,
StorageTextureAccess, SurfaceCapabilities, SurfaceColorSpace, SurfaceColorSpaces,
SurfaceFormatCapabilities, SurfaceStatus, TexelCopyBufferLayout, TextureAspect, TextureChannel,
TextureDimension, TextureFormat, TextureFormatFeatureFlags, TextureFormatFeatures,
TextureSampleType, TextureTransition, TextureUsages, TextureUses, TextureViewDimension, Trace,
VertexAttribute, VertexFormat, VertexStepMode, WasmNotSend, WasmNotSendSync, WasmNotSync,
WriteOnly, WriteOnlyIter, COPY_BUFFER_ALIGNMENT, COPY_BYTES_PER_ROW_ALIGNMENT,
IMMEDIATE_DATA_ALIGNMENT, MAP_ALIGNMENT, MAXIMUM_SUBGROUP_MAX_SIZE, MINIMUM_SUBGROUP_MIN_SIZE,
QUERY_RESOLVE_BUFFER_ALIGNMENT, QUERY_SET_MAX_QUERIES, QUERY_SIZE, VERTEX_ALIGNMENT,
};
#[expect(deprecated)]