Translator and runtime: a runtime pixel sampler samples at x itself through the level-0 element

The planner's group C ruling: a sample or gather through a runtime sampler slot whose state reads
unnormalized coordinates takes Metal's coordinates as they are, not scaled into normalized ones.

Translator: a slot sample or gather of a 1D or 2D texture, not an array, not multisampled, not
depth, with no compare, no residency, no footprint and no offset base, through [[sampler(n)]],
n < 16, records the sampler in TextureSlot::level_zero_samplers and branches on the sampler's word
(SamplerWord::reads_unnormalized: PIXEL with nearest or linear filters, clamp-to-edge or
clamp-to-zero or clamp-to-border s and t) and on the texture index (below 65,536). The exact arm
hands x itself, moved by its offset, at explicit level 0, to the sampler's unnormalized twin
(plain sampler element index + UNNORMALIZED_TWIN_ELEMENT) and the texture's level-0 element
(sampled element index + LEVEL_ZERO_ELEMENT); every other word runs the existing path.

Runtime: set 1's sampled array holds 3 x 65,536 elements (textures, seconds, level-0) and the
plain sampler array 16,000 (states, then their twins). A state whose word reads unnormalized
writes its unnormalized twin. A texture of one 1D or 2D layer writes its level-0 element at the
first dispatch or draw that samples it through such a state: its own sampled view for one level,
else a view of its first level it owns (Gauges::level_zero_views), released with the texture.
The floor's limits grow to hold the arrays (sampled images 4 x 65,536, samplers 32,000), which
every second element now fits, so Capabilities::attachment_reads is always true.
This commit is contained in:
Anees Iqbal committed 2026-12-03 16:17:56 -08:00
1 parent 4db5449f4d
commit 8f69218029
27 files changed
+904 -217

No files matched your search

+159 -64
View File
@@ -32,8 +32,8 @@
//! face: the translator samples the cube view there at the texel's centre and the read's level
//! (docs/RESOURCE-ID.md). The device writes every element once at creation ([`Arrays::new`]).
//!
//! Where the device reads attachments through textures (`floor::Capabilities::attachment_reads`),
//! the sampled-texture array is twice as long: element `i + 65,536` is texture `i`'s second
//! The sampled-texture array holds 196,608 elements. Where the device reads attachments through
//! textures (`floor::Capabilities::attachment_reads`), element `i + 65,536` is texture `i`'s second
//! element, which a draw pushes in place of the texture's own while it reads an attachment of its
//! pass through the texture (`crate::render_encoder`). Through the attachment feedback loop it is
//! the texture's sampled view in the feedback layout, written with element `i` for a texture whose
@@ -41,6 +41,20 @@
//! image's shadow, written at the first draw that reads through it where the texture still owns
//! the index (`crate::shadow`). It is a null descriptor otherwise. No index of a grant reaches it.
//!
//! Element `i + 131,072` of the sampled-texture array (the translator's
//! `pipeline::LEVEL_ZERO_ELEMENT` past `i`) is texture `i`'s level-0 element, and element
//! `i + 8,000` of the plain sampler array (`pipeline::UNNORMALIZED_TWIN_ELEMENT` past `i`) the
//! unnormalized twin of the sampler at `i`, a variant's included: a sample or gather through a
//! runtime sampler slot whose word reads unnormalized (`SamplerWord::reads_unnormalized`) reads
//! the texture's level-0 element through the twin at its coordinate itself. A sampler state
//! writes its twin with its other elements where its word reads unnormalized
//! (`crate::sampler`), and the arrays' default elsewhere. A texture writes its level-0 element at
//! the first dispatch or draw that binds such a state at a sampler slot the function samples the
//! texture's slot through so (`TextureSlot::level_zero_samplers`): its sampled view where that
//! has one level and one layer, else a view of its first level alone, which it makes then
//! ([`Arrays::place_level_zero`]); the element is null again with its index. No index of a grant
//! reaches either.
//!
//! Past its 65,536 textures the storage-texture array holds 65,536 level elements in runs of 16
//! (`floor::LEVEL_ELEMENTS`, `floor::LEVEL_RUN`): a texture of more than one level bound to a slot
//! a function writes or reads at a level other than the constant 0 takes a run at that bind, each
@@ -57,12 +71,13 @@ use crate::counters::{Counters, Gauge, Metric, Part};
use crate::device::lock;
use crate::error::{Error, Limit, Refusal};
use crate::floor::{
BelowFloor, Missing, LEVEL_ELEMENTS, LEVEL_RUN, SAMPLERS, SAMPLER_ARRAYS, SAMPLER_ELEMENTS,
SAMPLER_VARIANTS, TEXTURES,
BelowFloor, Missing, LEVEL_ELEMENTS, LEVEL_RUN, SAMPLERS, SAMPLER_ARRAYS, SAMPLER_DESCRIPTORS,
SAMPLER_ELEMENTS, SAMPLER_VARIANTS, TEXTURES,
};
use crate::Device;
use ash::vk;
use metal2vulkan::device::KERNEL_BUFFER_BINDINGS;
use metal2vulkan::pipeline::{LEVEL_ZERO_ELEMENT, UNNORMALIZED_TWIN_ELEMENT};
use std::collections::HashMap;
use std::ops::Range;
use std::sync::Mutex;
@@ -79,6 +94,31 @@ pub(crate) const UNIFORM_TEXELS_BINDING: u32 = 5;
/// The binding of the storage texel-buffer array: the texture buffers shaders write.
pub(crate) const STORAGE_TEXELS_BINDING: u32 = 6;
// The translator's level-0 elements lie past the textures' own and their second elements, and its
// unnormalized twins past the sampler arrays' indices and variants.
const _: () = assert!(LEVEL_ZERO_ELEMENT == 2 * TEXTURES);
const _: () = assert!(UNNORMALIZED_TWIN_ELEMENT == SAMPLER_ELEMENTS);
/// The elements of the sampled-texture array: the textures', their second elements' and their
/// level-0 elements'.
pub(crate) const SAMPLED_ELEMENTS: u32 = LEVEL_ZERO_ELEMENT + TEXTURES;
/// The elements of the plain sampler array: [`SAMPLER_ELEMENTS`], then each one's unnormalized
/// twin.
pub(crate) const PLAIN_SAMPLER_ELEMENTS: u32 = UNNORMALIZED_TWIN_ELEMENT + SAMPLER_ELEMENTS;
/// The elements of an index of the sampler arrays an element list names (`write_samplers`): the
/// plain, comparison and integer-texture arrays' at the index, and [`TWIN`].
pub(crate) const SAMPLER_USES: usize = SAMPLER_ARRAYS as usize + 1;
/// An element list's entry for the plain sampler array's element
/// [`UNNORMALIZED_TWIN_ELEMENT`] past the index: the unnormalized twin.
pub(crate) const TWIN: usize = SAMPLER_ARRAYS as usize;
/// The element list of an index's every element at its array's default ([`SAMPLER_USES`]).
const DEFAULTS: [(usize, Option<vk::Sampler>); SAMPLER_USES] =
[(0, None), (1, None), (2, None), (TWIN, None)];
/// Set 1's bindings, each its binding, descriptor type and count: the arrays a kernel's layout
/// names under the identity domains, which every pipeline's layout takes from this set. Shaders
/// declare the arrays unsized, and the set's layout holds [`layout_counts`] elements: more in the
@@ -323,18 +363,20 @@ pub(crate) struct Arrays {
pub(crate) plain: vk::Sampler,
/// The default sampler of the comparison array.
pub(crate) compare: vk::Sampler,
/// Whether the sampled-texture array holds the second elements.
/// Whether the sampled-texture array's second elements hold views: the device reads
/// attachments.
seconds: bool,
pub(crate) grants: Mutex<Grants>,
/// The sampler each sampler array's element at each index holds, plain, comparison and
/// integer texture, as last written: a default, or a sampler the index's owner holds, so a
/// handle here is never one destroyed. Written under the grants' lock.
samplers: Mutex<Box<[[vk::Sampler; SAMPLER_ARRAYS as usize]]>>,
/// integer texture, and its unnormalized twin ([`TWIN`]), as last written: a default, or a
/// sampler the index's owner holds, so a handle here is never one destroyed. Written under
/// the grants' lock.
samplers: Mutex<Box<[[vk::Sampler; SAMPLER_USES]]>>,
}
impl Arrays {
/// Makes set 1 and writes every element its default; with `seconds`, the sampled-texture
/// array holds the second elements too. With `buffers`, set 0's layout holds a kernel's
/// array's second elements hold views. With `buffers`, set 0's layout holds a kernel's
/// storage buffers ([`buffer_bindings`]); without, it is empty.
///
/// # Safety
@@ -378,9 +420,10 @@ impl Arrays {
/// `looped` the second element (`index` plus [`TEXTURES`]) with that view, the texture's
/// sampled view, in the attachment feedback layout: a colour render target shaders do not
/// read has it there alone. A texture without a storage view, or without a second element
/// written here, leaves that element null, as every element starts, unless it displaced a
/// texture, which may have had one: then it writes that element null, so nothing stale
/// answers there. A null second element is written shader-read-only on every device, as
/// written here, leaves that element null, as every element starts, and so does every
/// texture its level-0 element, which a later bind writes ([`Arrays::place_level_zero`]),
/// unless it displaced a texture, which may have had one: then it writes that element null,
/// so nothing stale answers there. A null second element is written shader-read-only on every device, as
/// [`Arrays::vacate_texture`] writes it: it holds no image, so its layout need only be one
/// every device takes for a sampled image, which the feedback layout is not: a device without
/// `VK_EXT_attachment_feedback_loop_layout` refuses it
@@ -428,6 +471,7 @@ impl Arrays {
self.write_texture(device, index, sampled, storage, second);
if displaced {
self.write_texels(device, index, [vk::BufferView::null(); 2]);
self.write_level_zero(device, index, None);
}
}
Ok(owner)
@@ -436,8 +480,8 @@ impl Arrays {
/// Places a texture buffer at `index` ([`Grants::place`]) and writes its elements before
/// another object can be placed there: the uniform texel-buffer array's with `views[0]` and
/// the storage one's with `views[1]`, a null descriptor where a view is null. Where it
/// displaced, it writes the index's texture elements null too (the sampled, the storage, and
/// the second where the set holds them), which a texture there may have held. The
/// displaced, it writes the index's texture elements null too (the sampled, the storage, the
/// level-0, and the second where the set holds them), which a texture there may have held. The
/// descriptor-slot gauge rises where no object held the index. Its owner word, which
/// [`Arrays::vacate_texels`] takes.
///
@@ -468,6 +512,7 @@ impl Arrays {
let second =
(self.seconds).then_some((null, vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL));
self.write_texture(device, index, None, Some(null), second);
self.write_level_zero(device, index, None);
}
}
Ok(owner)
@@ -558,7 +603,8 @@ impl Arrays {
/// The texture of `owner` goes from `index`: where it still owns the index, the index is free
/// and its elements are null again (the second element too, where `second` says it may hold
/// one), and the descriptor-slot gauge falls. A displaced texture's going touches nothing.
/// one, and the level-0 element, where `level_zero` says the texture wrote it), and the
/// descriptor-slot gauge falls. A displaced texture's going touches nothing.
///
/// # Safety
///
@@ -569,7 +615,7 @@ impl Arrays {
device: &ash::Device,
counters: &Counters,
(index, owner): (u32, Owner),
second: bool,
(second, level_zero): (bool, bool),
) {
let mut grants = lock(&self.grants);
if grants.vacate(IndexClass::Texture, index, owner) {
@@ -577,11 +623,73 @@ impl Arrays {
let second = second.then_some((null, vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL));
// SAFETY: the caller's contract; the lock is held, so no object is placed there
// before its elements are null.
unsafe { self.write_texture(device, index, None, Some(null), second) };
unsafe {
self.write_texture(device, index, None, Some(null), second);
if level_zero {
self.write_level_zero(device, index, None);
}
}
counters.fall(Gauge::DescriptorSlots);
}
}
/// Writes the level-0 element of the texture of `owner` at `index` with `element`, a view of
/// its first level alone and the layout it is read in, where the texture still owns the
/// index: whether it wrote it. A displaced texture writes nothing: the element is its
/// displacer's, which wrote it null.
///
/// # Safety
///
/// The view is live and of the device, of one level and one layer of an image in that layout
/// whenever work uses it, until the texture's elements are vacated.
pub(crate) unsafe fn place_level_zero(
&self,
device: &ash::Device,
(index, owner): (u32, Owner),
element: (vk::ImageView, vk::ImageLayout),
) -> bool {
let grants = lock(&self.grants);
let owns = grants.owns(IndexClass::Texture, index, owner);
if owns {
// SAFETY: the caller's contract; the texture owns the index, and the lock is held.
unsafe { self.write_level_zero(device, index, Some(element)) };
}
owns
}
/// Writes texture `index`'s level-0 element, the sampled-texture array's at `index` plus
/// [`LEVEL_ZERO_ELEMENT`], with `element`: a null descriptor, shader-read-only, where it is
/// `None`.
///
/// # Safety
///
/// As [`Arrays::write_texture`]'s, the grants' lock held for the index's owner.
unsafe fn write_level_zero(
&self,
device: &ash::Device,
index: u32,
element: Option<(vk::ImageView, vk::ImageLayout)>,
) {
let (view, layout) = element.unwrap_or((
vk::ImageView::null(),
vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
));
let info = [vk::DescriptorImageInfo::default()
.image_view(view)
.image_layout(layout)];
let write = write(
self.set,
SAMPLED_BINDING,
vk::DescriptorType::SAMPLED_IMAGE,
&info,
)
.dst_array_element(index + LEVEL_ZERO_ELEMENT);
// SAFETY: the caller's contract; the binding is update-after-bind and
// update-unused-while-pending, the element is the index's owner's alone, and a null image
// view is a null descriptor under `nullDescriptor`.
unsafe { device.update_descriptor_sets(&[write], &[]) };
}
/// Writes a texture's elements at `index`: the sampled-texture array's with `sampled` and its
/// layout, a null descriptor where it is `None`; the storage-texture array's with `storage`
/// where it is `Some`, a null descriptor where that view is null; and the second element with
@@ -743,11 +851,7 @@ impl Arrays {
let mut all = elements.to_vec();
if displaced {
let listed = |array: &usize| elements.iter().any(|&(at, _)| at == *array);
all.extend(
(0..SAMPLER_ARRAYS as usize)
.filter(|a| !listed(a))
.map(|a| (a, None)),
);
all.extend((0..SAMPLER_USES).filter(|a| !listed(a)).map(|a| (a, None)));
}
// SAFETY: the caller's contract; the object owns the index, and the lock is held.
unsafe { self.write_samplers(device, counters, index, &all) };
@@ -772,9 +876,7 @@ impl Arrays {
if grants.vacate(IndexClass::Sampler, index, owner) {
// SAFETY: the caller's contract; the lock is held, so no object is placed there
// before every element is its default.
unsafe {
self.write_samplers(device, counters, index, &[(0, None), (1, None), (2, None)])
};
unsafe { self.write_samplers(device, counters, index, &DEFAULTS) };
counters.fall(Gauge::DescriptorSlots);
}
}
@@ -819,7 +921,7 @@ impl Arrays {
let mut grants = lock(&self.grants);
// SAFETY: the caller's contract; the lock is held, so no variant is placed there before
// every element is its default.
unsafe { self.write_samplers(device, counters, index, &[(0, None), (1, None), (2, None)]) };
unsafe { self.write_samplers(device, counters, index, &DEFAULTS) };
grants.variants.push(index);
}
@@ -922,7 +1024,7 @@ impl Arrays {
index: u32,
elements: &[(usize, Option<vk::Sampler>)],
) {
let defaults = [self.plain, self.compare, self.plain];
let defaults = [self.plain, self.compare, self.plain, self.plain];
let mut all = lock(&self.samplers);
let held = &mut all[index as usize];
let changed: Vec<(usize, vk::Sampler)> = (elements.iter())
@@ -943,13 +1045,12 @@ impl Arrays {
.iter()
.zip(&infos)
.map(|(&(array, _), info)| {
write(
self.set,
FIRST_SAMPLER_BINDING + array as u32,
vk::DescriptorType::SAMPLER,
info,
)
.dst_array_element(index)
let (binding, element) = match array {
TWIN => (FIRST_SAMPLER_BINDING, index + UNNORMALIZED_TWIN_ELEMENT),
_ => (FIRST_SAMPLER_BINDING + array as u32, index),
};
write(self.set, binding, vk::DescriptorType::SAMPLER, info)
.dst_array_element(element)
})
.collect();
// SAFETY: the caller's contract; the bindings are update-after-bind and
@@ -995,7 +1096,6 @@ impl Made {
counters: &Counters,
(seconds, buffers): (bool, bool),
) -> Result<Arrays, Error> {
let sampled = sampled_images(seconds);
let bindings = buffer_bindings();
let first = vk::DescriptorSetLayoutCreateInfo::default().bindings(if buffers {
&bindings[..]
@@ -1011,7 +1111,7 @@ impl Made {
// SAFETY: the device is live, with the update-after-bind features of each binding's type
// (the floor's).
let layout = unsafe {
with_arrays_layout(layout_counts(seconds), |info| {
with_arrays_layout(layout_counts(), |info| {
supported(device, info, 1)?;
device
.create_descriptor_set_layout(info, None)
@@ -1022,7 +1122,7 @@ impl Made {
let sizes = [
vk::DescriptorPoolSize {
ty: vk::DescriptorType::SAMPLED_IMAGE,
descriptor_count: sampled,
descriptor_count: SAMPLED_ELEMENTS,
},
vk::DescriptorPoolSize {
ty: vk::DescriptorType::STORAGE_IMAGE,
@@ -1030,7 +1130,7 @@ impl Made {
},
vk::DescriptorPoolSize {
ty: vk::DescriptorType::SAMPLER,
descriptor_count: SAMPLER_ARRAYS * SAMPLER_ELEMENTS,
descriptor_count: SAMPLER_DESCRIPTORS,
},
vk::DescriptorPoolSize {
ty: vk::DescriptorType::UNIFORM_TEXEL_BUFFER,
@@ -1078,7 +1178,7 @@ impl Made {
let compare = default(true)?;
self.compare = Some(compare);
// SAFETY: the set is the device's and no command buffer uses it yet.
unsafe { fill(device, set, sampled, plain, compare) };
unsafe { fill(device, set, plain, compare) };
Ok(Arrays {
first,
layout,
@@ -1089,7 +1189,7 @@ impl Made {
seconds,
grants: Mutex::new(Grants::new()),
samplers: Mutex::new(
vec![[plain, compare, plain]; SAMPLER_ELEMENTS as usize].into_boxed_slice(),
vec![[plain, compare, plain, plain]; SAMPLER_ELEMENTS as usize].into_boxed_slice(),
),
})
}
@@ -1179,56 +1279,51 @@ pub(crate) unsafe fn supported(
}
/// The elements of each binding of set 1's layout, by [`BINDINGS`]: theirs, the sampled-texture
/// array's [`sampled_images`], the storage-texture array's level elements past its textures, and
/// array's [`SAMPLED_ELEMENTS`], the storage-texture array's level elements past its textures,
/// each sampler array's [`SAMPLER_ELEMENTS`], its variant elements past the [`SAMPLERS`] a
/// pipeline's layout names.
pub(crate) fn layout_counts(seconds: bool) -> [u32; 7] {
/// pipeline's layout names, and the plain one's twins past those ([`PLAIN_SAMPLER_ELEMENTS`]).
pub(crate) fn layout_counts() -> [u32; 7] {
let mut counts = BINDINGS.map(|(_, _, count)| count);
counts[SAMPLED_BINDING as usize] = sampled_images(seconds);
counts[SAMPLED_BINDING as usize] = SAMPLED_ELEMENTS;
counts[STORAGE_BINDING as usize] = TEXTURES + LEVEL_ELEMENTS;
for array in 0..SAMPLER_ARRAYS {
counts[(FIRST_SAMPLER_BINDING + array) as usize] = SAMPLER_ELEMENTS;
}
counts[FIRST_SAMPLER_BINDING as usize] = PLAIN_SAMPLER_ELEMENTS;
counts
}
/// The elements of the sampled-texture array: [`TEXTURES`], twice that with the second elements.
pub(crate) fn sampled_images(seconds: bool) -> u32 {
match seconds {
true => 2 * TEXTURES,
false => TEXTURES,
}
}
/// Writes every element of `set` its default: a null descriptor in each texture and texel-buffer
/// array, the sampled-texture array's `sampled` elements and the storage-texture array's level
/// elements among them, `plain` in the plain and
/// integer-texture sampler arrays and `compare` in the comparison array.
/// array, the sampled-texture array's second and level-0 elements and the storage-texture array's
/// level elements among them, `plain` in the plain sampler array, its twins among them, and the
/// integer-texture one, and `compare` in the comparison array.
///
/// # Safety
///
/// `set` is set 1 of `device`, of `sampled` sampled-texture elements, `nullDescriptor` is enabled,
/// and no other thread writes an element of it meanwhile.
/// `set` is set 1 of `device`, `nullDescriptor` is enabled, and no other thread writes an element
/// of it meanwhile.
unsafe fn fill(
device: &ash::Device,
set: vk::DescriptorSet,
sampled: u32,
plain: vk::Sampler,
compare: vk::Sampler,
) {
let sampled = vec![
vk::DescriptorImageInfo::default()
.image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL);
sampled as usize
SAMPLED_ELEMENTS as usize
];
let storage = vec![
vk::DescriptorImageInfo::default().image_layout(vk::ImageLayout::GENERAL);
(TEXTURES + LEVEL_ELEMENTS) as usize
];
let samplers = |sampler| {
vec![vk::DescriptorImageInfo::default().sampler(sampler); SAMPLER_ELEMENTS as usize]
};
let (plains, compares) = (samplers(plain), samplers(compare));
let samplers =
|sampler, count| vec![vk::DescriptorImageInfo::default().sampler(sampler); count];
let plains = samplers(plain, PLAIN_SAMPLER_ELEMENTS as usize);
let (integers, compares) = (
samplers(plain, SAMPLER_ELEMENTS as usize),
samplers(compare, SAMPLER_ELEMENTS as usize),
);
let texels = vec![vk::BufferView::null(); TEXTURES as usize];
let writes = [
write(
@@ -1259,7 +1354,7 @@ unsafe fn fill(
set,
FIRST_SAMPLER_BINDING + 2,
vk::DescriptorType::SAMPLER,
&plains,
&integers,
),
texel_write(
set,
+40 -1
View File
@@ -24,7 +24,7 @@ use crate::pipeline::{
use crate::record::Reach;
use crate::ring::{Placed, CHUNK};
use crate::sampler::SamplerState;
use crate::texture::{Region, StorageGap, Texture, TextureObject};
use crate::texture::{Region, StorageGap, Texture, TextureInner, TextureObject};
use ash::vk;
use metal2vulkan::metal::format::{integer_channels_word, BICUBIC_TEXELS_UNBOUND};
use metal2vulkan::metal::TextureUsage;
@@ -349,6 +349,30 @@ struct DispatchFacts {
/// buffer slot at a multiple of 4 below its argument's alignment ([`check_alignments`]),
/// found with the alignments.
variant: Option<Arc<Compiled>>,
/// The level-0 element of each texture the kernel samples at it through a sampler slot that
/// binds a state whose word reads unnormalized is written (`Interface::level_zero`): found
/// again after a texture, a sampler or the pipeline changes.
level_zero: bool,
}
/// Writes the level-0 element of each texture a function samples at it (`level_zero`, each its
/// texture slot and the sampler slots it does so through, `TextureSlot::level_zero_samplers`)
/// through a sampler slot that binds a state whose word reads unnormalized (`unnormalized`):
/// `texture` is the texture bound at a slot. A dispatch and a draw take it before they record.
///
/// Err: [`Error::Vulkan`] where a texture's view of its first level cannot be made.
pub(crate) fn hold_level_zero<'a>(
level_zero: &[(u32, u16)],
texture: impl Fn(u32) -> Option<&'a Arc<TextureInner>>,
unnormalized: impl Fn(u32) -> bool,
) -> Result<(), Error> {
for &(slot, samplers) in level_zero {
let binds = (0..u16::BITS).any(|n| samplers & (1 << n) != 0 && unnormalized(n));
if let (true, Some(texture)) = (binds, texture(slot)) {
texture.hold_level_zero()?;
}
}
Ok(())
}
/// Which of its state's modules a dispatch runs.
@@ -791,6 +815,7 @@ impl ComputeCommandEncoder {
None => None,
};
self.samplers[index as usize] = lent;
self.facts.level_zero = false;
Ok(())
}
@@ -1370,6 +1395,20 @@ impl ComputeCommandEncoder {
});
self.facts.aligned = true;
}
if !self.facts.level_zero {
hold_level_zero(
&inner.whole.interface.level_zero,
|slot| {
let texture = self.textures.get(slot as usize)?.as_deref()?;
Some(texture)
},
|slot| {
(self.samplers.get(slot as usize))
.is_some_and(|held| held.as_ref().is_some_and(|s| s.reads_unnormalized()))
},
)?;
self.facts.level_zero = true;
}
// A variant's content runs in place of the state's, kept by the command buffer.
let variant = self.facts.variant.clone();
if let Some(variant) = &variant {
+28 -34
View File
@@ -290,6 +290,15 @@ pub(crate) const SAMPLER_ELEMENTS: u32 = SAMPLERS + SAMPLER_VARIANTS;
/// Sampler arrays: one per use of a sampler (plain, depth comparison, integer texture).
pub(crate) const SAMPLER_ARRAYS: u32 = 3;
/// The sampler descriptors of set 1: each array's [`SAMPLER_ELEMENTS`], and the plain array's
/// unnormalized twin of each of its elements past them (`crate::arrays`).
pub(crate) const SAMPLER_DESCRIPTORS: u32 = SAMPLER_ARRAYS * SAMPLER_ELEMENTS + SAMPLER_ELEMENTS;
/// The sampled images of set 1 against the descriptor limits: the sampled-texture array's
/// textures, second elements and level-0 elements (`crate::arrays::SAMPLED_ELEMENTS`), and the
/// uniform texel buffers, which count as sampled images.
const SAMPLED_IMAGES: u32 = crate::arrays::SAMPLED_ELEMENTS + TEXTURES;
/// Threads in one compute workgroup: Metal's most threads per threadgroup.
pub(crate) const WORKGROUP_INVOCATIONS: u32 = 1024;
@@ -1131,9 +1140,9 @@ pub struct Capabilities {
/// takes the offset as its own `Offset` operand. Where it is false, the sample branches over
/// the offset's values, each branch with its value as `ConstOffset`.
pub texel_offset_operand: bool,
/// The device's descriptor limits hold the sampled-texture array's second elements beside the
/// floor's arrays: a draw may read, through a texture, an attachment its own pass renders, as
/// Metal reads a render target. It reads through the attachment feedback loop where
/// The device's descriptor limits hold the sampled-texture array's second elements, which the
/// floor's do on every device: a draw may read, through a texture, an attachment its own pass
/// renders, as Metal reads a render target. It reads through the attachment feedback loop where
/// [`feedback_loop`](Self::feedback_loop) holds, and through a copy of the image otherwise.
pub attachment_reads: bool,
/// The attachment reads hold, and so does the attachment-read feature, with
@@ -1505,7 +1514,10 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
}
let listed =
|extension: &CStr| (device.extensions.iter()).any(|name| name.as_c_str() == extension);
let attachment_reads = second_elements_fit(device);
// The floor's limits hold the sampled-texture array's second elements, which lie below its
// level-0 elements (`arrays::SAMPLED_ELEMENTS`): every device that meets it reads
// attachments.
let attachment_reads = true;
let feedback_loop = attachment_reads
&& ATTACHMENT_READ_EXTENSIONS.iter().all(|&name| listed(name))
&& (ATTACHMENT_READS.iter()).all(|feature| *(feature.field)(&mut reported) == vk::TRUE);
@@ -1538,7 +1550,7 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
*(feature.field)(&mut features) = *(feature.field)(&mut reported);
}
}
if listed(ash::ext::pipeline_robustness::NAME) && kernel_buffers_fit(device, attachment_reads) {
if listed(ash::ext::pipeline_robustness::NAME) && kernel_buffers_fit(device) {
for feature in PIPELINE_ROBUSTNESS {
*(feature.field)(&mut features) = *(feature.field)(&mut reported);
}
@@ -1733,34 +1745,16 @@ pub(crate) fn flag_names(flags: vk::MemoryPropertyFlags) -> String {
.join(" | ")
}
/// Whether the device's descriptor limits hold the sampled-texture array's second elements
/// (`arrays::sampled_images`) beside the floor's arrays: what the attachment reads take beyond
/// [`limits`]. A uniform texel buffer counts as a sampled image, and a storage one as a storage
/// image.
fn second_elements_fit(device: &Queried) -> bool {
let limits = &device.limits;
let descriptors = &device.vulkan12;
let sampled = 3 * TEXTURES;
let storage = 2 * TEXTURES + LEVEL_ELEMENTS;
descriptors.max_per_stage_descriptor_update_after_bind_sampled_images >= sampled
&& descriptors.max_descriptor_set_update_after_bind_sampled_images >= sampled
&& descriptors.max_per_stage_update_after_bind_resources
>= sampled + storage + limits.max_color_attachments
&& descriptors.max_update_after_bind_descriptors_in_all_pools
>= sampled + storage + SAMPLER_ARRAYS * SAMPLER_ELEMENTS
}
/// Whether `maxPerStageUpdateAfterBindResources` holds the compute stage's descriptors with set 0's
/// kernel storage buffers (`crate::arrays::buffer_bindings`): set 1's arrays, `seconds` their
/// second elements' (a uniform texel buffer counting as a sampled image, a storage one as a
/// storage image), and [`KERNEL_BUFFER_BINDINGS`]. It is the one limit of that layout the
/// kernel storage buffers (`crate::arrays::buffer_bindings`): set 1's arrays (a uniform texel
/// buffer counting as a sampled image, a storage one as a storage image), and
/// [`KERNEL_BUFFER_BINDINGS`]. It is the one limit of that layout the
/// translator's query (`DeviceProfile::binds_kernel_buffers`) cannot count, as set 1 is the
/// runtime's: [`PIPELINE_ROBUSTNESS`] is enabled only where it holds.
fn kernel_buffers_fit(device: &Queried, seconds: bool) -> bool {
let sampled = crate::arrays::sampled_images(seconds) + TEXTURES;
fn kernel_buffers_fit(device: &Queried) -> bool {
let storage = 2 * TEXTURES + LEVEL_ELEMENTS;
device.vulkan12.max_per_stage_update_after_bind_resources
>= sampled + storage + KERNEL_BUFFER_BINDINGS
>= SAMPLED_IMAGES + storage + KERNEL_BUFFER_BINDINGS
}
/// Each limit the floor sets: its Vulkan name, the device's value, and the least value the runtime
@@ -1775,12 +1769,12 @@ pub(crate) fn limits(device: &Queried) -> [(&'static str, u32, u32); 17] {
(
"maxPerStageDescriptorUpdateAfterBindSampledImages",
descriptors.max_per_stage_descriptor_update_after_bind_sampled_images,
2 * TEXTURES,
SAMPLED_IMAGES,
),
(
"maxDescriptorSetUpdateAfterBindSampledImages",
descriptors.max_descriptor_set_update_after_bind_sampled_images,
2 * TEXTURES,
SAMPLED_IMAGES,
),
(
"maxPerStageDescriptorUpdateAfterBindStorageImages",
@@ -1795,12 +1789,12 @@ pub(crate) fn limits(device: &Queried) -> [(&'static str, u32, u32); 17] {
(
"maxPerStageDescriptorUpdateAfterBindSamplers",
descriptors.max_per_stage_descriptor_update_after_bind_samplers,
SAMPLER_ARRAYS * SAMPLER_ELEMENTS,
SAMPLER_DESCRIPTORS,
),
(
"maxDescriptorSetUpdateAfterBindSamplers",
descriptors.max_descriptor_set_update_after_bind_samplers,
SAMPLER_ARRAYS * SAMPLER_ELEMENTS,
SAMPLER_DESCRIPTORS,
),
(
"maxSamplerAllocationCount",
@@ -1811,12 +1805,12 @@ pub(crate) fn limits(device: &Queried) -> [(&'static str, u32, u32); 17] {
(
"maxPerStageUpdateAfterBindResources",
descriptors.max_per_stage_update_after_bind_resources,
2 * TEXTURES + storage + limits.max_color_attachments,
SAMPLED_IMAGES + storage + limits.max_color_attachments,
),
(
"maxUpdateAfterBindDescriptorsInAllPools",
descriptors.max_update_after_bind_descriptors_in_all_pools,
2 * TEXTURES + storage + SAMPLER_ARRAYS * SAMPLER_ELEMENTS,
SAMPLED_IMAGES + storage + SAMPLER_DESCRIPTORS,
),
(
"maxComputeWorkGroupInvocations",
@@ -797,6 +797,11 @@ pub(crate) struct Interface {
pub(crate) views: Vec<u32>,
/// Each texture slot the kernel uses, with its access.
pub(crate) textures: Vec<(u32, Access)>,
/// Each texture slot the kernel samples or gathers at its level-0 element, with the sampler
/// slots it does so through (`TextureSlot::level_zero_samplers`, bit `n` sampler slot `n`):
/// a dispatch that binds a state whose word reads unnormalized at one of them writes the
/// bound texture's level-0 element first.
pub(crate) level_zero: Vec<(u32, u16)>,
/// Each texture slot the kernel uses, with the usage Metal asks of the texture bound there
/// ([`slot_usage`]).
pub(crate) usages: Vec<(u32, TextureUsage)>,
@@ -1862,6 +1867,7 @@ pub(crate) fn interface(
let mut storage_reads = Vec::new();
let mut formatless = Vec::new();
let mut texel_buffers = Vec::new();
let mut level_zero = Vec::new();
for (slot, used) in &translated.slots {
match (slot.stage, slot.class, used) {
(Stage::Kernel, SlotClass::Buffer, SlotInterface::Buffer(buffer))
@@ -1885,6 +1891,9 @@ pub(crate) fn interface(
if texture.texture_type == TextureType::TextureBuffer {
texel_buffers.push(slot.index);
}
if texture.level_zero_samplers != 0 {
level_zero.push((slot.index, texture.level_zero_samplers));
}
}
(Stage::Kernel, SlotClass::Sampler, SlotInterface::Sampler(_)) => {}
_ => return Err(KernelInputKind::Slot),
@@ -2107,6 +2116,7 @@ pub(crate) fn interface(
buffers,
views,
textures,
level_zero,
usages,
storage_reads,
open_cl_mode,
+14 -5
View File
@@ -91,6 +91,9 @@ pub(crate) enum Free {
LevelElements(u32),
/// A dropped texture's single-level storage views, which its run of level elements held.
LevelViews(Vec<vk::ImageView>),
/// A dropped texture's view of its first level alone, which its level-0 element held; the
/// level-0 views gauge falls with it.
LevelZeroView(vk::ImageView),
/// A dropped texture's resolve image (`crate::texture`'s `Resolved`), its attachment view
/// and its memory of `bytes`, freed as a texture's are; the resolve images gauges fall with
/// it.
@@ -112,9 +115,9 @@ pub(crate) enum Free {
AttachmentViews(Vec<vk::ImageView>),
/// A device sampler no sampler state holds; the device samplers gauge falls with it.
Sampler(vk::Sampler),
/// A released texture's index and owner word, its second element too where it says so
/// (`Arrays::vacate_texture`).
TextureIndex((u32, Owner), bool),
/// A released texture's index and owner word, its second element and its level-0 element
/// too where they say so (`Arrays::vacate_texture`).
TextureIndex((u32, Owner), (bool, bool)),
/// A released texture buffer's index and owner word (`Arrays::vacate_texels`).
TexelIndex((u32, Owner)),
/// A dropped texture buffer's buffer view; the textures gauge falls with it.
@@ -301,6 +304,12 @@ pub(crate) fn free(core: &Core, object: Free) {
}
}
}
Free::LevelZeroView(view) => {
// SAFETY: no pending work reads it: every command buffer that bound the texture held
// it until it retired, and its level-0 element is null or another texture's.
unsafe { device.destroy_image_view(view, None) };
core.counters.fall(Gauge::LevelZeroViews);
}
Free::Resolved {
view,
image,
@@ -352,8 +361,8 @@ pub(crate) fn free(core: &Core, object: Free) {
}
// SAFETY: no pending work reads the elements: the work committed before the release
// retired (`crate::memory::Wait`), and each command buffer that used the object held it.
Free::TextureIndex(at, second) => unsafe {
(core.arrays).vacate_texture(device, &core.counters, at, second)
Free::TextureIndex(at, elements) => unsafe {
(core.arrays).vacate_texture(device, &core.counters, at, elements)
},
// SAFETY: as above.
Free::TexelIndex(at) => unsafe { (core.arrays).vacate_texels(device, &core.counters, at) },
+10
View File
@@ -304,6 +304,11 @@ pub(crate) struct Draws {
/// of the bound texture's run of level elements, which a draw's checks hold first. Empty for
/// every other content.
pub(crate) levels: Vec<(usize, u32)>,
/// Each texture slot a function samples or gathers at its level-0 element, with its function
/// and the sampler slots it does so through (`TextureSlot::level_zero_samplers`, bit `n`
/// sampler slot `n`): a draw that binds a state whose word reads unnormalized at one of them
/// writes the bound texture's level-0 element first.
pub(crate) level_zero: Vec<(usize, u32, u16)>,
/// Each fixed-function vertex binding: its binding and the vertex buffer index it reads.
pub(crate) bindings: Vec<(u32, u32)>,
/// Whether a function reads through an address that is not one of its slots.
@@ -984,6 +989,7 @@ fn draws(
let mut usages = Vec::new();
let mut storage_reads = Vec::new();
let mut formatless = Vec::new();
let mut level_zero = Vec::new();
for (slot, used) in &translated.slots {
let at = table(slot.stage)?;
match (slot.class, used) {
@@ -1004,6 +1010,9 @@ fn draws(
if texture.storage && !texture.declared_format {
formatless.push((at, slot.index));
}
if texture.level_zero_samplers != 0 {
level_zero.push((at, slot.index, texture.level_zero_samplers));
}
}
(SlotClass::Sampler, SlotInterface::Sampler(_)) => {}
_ => return Err(draw_input(DrawInputCause::Slot)),
@@ -1223,6 +1232,7 @@ fn draws(
arrays,
bicubic,
levels,
level_zero,
bindings,
reads_unbound: translated.reads_unbound_resources,
writes_unbound: translated.writes_unbound_resources,
@@ -95,8 +95,8 @@ use crate::counters::Metric;
use crate::depth_stencil::{BitDraws, DepthStencilState, Face, Tests, EVERY_FRAGMENT};
use crate::device::Core;
use crate::encoder::{
check_alignment, check_usage, merge, Declared, Resource, ResourceUsage, BUFFER_SLOTS,
SAMPLER_SLOTS, TEXTURE_SLOTS,
check_alignment, check_usage, hold_level_zero, merge, Declared, Resource, ResourceUsage,
BUFFER_SLOTS, SAMPLER_SLOTS, TEXTURE_SLOTS,
};
use crate::error::{DrawKind, Error, Gap, IndirectCommandsKind, Limit, Refusal, RenderPassKind};
use crate::fence::Fence;
@@ -3189,6 +3189,18 @@ impl RenderCommandEncoder {
let (bind, first) = building.bind_graphics(pipeline);
if !self.push_filled || commands {
if let Some(state) = &self.pipeline {
// Each texture's level-0 element, where a sampler slot a function samples it at
// that element through binds a state whose word reads unnormalized: the bindings
// the push reads.
for &(table, slot, samplers) in &state.inner.compiled.draws.level_zero {
let tables = &self.tables[table];
let unnormalized = |n: u32| matches!(tables.samplers.get(n as usize), Some(Some(s)) if s.reads_unnormalized());
hold_level_zero(
&[(slot, samplers)],
|slot| tables.texture(slot),
unnormalized,
)?;
}
let factors = (self.factors.as_ref()).map_or(0, |(buffer, offset)| {
buffer.gpu_address().wrapping_add(*offset)
});
+47 -21
View File
@@ -3,7 +3,11 @@
//!
//! A sampler state takes the device sampler of each use it can be used in: the plain one always,
//! the comparison one where its descriptor sets a compare function, and the integer-texture one,
//! nearest with the integer border colour. Equal create infos share one `VkSampler` across uses
//! nearest with the integer border colour; and where its word reads unnormalized
//! (`SamplerWord::reads_unnormalized`), its unnormalized twin, the plain one with
//! `unnormalizedCoordinates`, in the plain array past its variants (`crate::arrays`), through
//! which a sample or gather through a runtime sampler slot reads the texture's level-0 element at
//! its coordinate itself. A variant takes its state's. Equal create infos share one `VkSampler` across uses
//! and states, and a border colour no address mode reads is not part of a create info, so a
//! state's integer-texture use takes its plain sampler wherever the two read alike. The device's
//! `maxSamplerAllocationCount` bounds the samplers, the arrays' two defaults among them; past it a
@@ -22,7 +26,7 @@
//! where work holds every one, the new one is held by its command buffer alone. A NaN bound,
//! which Metal documents no answer for, binds the state as it is.
use crate::arrays::{Owner, ResourceId};
use crate::arrays::{Owner, ResourceId, SAMPLER_USES, TWIN};
use crate::counters::Gauge;
use crate::device::{lock, Core, Device};
use crate::error::{Error, Limit};
@@ -171,8 +175,9 @@ pub(crate) struct SamplerInner {
index: u32,
word: u32,
/// The create info of each array's element at the index, plain, comparison and integer
/// texture; `None` where the array keeps its default.
uses: [Option<SamplerDesc>; 3],
/// texture, and of its unnormalized twin ([`TWIN`]); `None` where the array keeps its
/// default.
uses: [Option<SamplerDesc>; SAMPLER_USES],
kind: Kind,
}
@@ -198,6 +203,13 @@ impl SamplerInner {
word: self.word,
}
}
/// Whether its word reads unnormalized (`SamplerWord::reads_unnormalized`): it holds its
/// unnormalized twin, and a sample or gather through a slot that binds it reads the texture's
/// level-0 element.
pub(crate) fn reads_unnormalized(&self) -> bool {
self.uses[TWIN].is_some()
}
}
impl Drop for SamplerInner {
@@ -251,25 +263,34 @@ impl SamplerInner {
}
/// The translator's create info of each use a state of `descriptor` can be used in, plain,
/// comparison and integer texture (`metal::sampler::vk_sampler`): the comparison one where its
/// compare function is not `Never`, `None` otherwise.
/// comparison and integer texture (`metal::sampler::vk_sampler`), and of its unnormalized twin
/// ([`TWIN`]): the comparison one where its compare function is not `Never`, the twin where its
/// word reads unnormalized (`SamplerWord::reads_unnormalized`), `None` otherwise.
///
/// Err: [`Error::Translation`] where the translator makes no device sampler of the descriptor.
fn uses_of(core: &Core, descriptor: &SamplerDescriptor) -> Result<[Option<SamplerDesc>; 3], Error> {
fn uses_of(
core: &Core,
descriptor: &SamplerDescriptor,
) -> Result<[Option<SamplerDesc>; SAMPLER_USES], Error> {
let profile = core.translator.profile();
let desc = |compare, integer| {
vk_sampler(descriptor, SamplerUse::new(compare, integer), profile)
let desc = |use_: SamplerUse| {
vk_sampler(descriptor, use_, profile)
.map(canonical)
.map_err(Error::translation)
};
let compare = descriptor.compare_function != CompareFunction::Never;
let unnormalized = SamplerWord::of(descriptor).reads_unnormalized();
Ok([
Some(desc(false, false)?),
Some(desc(SamplerUse::new(false, false))?),
match compare {
true => Some(desc(true, false)?),
true => Some(desc(SamplerUse::new(true, false))?),
false => None,
},
Some(desc(SamplerUse::new(false, true))?),
match unnormalized {
true => Some(desc(SamplerUse::new(false, false).with_unnormalized(true))?),
false => None,
},
Some(desc(false, true)?),
])
}
@@ -280,10 +301,10 @@ fn uses_of(core: &Core, descriptor: &SamplerDescriptor) -> Result<[Option<Sample
/// held then.
fn take_samplers(
core: &Core,
uses: &[Option<SamplerDesc>; 3],
) -> Result<[Option<vk::Sampler>; 3], Error> {
let mut taken = Vec::with_capacity(3);
let mut samplers = [None; 3];
uses: &[Option<SamplerDesc>; SAMPLER_USES],
) -> Result<[Option<vk::Sampler>; SAMPLER_USES], Error> {
let mut taken = Vec::with_capacity(SAMPLER_USES);
let mut samplers = [None; SAMPLER_USES];
for (slot, use_) in uses.iter().enumerate() {
let Some(use_) = use_ else { continue };
let sampler = lock(&core.samplers).take(use_, || make(core, use_));
@@ -301,10 +322,12 @@ fn take_samplers(
Ok(samplers)
}
/// Each sampler array's element at an index, plain, comparison and integer texture, from
/// `samplers`.
fn every(samplers: [Option<vk::Sampler>; 3]) -> [(usize, Option<vk::Sampler>); 3] {
[0, 1, 2].map(|array| (array, samplers[array]))
/// Each sampler array's element at an index, plain, comparison and integer texture, and its
/// unnormalized twin ([`TWIN`]), from `samplers`.
fn every(
samplers: [Option<vk::Sampler>; SAMPLER_USES],
) -> [(usize, Option<vk::Sampler>); SAMPLER_USES] {
std::array::from_fn(|array| (array, samplers[array]))
}
/// A constexpr sampler at an index of the sampler arrays, by its index and state words: the
@@ -452,7 +475,10 @@ impl Device {
/// of each use the state can be used in (`metal::sampler::vk_sampler`), taken from the
/// device's samplers, which share one `VkSampler` per create info, and written into the three
/// sampler arrays at `index` before the call returns. The comparison array takes the state's
/// sampler where its compare function is not `Never`, and keeps its default otherwise. An
/// sampler where its compare function is not `Never`, and keeps its default otherwise. Where
/// its word reads unnormalized (`SamplerWord::reads_unnormalized`), the plain array takes its
/// unnormalized twin past its variants (the module docs); elsewhere that element keeps its
/// default. An
/// index another state or a constexpr sampler holds, live or released and held by a command
/// buffer not yet retired, is taken at once, as a texture's is
/// ([`Device::new_texture`](crate::Device::new_texture)): the earlier one's going leaves it.
@@ -198,8 +198,7 @@ mod on_device {
/// The floor's last item, asked of the created device: every device of the cfg's kind
/// supports both of the runtime's set layouts (`vkGetDescriptorSetLayoutSupport`), the empty
/// set 0 and set 1 of the arrays, with the sampled-texture array's second elements where the
/// device reads attachments, which `Device::new` asks before it makes them.
/// set 0 and set 1 of the arrays, which `Device::new` asks before it makes them.
#[test]
fn every_device_supports_the_runtimes_set_layouts() {
let instance = crate::tests::validation::instance(&[]);
@@ -215,13 +214,11 @@ mod on_device {
let empty = vk::DescriptorSetLayoutCreateInfo::default();
// SAFETY: the device is live, with the floor's features.
unsafe { supported(raw, &empty, 0) }.unwrap_or_else(|error| panic!("{name}: {error}"));
for seconds in [false, device.core().attachment_reads] {
with_arrays_layout(layout_counts(seconds), |info| {
// SAFETY: the device is live, with the floor's features.
unsafe { supported(raw, info, 1) }
})
.unwrap_or_else(|error| panic!("{name}: {error}"));
}
with_arrays_layout(layout_counts(), |info| {
// SAFETY: the device is live, with the floor's features.
unsafe { supported(raw, info, 1) }
})
.unwrap_or_else(|error| panic!("{name}: {error}"));
println!("floor: {name}: set layouts 0 and 1 supported");
}
}
@@ -43,6 +43,7 @@ pub(crate) mod on_device {
buffers,
views: Vec::new(),
textures: Vec::new(),
level_zero: Vec::new(),
usages: Vec::new(),
storage_reads: Vec::new(),
open_cl_mode: false,
@@ -7,8 +7,8 @@
use super::floor::{at_the_floor, table};
use crate::floor::{
creation_extensions, decide, enable_set, shader_enables, shader_extension, vulkan_name,
Capabilities, Queried, DEVICE_EXTENSIONS, ENABLED, LEVEL_ELEMENTS, SAMPLER_ARRAYS,
SAMPLER_ELEMENTS, TEXTURES,
Capabilities, Queried, DEVICE_EXTENSIONS, ENABLED, LEVEL_ELEMENTS, SAMPLER_DESCRIPTORS,
TEXTURES,
};
use ash::vk;
use metal2vulkan::device::{
@@ -196,15 +196,13 @@ fn the_enable_set_is_what_creation_enables_on_a_device_with_everything() {
}
device.extensions = creation_extensions().map(CStr::to_owned).collect();
let descriptors = &mut device.vulkan12;
descriptors.max_per_stage_descriptor_update_after_bind_sampled_images = 3 * TEXTURES;
descriptors.max_descriptor_set_update_after_bind_sampled_images = 3 * TEXTURES;
// The sampled array with its second elements, and the storage array with its level elements.
let images = 3 * TEXTURES + 2 * TEXTURES + LEVEL_ELEMENTS;
// The sampled array with its second and level-0 elements and the uniform texel buffers, and
// the storage array with its level elements and the storage texel buffers.
let images = 4 * TEXTURES + 2 * TEXTURES + LEVEL_ELEMENTS;
// The fragment stage's attachments, or the compute stage's kernel storage buffers.
descriptors.max_per_stage_update_after_bind_resources =
images + (device.limits.max_color_attachments).max(KERNEL_BUFFER_BINDINGS);
descriptors.max_update_after_bind_descriptors_in_all_pools =
images + SAMPLER_ARRAYS * SAMPLER_ELEMENTS;
descriptors.max_update_after_bind_descriptors_in_all_pools = images + SAMPLER_DESCRIPTORS;
let capabilities = decide(&device).unwrap_or_else(|below| panic!("{below}"));
assert!(capabilities.feedback_loop, "the attachment reads' room");
assert_eq!(shader_enables(&capabilities), enable_set());
+24 -46
View File
@@ -140,14 +140,14 @@ pub(super) fn at_the_floor() -> Queried {
.timestamp_compute_and_graphics(true)
.standard_sample_locations(true),
vulkan12: vk::PhysicalDeviceVulkan12Properties::default()
.max_per_stage_descriptor_update_after_bind_sampled_images(2 * 65_536)
.max_descriptor_set_update_after_bind_sampled_images(2 * 65_536)
.max_per_stage_descriptor_update_after_bind_sampled_images(4 * 65_536)
.max_descriptor_set_update_after_bind_sampled_images(4 * 65_536)
.max_per_stage_descriptor_update_after_bind_storage_images(3 * 65_536)
.max_descriptor_set_update_after_bind_storage_images(3 * 65_536)
.max_per_stage_descriptor_update_after_bind_samplers(3 * 8000)
.max_descriptor_set_update_after_bind_samplers(3 * 8000)
.max_per_stage_update_after_bind_resources(5 * 65_536 + 8)
.max_update_after_bind_descriptors_in_all_pools(5 * 65_536 + 3 * 8000),
.max_per_stage_descriptor_update_after_bind_samplers(4 * 8000)
.max_descriptor_set_update_after_bind_samplers(4 * 8000)
.max_per_stage_update_after_bind_resources(7 * 65_536 + 8)
.max_update_after_bind_descriptors_in_all_pools(7 * 65_536 + 4 * 8000),
features,
extensions: DEVICE_EXTENSIONS
.iter()
@@ -797,18 +797,18 @@ fn each_low_limit_is_named() {
(
|d| {
d.vulkan12
.max_per_stage_descriptor_update_after_bind_sampled_images = 2 * 65_536 - 1
.max_per_stage_descriptor_update_after_bind_sampled_images = 4 * 65_536 - 1
},
"maxPerStageDescriptorUpdateAfterBindSampledImages",
2 * 65_536,
4 * 65_536,
),
(
|d| {
d.vulkan12
.max_descriptor_set_update_after_bind_sampled_images = 2 * 65_536 - 1
.max_descriptor_set_update_after_bind_sampled_images = 4 * 65_536 - 1
},
"maxDescriptorSetUpdateAfterBindSampledImages",
2 * 65_536,
4 * 65_536,
),
(
|d| {
@@ -829,15 +829,15 @@ fn each_low_limit_is_named() {
(
|d| {
d.vulkan12
.max_per_stage_descriptor_update_after_bind_samplers = 23_999
.max_per_stage_descriptor_update_after_bind_samplers = 31_999
},
"maxPerStageDescriptorUpdateAfterBindSamplers",
24_000,
32_000,
),
(
|d| d.vulkan12.max_descriptor_set_update_after_bind_samplers = 23_999,
|d| d.vulkan12.max_descriptor_set_update_after_bind_samplers = 31_999,
"maxDescriptorSetUpdateAfterBindSamplers",
24_000,
32_000,
),
(
|d| d.limits.max_sampler_allocation_count = 3999,
@@ -845,14 +845,14 @@ fn each_low_limit_is_named() {
4000,
),
(
|d| d.vulkan12.max_per_stage_update_after_bind_resources = 5 * 65_536 + 7,
|d| d.vulkan12.max_per_stage_update_after_bind_resources = 7 * 65_536 + 7,
"maxPerStageUpdateAfterBindResources",
5 * 65_536 + 8,
7 * 65_536 + 8,
),
(
|d| d.vulkan12.max_update_after_bind_descriptors_in_all_pools = 5 * 65_536 + 23_999,
|d| d.vulkan12.max_update_after_bind_descriptors_in_all_pools = 7 * 65_536 + 31_999,
"maxUpdateAfterBindDescriptorsInAllPools",
5 * 65_536 + 24_000,
7 * 65_536 + 32_000,
),
(
|d| d.limits.max_compute_work_group_invocations = 1023,
@@ -1894,21 +1894,13 @@ fn a_run_time_texel_offset_is_the_sample_s_operand_where_maintenance8_is_reporte
assert_eq!(answer(&device), (true, true, true, true, true));
}
/// A device reads attachments where its descriptor limits hold the sampled-texture array's second
/// elements: through the attachment feedback loop where it lists
/// Every device at the floor reads attachments, whose limits hold the sampled-texture array's
/// second elements: through the attachment feedback loop where it lists
/// `VK_EXT_attachment_feedback_loop_layout` and reports its feature, which device creation then
/// enables, with no other extension (its dynamic state is never enabled, listed or not), and
/// through a copy of the image where it does not, enabling neither. A device without the room
/// reads no attachment, whatever it reports.
/// through a copy of the image where it does not, enabling neither.
#[test]
fn the_attachment_reads_take_the_feedback_loop_where_reported_and_a_copy_elsewhere() {
let roomy = |device: &mut Queried| {
let descriptors = &mut device.vulkan12;
descriptors.max_per_stage_descriptor_update_after_bind_sampled_images = 3 * 65_536;
descriptors.max_descriptor_set_update_after_bind_sampled_images = 3 * 65_536;
descriptors.max_per_stage_update_after_bind_resources = 6 * 65_536 + 8;
descriptors.max_update_after_bind_descriptors_in_all_pools = 6 * 65_536 + 3 * 8000;
};
let looped = |device: &mut Queried| {
(device.extensions).push(ash::ext::attachment_feedback_loop_layout::NAME.to_owned());
device
@@ -1933,35 +1925,21 @@ fn the_attachment_reads_take_the_feedback_loop_where_reported_and_a_copy_elsewhe
)
};
let mut device = at_the_floor();
assert_eq!(answer(&device), (false, false, 0, 0), "at the floor");
looped(&mut device);
assert_eq!(
answer(&device),
(false, false, 0, 0),
"no room, the loop reported"
);
let mut device = at_the_floor();
roomy(&mut device);
assert_eq!(
answer(&device),
(true, false, 0, 0),
"room, no loop: the copy"
);
assert_eq!(answer(&device), (true, false, 0, 0), "no loop: the copy");
device
.extensions
.extend((ATTACHMENT_READ_EXTENSIONS.iter()).map(|&name| name.to_owned()));
assert_eq!(
answer(&device),
(true, false, 0, 0),
"room, the extensions listed and the features unreported: the copy"
"the extensions listed and the features unreported: the copy"
);
let mut device = at_the_floor();
roomy(&mut device);
looped(&mut device);
assert_eq!(
answer(&device),
(true, true, 1, 1),
"room and the layout extension alone: the loop"
"the layout extension alone: the loop"
);
device.extensions.push(dynamic.to_owned());
let capabilities = decide(&device).unwrap_or_else(|below| panic!("{below}"));
@@ -99,6 +99,7 @@ fn draws(fields: Vec<(DrawPlace, usize, FieldValue)>) -> Draws {
arrays: 0,
bicubic: Vec::new(),
levels: Vec::new(),
level_zero: Vec::new(),
bindings: Vec::new(),
reads_unbound: false,
writes_unbound: false,
+180 -5
View File
@@ -270,6 +270,67 @@ pub(crate) struct TextureInner {
/// draw bound it to a slot written or read at a level other than the constant 0, and given
/// back with it.
levels: Mutex<Option<LevelRun>>,
/// Its level-0 element of set 1's sampled-texture array ([`TextureObject::hold_level_zero`]),
/// where it has a sampled element and is a 1D or 2D texture of one layer; `None` otherwise,
/// whose level-0 element stays null.
level_zero: Option<LevelZero>,
}
/// A texture's level-0 element of set 1's sampled-texture array (`crate::arrays`, the
/// translator's `pipeline::LEVEL_ZERO_ELEMENT` past its index), which a sample or gather through
/// a runtime sampler slot whose word reads unnormalized reads through the state's unnormalized
/// twin: a view of one level and one layer, its first. Written at the first dispatch or draw
/// that binds the texture to a slot a function samples so through a sampler slot that binds
/// such a state (`TextureSlot::level_zero_samplers`), and null again with its index.
struct LevelZero {
/// Its sampled element: its sampled view and the layout it is read in.
element: (vk::ImageView, vk::ImageLayout),
/// The type, mapping and range of a view of its first level alone, where its sampled view
/// has more than one level; `None` where the sampled view is that view.
first_level: Option<(
vk::ImageViewType,
vk::ComponentMapping,
vk::ImageSubresourceRange,
)>,
/// Whether the element is written: a later bind reads it without the lock.
written: AtomicBool,
/// The view of its first level alone, once made, which goes with the texture.
view: Mutex<Option<vk::ImageView>>,
}
impl LevelZero {
/// The level-0 element of a texture whose sampled element is `element`, of `view_type`,
/// mapping `components` and `range`, its levels and layers counted: where it has a sampled
/// element and is a 1D or 2D texture of one layer.
fn of(
element: Option<(vk::ImageView, vk::ImageLayout)>,
view_type: vk::ImageViewType,
components: Option<vk::ComponentMapping>,
range: vk::ImageSubresourceRange,
) -> Option<LevelZero> {
let plane = matches!(
view_type,
vk::ImageViewType::TYPE_1D | vk::ImageViewType::TYPE_2D
);
let (element, components) = (element?, components?);
if !plane || range.layer_count != 1 {
return None;
}
let first_level = (range.level_count > 1).then_some((
view_type,
components,
vk::ImageSubresourceRange {
level_count: 1,
..range
},
));
Some(LevelZero {
element,
first_level,
written: AtomicBool::new(false),
view: Mutex::new(None),
})
}
}
/// A texture's run of set 1's level elements ([`TextureInner`]'s `levels`): its first element,
@@ -1360,10 +1421,19 @@ impl Drop for TextureInner {
}
}
}
// Its level-0 element goes null with its index where it wrote it, before its view goes.
let level_zero = (self.level_zero.as_mut()).map(|zero| {
let view = (zero.view.get_mut())
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
(*zero.written.get_mut(), view)
});
match (self.index, &self.body) {
(Some(at), Body::Image(image)) => {
let second = image.attachment_reads;
core.pool.release(core, Free::TextureIndex(at, second));
let written = level_zero.is_some_and(|(written, _)| written);
core.pool
.release(core, Free::TextureIndex(at, (second, written)));
}
(Some(at), Body::Texels(_)) => core.pool.release(core, Free::TexelIndex(at)),
(None, _) => {}
@@ -1385,6 +1455,9 @@ impl Drop for TextureInner {
if let Some(view) = shadow {
core.pool.release(core, Free::ShadowView(view));
}
if let Some((_, Some(view))) = level_zero {
core.pool.release(core, Free::LevelZeroView(view));
}
// Its run's elements go null before its views go.
let levels = (self.levels.get_mut())
.unwrap_or_else(std::sync::PoisonError::into_inner)
@@ -1909,9 +1982,16 @@ impl Device {
});
// The texture's elements of set 1, written as it takes its index; a refusal frees the
// views as `image` drops.
let element = sampled.map(|view| (view, plan.home));
let level_zero = LevelZero::of(
element.filter(|_| index.is_some()),
shape.view_type,
plan.sampled.map(|(components, _)| components),
counted(&d, &shape, &plan),
);
let index = match index {
Some(index) => {
let sampled = sampled.map(|view| (view, plan.home));
let sampled = element;
// SAFETY: the texture's views are live; its image is in its home layout whenever
// work uses it, from the upload after each acquire to its present.
let owner = unsafe {
@@ -1947,6 +2027,7 @@ impl Device {
attachments: Mutex::default(),
shadow: None,
levels: Mutex::new(None),
level_zero,
};
Ok(Texture {
inner: Arc::new(inner),
@@ -2281,11 +2362,17 @@ impl Device {
*lock(scratch) = Some(Arc::new(Block::new(memory, Arc::clone(core))));
}
let shadow = ShadowView::of(&image, &plan, index, shape.view_type, whole);
let element = sampled.filter(|_| plan.read).map(|view| (view, home));
let level_zero = LevelZero::of(
element.filter(|_| index.is_some()),
shape.view_type,
plan.sampled.map(|(components, _)| components),
counted(&d, &shape, &plan),
);
// The texture's elements of set 1, written as it takes its index; a refusal frees the
// image as `image` drops.
let index = match index {
Some(index) => {
let element = sampled.filter(|_| plan.read).map(|view| (view, home));
let looped = sampled.filter(|_| image.looped());
// SAFETY: the texture's views are live; its image is in its home layout whenever
// work uses it, the upload of the next commit going first.
@@ -2323,6 +2410,7 @@ impl Device {
attachments: Mutex::default(),
shadow,
levels: Mutex::new(None),
level_zero,
};
// Over a buffer of no device copy, the commands track what they write while it lives
// (`crate::over`).
@@ -3765,6 +3853,19 @@ unsafe fn destroy_views(device: &ash::Device, views: Vec<vk::ImageView>) {
}
}
/// The range of a texture of descriptor `d` and `shape`, of the aspect of `plan`'s sampled view:
/// every level and layer, counted, which [`LevelZero::of`] reads.
fn counted(d: &TextureDescriptor, shape: &Shape, plan: &Plan) -> vk::ImageSubresourceRange {
let aspect = (plan.sampled).map_or(vk::ImageAspectFlags::COLOR, |(_, aspect)| aspect);
vk::ImageSubresourceRange {
aspect_mask: aspect,
base_mip_level: 0,
level_count: d.mipmap_level_count,
base_array_layer: 0,
layer_count: shape.layers,
}
}
/// Every level and layer of an image of `aspects`.
fn whole(aspects: vk::ImageAspectFlags) -> vk::ImageSubresourceRange {
vk::ImageSubresourceRange {
@@ -5385,9 +5486,18 @@ impl Texture {
made?;
let image = inner.imaged();
let shadow = ShadowView::of(image, &plan, index, shape.view_type, range);
let element = (sampled.filter(|_| plan.read)).map(|view| (view, image.home));
let level_zero = LevelZero::of(
element.filter(|_| index.is_some()),
shape.view_type,
plan.sampled.map(|(components, _)| components),
range(
plan.sampled
.map_or(vk::ImageAspectFlags::COLOR, |(_, aspect)| aspect),
),
);
let index = match index {
Some(index) => {
let element = (sampled.filter(|_| plan.read)).map(|view| (view, image.home));
let looped = sampled.filter(|_| image.looped());
// SAFETY: the view's image views are live; the image is in its home layout
// whenever work uses it.
@@ -5450,6 +5560,7 @@ impl Texture {
attachments: Mutex::default(),
shadow,
levels: Mutex::new(None),
level_zero,
};
Ok(Texture {
inner: Arc::new(view),
@@ -6810,6 +6921,62 @@ pub(crate) trait TextureObject {
}
}
/// Its level-0 element of set 1's sampled-texture array, written where it has one
/// ([`LevelZero`]) and has not written it yet: its sampled view where that has one level, else
/// a view of its first level alone, which it makes now and keeps until it goes. Called by the
/// dispatch or draw that binds it to a slot a function samples through its level-0 element
/// at a sampler slot that binds a state whose word reads unnormalized
/// (`TextureSlot::level_zero_samplers`); a later bind reads one flag and makes nothing. A
/// view displaced from its index writes nothing: its element is its displacer's.
///
/// Err: [`Error::Vulkan`] where the view cannot be made.
fn hold_level_zero(&self) -> Result<(), Error> {
let inner = self.object();
let (Some(zero), Some(at)) = (&inner.level_zero, inner.index) else {
return Ok(());
};
if zero.written.load(Ordering::Acquire) {
return Ok(());
}
let mut held = lock(&zero.view);
if zero.written.load(Ordering::Acquire) {
return Ok(());
}
let core = &inner.core;
let element = match zero.first_level {
None => zero.element,
Some((view_type, components, range)) => {
let usage = (inner.views_usage).map(|usage| {
usage
& (vk::ImageUsageFlags::SAMPLED
| vk::ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT)
});
// SAFETY: the image is bound, lists the view's format, has the sampled view's
// usage, and holds the range: the sampled view's first level.
let view = unsafe {
image_view(
core,
inner.imaged().image,
view_type,
inner.format,
components,
range,
usage,
)
}?;
*held = Some(view);
core.counters.rise(Gauge::LevelZeroViews);
(view, zero.element.1)
}
};
// SAFETY: the view is live, of one level and one layer of the texture's image, in the
// sampled element's layout whenever work uses it, until the texture's drop vacates its
// elements before the view goes.
unsafe { (core.arrays).place_level_zero(&core.device, at, element) };
zero.written.store(true, Ordering::Release);
Ok(())
}
/// How Metal's bicubic filter treats its texels, under the swizzle it is sampled through
/// (`metal::format::bicubic_texels_word`): `None` for a format with no such treatment.
fn bicubic_texels(&self) -> Option<u32> {
@@ -7790,6 +7957,7 @@ impl Device {
attachments: Mutex::default(),
shadow: None,
levels: Mutex::new(None),
level_zero: None,
};
if form.words.is_some() {
core.counters.rise(Gauge::WordTextureBuffers);
@@ -8033,11 +8201,17 @@ impl Device {
}),
});
let shadow = ShadowView::of(&image, &plan, index, shape.view_type, whole);
let element = sampled.filter(|_| plan.read).map(|view| (view, home));
let level_zero = LevelZero::of(
element.filter(|_| index.is_some()),
shape.view_type,
plan.sampled.map(|(components, _)| components),
counted(&d, &shape, &plan),
);
// The texture's elements of set 1, written as it takes its index; a refusal frees the
// image as `image` drops.
let index = match index {
Some(index) => {
let element = sampled.filter(|_| plan.read).map(|view| (view, home));
let looped = sampled.filter(|_| image.looped());
// SAFETY: the texture's views are live; its image is in its home layout whenever
// work uses it: its making's command buffer moves it ahead of that work, or its
@@ -8075,6 +8249,7 @@ impl Device {
attachments: Mutex::default(),
shadow,
levels: Mutex::new(None),
level_zero,
};
let texture = Texture {
inner: Arc::new(inner),
@@ -1 +1 @@
1ab29fff848f010e243b8454d5f31fef65d11daca90b4a1e2f32f8d3917b390e
8af4288375badbddb1b814d7c5ab4693dab8ae4928fd16b08267964c736cf188
+4 -1
View File
@@ -1106,7 +1106,10 @@ codec_struct! {
output_winding_order, control_point_index_type, factor_scale_enabled,
}
BufferSlot { access, window, form, kind }
TextureSlot { texture_type, sampled_type, depth_compare, access, storage, declared_format }
TextureSlot {
texture_type, sampled_type, depth_compare, access, storage, declared_format,
level_zero_samplers,
}
TextureAccess { sample, read, write }
SamplerSlot { compare, coordinate_sensitive }
AccessSet { read, write }
@@ -849,6 +849,163 @@ pub(super) fn sampled_value(
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
grads: Option<(SValue, SValue)>,
) -> BResult<SValue> {
// Where the bound sampler's word reads unnormalized and the slot's index is a texture's own,
// the coordinate itself through the texture's level-0 element; the rest of this path
// elsewhere.
if let (true, Source::Combined(key)) = (s.level_zero, s.source) {
let Some(at) = level_zero_test(cx, fb, key)? else {
return Err(cx.fail("a level-0 sample through no runtime sampler slot"));
};
let exact: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| {
let x = level_zero_value(cx, fb, s, key)?;
Ok(ArmEnd::FallThrough(vec![x]))
});
let rest: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| {
let x = device_sampled_value(cx, fb, s, grads)?;
Ok(ArmEnd::FallThrough(vec![x]))
});
let Merged(merged) = fb.if_(cx, at, exact, Some(rest))?;
return match merged[..] {
[x] => Ok(x),
_ => Err(cx.fail("a level-0 sample without its merged result")),
};
}
device_sampled_value(cx, fb, s, grads)
}
/// Whether a sampling of combined binding `key` through runtime sampler slot `n` reads the
/// texture's level-0 element ([`Sampling::level_zero`]), a `bool`: the slot's word reads
/// unnormalized (`SamplerWord::reads_unnormalized`) and the texture slot's pushed index is a
/// texture's own, below the second elements. `None` for a binding of no runtime sampler slot.
fn level_zero_test(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
key: super::BindingKey,
) -> BResult<Option<SValue>> {
let SamplerRef::Slot(n) = key.sampler else {
return Ok(None);
};
let k = |fb: &mut FunctionBuilder<'_>, v: u32| -> BResult<SValue> {
let c = fb.u32_const(v)?;
fb.module().const_value(c)
};
let word = sampler_word(cx, fb, Pixel::Spec(n))?;
let mask = k(fb, SamplerWord::UNNORMALIZED_FILTERS)?;
let filters = fb.binary(BinOp::BitwiseAnd, word, mask)?;
let nearest = k(fb, SamplerWord::UNNORMALIZED_NEAREST)?;
let linear = k(fb, SamplerWord::UNNORMALIZED_LINEAR)?;
let is_nearest = fb.binary(BinOp::IEqual, filters, nearest)?;
let is_linear = fb.binary(BinOp::IEqual, filters, linear)?;
let mut at = fb.binary(BinOp::LogicalOr, is_nearest, is_linear)?;
for axis in 0..2 {
let shift = k(fb, SamplerWord::ADDRESS_SHIFT[axis])?;
let bits = k(
fb,
SamplerWord::ADDRESS[axis] >> SamplerWord::ADDRESS_SHIFT[axis],
)?;
let mode = fb.binary(BinOp::ShiftRightLogical, word, shift)?;
let mode = fb.binary(BinOp::BitwiseAnd, mode, bits)?;
let mut clamps = None;
for raw in SamplerWord::UNNORMALIZED_MODES {
let raw = k(fb, raw)?;
let is = fb.binary(BinOp::IEqual, mode, raw)?;
clamps = Some(match clamps {
Some(c) => fb.binary(BinOp::LogicalOr, c, is)?,
None => is,
});
}
let Some(clamps) = clamps else {
return Err(cx.fail("no address mode the unnormalized sampler reads"));
};
at = fb.binary(BinOp::LogicalAnd, at, clamps)?;
}
// A second element, pushed while a draw reads an attachment through the texture, has no
// level-0 element.
let element = slot_element(cx, fb, key)?;
let textures = k(fb, crate::pipeline::link::IDENTITY_TEXTURES)?;
let own = fb.binary(BinOp::ULessThan, element, textures)?;
Ok(Some(fb.binary(BinOp::LogicalAnd, at, own)?))
}
/// The texture slot's pushed index of combined binding `key` (`PushField::SlotGuestBase`).
fn slot_element(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
key: super::BindingKey,
) -> BResult<SValue> {
let Some(slot) = (cx.plan.families.texture.slots.get(&key.texture)).map(|s| s.slot) else {
return Err(cx.fail(format!("combined binding {key:?} is not declared")));
};
let id = cx.push_field(fb, crate::pipeline::sym::PushField::SlotGuestBase(slot))?;
fb.composite_extract(id, &[0])
}
/// Sampling `s` of combined binding `key` through the texture's level-0 element
/// (`pipeline::LEVEL_ZERO_ELEMENT` past its index) and the slot sampler's unnormalized twin
/// (`pipeline::UNNORMALIZED_TWIN_ELEMENT` past its index in the plain array), at its coordinate
/// itself moved by its offset, at level 0: the texels and weights the device's unnormalized
/// sampler reads from `x`, which Metal's sampler reads from `x` on its own grid.
fn level_zero_value(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
key: super::BindingKey,
) -> BResult<SValue> {
let Some(i) = cx.plan.families.sampler.identity.get(&key).copied() else {
return Err(cx.fail(format!("combined binding {key:?} has no identity sampling")));
};
let SamplerRef::Slot(n) = key.sampler else {
return Err(cx.fail("a level-0 sample through no runtime sampler slot"));
};
let images = cx.decl.families.texture.heap.get(&i.class).copied();
let samplers = cx.decl.families.sampler.identity.get(&i.use_).copied();
let (Some(images), Some(samplers)) = (images, samplers) else {
return Err(cx.fail(format!("combined binding {key:?} is not declared")));
};
let k = |fb: &mut FunctionBuilder<'_>, v: u32| -> BResult<SValue> {
let c = fb.u32_const(v)?;
fb.module().const_value(c)
};
let element = slot_element(cx, fb, key)?;
let first = k(fb, crate::pipeline::LEVEL_ZERO_ELEMENT)?;
let element = fb.binary(BinOp::IAdd, element, first)?;
let base = fb.module().global_value(images)?;
let p = fb.access_chain(base, &[element])?;
let img = fb.load(p, MemAccess::default())?;
let id = sampler_id(cx, fb, n)?;
let twin = fb.composite_extract(id, &[0])?;
let offset = k(fb, crate::pipeline::UNNORMALIZED_TWIN_ELEMENT)?;
let twin = fb.binary(BinOp::IAdd, twin, offset)?;
let base = fb.module().global_value(samplers)?;
let p = fb.access_chain(base, &[twin])?;
let sampler = fb.load(p, MemAccess::default())?;
let si = fb.sampled_image(img, sampler)?;
// The device's unnormalized sampler takes no offset operand: the coordinate holds it.
let coord = plane_coord(cx, fb, s)?;
let coord = offset_texels(cx, fb, s, coord)?;
let x = match &s.op {
SampleOp::Sample { .. } => {
let ops = ImageOperands {
lod: Some(f32_const(fb, 0)?),
..ImageOperands::default()
};
fb.sample(si, coord, None, false, &ops)?
}
SampleOp::Gather { component, .. } => {
fb.gather(si, coord, *component, &ImageOperands::default())?
}
_ => return Err(cx.fail("a level-0 access neither a sample nor a gather")),
};
texel_value(cx, fb, s, i.combined(), x)
}
/// [`sampled_value`] past its level-0 arm: the device's sampler at the texture's own element.
fn device_sampled_value(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
grads: Option<(SValue, SValue)>,
) -> BResult<SValue> {
let (si, image, live) = sampled_image(cx, fb, s.source)?;
if let SampleOp::QueryLevel { min } = &s.op {
@@ -644,6 +644,15 @@ pub struct Sampling {
/// reference is clamped to `[0, 1]`, a NaN taken as 0, before every comparison
/// ([`emit::reference`]).
pub clamp_reference: bool,
/// A sample or gather through a runtime sampler slot of a float 1D or 2D texture that is no
/// array ([`Pixel::Spec`]), without a comparison, whose offset no rule of Metal's places:
/// where the bound sampler's word reads unnormalized (`SamplerWord::reads_unnormalized`) and
/// the slot's pushed index is a texture's own, not a second element, it hands its coordinate
/// itself, moved by its offset, to the sampler's unnormalized twin
/// (`pipeline::UNNORMALIZED_TWIN_ELEMENT`) at the texture's level-0 element
/// (`pipeline::LEVEL_ZERO_ELEMENT`), at level 0 ([`emit::sampled_value`]); any other word
/// takes the sampling's other arms.
pub level_zero: bool,
}
impl Sampling {
@@ -1946,6 +1946,41 @@ fn select_one(
cx.derivatives.insert(value);
}
let clamp_reference = clamps_reference(cx, comparison, sampler)?;
// A sample or gather through a runtime sampler slot of a float 1D or 2D texture that is no
// array, without a comparison or an offset placed by Metal's rule: where the bound sampler's
// word reads unnormalized, the device's unnormalized sampler reads its coordinate itself at
// the texture's level-0 element, and the slot names the sampler slot
// (`TextureSlot::level_zero_samplers`).
let level_zero = match (source, image) {
(Source::Combined(key), ImageRef::Slot(index)) => {
let plain_op = matches!(
op,
SampleOp::Sample { dref: None, .. } | SampleOp::Gather { dref: None, .. }
);
let plane = matches!(shape.dim, ImageDim::D1 | ImageDim::D2)
&& !shape.array
&& !shape.ms
&& !shape.depth;
let exact = match key.sampler {
SamplerRef::Slot(n) if pixel == Pixel::Spec(n) && n < 16 => {
plain_op
&& plane
&& !integer
&& !key.compare
&& !key.unnormalized
&& !offset_base
}
_ => false,
};
if let (true, SamplerRef::Slot(n)) = (exact, key.sampler) {
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
s.uses.level_zero_samplers |= 1 << n;
}
}
exact
}
_ => false,
};
let sampling = Sampling {
source,
op,
@@ -1961,6 +1996,7 @@ fn select_one(
swizzle,
offset_base,
clamp_reference,
level_zero,
};
Ok(sampling)
}
@@ -75,6 +75,11 @@ pub struct Uses {
/// An integer texel's write reads the widths of the bound texture's channels
/// (`IntRange::SlotWord`): the slot's storage choice declares no format.
pub int_channels: bool,
/// Under the identity domains, the runtime sampler slots through which a sample or gather
/// reads the slot's level-0 element where the bound sampler's word reads unnormalized
/// (`Sampling::level_zero`): bit `n` for `[[sampler(n)]]`
/// (`TextureSlot::level_zero_samplers`).
pub level_zero_samplers: u16,
}
/// The `OpTypeImage` a slot is declared as, and the conversion a storage image's class needs.
@@ -248,6 +253,7 @@ impl SlotPlan {
declared_format: (self.decl.as_ref()).is_some_and(|d| {
d.usage == ImageUsage::Storage && d.format != crate::spv::ImageFormat::Unknown
}),
level_zero_samplers: u.level_zero_samplers,
})
}
}
+82
View File
@@ -980,6 +980,43 @@ impl SamplerWord {
}
mask
}
/// The bits of a sampler's filters that decide whether the device's unnormalized sampler reads
/// it ([`reads_unnormalized`](Self::reads_unnormalized)): the word masked by them is
/// [`UNNORMALIZED_NEAREST`](Self::UNNORMALIZED_NEAREST) or
/// [`UNNORMALIZED_LINEAR`](Self::UNNORMALIZED_LINEAR) exactly for one.
pub const UNNORMALIZED_FILTERS: u32 = Self::PIXEL_COORDINATES
| Self::MIN_LINEAR
| Self::MAG_LINEAR
| Self::MIP_FILTER
| Self::ANISOTROPIC;
/// [`UNNORMALIZED_FILTERS`](Self::UNNORMALIZED_FILTERS) of a pixel sampler of nearest filters,
/// no mip filter, isotropic.
pub const UNNORMALIZED_NEAREST: u32 = Self::PIXEL_COORDINATES;
/// [`UNNORMALIZED_FILTERS`](Self::UNNORMALIZED_FILTERS) of a pixel sampler of linear filters,
/// no mip filter, isotropic.
pub const UNNORMALIZED_LINEAR: u32 = Self::PIXEL_COORDINATES | Self::LINEAR;
/// The address modes the device's unnormalized sampler reads on the `s` and `t` axes, by their
/// raw values: `ClampToEdge` (0), `ClampToZero` (4) and `ClampToBorderColor` (5), which the
/// device's `CLAMP_TO_EDGE` and `CLAMP_TO_BORDER` are.
pub const UNNORMALIZED_MODES: [u32; 3] = [0, 4, 5];
/// Whether the device's unnormalized sampler (`VkSamplerCreateInfo::unnormalizedCoordinates`)
/// reads the sampler of this word as it is, the word's form of a descriptor's
/// `metal::sampler::unnormalized_reads`: pixel coordinates, one minification and
/// magnification filter (nearest or linear), no mip filter, no anisotropy, and on the `s` and
/// `t` axes one of [`UNNORMALIZED_MODES`](Self::UNNORMALIZED_MODES). A sample or gather
/// through a runtime sampler slot whose word this holds for reads the texture's level-0
/// element through the state's unnormalized twin at the coordinate itself (docs/RESOURCE-ID.md,
/// [`TextureSlot::level_zero_samplers`](crate::pipeline::TextureSlot::level_zero_samplers)).
pub fn reads_unnormalized(self) -> bool {
let filters = self.0 & Self::UNNORMALIZED_FILTERS;
let mode = |axis: usize| (self.0 & Self::ADDRESS[axis]) >> Self::ADDRESS_SHIFT[axis];
matches!(
filters,
Self::UNNORMALIZED_NEAREST | Self::UNNORMALIZED_LINEAR
) && (0..2).all(|axis| Self::UNNORMALIZED_MODES.contains(&mode(axis)))
}
}
#[cfg(test)]
@@ -1011,6 +1048,51 @@ mod tests {
}
}
/// A word's `reads_unnormalized` is its descriptor's `unnormalized_reads`, over every
/// coordinate kind, pair of filters, mip filter, anisotropy and pair of `s` and `t` address
/// modes, with the `r` axis's mode, the border, the comparison and the reduction moved too.
#[test]
fn a_words_unnormalized_reads_are_its_descriptors() {
let mut seen = [0usize; 2];
for normalized_coordinates in [false, true] {
for &min_filter in SamplerMinMagFilter::ALL {
for &mag_filter in SamplerMinMagFilter::ALL {
for &mip_filter in SamplerMipFilter::ALL {
for max_anisotropy in [1, 2, 16] {
for &s in SamplerAddressMode::ALL {
for &t in SamplerAddressMode::ALL {
let desc = SamplerDescriptor {
normalized_coordinates,
min_filter,
mag_filter,
mip_filter,
max_anisotropy,
s_address_mode: s,
t_address_mode: t,
r_address_mode: SamplerAddressMode::Repeat,
border_color: SamplerBorderColor::OpaqueWhite,
compare_function: CompareFunction::Less,
reduction_mode: SamplerReductionMode::Minimum,
..metal_default()
};
let reads = unnormalized_reads(&desc);
assert_eq!(
SamplerWord::of(&desc).reads_unnormalized(),
reads,
"{desc:?}"
);
seen[usize::from(reads)] += 1;
}
}
}
}
}
}
}
// Each answer is met: two filters, three modes on each axis.
assert_eq!(seen[1], 2 * 3 * 3);
}
/// Bind-time clamps read as the descriptor's own where each bound held to the levels a sample
/// can read is the descriptor's: a replay's `(0, 1000)` over a state's `(0, FLT_MAX)` among
/// them. Each pair that reads alike gives the descriptor's word and its device sampler's
@@ -408,6 +408,7 @@ mod serde_round_trips {
access: TextureAccess::new(false, true, true),
storage: true,
declared_format: false,
level_zero_samplers: 0b10,
}),
);
slots.insert(
+21 -12
View File
@@ -421,18 +421,27 @@ pub enum PrecisionNote {
/// neither), a level query, and every linear sample, gather and comparison through a runtime
/// sampler slot (whose state the function does not know), held where the bound sampler states
/// pixel coordinates and, for a sample or comparison, that it is not a nearest one of one
/// isotropic level (`SpecKey::NearestPixelSampler`). Not recorded where Metal's texel or
/// footprint follows from `x` itself: a constexpr pixel sampler's sample or gather of a 1D or
/// 2D texture that is no array hands `x` (moved by its offset) to the device's unnormalized
/// sampler; a nearest sample elsewhere hands the device its texel's centre `floor(x) + 0.5`
/// over the size, where the device reads exactly that texel (through a runtime slot behind the
/// slot's `NearestPixelSampler` specialization); and a nearest constexpr sampler clamped to the
/// edge fetches its texel (`sampler.pixel_fetch`). Measured: the device answers as its
/// normalized sampler at a coordinate within one `f32` ulp of the quotient `x / N` on MoltenVK,
/// and at the quotient itself on lavapipe (800 coordinates at and around each texel edge of a
/// 5x3 texture, every filter and address mode); on MoltenVK a linear sample through a runtime
/// or argument buffer's sampler or of an array reads another weight step than Metal's at under
/// 1% of the coordinates at and around each texel edge of textures 258, 21 and 37 texels wide
/// isotropic level (`SpecKey::NearestPixelSampler`), and for a sample or gather of a float 1D
/// or 2D texture that is no array, that its word does not read unnormalized
/// ([`SamplerWord::reads_unnormalized`](crate::metal::sampler::SamplerWord::reads_unnormalized))
/// or that a draw reads the texture as its pass's attachment. Not
/// recorded where Metal's texel or footprint
/// follows from `x` itself: a constexpr pixel sampler's sample or gather of a 1D or 2D texture
/// that is no array hands `x` (moved by its offset) to the device's unnormalized sampler, and
/// so does such a sample or gather through a runtime sampler slot whose bound state's word
/// reads unnormalized, through the state's unnormalized twin at the texture's level-0 element
/// ([`LEVEL_ZERO_ELEMENT`](crate::pipeline::LEVEL_ZERO_ELEMENT),
/// [`UNNORMALIZED_TWIN_ELEMENT`](crate::pipeline::UNNORMALIZED_TWIN_ELEMENT)), the operation
/// recording the note for the states whose word does not; a
/// nearest sample elsewhere hands the device its texel's centre `floor(x) + 0.5` over the size,
/// where the device reads exactly that texel (through a runtime slot behind the slot's
/// `NearestPixelSampler` specialization); and a nearest constexpr sampler clamped to the edge
/// fetches its texel (`sampler.pixel_fetch`). Measured: the device answers as its normalized
/// sampler at a coordinate within one `f32` ulp of the quotient `x / N` on MoltenVK, and at the
/// quotient itself on lavapipe (800 coordinates at and around each texel edge of a 5x3
/// texture, every filter and address mode); on MoltenVK a linear sample through a runtime or
/// argument buffer's sampler or of an array reads another weight step than Metal's at under 1%
/// of the coordinates at and around each texel edge of textures 258, 21 and 37 texels wide
/// (where `x - 0.5` lies at a half step of Metal's `1/256` grid); a linear downscale by 8 of
/// textures 1000 to 1920 texels wide is within 1/255 of Metal's on MoltenVK and 2/255 on
/// lavapipe (a weight one 1/256 step off on each axis); other devices unmeasured. A cube's
@@ -143,6 +143,18 @@ pub struct TextureSlot {
/// slot declared without a format, and for a `sample` or `read` slot.
#[cfg_attr(feature = "serde", serde(default))]
pub declared_format: bool,
/// Under the identity domains, the runtime sampler slots through which the function samples
/// or gathers the slot's texture at its level-0 element ([`LEVEL_ZERO_ELEMENT`] plus its
/// index) where the bound sampler's word reads unnormalized
/// ([`SamplerWord::reads_unnormalized`]): bit `n` for `[[sampler(n)]]`. A binder writes the
/// bound texture's level-0 element before a draw or dispatch that binds such a sampler at
/// one of them: its sampled view where that has one level and one layer, else a view of its
/// first level alone. 0 for a slot sampled through none, and outside the identity domains.
///
/// [`LEVEL_ZERO_ELEMENT`]: crate::pipeline::LEVEL_ZERO_ELEMENT
/// [`SamplerWord::reads_unnormalized`]: crate::metal::sampler::SamplerWord::reads_unnormalized
#[cfg_attr(feature = "serde", serde(default))]
pub level_zero_samplers: u16,
}
/// How a texture is used (Metal `access::` qualifiers plus sampling).
+18
View File
@@ -848,6 +848,24 @@ fn layout(
pub(crate) const IDENTITY_TEXTURES: u32 = 65_536;
const _: () = assert!(IDENTITY_TEXTURES.is_power_of_two());
/// The identity domains' sampled-image array's (binding 0) level-0 element of texture index 0:
/// index `i`'s is this plus `i` (`docs/RESOURCE-ID.md`). It holds a view of the texture's first
/// level alone, one level and one layer, which a sample or gather through a runtime sampler slot
/// whose word reads unnormalized (`SamplerWord::reads_unnormalized`) reads with the sampler's
/// unnormalized twin ([`UNNORMALIZED_TWIN_ELEMENT`]): the elements past the textures' own and
/// their second elements, which no resource ID reaches. A function names the texture slots it
/// samples so ([`TextureSlot::level_zero_samplers`](crate::pipeline::TextureSlot)).
pub const LEVEL_ZERO_ELEMENT: u32 = 2 * IDENTITY_TEXTURES;
/// The offset in the identity domains' plain sampler array (binding 2) of each element's
/// unnormalized twin: element `i`'s, of a sampler whose word reads unnormalized
/// (`SamplerWord::reads_unnormalized`), is this plus `i`, the device sampler of its descriptor
/// with `unnormalizedCoordinates`, which samples the texture's level-0 element
/// ([`LEVEL_ZERO_ELEMENT`]) at the pixel coordinate itself. Past the 4,000 indices a resource ID
/// reaches and the 4,000 a consumer may place a sampler state's LOD-clamp variants at
/// (`docs/RESOURCE-ID.md`).
pub const UNNORMALIZED_TWIN_ELEMENT: u32 = 8_000;
/// Each sampler array of the identity domains' set 1: bindings 2, 3 and 4, one element per index a
/// sampler's resource ID may hold (`docs/RESOURCE-ID.md`). An argument buffer's sampler index not
/// below it reads element 0 (`lower::access::handle`).
+3 -1
View File
@@ -128,7 +128,9 @@ pub use interface::{
pub use layout::{
BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange,
};
pub use link::{heap_sampler_capacity, heap_unused_while_pending};
pub use link::{
heap_sampler_capacity, heap_unused_while_pending, LEVEL_ZERO_ELEMENT, UNNORMALIZED_TWIN_ELEMENT,
};
pub use lower_inputs::{
AliasView, AmplificationDraws, ChannelWrite, ExtendedRangeColor, FactorLane, KernelVariant,
LoweringInputs, StorageImageChoice, StorageImageClass, VertexFetch, VertexFetchProjection,
+14 -7
View File
@@ -1828,15 +1828,22 @@ category, and says what makes an operation carry the note and what may differ. E
filter's pair of texels, a gather's block or one of the filter's sub-texel steps it may read the
neighbouring pair, block or step, where Metal's sampler reads the coordinate as given. Recorded
for a linear sample, a gather and a level query through a constexpr pixel sampler of an array or a
3D texture, and through a runtime sampler slot (where the bound state reads pixel coordinates, and
for a sample or comparison where it is not a nearest one of one isotropic level). Measured: the
device's normalized sampler's answer within one `f32` ulp of the quotient on MoltenVK and at the
quotient on lavapipe; a linear downscale by 8 within 1/255 of Metal's on MoltenVK and 2/255 on
lavapipe. Under the identity domains it is also recorded for a linear sample and a gather through
any constexpr pixel sampler, whose device sampler the consumer makes normalized. Nothing is
3D texture, and through a runtime sampler slot (where the bound state reads pixel coordinates, for
a sample or comparison where it is not a nearest one of one isotropic level, and for a sample or
gather of a float 1D or 2D texture that is no array where the state's word does not read
unnormalized, `SamplerWord::reads_unnormalized`, or a draw reads the texture as its pass's
attachment). Measured: the device's normalized sampler's answer within one `f32` ulp of the
quotient on MoltenVK and at the quotient on lavapipe; a linear downscale by 8 within 1/255 of
Metal's on MoltenVK and 2/255 on lavapipe. Under the identity domains it is also recorded for a
linear sample and a gather through any constexpr pixel sampler, whose device sampler the consumer
makes normalized. Nothing is
recorded where Metal's texel or footprint follows from the coordinate itself: elsewhere a
constexpr pixel sampler's sample or gather of a 1D or 2D texture that is no array hands the
coordinate, moved by its offset, to the device's unnormalized sampler; a nearest sample elsewhere
coordinate, moved by its offset, to the device's unnormalized sampler; so does such a sample or
gather through a runtime sampler slot whose bound state's word reads unnormalized (one nearest
or linear filter, no mip filter, isotropic, clamping to the edge, zero or the border on `s` and
`t`), through the state's unnormalized twin at the texture's level-0 element (docs/RESOURCE-ID.md),
where the note stays recorded for the states whose word does not; a nearest sample elsewhere
hands the device its texel's centre, where the device reads exactly Metal's texel; and a nearest
constexpr sampler clamped to the edge fetches its texel.
- `metal2vulkan-degrade-device-arithmetic` (precision). `PrecisionNote::DeviceArithmetic`: Float