From efff24d51c2bc656d88a6e34349b1c19672655fc Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 15:24:38 +0200 Subject: [PATCH 1/2] =?UTF-8?q?fix(=F0=9F=8D=8F):=20clip=20toneMapping=20"?= =?UTF-8?q?standard"=20at=20SDR=20white=20on=20iOS=2018+=20and=20macOS=201?= =?UTF-8?q?5+?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With wantsExtendedDynamicRangeContent = NO alone, a "standard" float canvas stops clipping at SDR white as soon as another layer on screen shows EDR: per CAMetalLayer.h, all rendered content is then clamped to the screen's EDR maximum rather than 1.0. On iOS and macOS 27.2.1, an "extended" canvas next to a "standard" one made both look the same. The layer now sets toneMapMode. "standard" is tone mapped to SDR from a declared contentsHeadroom of 1.0, which keeps values up to 1.0 as they are and clips above, next to an EDR layer too. "extended" is never tone mapped, so its values are shown up to the display's headroom without being compressed. On the 26 SDKs the layer also sets preferredDynamicRange and contentsHeadroom, which replace the deprecated wantsExtendedDynamicRangeContent (still set for iOS 16 to 25). The 18 and 26 SDK APIs are guarded at compile time, so older Xcodes keep building. --- .../docs/getting-started/native-api.mdx | 2 +- packages/webgpu/apple/MetalLayerColorSpace.h | 4 +- packages/webgpu/apple/MetalLayerColorSpace.mm | 71 +++++++++++++++---- 3 files changed, 62 insertions(+), 15 deletions(-) diff --git a/apps/docs/content/docs/getting-started/native-api.mdx b/apps/docs/content/docs/getting-started/native-api.mdx index eb651233d5..bcb4c4f6cd 100644 --- a/apps/docs/content/docs/getting-started/native-api.mdx +++ b/apps/docs/content/docs/getting-started/native-api.mdx @@ -124,7 +124,7 @@ This only works with a library that links the same Dawn build as React Native We ## Rendering to a native window -`RNWebGPU.MakeWebGPUCanvasContextFromNativeWindow()` makes a canvas context that presents to a native window other than a `Canvas`, for instance the input `Surface` of a `MediaCodec` encoder on Android. The window is an `ANativeWindow*` on Android or a `CAMetalLayer*` on Apple platforms, passed as a `BigInt`; `width` and `height` size the drawing buffer, like `canvas.width` and `canvas.height`. The context retains the window for as long as it lives, so the pointer stays valid; whatever the window belongs to (the encoder, the layer's view) is yours to keep alive while you present to it. Unlike a `Canvas`, nothing drives the context for you: call it from one thread at a time. On Apple platforms, `configure()` leaves the layer's `colorspace` as it is: set it yourself, on the main thread, to match the `colorSpace` and format you configure. +`RNWebGPU.MakeWebGPUCanvasContextFromNativeWindow()` makes a canvas context that presents to a native window other than a `Canvas`, for instance the input `Surface` of a `MediaCodec` encoder on Android. The window is an `ANativeWindow*` on Android or a `CAMetalLayer*` on Apple platforms, passed as a `BigInt`; `width` and `height` size the drawing buffer, like `canvas.width` and `canvas.height`. The context retains the window for as long as it lives, so the pointer stays valid; whatever the window belongs to (the encoder, the layer's view) is yours to keep alive while you present to it. Unlike a `Canvas`, nothing drives the context for you: call it from one thread at a time. On Apple platforms, `configure()` leaves the layer's `colorspace` as it is: set it yourself, on the main thread, to match the `colorSpace` and format you configure. The same goes for `toneMapping` on a float format: set `toneMapMode` (and on the 26 SDKs `preferredDynamicRange` and `contentsHeadroom`) as `applyCAMetalLayerColorSpace` in `apple/MetalLayerColorSpace.mm` does for a `Canvas`. Without tone mapping the layer may not clip at SDR white: while another layer on screen shows EDR, Core Animation clamps it at the display's headroom instead. ```tsx const context = RNWebGPU.MakeWebGPUCanvasContextFromNativeWindow( diff --git a/packages/webgpu/apple/MetalLayerColorSpace.h b/packages/webgpu/apple/MetalLayerColorSpace.h index aaa7f6944d..7edc7c0e6a 100644 --- a/packages/webgpu/apple/MetalLayerColorSpace.h +++ b/packages/webgpu/apple/MetalLayerColorSpace.h @@ -6,8 +6,8 @@ namespace rnwgpu { -// Tags a new CAMetalLayer with the colorspace of the canvas, and opts it into -// the display's extended dynamic range for an "extended" toneMapping mode. +// Tags a new CAMetalLayer with the colorspace of the canvas, and sets its +// dynamic range and tone mapping from the canvas's toneMapping mode. // Main thread only, where the platform view calls it as the canvas mounts (see // -[MetalView configure]): the threads that configure and present the surface // (JS, worklet runtimes) never touch a CATransaction. diff --git a/packages/webgpu/apple/MetalLayerColorSpace.mm b/packages/webgpu/apple/MetalLayerColorSpace.mm index 0e8e7f373a..b39f775ab8 100644 --- a/packages/webgpu/apple/MetalLayerColorSpace.mm +++ b/packages/webgpu/apple/MetalLayerColorSpace.mm @@ -2,8 +2,37 @@ #import #import +#include +#include + #include "MetalLayerColorSpace.h" +// @available guards the runtime, not the compilation: these say which SDK +// declares the APIs, so older Xcodes keep building. The visionOS SDK keeps +// __IPHONE_OS_VERSION_MAX_ALLOWED at 17.0, hence its own macro. +// CALayer.toneMapMode: iOS 18 / macOS 15 / visionOS 2 SDKs (Xcode 16). +#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 +// preferredDynamicRange, contentsHeadroom, CADynamicRange*: 26 SDKs (Xcode 26). +#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 + namespace rnwgpu { // WebGPU canvas values are encoded with the sRGB transfer function regardless @@ -20,12 +49,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 @@ -41,17 +68,37 @@ void applyCAMetalLayerColorSpace(CAMetalLayer *layer, : kCGColorSpaceExtendedSRGB); layer.colorspace = cgColorSpace; CGColorSpaceRelease(cgColorSpace); - const bool extendedRange = + [[maybe_unused]] 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; +#endif + // The flag alone does not keep "standard" in SDR: while any layer on screen + // shows EDR, Core Animation clamps all content to the display's headroom + // rather than 1.0 (see wantsExtendedDynamicRangeContent in CAMetalLayer.h). + // "standard" is tone mapped to SDR; "extended" is not tone mapped, so it is + // shown up to the display's headroom, never compressed. +#if RNWGPU_HAS_CA_TONE_MAP_MODE + if (@available(iOS 18.0, macOS 15.0, visionOS 2.0, *)) { + layer.toneMapMode = + extendedRange ? CAToneMapModeNever : CAToneMapModeIfSupported; + } +#endif + // The 26 SDKs replace the flag with preferredDynamicRange, which lights EDR + // only for a contentsHeadroom above 1.0. "extended" declares more than any + // display has; "standard" declares 1.0 (SDR), so its tone mapping keeps + // values up to 1.0 as they are and clips above. +#if RNWGPU_HAS_CA_DYNAMIC_RANGE + if (@available(iOS 26.0, macOS 26.0, visionOS 26.0, *)) { + layer.preferredDynamicRange = + extendedRange ? CADynamicRangeHigh : CADynamicRangeStandard; + layer.contentsHeadroom = extendedRange ? 16.0 : 1.0; + } #endif } From 947226ee9e61e6d3521b4bce16da60d462cfcdcc Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 15:24:38 +0200 Subject: [PATCH 2/2] =?UTF-8?q?chore(=F0=9F=A7=AA):=20diagnostic=20screen?= =?UTF-8?q?=20for=20the=20Canvas=20toneMapping=20prop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Diagnostics > Canvas toneMapping shows an "extended" and a "standard" canvas side by side, each a ramp from 0 to 4.0 with a marker at 1.0 and steps of 0.5 above it, next to a strip of plain SDR white. Buttons mount either canvas alone and switch the format between rgba16float and bgra8unorm. A screenshot does not capture EDR, so the result is checked by eye on an HDR display. --- apps/example/src/App.tsx | 3 + .../src/Diagnostics/DiagnosticsList.tsx | 4 + apps/example/src/Diagnostics/ToneMapping.tsx | 241 ++++++++++++++++++ apps/example/src/Route.ts | 1 + 4 files changed, 249 insertions(+) create mode 100644 apps/example/src/Diagnostics/ToneMapping.tsx diff --git a/apps/example/src/App.tsx b/apps/example/src/App.tsx index d2aa9ddd69..ff036d6f16 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 0000000000..cd2785e36b --- /dev/null +++ b/apps/example/src/Diagnostics/ToneMapping.tsx @@ -0,0 +1,241 @@ +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, useDevice } from "react-native-webgpu"; + +// Canvases with toneMapping "extended" (left) and "standard" (right), each a +// gray ramp from 0 (bottom) to MAX_VALUE (top): smooth up to a black line at +// 1.0, then in steps of 0.5, beside a strip of plain SDR white. On an HDR +// display, with rgba16float, the extended steps above 1.0 are brighter than +// the strip up to the display's headroom, and standard is the strip's white; +// with bgra8unorm both clip at 1.0. Below 1.0 they all look the same. +// A screenshot does not capture EDR: look at the device. +const MAX_VALUE = 4; +const LABEL_HEIGHT = 14; + +const MODES = ["extended", "standard"] as const; +const SHOWN = ["both", ...MODES] as const; +const FORMATS = ["rgba16float", "bgra8unorm"] as const; + +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); +} +`; + +interface RampCanvasProps { + device: GPUDevice; + mode: GPUCanvasToneMappingMode; + format: GPUTextureFormat; +} + +const RampCanvas = ({ device, mode, format }: RampCanvasProps) => { + const ref = useRef(null); + useEffect(() => { + const context = ref.current?.getContext("webgpu"); + if (!context) { + return; + } + const canvas = context.canvas as HTMLCanvasElement; + canvas.width = canvas.clientWidth * PixelRatio.get(); + canvas.height = canvas.clientHeight * PixelRatio.get(); + 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(); + }, [device, mode, format]); + return ( + + + {/* Plain SDR white, the reference for the part above 1.0. */} + + + ); +}; + +const Buttons = ({ + options, + value, + onChange, +}: { + options: readonly T[]; + value: T; + onChange: (value: T) => void; +}) => ( + + {options.map((option) => ( + onChange(option)} + style={[styles.button, value === option && styles.buttonActive]} + > + {option} + + ))} + +); + +export const ToneMapping = () => { + const { device } = useDevice(); + const [shown, setShown] = useState<(typeof SHOWN)[number]>("both"); + const [format, setFormat] = useState<(typeof FORMATS)[number]>(FORMATS[0]); + return ( + + + + + {MODES.map((mode, index) => ( + + {index > 0 && } + {mode} + + ))} + + + {MODES.map((mode, index) => ( + + {index > 0 && ( + + {Array.from({ length: MAX_VALUE + 1 }, (_, value) => ( + + {value.toFixed(1)} + + ))} + + )} + + {device && (shown === "both" || shown === mode) && ( + // A new format needs a new canvas: the layer is tagged as the + // canvas mounts. + + )} + + + ))} + + + ); +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + padding: 16, + backgroundColor: "black", + }, + row: { + flexDirection: "row", + }, + ramps: { + flex: 1, + }, + column: { + flex: 1, + }, + title: { + color: "white", + textAlign: "center", + marginBottom: 8, + }, + pair: { + flex: 1, + flexDirection: "row", + }, + canvas: { + flex: 1, + }, + sdrWhite: { + width: 12, + marginTop: "auto", + height: `${((MAX_VALUE - 1) / MAX_VALUE) * 100}%`, + 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, + }, + label: { + position: "absolute", + width: "100%", + textAlign: "center", + color: "white", + fontSize: 12, + lineHeight: LABEL_HEIGHT, + transform: [{ translateY: LABEL_HEIGHT / 2 }], + }, +}); diff --git a/apps/example/src/Route.ts b/apps/example/src/Route.ts index 3b16552fbe..eda62b1f67 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;