diff --git a/crates/metal2vulkan-conformance/probes/extended_linear_mip_blends.m b/crates/metal2vulkan-conformance/probes/extended_linear_mip_blends.m new file mode 100644 index 000000000..97dcd9d5e --- /dev/null +++ b/crates/metal2vulkan-conformance/probes/extended_linear_mip_blends.m @@ -0,0 +1,241 @@ +// How Metal blends an extended-range texture's two levels under a linear mip filter, for the forms +// `metal2vulkan`'s `lower/sampler/extended.rs` does not blend (`ExtendedRange::blends_levels`: the +// padded `R10Unorm_X6`, `RG10Unorm_X12` and their `_sRGB` twins, `RGB10A2Unorm_sRGB`, the bfloat +// formats) and, in 3D, for `BGR10_XR`, `BGRA10_XR` and their twins, against the rule the 2D +// samples of `BGR10_XR` and `BGRA10_XR` take: the two levels' samples blended by `mix` at the level +// fraction truncated onto sixty-fourths. +// +// Each form's texture (2D 16 x 16, or 3D 16 x 16 x 16, five levels, random codes: a padded form's +// low bits 0, a bfloat form's values in [0, 2)) is sampled by a kernel at 4,096 points per filter +// (nearest, linear), coordinates up to 0.15 past the edges and levels between two (a quarter on a +// sixty-fourth, a quarter one `f32` step beside one, the rest random), through a sampler clamping +// to the edge with a linear mip filter, and at the two levels themselves (the level's integer +// below and above) through the same sampler with a nearest mip filter. For each lane the line +// counts the samples equal to the rule (`mix(a, b, w)` as `a * (1 - w) + b * w` in `f32`, no fused +// multiply-add), within one `f32` step of it, equal to the lower or upper level's sample, and +// equal to the blend at the unrounded fraction, and gives the largest distance from the rule, +// absolute and in units of the two samples' difference. +// +// xcrun clang -fobjc-arc -framework Metal -framework Foundation -o extended_linear_mip_blends \ +// extended_linear_mip_blends.m +// /usr/bin/env -u MTL_DEBUG_LAYER ./extended_linear_mip_blends +#pragma STDC FP_CONTRACT OFF +#import +#import +#include +#include +#include +#include +#include + +enum { SIDE = 16, LEVELS = 5, POINTS = 4096 }; + +static const char *SRC = + "#include \n" + "using namespace metal;\n" + "kernel void k2(texture2d t [[texture(0)]], sampler s [[sampler(0)]],\n" + " device const float4 *p [[buffer(0)]], device float4 *o [[buffer(1)]],\n" + " uint i [[thread_position_in_grid]]) {\n" + " o[i] = t.sample(s, p[i].xy, level(p[i].w));\n" + "}\n" + "kernel void k3(texture3d t [[texture(0)]], sampler s [[sampler(0)]],\n" + " device const float4 *p [[buffer(0)]], device float4 *o [[buffer(1)]],\n" + " uint i [[thread_position_in_grid]]) {\n" + " o[i] = t.sample(s, p[i].xyz, level(p[i].w));\n" + "}\n"; + +static uint64_t sm = 11; + +static uint64_t next64(void) { + uint64_t z = (sm += 0x9E3779B97F4A7C15ull); + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + return z ^ (z >> 31); +} + +static uint32_t r32(void) { return (uint32_t)(next64() >> 32); } + +static float unit(void) { return (float)(r32() >> 8) / 16777216.0f; } + +// A form: its raw `MTLPixelFormat`, name, bytes per texel and how a random texel's bytes are made +// (0: every bit random, 1: 16-bit words with their low 6 bits 0, 2: 16-bit bfloats in [0, 2), +// 3: a 32-bit word of three 10-bit fields and two bits 0). +typedef struct { + NSUInteger raw; + const char *name; + int bytes, kind, volume; +} Form; + +static void texel(const Form *f, uint8_t *out) { + for (int b = 0; b < f->bytes; b += 2) { + uint16_t w = (uint16_t)r32(); + if (f->kind == 1) w &= 0xffc0; + if (f->kind == 2) w = (uint16_t)(0x3b00 + (r32() % 0x500)); // bfloat 2^-9 .. ~2 + memcpy(out + b, &w, 2); + } + if (f->kind == 3) { + uint32_t w = r32() & 0x3fffffff; + memcpy(out, &w, 4); + } +} + +int main(void) { + @autoreleasepool { + id dev = MTLCreateSystemDefaultDevice(); + printf("device %s\n", dev.name.UTF8String); + NSError *err = nil; + MTLCompileOptions *co = [MTLCompileOptions new]; + co.mathMode = MTLMathModeSafe; + id lib = [dev newLibraryWithSource:@(SRC) options:co error:&err]; + if (!lib) { + printf("library: %s\n", err.description.UTF8String); + return 1; + } + id k2 = [dev newComputePipelineStateWithFunction:[lib newFunctionWithName:@"k2"] error:&err]; + id k3 = [dev newComputePipelineStateWithFunction:[lib newFunctionWithName:@"k3"] error:&err]; + id q = [dev newCommandQueue]; + Form forms[] = { + {576, "R10Unorm_X6", 2, 1, 0}, {577, "R10Unorm_X6_sRGB", 2, 1, 0}, + {578, "RG10Unorm_X12", 4, 1, 0}, {579, "RG10Unorm_X12_sRGB", 4, 1, 0}, + {586, "RGB10A2Unorm_sRGB", 4, 0, 0}, {26, "R16Bfloat", 2, 2, 0}, + {66, "RG16Bfloat", 4, 2, 0}, {116, "RGBA16Bfloat", 8, 2, 0}, + {554, "BGR10_XR", 4, 3, 1}, {555, "BGR10_XR_sRGB", 4, 3, 1}, + {552, "BGRA10_XR", 8, 1, 1}, {553, "BGRA10_XR_sRGB", 8, 1, 1}, + {554, "BGR10_XR", 4, 3, 0}, {552, "BGRA10_XR", 8, 1, 0}, + }; + for (unsigned fi = 0; fi < sizeof forms / sizeof forms[0]; fi++) { + Form f = forms[fi]; + MTLTextureDescriptor *td = [MTLTextureDescriptor new]; + td.textureType = f.volume ? MTLTextureType3D : MTLTextureType2D; + td.pixelFormat = (MTLPixelFormat)f.raw; + td.width = td.height = SIDE; + td.depth = f.volume ? SIDE : 1; + td.mipmapLevelCount = LEVELS; + td.usage = MTLTextureUsageShaderRead; + td.storageMode = MTLStorageModePrivate; + id tex = [dev newTextureWithDescriptor:td]; + if (!tex) { + printf("RESULT %s %s: no texture\n", f.name, f.volume ? "3d" : "2d"); + continue; + } + // Each level's random texels, through a buffer. + id cb = [q commandBuffer]; + id bl = [cb blitCommandEncoder]; + for (int l = 0; l < LEVELS; l++) { + NSUInteger w = SIDE >> l, d = f.volume ? w : 1, n = w * w * d; + NSUInteger row = w * (NSUInteger)f.bytes; + uint8_t *bytes = malloc(n * f.bytes); + for (NSUInteger t = 0; t < n; t++) texel(&f, bytes + t * f.bytes); + id src = [dev newBufferWithBytes:bytes length:n * f.bytes options:MTLResourceStorageModeShared]; + free(bytes); + [bl copyFromBuffer:src + sourceOffset:0 + sourceBytesPerRow:row + sourceBytesPerImage:row * w + sourceSize:MTLSizeMake(w, w, d) + toTexture:tex + destinationSlice:0 + destinationLevel:l + destinationOrigin:MTLOriginMake(0, 0, 0)]; + } + [bl endEncoding]; + [cb commit]; + [cb waitUntilCompleted]; + for (int linear = 0; linear < 2; linear++) { + // The points, and the same points at the level below and above. + float *pts = calloc(POINTS * 4 * 3, sizeof(float)); + for (int i = 0; i < POINTS; i++) { + float *p = pts + 4 * i; + for (int c = 0; c < 3; c++) p[c] = unit() * 1.3f - 0.15f; + int l0 = (int)(r32() % 4); + float frac; + uint32_t pick = r32() % 4; + int k = 1 + (int)(r32() % 63); + if (pick == 0) { + frac = (float)k / 64.0f; + } else if (pick == 1) { + frac = nextafterf((float)k / 64.0f, (r32() & 1) ? 1.0f : 0.0f); + } else { + frac = unit(); + if (frac == 0.0f) frac = 0.5f; + } + p[3] = (float)l0 + frac; + memcpy(pts + 4 * (POINTS + i), p, 16); + memcpy(pts + 4 * (2 * POINTS + i), p, 16); + pts[4 * (POINTS + i) + 3] = (float)l0; + pts[4 * (2 * POINTS + i) + 3] = (float)(l0 + 1); + } + id pb = [dev newBufferWithBytes:pts length:POINTS * 48 options:MTLResourceStorageModeShared]; + id ob = [dev newBufferWithLength:POINTS * 48 options:MTLResourceStorageModeShared]; + id ss[2]; + for (int mip = 0; mip < 2; mip++) { + MTLSamplerDescriptor *sd = [MTLSamplerDescriptor new]; + sd.minFilter = sd.magFilter = linear ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest; + sd.mipFilter = mip ? MTLSamplerMipFilterNearest : MTLSamplerMipFilterLinear; + sd.sAddressMode = sd.tAddressMode = sd.rAddressMode = MTLSamplerAddressModeClampToEdge; + ss[mip] = [dev newSamplerStateWithDescriptor:sd]; + } + cb = [q commandBuffer]; + id en = [cb computeCommandEncoder]; + [en setComputePipelineState:f.volume ? k3 : k2]; + [en setTexture:tex atIndex:0]; + for (int part = 0; part < 3; part++) { + [en setSamplerState:ss[part == 0 ? 0 : 1] atIndex:0]; + [en setBuffer:pb offset:part * POINTS * 16 atIndex:0]; + [en setBuffer:ob offset:part * POINTS * 16 atIndex:1]; + [en dispatchThreads:MTLSizeMake(POINTS, 1, 1) threadsPerThreadgroup:MTLSizeMake(64, 1, 1)]; + } + [en endEncoding]; + [cb commit]; + [cb waitUntilCompleted]; + if (cb.status != MTLCommandBufferStatusCompleted) { + printf("RESULT %s: command buffer status %ld\n", f.name, (long)cb.status); + return 1; + } + const float *o = ob.contents; + long lanes = 0, rule = 0, ulp = 0, lower = 0, upper = 0, unrounded = 0, flat = 0; + double maxd = 0, maxrel = 0; + int shown = 0; + for (int i = 0; i < POINTS; i++) { + float frac = pts[4 * i + 3] - floorf(pts[4 * i + 3]); + float w = floorf(frac * 64.0f) / 64.0f; + for (int c = 0; c < 4; c++) { + float x = o[4 * i + c], a = o[4 * (POINTS + i) + c], b = o[4 * (2 * POINTS + i) + c]; + if (isnan(x) || isnan(a) || isnan(b)) continue; + lanes++; + float one = 1.0f - w; + float pa = a * one; + float pb2 = b * w; + float m = pa + pb2; + float mu = (float)((double)a + ((double)b - (double)a) * (double)frac); + if (a == b) flat++; + rule += x == m; + ulp += fabsf(x - m) <= fabsf(nextafterf(m, INFINITY) - m); + lower += x == a && a != b; + upper += x == b && a != b; + unrounded += x == mu; + double d = fabs((double)x - (double)m); + if (d > maxd) maxd = d; + if (a != b) { + double rel = d / fabs((double)b - (double)a); + if (rel > maxrel) maxrel = rel; + } + if (x != m && shown < 4) { + shown++; + printf(" %s %s point (%.6g %.6g %.6g) level %.9g lane %d: %.9g, rule %.9g (levels %.9g %.9g, w %.6g)\n", + f.name, linear ? "linear" : "nearest", pts[4 * i], pts[4 * i + 1], pts[4 * i + 2], + pts[4 * i + 3], c, x, m, a, b, w); + } + } + } + printf("RESULT %s %s %s: %ld lanes (%ld of equal levels); the rule %ld, within an f32 step %ld; " + "the lower level %ld, the upper %ld; the unrounded fraction %ld; largest distance %.3g " + "(%.4g of the levels' difference)\n", + f.name, f.volume ? "3d" : "2d", linear ? "linear" : "nearest", lanes, flat, rule, ulp, lower, + upper, unrounded, maxd, maxrel); + free(pts); + } + } + } + return 0; +} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index d52664db3..faf95cc47 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2337; +pub const SEMANTICS_VERSION: u32 = 2338; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/sampler/extended.rs b/crates/metal2vulkan/src/lower/sampler/extended.rs index fb941e072..79af65d79 100644 --- a/crates/metal2vulkan/src/lower/sampler/extended.rs +++ b/crates/metal2vulkan/src/lower/sampler/extended.rs @@ -67,10 +67,14 @@ //! values by the device's `FMix` along each axis ([`filtered`]), where Metal weighs each tap by the //! product of the axes' weights rounded onto `2^-16` and truncates each term as a 2D sum's //! (`PrecisionNote::BicubicFilterArithmetic`). The level follows the 2D rules under a nearest -//! mip filter. A linear mip filter's blend of a 3D texture's two levels fits no rule tried (the -//! closest, 284 of 8,192 samples apart), so it is refused, by the lowering for a constexpr sampler -//! and by the binder for a runtime one; so are another form's 3D sample (not measured) and a 3D -//! bicubic sample. +//! mip filter. Under a linear one the sample blends its two levels' 3D filters as a 2D sample +//! blends its levels' (the device's `FMix` at the clamped level's `f32` fraction), through a +//! constexpr sampler and through a runtime one whose word states the filter. Metal's blend of a 3D texture's +//! two levels fits no rule tried (the XR mip probe: the closest, 284 of 8,192 samples apart; the +//! conformance crate's probe `extended_linear_mip_blends`: Metal's two levels' samples blended so +//! lie within 0.033 of its 3D sample, and within 0.031 of its 2D one), so the blend records +//! `PrecisionNote::BicubicFilterArithmetic`, as every level blend does. Another +//! form's 3D sample (not measured) and a 3D bicubic sample are refused. //! //! **Bicubic samples** (an Apple M3 Max on macOS 26.7, the owned fixture `xr_bicubic`: random codes //! of each `BGR10_XR`, `BGRA10_XR` and two-plane format and `_sRGB` twin at 16 x 16, 7 x 5, 3 x 3, @@ -457,7 +461,7 @@ impl Sample { let blends = match self.level { Level::Base => return (0, false), Level::Stated { stated, .. } => stated.linear, - Level::Word { .. } => self.form.blends_levels() && !self.volume, + Level::Word { .. } => self.form.blends_levels(), }; let pair = if blends { super::level::LEVEL_WORDS } else { 0 }; (super::level::LEVEL_WORDS + pair, blends) @@ -928,8 +932,7 @@ fn levels( // leaves. let near = super::level::word_level(fb, word, Some(x))?; let near = fb.glsl(GlslOp::UMin, &[near, last])?; - // A 3D texture's linear mip filter is the binder's refusal. - if !r.form.blends_levels() || r.volume { + if !r.form.blends_levels() { return Ok(Some(Levels { first: near, blend: None, diff --git a/crates/metal2vulkan/src/lower/sampler/select.rs b/crates/metal2vulkan/src/lower/sampler/select.rs index 55a68a376..e50b746e0 100644 --- a/crates/metal2vulkan/src/lower/sampler/select.rs +++ b/crates/metal2vulkan/src/lower/sampler/select.rs @@ -1311,7 +1311,7 @@ fn select_slot( /// format `form`, through `sampler`: Metal's nearest or linear filter of the decoded texels, /// emulated by fetches of the raw texels on every device (`extended`). Built: a 2D or 2D array /// texture's sample or gradient sample without comparison (and a `BGR10_XR` or `BGRA10_XR` -/// form's, or `_sRGB` twin's, 3D texture's under no mip filter or a nearest one), with a `float` or `half` result, a +/// form's, or `_sRGB` twin's, 3D texture's sample), with a `float` or `half` result, a /// constant texel offset or none, no `min_lod_clamp`, and no observed residency, through a /// constexpr sampler with one filter for minification and magnification (nearest or linear), no /// anisotropy, and no mip filter, a nearest one, or a linear one of a form whose levels' blend is @@ -1331,7 +1331,7 @@ fn select_slot( /// swizzled texture (not measured). Every other sampling of the slot is `NotImplemented(Format)`: /// a two-plane form's gather, or a padded form's `half` one, an LOD query, a comparison, a 1D or /// cube texture, another form's 3D texture, an anisotropic or mixed filter, a linear mip filter of -/// another form or of a 3D texture, a constexpr sampler's level bias of its own or empty clamp, +/// another form, a constexpr sampler's level bias of its own or empty clamp, /// and a dynamic offset. fn select_extended( cx: &mut SelectCx<'_>, @@ -1510,11 +1510,6 @@ fn select_extended( let Some(stated) = super::extended::Stated::of(&s, form) else { return Err(refused()); }; - // A 3D texture's blend of two levels is not modelled (the XR mip probe's 3D - // samples under a linear mip filter fit no rule tried). - if volume && stated.linear { - return Err(refused()); - } // A level from derivatives or gradients is Vulkan's level of detail. if matches!(at_level, LevelAt::Derived { .. }) { cx.precision.insert(PrecisionNote::DeviceSampleLevel); @@ -1552,8 +1547,7 @@ fn select_extended( s.linear = true; if gather.is_none() { s.fetch_levels = true; - // A 3D texture's linear mip filter is the binder's refusal. - s.min_level |= form.blends_levels() && !volume; + s.min_level |= form.blends_levels(); level = Level::Word { sampler: n, at: at_level, @@ -1625,8 +1619,8 @@ fn select_extended( .insert(super::bicubic::routines::Routine::Plane); cx.precision.insert(PrecisionNote::BicubicFilterArithmetic); } - // A linear mip filter's blend of two levels (not a 3D texture's): a runtime sampler slot's - // where the word bound there states one. + // A linear mip filter's blend of two levels: a runtime sampler slot's where the word bound + // there states one. match level { Level::Base => {} Level::Stated { stated, .. } => { @@ -1635,7 +1629,7 @@ fn select_extended( } } Level::Word { sampler, .. } => { - if form.blends_levels() && !volume { + if form.blends_levels() { let [_, linear_mip] = super::linear::filtering_word(sampler); let when = any_of([linear_mip]); cx.note_when(PrecisionNote::BicubicFilterArithmetic, when, m)?; diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index d67d759f6..3a784fb94 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -723,7 +723,14 @@ pub enum PrecisionNote { /// truncates a linear mip filter's level fraction onto sixty-fourths: a lane may differ by a /// few grid steps (`1/4080` at 8 bits), by the weights' distance times the taps (`2.1e-3` at /// most on an extended-range `_sRGB` texture's taps), and by up to `1/64` of the two levels' - /// difference under a linear mip filter. A tap of an 8-bit sRGB texture held as its UNORM twin + /// difference under a linear mip filter. An extended-range 3D texture's linear mip filter + /// blends its two levels' 3D filters as a 2D texture's do, where Metal's blend of a 3D + /// texture's levels fits no rule tried (the XR mip probe, an Apple M3 Max on macOS 27.0.1: the + /// closest rule 284 of 8,192 samples apart). The conformance crate's probe + /// `extended_linear_mip_blends` (the M3 Max, 16,384 lanes per form, filter and shape) puts + /// Metal's own two levels' samples, blended by `mix` at the fraction on sixty-fourths, within + /// `0.031` of its linear-mip sample of a `BGR10_XR` or `BGRA10_XR` 2D texture and within + /// `0.033` of a 3D one's. A tap of an 8-bit sRGB texture held as its UNORM twin /// is the device's decode of its code ([`PrecisionNote::SrgbTexelDecode`]). Through a runtime /// sampler slot the note is specialized on the word of the sampler bound there /// (`SpecKey::BoundSamplerWord`, which the runtime reads at each draw or dispatch): it holds diff --git a/crates/metal2vulkan/src/tests/engine_extended_range/volumes.rs b/crates/metal2vulkan/src/tests/engine_extended_range/volumes.rs index 1279ea787..6f372683c 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/volumes.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/volumes.rs @@ -7,8 +7,8 @@ //! textures of five levels, nearest and linear filters under a nearest mip filter, `float` and //! `half` results, at explicit levels, clamped to the edge, and linear samples under mirrored //! repeat and repeat. -//! - What is not built is refused: a 3D texture's linear mip filter, by the lowering for a -//! constexpr sampler and by the binder for a runtime one, and a padded form's 3D sample. +//! - A linear mip filter blends the two levels' 3D filters, through a constexpr sampler and +//! through a runtime one; a padded form's 3D sample, not measured, is refused. use super::levels::{constexpr_words, descriptor, level_kernel, probe_texture, run_levels, Shape}; use super::samples::{form_of, Through}; @@ -188,11 +188,16 @@ fn volume_samples_are_metals_bytes() { assert!(checked > 0); } -/// A 3D texture's linear mip filter is not built (its blend of two levels fits no rule tried): -/// the lowering refuses a constexpr sampler's, `NotImplemented(Format)`, and builds its nearest -/// one. A padded form's 3D sample is refused too (not measured). +/// A 3D texture's linear mip filter blends its two levels' 3D filters as a 2D texture's does +/// (Metal's blend of a 3D texture's levels fits no rule tried, the closest 284 of 8,192 samples +/// apart; `PrecisionNote::BicubicFilterArithmetic`). A constexpr sampler's nearest and linear mip +/// filters compile, valid, and the linear one records the note. On the CPU interpreter a sample +/// through a runtime sampler whose word states a linear mip filter, at a level between two, lies +/// on every lane between the nearest mip filter's samples of those two levels, and strictly +/// between them on some. A padded form's 3D sample is refused (not measured). #[test] -fn volume_linear_mip_filters_and_padded_forms_are_refused() { +fn volume_linear_mip_filters_blend_two_levels() { + use crate::pipeline::artifact::PrecisionNote; let forms = [ (PixelFormat::BGRA10XR, ExtendedRange::Bgra10 { srgb: false }), ( @@ -209,7 +214,7 @@ fn volume_linear_mip_filters_and_padded_forms_are_refused() { other => panic!("{what}: {other:?}"), }; for mip in [SamplerMipFilter::Nearest, SamplerMipFilter::Linear] { - let words = volume_words(true, mip, edge); + let words = volume_words(false, mip, edge); let Some(bc) = assemble( "constexpr 3D mip", &volume_kernel(Through::Constexpr(words), false), @@ -221,11 +226,11 @@ fn volume_linear_mip_filters_and_padded_forms_are_refused() { let mut i = LowerInputs::new(); i.extended_range.insert(SOURCE, form); let what = format!("{mip:?} {form:?} on {stem}"); - let r = typed_module_with(&bc, "k", &p, &i).map(|_| ()); - match mip { - SamplerMipFilter::Nearest => r.unwrap_or_else(|e| panic!("{what}: {e}")), - _ => refused(&what, r), - } + let a = validate_entry(&bc, "k", &i, &p, &what); + let noted = a + .precision + .contains(&PrecisionNote::BicubicFilterArithmetic); + assert_eq!(noted, mip == SamplerMipFilter::Linear, "{what}"); } let mut i = LowerInputs::new(); i.extended_range.insert(SOURCE, ExtendedRange::R10X6); @@ -233,4 +238,62 @@ fn volume_linear_mip_filters_and_padded_forms_are_refused() { refused(&format!("{mip:?} R10X6 on {stem}"), r); } } + // Through a runtime sampler: the blend between the two levels' nearest samples. + let form = ExtendedRange::Bgra10 { srgb: false }; + let levels = probe_texture(form, Shape::Volume, 7); + let Some(bc) = assemble("runtime 3D mip", &volume_kernel(Through::Runtime, false)) else { + return; + }; + let mut inputs = LowerInputs::new(); + inputs.extended_range.insert(SOURCE, form); + let mut s = 0x2545_f491_4f6c_dd1du64; + let mut unit = || { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + (s >> 40) as f32 / (1u64 << 24) as f32 + }; + let mut points = Vec::new(); + for k in 0..64 { + let level = (k % 3) as f32 + (1 + k % 63) as f32 / 64.0; + points.push([unit(), unit(), unit(), level]); + } + let at = |level: fn(f32) -> f32| -> Vec<[f32; 4]> { + points + .iter() + .map(|&[u, v, w, l]| [u, v, w, level(l)]) + .collect() + }; + let (below, above) = (at(f32::floor), at(|l| l.floor() + 1.0)); + for (stem, p) in profiles() { + let what = format!("runtime linear mip on {stem}"); + validate(&bc, &inputs, &p, &what); + let (plan, m) = + typed_module_with(&bc, "k", &p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}")); + let run = |mip, points: &[[f32; 4]]| { + let desc = volume_descriptor(false, mip, edge); + let shape = (form, levels.as_slice(), Shape::Volume); + run_levels(&plan, &m, shape, (points, false, false), Some(desc), &what) + }; + let blended = run(SamplerMipFilter::Linear, &points); + let lo = run(SamplerMipFilter::Nearest, &below); + let hi = run(SamplerMipFilter::Nearest, &above); + let mut between = 0; + for (k, ((x, a), b)) in blended.iter().zip(&lo).zip(&hi).enumerate() { + for (lane, ((&x, &a), &b)) in x.iter().zip(a).zip(b).enumerate() { + let [x, a, b] = [x, a, b].map(f32::from_bits); + let (min, max) = (a.min(b), a.max(b)); + assert!( + x >= min - 1e-6 && x <= max + 1e-6, + "{what}: point {:?} lane {lane}: {x} outside [{a}, {b}]", + points[k] + ); + between += usize::from(x > min && x < max); + } + } + assert!( + between > 0, + "{what}: no lane between its two levels' samples" + ); + } } diff --git a/docs/API.md b/docs/API.md index 66cabc3a0..41d436eba 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1975,7 +1975,14 @@ category, and says what makes an operation carry the note and what may differ. E filter choice, level and clamps are Metal's. Metal's fixed-point weights, exact grid sums, float accumulators and sixty-fourth level fractions are not reproduced: a lane may differ by a few grid steps (`1/4080` at 8 bits), by up to `2.1e-3` on an extended-range sRGB texture's bicubic sample, - and by up to `1/64` of the two levels' difference under a linear mip filter. Measured for the + and by up to `1/64` of the two levels' difference under a linear mip filter. An extended-range + 3D texture's linear mip filter blends its two levels' 3D filters as a 2D texture's do, where + Metal's blend of a 3D texture's levels fits no rule tried (the XR mip probe, an Apple M3 Max on + macOS 27.0.1: the closest rule 284 of 8,192 samples apart). The conformance crate's probe + `extended_linear_mip_blends` (the M3 Max, 16,384 lanes per form, filter and shape) puts Metal's + own two levels' samples, blended by `mix` at the fraction on sixty-fourths, within `0.031` of + its linear-mip sample of a `BGR10_XR` or `BGRA10_XR` 2D texture and within `0.033` of a 3D + one's. Measured for the bicubic filter by the conformance case `bicubic-texel-classes` (Metal on an Apple M3 Max, macOS 27.0.1): Metal's results lie on the format's grid, a sixteenth of a code for `RGBA8Unorm`, `R8Unorm` and `RGBA8Snorm`, a whole code for `RGBA16Unorm` and an exact `half` for