Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

MetalFX on iOS; dynamic resolution stays within the requested reconstruction's range (#190)

Evan (Yifeng) Wanga37f9c8fe94d
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 6e065ae..1932368 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -1641,19 +1641,25 @@ provider, which read different signals:
|---|---|---|
| `builtin` (default) | ThreeRT | ThreeRT (temporal) |
| `fsr` | ThreeRT | AMD FidelityFX Super Resolution **1** (spatial EASU + RCAS; also on WebGPU) |
-| `metalfx` | ThreeRT | Apple's temporal scaler (macOS 13+) |
+| `metalfx` | ThreeRT | Apple's temporal scaler (macOS 13+, iOS 16+) |
| `dlss` | ThreeRT | NVIDIA DLSS Super Resolution; DLAA at scale 1 (x86-64 Windows/Linux, RTX on Vulkan, feature `dlss`) |
-| `metalfx-denoised` | Apple's temporal denoised scaler: both (macOS 26+, Apple silicon) | |
+| `metalfx-denoised` | Apple's temporal denoised scaler: both (macOS 26+ on Apple silicon, iOS 26+) | |
| `dlss-rr` | NVIDIA DLSS Ray Reconstruction: both (as `dlss`) | |
| `off` | none | none: each frame's samples as traced, without history (the joint denoisers' input; for comparison) |
| `custom:<id>` | a provider an embedding host registered, of either kind | |
-| `auto` | the best this device runs: `metalfx-denoised`, `metalfx` on a Mac; `dlss-rr`, `dlss` with DLSS; else `builtin` | |
+| `auto` | the best this device runs: `metalfx-denoised`, `metalfx` on a Mac or an iPhone; `dlss-rr`, `dlss` with DLSS; else `builtin` | |
A list (`dlss-rr,dlss,fsr`) is an order of preference; `builtin` ends every list. `quality` presets are the vendors'
ratios exactly (`ultra-performance` is a third: 640 pixels across 1080p, the smallest input DLSS takes, where a typed
`--scale 0.333` gives 639 and DLSS reports itself unsupported). Diagnostic views use `builtin`. A provider that
fails while encoding a frame falls back to `builtin` from that frame on.
+A provider says which render scales it takes (`scale_range`: MetalFX scales its output up to 3x the input, so a third
+and up; DLSS from its modes' input ranges). Under dynamic resolution (`quality: auto`) the governor does not go below
+the range of the method that runs, nor below that of the first method asked for that did not run for the scale alone:
+it goes up to it, and from there the method runs. (A 2560 x 1440 view that dynamic resolution held at a quarter never
+ran MetalFX before.)
+
### TypeScript
```ts
@@ -1690,8 +1696,9 @@ The engine does not bundle NVIDIA's SDK or runtime.
### Apple MetalFX
-The temporal scaler requires a supporting Metal device and macOS 13 or later. Build with the macOS 26 SDK
-or newer to include the denoised scaler, which also requires macOS 26 or newer at runtime. A plain temporal scaler
+The temporal scaler requires a supporting Metal device and macOS 13 or iOS 16 or later. Build with the macOS / iOS 26
+SDK or newer to include the denoised scaler, which also requires macOS 26 or iOS 26 at runtime (an iPhone 17 Pro Max
+runs both). The framework is loaded at run time, so one binary runs on systems without it. A plain temporal scaler
can keep its history across dynamic resolution changes inside its supported range (its inputs are textures of the
output's size); the denoised scaler starts a new history when input dimensions change.
diff --git a/renderer/build.rs b/renderer/build.rs
index 4332376..870b753 100644
--- a/renderer/build.rs
+++ b/renderer/build.rs
@@ -15,7 +15,11 @@ fn main() {
if std::env::var_os("CARGO_FEATURE_DLSS").is_some() && std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() == Ok("x86_64") && (os == "windows" || os == "linux") {
println!("cargo:rustc-cfg=dlss");
}
- if os == "macos" {
+ // `cfg(metalfx)`: Apple's platforms, where MetalFX's scalers exist (macOS 13 / iOS 16; the denoised one 26). The
+ // framework is loaded at run time (metalfx.m), so the same binary runs on systems without it.
+ println!("cargo:rustc-check-cfg=cfg(metalfx)");
+ if os == "macos" || os == "ios" {
+ println!("cargo:rustc-cfg=metalfx");
println!("cargo:rerun-if-changed=src/live/metalfx.m");
cc::Build::new().file("src/live/metalfx.m").flag("-fobjc-arc").compile("threert_metalfx");
println!("cargo:rustc-link-lib=framework=Foundation");
diff --git a/renderer/src/live/dlss.rs b/renderer/src/live/dlss.rs
index c65223d..8c2176c 100644
--- a/renderer/src/live/dlss.rs
+++ b/renderer/src/live/dlss.rs
@@ -64,6 +64,8 @@ struct State<C> {
struct Feature<C> {
name: &'static str,
state: Option<State<C>>,
+ /// The render scales (input / output width) its modes take at the output last prepared.
+ scales: Option<[f32; 2]>,
}
impl<C: NgxFeature> Feature<C> {
@@ -94,6 +96,7 @@ impl<C: NgxFeature> Feature<C> {
&scaled[..]
};
let mut ranges = vec![];
+ let mut scales: Option<[f32; 2]> = None;
for &(mode, _) in modes {
let context = match C::create(gpu, sdk, size.output, mode) {
Ok(c) => c,
@@ -101,6 +104,9 @@ impl<C: NgxFeature> Feature<C> {
Err(e) => return Err(e).with_context(|| format!("create {} {mode:?} for {:?}", self.name, size.output)),
};
let r = context.range();
+ let (lo, hi) = (r.start()[0] as f32 / size.output[0] as f32, r.end()[0] as f32 / size.output[0] as f32);
+ scales = Some(scales.map_or([lo, hi], |[a, b]| [a.min(lo), b.max(hi)]));
+ self.scales = scales;
if contains(&r, size.input) {
self.state = Some(State { context, mode, input: size.input, reset: true });
return Ok(Prepared::ready(size));
@@ -139,11 +145,12 @@ fn check_frame(f: &ReconstructionFrame<'_>) -> Result<()> {
pub(super) struct Dlss(Feature<DlssSuperResolution>);
impl Default for Dlss {
- fn default() -> Self { Self(Feature { name: "DLSS Super Resolution", state: None }) }
+ fn default() -> Self { Self(Feature { name: "DLSS Super Resolution", state: None, scales: None }) }
}
impl UpscaleProvider for Dlss {
fn prepare(&mut self, gpu: &gpu::Gpu, size: ReconstructionSize) -> Result<Prepared> { self.0.prepare(gpu, true, size) }
+ fn scale_range(&self) -> Option<[f32; 2]> { self.0.scales }
fn encode(&mut self, frame: ReconstructionFrame<'_>, encoder: &mut CommandEncoder) -> Result<Option<CommandBuffer>> {
check_frame(&frame)?;
@@ -167,11 +174,12 @@ impl UpscaleProvider for Dlss {
pub(super) struct DlssRr(Feature<DlssRayReconstruction>);
impl Default for DlssRr {
- fn default() -> Self { Self(Feature { name: "DLSS Ray Reconstruction", state: None }) }
+ fn default() -> Self { Self(Feature { name: "DLSS Ray Reconstruction", state: None, scales: None }) }
}
impl JointProvider for DlssRr {
fn prepare(&mut self, gpu: &gpu::Gpu, size: ReconstructionSize) -> Result<Prepared> { self.0.prepare(gpu, gpu.dlss_rr, size) }
+ fn scale_range(&self) -> Option<[f32; 2]> { self.0.scales }
fn encode(&mut self, frame: ReconstructionFrame<'_>, g: JointGuides<'_>, encoder: &mut CommandEncoder) -> Result<Option<CommandBuffer>> {
check_frame(&frame)?;
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index fab6a52..f6bba82 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -3356,9 +3356,9 @@ fn reconstruction_keeps_hdr_emitters_and_resets_on_a_cut() {
let methods = [
Method::Fsr,
Method::Off,
- #[cfg(target_os = "macos")]
+ #[cfg(metalfx)]
Method::MetalFx,
- #[cfg(target_os = "macos")]
+ #[cfg(metalfx)]
Method::MetalFxDenoised,
];
for method in methods {
@@ -3528,3 +3528,32 @@ fn a_joint_denoiser_gets_the_noisy_signal_and_the_guides() {
let hdr = live.read_hdr().unwrap();
assert!((hdr[p] / (4.0 * unit) - 1.0).abs() < 0.01 && (hdr[p + 2] / (12.0 * unit) - 1.0).abs() < 0.01, "{:?} at {unit}", &hdr[p..p + 3]);
}
+
+/// Dynamic resolution below a provider's range does not lose it: the governor goes up to the lowest scale the method
+/// asked for takes (MetalFX: a third), and from there the method runs.
+#[cfg(metalfx)]
+#[test]
+fn dynamic_resolution_rises_to_the_range_of_the_method_asked_for() {
+ let Ok(g) = gpu::Gpu::new() else { return };
+ let mut live = LiveCore::new(g, &world(), Path::new("."), &crate::default_presets_dir(), 640, 360).unwrap();
+ live.view_mode = 0;
+ live.set_scale(0.0);
+ live.min_scale = 0.2;
+ live.render_scale = 0.25;
+ live.set_reconstruction(Method::MetalFxDenoised);
+ live.render(1, |_, _| {});
+ let st = live.reconstruction_status();
+ if st.skipped.first().is_some_and(|s| !s.2.contains("takes outputs")) {
+ eprintln!("MetalFX denoised unsupported here: {:?}", st.skipped);
+ return;
+ }
+ assert_eq!(live.reconstruction(), Method::Builtin, "4x is outside MetalFX's range: {:?}", st.skipped);
+ let floor = live.reconstructor.scale_floor().expect("a floor from MetalFX's range");
+ assert!((floor - 1.0 / 3.0).abs() < 0.01, "{floor}");
+ // A frame far over its time: the governor would go down, and goes to the floor instead.
+ (live.gpu_ms, live.gpu_frame, live.frame) = (200.0, 1000, 1021);
+ live.govern_resolution(60);
+ assert!(live.render_scale >= floor, "{} under {floor}", live.render_scale);
+ live.render(1, |_, _| {});
+ assert_eq!(live.reconstruction(), Method::MetalFxDenoised, "{:?}", live.reconstruction_status().skipped);
+}
diff --git a/renderer/src/live/metalfx.m b/renderer/src/live/metalfx.m
index 43103fb..98313eb 100644
--- a/renderer/src/live/metalfx.m
+++ b/renderer/src/live/metalfx.m
@@ -17,13 +17,25 @@ float threert_fx_gpu_ms(void) {
#if __has_include(<MetalFX/MetalFX.h>)
#import <MetalFX/MetalFX.h>
#endif
+// What the SDK declares, on either platform: input content scale queries (macOS 14, iOS 17) and the reactive mask
+// (macOS 14.4, iOS 17.4). Each use also asks the object at run time.
+#if defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
+#define FX_SDK_SCALE_QUERY (__MAC_OS_X_VERSION_MAX_ALLOWED >= 140000)
+#define FX_SDK_REACTIVE (__MAC_OS_X_VERSION_MAX_ALLOWED >= 140400)
+#elif defined(__IPHONE_OS_VERSION_MAX_ALLOWED)
+#define FX_SDK_SCALE_QUERY (__IPHONE_OS_VERSION_MAX_ALLOWED >= 170000)
+#define FX_SDK_REACTIVE (__IPHONE_OS_VERSION_MAX_ALLOWED >= 170400)
+#else
+#define FX_SDK_SCALE_QUERY 0
+#define FX_SDK_REACTIVE 0
+#endif
// NULL with *why: 1 = no such scaler on this OS or device, 2 = the input's scale is outside scales[0..2], 3 = it failed.
void *threert_fx_create(void *device, bool denoise, bool dynamic, uint32_t iw, uint32_t ih, uint32_t ow, uint32_t oh, float *scales, int32_t *why) {
@autoreleasepool {
*why = 1;
#if __has_include(<MetalFX/MetalFX.h>)
- if (@available(macOS 13, *)) {
+ if (@available(macOS 13, iOS 16, *)) {
// Resolve the framework at runtime so the same binary runs on older systems.
NSBundle *framework = [NSBundle bundleWithPath:@"/System/Library/Frameworks/MetalFX.framework"];
if (![framework load]) return NULL;
@@ -34,7 +46,7 @@ void *threert_fx_create(void *device, bool denoise, bool dynamic, uint32_t iw, u
// Earlier SDKs have no capability query. Limit reuse to this configuration there.
scales[0] = fminf((float)ow / iw, (float)oh / ih);
scales[1] = fmaxf((float)ow / iw, (float)oh / ih);
-#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 140000
+#if FX_SDK_SCALE_QUERY
if ([cls respondsToSelector:@selector(supportedInputContentMaxScaleForDevice:)]) {
float maxScale = [cls supportedInputContentMaxScaleForDevice:gpu];
float minScale = [cls supportedInputContentMinScaleForDevice:gpu];
@@ -55,7 +67,7 @@ void *threert_fx_create(void *device, bool denoise, bool dynamic, uint32_t iw, u
[desc setMotionTextureFormat:MTLPixelFormatRG16Float];
[desc setOutputTextureFormat:MTLPixelFormatRGBA16Float];
[desc setAutoExposureEnabled:NO];
-#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 140400
+#if FX_SDK_REACTIVE
if ([desc respondsToSelector:@selector(setReactiveMaskTextureEnabled:)]) {
[desc setReactiveMaskTextureEnabled:YES];
[desc setReactiveMaskTextureFormat:MTLPixelFormatR8Unorm];
@@ -63,7 +75,7 @@ void *threert_fx_create(void *device, bool denoise, bool dynamic, uint32_t iw, u
#endif
if (denoise) {
#if __has_include(<MetalFX/MTLFXTemporalDenoisedScaler.h>)
- if (@available(macOS 26, *)) {
+ if (@available(macOS 26, iOS 26, *)) {
MTLFXTemporalDenoisedScalerDescriptor *d = desc;
d.diffuseAlbedoTextureFormat = MTLPixelFormatRGBA8Unorm;
d.specularAlbedoTextureFormat = MTLPixelFormatRGBA8Unorm;
@@ -106,7 +118,7 @@ void threert_fx_bind(void *scaler, bool denoise, void *const *inputs, void *outp
[s setColorTexture:(__bridge id)inputs[0]];
[s setDepthTexture:(__bridge id)inputs[1]];
[s setMotionTexture:(__bridge id)inputs[2]];
-#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 140400
+#if FX_SDK_REACTIVE
if ([s respondsToSelector:@selector(setReactiveMaskTexture:)]) [s setReactiveMaskTexture:(__bridge id)inputs[3]];
#endif
[s setOutputTexture:(__bridge id)output];
diff --git a/renderer/src/live/metalfx.rs b/renderer/src/live/metalfx.rs
index 6d7298b..dec04ac 100644
--- a/renderer/src/live/metalfx.rs
+++ b/renderer/src/live/metalfx.rs
@@ -37,11 +37,13 @@ pub(super) struct MetalFx {
range: Option<[f32; 2]>,
/// A new scaler: no history yet.
fresh: bool,
+ /// The render scales it takes (input / output), as the system reported them at the last prepare.
+ scales: Option<[f32; 2]>,
}
impl MetalFx {
- pub(super) fn upscaler() -> Self { Self { denoise: false, scaler: None, key: None, range: None, fresh: true } }
- pub(super) fn denoiser() -> Self { Self { denoise: true, scaler: None, key: None, range: None, fresh: true } }
+ pub(super) fn upscaler() -> Self { Self { denoise: false, scaler: None, key: None, range: None, fresh: true, scales: None } }
+ pub(super) fn denoiser() -> Self { Self { denoise: true, scaler: None, key: None, range: None, fresh: true, scales: None } }
fn name(&self) -> &'static str {
if self.denoise { "the MetalFX temporal denoised scaler" } else { "the MetalFX temporal scaler" }
@@ -70,9 +72,11 @@ impl MetalFx {
let ptr = std::ptr::from_ref(&**dev.raw_device()).cast();
NonNull::new(unsafe { threert_fx_create(ptr, self.denoise, dynamic_inputs, input[0], input[1], output[0], output[1], scales.as_mut_ptr(), &mut why) })
});
+ // (MetalFX reports output / input; a render scale is its inverse.)
+ self.scales = (why == 0 || why == 2).then(|| [1.0 / scales[1].max(1e-3), 1.0 / scales[0].max(1e-3)]);
let Some(raw) = raw else {
return Prepared::Unsupported(match why {
- 1 => format!("this Mac has no {} (macOS {} or later on Apple silicon)", self.name(), if self.denoise { 26 } else { 13 }),
+ 1 => format!("this device has no {} (macOS {} or iOS {} or later, Apple silicon)", self.name(), if self.denoise { 26 } else { 13 }, if self.denoise { 26 } else { 16 }),
2 => format!("{} takes outputs {:.2}x to {:.2}x its input; {}x{} to {}x{} is {:.2}x", self.name(), scales[0], scales[1],
input[0], input[1], output[0], output[1], output[0] as f32 / input[0] as f32),
_ => format!("{} could not be made for {}x{} to {}x{}", self.name(), input[0], input[1], output[0], output[1]),
@@ -125,6 +129,7 @@ impl UpscaleProvider for MetalFx {
MetalFx::encode(self, &frame, None)
}
fn untimed_gpu_ms(&self) -> f32 { if self.scaler.is_some() { unsafe { threert_fx_gpu_ms() } } else { 0.0 } }
+ fn scale_range(&self) -> Option<[f32; 2]> { self.scales }
fn invalidate(&mut self) { self.scaler = None; self.key = None; }
}
@@ -134,5 +139,6 @@ impl JointProvider for MetalFx {
MetalFx::encode(self, &frame, Some(&guides))
}
fn untimed_gpu_ms(&self) -> f32 { if self.scaler.is_some() { unsafe { threert_fx_gpu_ms() } } else { 0.0 } }
+ fn scale_range(&self) -> Option<[f32; 2]> { self.scales }
fn invalidate(&mut self) { self.scaler = None; self.key = None; }
}
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index 9da5930..88ce81c 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -53,7 +53,7 @@ mod frame;
mod dlss;
mod fsr;
mod layout;
-#[cfg(target_os = "macos")]
+#[cfg(metalfx)]
mod metalfx;
mod load;
mod reconstruction;
@@ -875,7 +875,10 @@ impl LiveCore {
// Not in the first 2 s: those frames run while caches fill (Kabukichō's first frames at 0.7 take ~47 ms), and
// the regular check settles the start as before.
let warm = self.frame >= 120 || (clock && self.born.elapsed().as_secs_f32() >= 2.0);
- self.over_budget.0 = if warm && self.gpu_ms > 1250.0 / fps as f32 && self.render_scale > self.min_scale { self.over_budget.0 + 1 } else { 0 };
+ // (The floor: the budget's, or higher where the reconstruction asked for takes no lower scale: MetalFX scales
+ // outputs up to 3x its input, so a third.)
+ let floor = self.min_scale.max(self.reconstructor.scale_floor().unwrap_or(0.0)).min(1.0);
+ self.over_budget.0 = if warm && self.gpu_ms > 1250.0 / fps as f32 && self.render_scale > floor { self.over_budget.0 + 1 } else { 0 };
let urgent = self.over_budget.0 >= 2;
// (By the clock only when 30 frames take longer than 0.75 s: at 40 frames a second and above the frame count
// comes first, as it always did.)
@@ -887,10 +890,10 @@ impl LiveCore {
self.over_budget.0 = 0;
let before = self.render_scale;
let budget = 1000.0 / fps as f32 * 0.9;
- let target = (self.render_scale * (budget / self.gpu_ms).sqrt()).clamp(self.min_scale, 1.0);
+ let target = (self.render_scale * (budget / self.gpu_ms).sqrt()).clamp(floor, 1.0);
// The hysteresis (0.03) does not hold the scale just short of either end: 0.525 with the floor as the target
// kept the district's return drive at 21-22 ms.
- let to_end = (target == 1.0 && self.render_scale < 1.0 && self.gpu_ms < budget * 0.8) || (target == self.min_scale && self.render_scale > self.min_scale);
+ let to_end = (target == 1.0 && self.render_scale < 1.0 && self.gpu_ms < budget * 0.8) || (target == floor && self.render_scale > floor) || self.render_scale < floor;
// (The hysteresis, the steps and the grid of scales are a view in points'; on a display of k pixels a point the
// same share of the rays is 1 / k of the scale. Left absolute, a Retina view held 0.325 at 17.3 ms: its target,
// 0.30, was inside the hysteresis.)
@@ -899,6 +902,8 @@ impl LiveCore {
// Down fast when far over budget (a heavy scene just opened), up slowly; straight to the target when urgent.
let step = if urgent { target - self.render_scale } else { (target - self.render_scale).clamp(if self.gpu_ms > budget * 1.5 { -0.3 } else { -0.15 } / k, 0.1 / k) };
self.render_scale = ((self.render_scale + step) * 40.0 * k).round() / (40.0 * k);
+ // (On the grid, not below the floor: a step rounded down under a provider's range would lose it again.)
+ if self.render_scale < floor { self.render_scale = floor; }
}
if self.render_scale != before {
// `frame` is already the next frame's index (render advanced it): the first one at the new scale.
diff --git a/renderer/src/live/reconstruction.rs b/renderer/src/live/reconstruction.rs
index 9bf17e3..dcc897c 100644
--- a/renderer/src/live/reconstruction.rs
+++ b/renderer/src/live/reconstruction.rs
@@ -35,9 +35,9 @@ pub enum Method {
Off,
/// ThreeRT's denoiser, then FidelityFX Super Resolution 1 (spatial: no history).
Fsr,
- /// ThreeRT's denoiser, then the MetalFX temporal scaler (macOS 13+).
+ /// ThreeRT's denoiser, then the MetalFX temporal scaler (macOS 13+, iOS 16+).
MetalFx,
- /// The MetalFX temporal denoised scaler: both jobs (macOS 26+, Apple silicon).
+ /// The MetalFX temporal denoised scaler: both jobs (macOS 26+ on Apple silicon, iOS 26+).
MetalFxDenoised,
/// ThreeRT's denoiser, then DLSS Super Resolution (DLAA at scale 1; NVIDIA RTX, feature `dlss`).
Dlss,
@@ -80,7 +80,7 @@ impl Method {
/// The methods this build could run on its platform, in the order the viewer's key cycles them.
pub fn platform() -> Vec<Method> {
let mut m = vec![Self::Builtin];
- #[cfg(target_os = "macos")]
+ #[cfg(metalfx)]
m.extend([Self::MetalFxDenoised, Self::MetalFx]);
#[cfg(dlss)]
m.extend([Self::DlssRr, Self::Dlss]);
@@ -140,7 +140,7 @@ impl Reconstruction {
Self::Auto => {
#[allow(unused_mut)]
let mut m = vec![];
- #[cfg(target_os = "macos")]
+ #[cfg(metalfx)]
m.extend([Method::MetalFxDenoised, Method::MetalFx]);
#[cfg(dlss)]
m.extend([Method::DlssRr, Method::Dlss]);
@@ -239,6 +239,10 @@ pub trait UpscaleProvider: Send {
/// which the dynamic-resolution governor steers by.
fn untimed_gpu_ms(&self) -> f32 { 0.0 }
+ /// The render scales (input / output, a side) it takes at the output last prepared, when it knows them (also after
+ /// answering `Unsupported`): dynamic resolution stays within them while it is the method asked for.
+ fn scale_range(&self) -> Option<[f32; 2]> { None }
+
/// The view was resized: release size-dependent state.
fn invalidate(&mut self) {}
}
@@ -249,6 +253,8 @@ pub trait JointProvider: Send {
/// As [`UpscaleProvider::encode`].
fn encode(&mut self, frame: ReconstructionFrame<'_>, guides: JointGuides<'_>, encoder: &mut CommandEncoder) -> Result<Option<CommandBuffer>>;
fn untimed_gpu_ms(&self) -> f32 { 0.0 }
+ /// As [`UpscaleProvider::scale_range`].
+ fn scale_range(&self) -> Option<[f32; 2]> { None }
fn invalidate(&mut self) {}
}
@@ -268,6 +274,9 @@ impl Provider {
fn invalidate(&mut self) {
match self { Self::Upscale(p) => p.invalidate(), Self::Joint(p) => p.invalidate() }
}
+ fn scale_range(&self) -> Option<[f32; 2]> {
+ match self { Self::Upscale(p) => p.scale_range(), Self::Joint(p) => p.scale_range() }
+ }
}
/// What ran: the pipeline's configuration for a frame.
@@ -370,6 +379,9 @@ pub(super) struct Reconstructor {
pub(super) active: Active,
key: Option<(ReconstructionSize, bool)>,
skipped: Vec<(Method, Skip, String)>,
+ /// The lowest render scale dynamic resolution may go to: the range of the method that runs, or of the first one
+ /// asked for that did not run for the scale alone (the governor raises the scale until it does).
+ scale_floor: Option<f32>,
fsr: Option<fsr::Fsr>,
providers: Vec<(Method, Provider)>,
// Fields drop in declaration order: providers release GPU work before their input/output textures.
@@ -381,7 +393,7 @@ impl Default for Reconstructor {
fn default() -> Self {
#[allow(unused_mut)]
let mut providers: Vec<(Method, Provider)> = vec![];
- #[cfg(target_os = "macos")]
+ #[cfg(metalfx)]
providers.extend([
(Method::MetalFx, Provider::Upscale(Box::new(super::metalfx::MetalFx::upscaler()))),
(Method::MetalFxDenoised, Provider::Joint(Box::new(super::metalfx::MetalFx::denoiser()))),
@@ -391,7 +403,7 @@ impl Default for Reconstructor {
(Method::Dlss, Provider::Upscale(Box::new(super::dlss::Dlss::default()))),
(Method::DlssRr, Provider::Joint(Box::new(super::dlss::DlssRr::default()))),
]);
- Self { requested: Reconstruction::default(), active: Active::Builtin, key: None, skipped: vec![], fsr: None, providers, textures: None, pipes: None }
+ Self { requested: Reconstruction::default(), active: Active::Builtin, key: None, skipped: vec![], scale_floor: None, fsr: None, providers, textures: None, pipes: None }
}
}
@@ -467,11 +479,26 @@ impl Reconstructor {
self.active != old
}
+ /// The lowest render scale the governor may go to for this reconstruction (None: its own floor).
+ pub(super) fn scale_floor(&self) -> Option<f32> { self.scale_floor }
+
fn select(&mut self, g: &gpu::Gpu, targets: &Targets, size: ReconstructionSize) -> Active {
+ self.scale_floor = None;
+ let range_of = |s: &Self, m: &Method| s.providers.iter().find(|(k, _)| k == m).and_then(|(_, p)| p.scale_range());
+ let scale = size.input[0] as f32 / size.output[0].max(1) as f32;
for m in self.requested.chain() {
match self.try_method(g, targets, &m, size) {
- Ok(active) => return active,
+ Ok(active) => {
+ if size.dynamic && self.scale_floor.is_none() {
+ self.scale_floor = range_of(self, &m).map(|r| r[0]);
+ }
+ return active;
+ }
Err((skip, detail)) => {
+ // (Below the range of a method asked for before the one that runs: the governor goes up to it.)
+ if size.dynamic && self.scale_floor.is_none() && skip == Skip::Unsupported {
+ self.scale_floor = range_of(self, &m).filter(|r| scale < r[0] && r[0] <= 1.0).map(|r| r[0]);
+ }
if skip == Skip::ProviderError { eprintln!("live: {} reconstruction failed: {detail}", m.name()); }
self.skipped.push((m, skip, detail));
}
@@ -496,7 +523,7 @@ impl Reconstructor {
}
let Some(i) = self.providers.iter().position(|(k, _)| k == m) else {
return Err((Skip::Unavailable, match m {
- Method::MetalFx | Method::MetalFxDenoised => "MetalFX runs on macOS only".into(),
+ Method::MetalFx | Method::MetalFxDenoised => "MetalFX runs on macOS and iOS only".into(),
Method::Dlss | Method::DlssRr => "this build has no DLSS (feature `dlss`, x86-64 Windows or Linux)".into(),
_ => format!("no provider is registered as {}", m.name()),
}));