diff --git a/apps/example/src/App.tsx b/apps/example/src/App.tsx index d2aa9ddd6..ff036d6f1 100644 --- a/apps/example/src/App.tsx +++ b/apps/example/src/App.tsx @@ -49,6 +49,7 @@ import { BackgroundDetach } from "./Diagnostics/BackgroundDetach"; import { SurfaceChurn } from "./Diagnostics/SurfaceChurn"; import { TransparencyMode } from "./Diagnostics/TransparencyMode"; import { DeviceDestroyBeforeDetach } from "./Diagnostics/DeviceDestroyBeforeDetach"; +import { ToneMapping } from "./Diagnostics/ToneMapping"; import { StorageBufferVertices } from "./StorageBufferVertices"; import { SharedTextureMemory } from "./SharedTextureMemory"; import { ImportExternalTexture } from "./ImportExternalTexture"; @@ -113,6 +114,7 @@ const linking: LinkingOptions = { SurfaceChurn: "diagnostics/surface-churn", TransparencyMode: "diagnostics/transparency-mode", DeviceDestroyBeforeDetach: "diagnostics/device-destroy-before-detach", + ToneMapping: "diagnostics/tone-mapping", StorageBufferVertices: "storage-buffer-vertices", SharedTextureMemory: "shared-texture-memory", ImportExternalTexture: "import-external-texture", @@ -215,6 +217,7 @@ function App() { name="DeviceDestroyBeforeDetach" component={DeviceDestroyBeforeDetach} /> + { diff --git a/apps/example/src/Diagnostics/ToneMapping.tsx b/apps/example/src/Diagnostics/ToneMapping.tsx new file mode 100644 index 000000000..916af71dd --- /dev/null +++ b/apps/example/src/Diagnostics/ToneMapping.tsx @@ -0,0 +1,216 @@ +import React, { useEffect, useRef, useState } from "react"; +import { PixelRatio, Pressable, StyleSheet, Text, View } from "react-native"; +import type { CanvasRef } from "react-native-webgpu"; +import { Canvas } from "react-native-webgpu"; + +// Two rgba16float canvases side by side, toneMapping "extended" on the left +// and "standard" on the right, each a gray ramp from 0 (bottom) to MAX_VALUE +// (top) in canvas values: smooth up to a full-width black line at 1.0, then +// in steps of 0.5, with short ticks at every other whole value. A strip of +// plain SDR white runs beside each canvas, and the buttons mount one canvas +// alone. On an HDR display: +// - extended: the steps above 1.0 are brighter than the white strip, up to +// the display's headroom (about 2.5 for 8x, the values being sRGB-encoded), +// and are flat only from there; +// - standard: everything above 1.0 is the white of the strip, with no steps; +// - below the 1.0 line both look the same. +// A screenshot does not capture EDR: look at the device. +const MAX_VALUE = 4; + +const shader = /* wgsl */ ` +struct VertexOut { + @builtin(position) position: vec4f, + @location(0) uv: vec2f, +}; + +@vertex +fn vs(@builtin(vertex_index) index: u32) -> VertexOut { + let corners = array(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3)); + var out: VertexOut; + out.position = vec4f(corners[index], 0, 1); + out.uv = (corners[index] + 1) * 0.5; + return out; +} + +@fragment +fn fs(in: VertexOut) -> @location(0) vec4f { + let ramp = in.uv.y * ${MAX_VALUE}.0; + // Smooth up to 1.0, then steps of 0.5, so the step where it stops shows. + let value = select(floor(ramp * 2) / 2, ramp, ramp <= 1); + let line = abs(ramp - round(ramp)) < fwidth(ramp) * 2; + let marker = line && round(ramp) == 1; + let tick = line && round(ramp) > 1 && in.uv.x < 0.25; + if (marker || tick) { + return vec4f(0, 0, 0, 1); + } + return vec4f(value, value, value, 1); +} +`; + +const RampCanvas = ({ mode }: { mode: GPUCanvasToneMappingMode }) => { + const ref = useRef(null); + useEffect(() => { + let cancelled = false; + (async () => { + const adapter = await navigator.gpu.requestAdapter(); + const device = await adapter?.requestDevice(); + const context = ref.current?.getContext("webgpu"); + if (cancelled || !device || !context) { + return; + } + const canvas = context.canvas as HTMLCanvasElement; + canvas.width = canvas.clientWidth * PixelRatio.get(); + canvas.height = canvas.clientHeight * PixelRatio.get(); + const format: GPUTextureFormat = "rgba16float"; + context.configure({ + device, + format, + alphaMode: "opaque", + toneMapping: { mode }, + }); + const module = device.createShaderModule({ code: shader }); + const pipeline = device.createRenderPipeline({ + layout: "auto", + vertex: { module, entryPoint: "vs" }, + fragment: { module, entryPoint: "fs", targets: [{ format }] }, + }); + const encoder = device.createCommandEncoder(); + const pass = encoder.beginRenderPass({ + colorAttachments: [ + { + view: context.getCurrentTexture().createView(), + loadOp: "clear", + storeOp: "store", + }, + ], + }); + pass.setPipeline(pipeline); + pass.draw(3); + pass.end(); + device.queue.submit([encoder.finish()]); + context.present(); + })(); + return () => { + cancelled = true; + }; + }, [mode]); + return ( + + {mode} + + + {/* Plain SDR white, the reference for the part above 1.0. */} + + + + ); +}; + +type Shown = "both" | "extended" | "standard"; + +export const ToneMapping = () => { + const [shown, setShown] = useState("both"); + return ( + + + {(["both", "extended", "standard"] as const).map((option) => ( + setShown(option)} + style={[styles.button, shown === option && styles.buttonActive]} + > + {option} + + ))} + + + {shown !== "standard" ? ( + + ) : ( + + )} + + {Array.from({ length: MAX_VALUE + 1 }, (_, value) => ( + + {value.toFixed(1)} + + ))} + + {shown !== "extended" ? ( + + ) : ( + + )} + + + ); +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + padding: 16, + backgroundColor: "black", + }, + row: { + flex: 1, + flexDirection: "row", + }, + column: { + flex: 1, + }, + title: { + color: "white", + textAlign: "center", + marginBottom: 8, + }, + pair: { + flex: 1, + flexDirection: "row", + }, + canvas: { + flex: 1, + }, + sdrWhite: { + width: 12, + marginTop: "auto", + height: "75%", + backgroundColor: "white", + }, + buttons: { + flexDirection: "row", + justifyContent: "center", + gap: 8, + marginBottom: 8, + }, + button: { + paddingHorizontal: 12, + paddingVertical: 6, + borderRadius: 6, + backgroundColor: "#333", + }, + buttonActive: { + backgroundColor: "#06c", + }, + buttonText: { + color: "white", + }, + scale: { + width: 40, + marginTop: 28, + }, + label: { + position: "absolute", + width: "100%", + textAlign: "center", + color: "white", + fontSize: 12, + transform: [{ translateY: 7 }], + }, +}); diff --git a/apps/example/src/Route.ts b/apps/example/src/Route.ts index 3b16552fb..eda62b1f6 100644 --- a/apps/example/src/Route.ts +++ b/apps/example/src/Route.ts @@ -40,6 +40,7 @@ export type Routes = { SurfaceChurn: undefined; TransparencyMode: undefined; DeviceDestroyBeforeDetach: undefined; + ToneMapping: undefined; StorageBufferVertices: undefined; SharedTextureMemory: undefined; ImportExternalTexture: undefined; diff --git a/packages/webgpu/apple/MetalLayerColorSpace.h b/packages/webgpu/apple/MetalLayerColorSpace.h index aaa7f6944..632006f8f 100644 --- a/packages/webgpu/apple/MetalLayerColorSpace.h +++ b/packages/webgpu/apple/MetalLayerColorSpace.h @@ -1,9 +1,40 @@ #pragma once +#include +#include + #import #include "CanvasColorSpace.h" +// preferredDynamicRange, contentsHeadroom and CADynamicRange* are declared +// only by the 26 SDKs (Xcode 26). @available guards the runtime, not the +// compilation, so older Xcodes need this too. The visionOS SDK keeps +// __IPHONE_OS_VERSION_MAX_ALLOWED at 17.0, hence its own macro. +#if (TARGET_OS_IOS && defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + __IPHONE_OS_VERSION_MAX_ALLOWED >= 260000) || \ + (TARGET_OS_VISION && defined(__VISION_OS_VERSION_MAX_ALLOWED) && \ + __VISION_OS_VERSION_MAX_ALLOWED >= 260000) || \ + (TARGET_OS_OSX && defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \ + __MAC_OS_X_VERSION_MAX_ALLOWED >= 260000) +#define RNWGPU_HAS_CA_DYNAMIC_RANGE 1 +#else +#define RNWGPU_HAS_CA_DYNAMIC_RANGE 0 +#endif + +// CALayer.toneMapMode is declared only by the iOS 18 / macOS 15 / visionOS 2 +// SDKs (Xcode 16) and later. +#if (TARGET_OS_IOS && defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + __IPHONE_OS_VERSION_MAX_ALLOWED >= 180000) || \ + (TARGET_OS_VISION && defined(__VISION_OS_VERSION_MAX_ALLOWED) && \ + __VISION_OS_VERSION_MAX_ALLOWED >= 20000) || \ + (TARGET_OS_OSX && defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \ + __MAC_OS_X_VERSION_MAX_ALLOWED >= 150000) +#define RNWGPU_HAS_CA_TONE_MAP_MODE 1 +#else +#define RNWGPU_HAS_CA_TONE_MAP_MODE 0 +#endif + namespace rnwgpu { // Tags a new CAMetalLayer with the colorspace of the canvas, and opts it into diff --git a/packages/webgpu/apple/MetalLayerColorSpace.mm b/packages/webgpu/apple/MetalLayerColorSpace.mm index 0e8e7f373..4ed655bda 100644 --- a/packages/webgpu/apple/MetalLayerColorSpace.mm +++ b/packages/webgpu/apple/MetalLayerColorSpace.mm @@ -6,6 +6,13 @@ namespace rnwgpu { +#if RNWGPU_HAS_CA_DYNAMIC_RANGE +// The headroom an "extended" layer declares. A WebGPU canvas puts no ceiling +// on its values, so it asks for more than any display has (float16 holds far +// more). With tone mapping off the display clips at what it can show. +static constexpr CGFloat kExtendedContentsHeadroom = 16.0; +#endif + // WebGPU canvas values are encoded with the sRGB transfer function regardless // of the texture format, and the canvas's colorSpace says which primaries they // are in: "srgb" (the default) or "display-p3". The same shader output must @@ -20,12 +27,10 @@ // converted from sRGB first. // // The toneMapping mode says what happens to values above 1.0 on a float -// canvas. Core Animation keeps an extended colorspace inside the display's -// SDR range unless the layer asks for extended dynamic range content, so -// without it the values clip at white: that is "standard". For "extended" the -// layer opts in, and the values use the display's headroom (EDR) as they do in -// a browser. An 8-bit canvas cannot hold values above 1.0, so the flag has no -// visible effect there. +// canvas: "standard" clips them at SDR white, and "extended" shows them +// brighter, up to the display's headroom (EDR), as a browser does. An 8-bit +// canvas cannot hold values above 1.0, so the mode has no visible effect +// there. void applyCAMetalLayerColorSpace(CAMetalLayer *layer, CanvasLayerColorSpace colorSpace) { // Main thread only: the properties land in the calling thread's implicit @@ -43,16 +48,39 @@ void applyCAMetalLayerColorSpace(CAMetalLayer *layer, CGColorSpaceRelease(cgColorSpace); const bool extendedRange = colorSpace.toneMappingMode == CanvasToneMappingMode::Extended; - // The property does not exist on tvOS (the SDK marks it unavailable, which - // @available cannot work around), so it is compiled only where it exists. - // On tvOS "extended" behaves like "standard". + // The EDR properties do not exist on tvOS (the SDK marks them unavailable, + // which @available cannot work around), so they are compiled only where + // they exist. On tvOS "extended" behaves like "standard". #if TARGET_OS_IOS || TARGET_OS_OSX || TARGET_OS_VISION if (@available(iOS 16.0, macOS 10.11, visionOS 1.0, *)) { layer.wantsExtendedDynamicRangeContent = extendedRange; } -#else - (void)extendedRange; +#if RNWGPU_HAS_CA_TONE_MAP_MODE + // The wantsExtendedDynamicRangeContent flag no longer clips by itself: a + // float drawable is untagged, and Core Animation shows it as is, above 1.0 + // too, unless the layer asks for tone mapping. "standard" asks for it (to + // SDR, see preferredDynamicRange below), and "extended" turns it off, so + // values up to the display's headroom are shown as they are, not + // compressed to fit the declared headroom. + if (@available(iOS 18.0, macOS 15.0, visionOS 2.0, *)) { + layer.toneMapMode = + extendedRange ? CAToneMapModeNever : CAToneMapModeIfSupported; + } #endif +#if RNWGPU_HAS_CA_DYNAMIC_RANGE + // Since iOS and macOS 26 the flag alone no longer lights EDR: the layer + // asks for it with preferredDynamicRange, which needs a contentsHeadroom + // above 1.0 to take effect. "standard" declares a headroom of 1.0: tone + // mapped from an untagged headroom (0), its values below 1.0 come out + // darker, while from 1.0 to SDR they are kept as is and clipped above. + if (@available(iOS 26.0, macOS 26.0, visionOS 26.0, *)) { + layer.preferredDynamicRange = + extendedRange ? CADynamicRangeHigh : CADynamicRangeStandard; + layer.contentsHeadroom = extendedRange ? kExtendedContentsHeadroom : 1.0; + } +#endif +#endif + (void)extendedRange; } } // namespace rnwgpu