diff --git a/crates/metal2vulkan-runtime/src/binding.rs b/crates/metal2vulkan-runtime/src/binding.rs index 08ed06cc3..b60ede9a2 100644 --- a/crates/metal2vulkan-runtime/src/binding.rs +++ b/crates/metal2vulkan-runtime/src/binding.rs @@ -2098,12 +2098,17 @@ fn texel_descriptor( let texels = texture .texels() .ok_or_else(|| internal("a texel buffer write of a texture with an image"))?; + let place = (write.set, write.binding, write.array_element); let range = command .descriptor_ranges .iter() - .find(|r| (r.set, r.binding) == (write.set, write.binding)) + .find(|r| (r.set, r.binding, r.element) == place) .ok_or_else(|| internal("a texel buffer write without its range"))? .range; + // A part of a texture buffer wider than one view holds (`bind::texel_parts`). + if write.array_element > 0 { + device.shared().counts.thread().texel_buffer_parts_bound(); + } texels.view(*format, storage, range) } WriteSource::Neutral(NeutralResource::TexelBuffer { format }) => { diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index 62d8f6427..36bd5676d 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -2545,12 +2545,18 @@ impl Texels { /// What a binding plan reads of a texture buffer of `pixel_format` and `swizzle` over these /// texels: the texels' offset in the `VkBuffer` its bindings view (`Texels::viewed`), which - /// the plan's view ranges address, and the swizzle a function's reads apply. + /// the plan's view ranges address, the swizzle a function's reads apply, and the texel buffer + /// views its texels take on the device (`bind::texel_buffer_parts`): past one where they + /// pass its `maxTexelBufferElements`, which a slot that reads them through their parts binds + /// (`bind::texel_parts`). pub(super) fn bound( &self, pixel_format: PixelFormat, swizzle: TextureSwizzleChannels, ) -> BoundTexture { + let device = self.buffer.generation(); + let limits = device.compile_device().profile().limits(); + let texels = self.shader.row_bytes / self.texel_bytes.max(1); BoundTexture::Buffer { pixel_format, offset: self.viewed().1, @@ -2558,6 +2564,7 @@ impl Texels { bytes_per_row: self.shader.row_pitch, resource_id: None, swizzle, + parts: metal2vulkan::bind::texel_buffer_parts(limits, texels), } } diff --git a/crates/metal2vulkan-runtime/src/families/limits.rs b/crates/metal2vulkan-runtime/src/families/limits.rs index d6ab8fb22..8a707d3ba 100644 --- a/crates/metal2vulkan-runtime/src/families/limits.rs +++ b/crates/metal2vulkan-runtime/src/families/limits.rs @@ -896,12 +896,16 @@ impl LimitRow { VkLimit::MaxImageArrayLayers, l.max_image_array_layers, )]), - // A texture buffer's texels: `maxTexelBufferElements`. - L::TextureBufferWidth => first([at_least( - Feature::TexelBuffer, - VkLimit::MaxTexelBufferElements, - l.max_texel_buffer_elements, - )]), + // A texture buffer's texels: `maxTexelBufferElements` through one view, and past it + // through views of its parts ([`parts_reach`]). + L::TextureBufferWidth => match need { + Need::AtLeast(n) if parts_reach(f.profile, n) => RowState::Exact, + _ => first([at_least( + Feature::TexelBuffer, + VkLimit::MaxTexelBufferElements, + l.max_texel_buffer_elements, + )]), + }, // A pass's color attachments: `maxColorAttachments` and // `maxFragmentOutputAttachments`. Past the lesser, a pass draws its colors in groups // of that many (`render/color_groups.rs`), whose refusals keep the row a gap. @@ -1075,6 +1079,22 @@ impl LimitRow { /// `feature`, refused where the device's `limit`, `available`, is below what `need` asks. The /// rows it serves ask a bound in every column. +/// Whether a texture buffer of `texels` texels binds on `profile`'s device through views of its +/// parts (`metal2vulkan::bind::texel_parts`): the device indexes arrays of uniform and of storage +/// texel buffers by a `NonUniform` value, and a stage holds as many sampled and as many storage +/// image descriptors as the texture buffer has parts. A function that does more with the texture +/// buffer than read, write, update or ask its width binds one view, which +/// `maxTexelBufferElements` bounds (`BindError::TexelBufferTooLarge`). +fn parts_reach(profile: &metal2vulkan::device::DeviceProfile, texels: u64) -> bool { + let l = profile.limits(); + let d = profile.descriptors(); + let parts = metal2vulkan::bind::texel_buffer_parts(l, texels); + d.non_uniform_uniform_texel_buffer + && d.non_uniform_storage_texel_buffer + && parts <= l.max_per_stage_descriptor_sampled_images + && parts <= l.max_per_stage_descriptor_storage_images +} + fn at_least(need: Need, feature: Feature, limit: VkLimit, available: u64) -> Check { match need { Need::AtLeast(required) if available < required => Some(refused(Unsupported::needs( diff --git a/crates/metal2vulkan-runtime/src/tests/buffer_tail_device.rs b/crates/metal2vulkan-runtime/src/tests/buffer_tail_device.rs index 74554b5b4..8b71be24a 100644 --- a/crates/metal2vulkan-runtime/src/tests/buffer_tail_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/buffer_tail_device.rs @@ -818,14 +818,14 @@ fn an_array_s_slice_past_the_length_lies_in_its_tail() { /// `validation/fixtures/public/engine/ob1_texel_buffer.ll`), whose thread `t` of eight reads /// texel `idx[t]` of its first texture buffer into `out[t]` and writes `0xA0000000 | t` to texel /// `idx[8 + t]` of its second. -struct TexelKernel { +pub(super) struct TexelKernel { queue: CommandQueue, pipeline: ComputePipelineState, device: Device, } impl TexelKernel { - fn new(device: &Device) -> TexelKernel { + pub(super) fn new(device: &Device) -> TexelKernel { let library = library(device, "engine/ob1_texel_buffer.ll"); let function = library.new_function_with_name("ob1_texel_buffer").unwrap(); let options = PipelineOptions::default(); @@ -840,7 +840,7 @@ impl TexelKernel { /// A texture buffer of `width` `R32Uint` texels at `offset` of `buffer`, read and written by /// shaders. - fn over(buffer: &Buffer, width: u64, offset: u64) -> Texture { + pub(super) fn over(buffer: &Buffer, width: u64, offset: u64) -> Texture { let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; let descriptor = TextureDescriptor::texture_buffer( PixelFormat::R32Uint, @@ -853,7 +853,7 @@ impl TexelKernel { /// One dispatch: texels `reads` of `from` into the answer, `0xA0000000 | t` into texel /// `writes[t]` of `into`. - fn run( + pub(super) fn run( &self, (from, reads): (&Texture, [u32; 8]), (into, writes): (&Texture, [u32; 8]), diff --git a/crates/metal2vulkan-runtime/src/tests/families.rs b/crates/metal2vulkan-runtime/src/tests/families.rs index 1a7abbe5c..22eee4bcb 100644 --- a/crates/metal2vulkan-runtime/src/tests/families.rs +++ b/crates/metal2vulkan-runtime/src/tests/families.rs @@ -266,11 +266,13 @@ fn each_family_lists_its_columns_rows() { } /// States read from the device: framebuffer fetch's form, cube arrays, the SIMD and quad rows by -/// the stages' classes, and a limit's cell against the device's limit. +/// the stages' classes, and a limit's cell against the device's limit, the texture buffer's width +/// through its parts past it. #[test] fn states_follow_their_sources() { use FeatureRow as F; let mut storage_fetch = BTreeSet::new(); + let mut parted = BTreeSet::new(); for (stem, desc) in committed_descriptions() { let all = all_audits(&stem, &desc); let (enabled, _) = created(&stem, &desc); @@ -359,15 +361,27 @@ fn states_follow_their_sources() { ); } } - // Apple3's texture buffers: 256 M texels (2^28) against `maxTexelBufferElements`. + // Apple3's texture buffers: 256 M texels (2^28) against `maxTexelBufferElements`, or past + // it through views of their parts, where the device indexes texel buffer arrays by a + // `NonUniform` value and a stage holds that many views. let width = state( &all[&GpuFamily::Apple3], FamilyRow::Limit(LimitRow::TextureBufferWidth), ) .unwrap(); let available = u64::from(enabled.limits.max_texel_buffer_elements); - if available >= 1 << 28 { + let compile = Device::new(enabled.clone(), DevicePolicy::UNTRUSTED).unwrap(); + let d = compile.profile().descriptors(); + let parts = metal2vulkan::bind::texel_buffer_parts(compile.profile().limits(), 1 << 28); + let in_parts = d.non_uniform_uniform_texel_buffer + && d.non_uniform_storage_texel_buffer + && parts <= enabled.limits.max_per_stage_descriptor_sampled_images + && parts <= enabled.limits.max_per_stage_descriptor_storage_images; + if available >= 1 << 28 || in_parts { assert_eq!(width, RowState::Exact, "{stem}"); + if available < 1 << 28 { + parted.insert(stem.clone()); + } } else { assert_eq!( width, @@ -384,6 +398,10 @@ fn states_follow_their_sources() { } } assert_eq!(storage_fetch.len(), 4, "{storage_fetch:?}"); + // lavapipe's and ANV's 2^27 and MoltenVK's 2^26 reach 2^28 through parts. + for stem in ["lavapipe", "intel-irisxe-anv", "moltenvk-m3"] { + assert!(parted.contains(stem), "{stem}: {parted:?}"); + } } /// Vertex amplification: Apple7's count of 8 is exact on a device with `multiview`, through the diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index adea40f8b..298a0a07d 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -783,6 +783,8 @@ mod texel_rows_device; mod texture; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod texture_aggregates; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod texture_buffer_width_device; mod texture_descriptor; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod texture_facts; diff --git a/crates/metal2vulkan-runtime/src/tests/texture_buffer_width_device.rs b/crates/metal2vulkan-runtime/src/tests/texture_buffer_width_device.rs new file mode 100644 index 000000000..8ece95d56 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/texture_buffer_width_device.rs @@ -0,0 +1,121 @@ +//! A texture buffer wider than the device's `maxTexelBufferElements`: Metal makes one of up to +//! 2^28 texels on every Mac (`texture_descriptor.rs`'s `MAX_TEXTURE_BUFFER_WIDTH`), and a kernel +//! reads and writes each of its texels, while lavapipe and ANV view at most 2^27 texels through one +//! texel buffer. The runtime binds such a texture buffer through views of its parts +//! (`metal2vulkan::bind::texel_buffer_parts`). +//! +//! The kernel is `ob1_texel_buffer` (the owned fixture +//! `validation/fixtures/public/engine/ob1_texel_buffer.ll`): thread `t` of eight reads texel +//! `idx[t]` of its first texture buffer into `out[t]` and writes `0xA0000000 | t` to texel +//! `idx[8 + t]` of its second. +//! +//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. + +use super::blit_holds::{device, Scratch}; +use super::buffer_tail_device::TexelKernel; +use crate::ResourceOptions; + +/// The widest texture buffer Metal makes. +const METAL_WIDEST: u64 = 1 << 28; + +/// The word texel `at` holds before the kernel writes: never zero, Metal's out-of-bounds read. +fn word(at: u64) -> u32 { + 0x5000_0000 ^ at as u32 +} + +/// A texture buffer of `R32Uint` texels 64 past the device's `maxTexelBufferElements` (the +/// device's limit `L`, its width `L + 64`): a kernel reads texels on both sides of `L`, and its +/// last, as the buffer holds them, and Metal's zero past its last; it writes texels on both +/// sides of `L` and its last, which the buffer and a kernel then read, and drops the writes past +/// its last. Each dispatch binds the texture buffer through its parts +/// (`WorkCounts::texel_buffer_parts_bound`). A device that views 2^28 texels through one texel +/// buffer has no texture buffer past its limit to make, and runs nothing. +#[test] +fn a_texture_buffer_past_the_device_s_texel_buffer_elements_reads_and_writes_every_texel() { + let scratch = Scratch::new("texture-buffer-width"); + let device = device(&scratch.0); + let limit = u64::from( + device + .compile_device() + .profile() + .limits() + .max_texel_buffer_elements, + ); + if limit + 64 > METAL_WIDEST { + eprintln!("maxTexelBufferElements {limit}: no texture buffer Metal makes is wider"); + return; + } + let width = limit + 64; + let kernel = TexelKernel::new(&device); + let shared = ResourceOptions::shared(); + let buffer = device.new_buffer(width * 4, shared).unwrap(); + let texels = TexelKernel::over(&buffer, width, 0); + let other = TexelKernel::over(&device.new_buffer(256, shared).unwrap(), 64, 0); + let words = buffer.contents().unwrap().as_ptr().cast::(); + let held: [u64; 8] = [0, 1, 2, limit - 1, limit, limit + 1, limit + 2, width - 1]; + for &at in &held { + // SAFETY: texel `at` lies in the buffer's mapped words, which no command uses yet. + unsafe { words.add(at as usize).write_unaligned(word(at)) }; + } + let index = |at: u64| u32::try_from(at).unwrap(); + let before = device.work_counts(); + // Reads on both sides of the limit and the last texel, then past the last. + let reads = [ + 0, + limit - 1, + limit, + limit + 1, + width - 1, + 1, + width, + u64::from(u32::MAX), + ]; + let got = kernel.run((&texels, reads.map(index)), (&other, [0; 8])); + let want: Vec = reads + .iter() + .map(|&at| if at < width { word(at) } else { 0 }) + .collect(); + assert_eq!( + got, want, + "reads of {reads:?} in {width} texels (limit {limit})" + ); + // Writes on both sides of the limit and the last texel; those past the last are dropped. + let writes = [ + limit - 1, + limit, + limit + 2, + width - 1, + 2, + width, + u64::from(u32::MAX), + 0, + ]; + kernel.run((&other, [0; 8]), (&texels, writes.map(index))); + let written = |at: u64| -> u32 { + match writes.iter().position(|&w| w == at) { + Some(t) => 0xA000_0000 | t as u32, + None => word(at), + } + }; + for &at in &held { + // SAFETY: texel `at` lies in the buffer's mapped words, which no command uses now. + let now = unsafe { words.add(at as usize).read_unaligned() }; + assert_eq!( + now, + written(at), + "texel {at} after the writes of {writes:?}" + ); + } + let got = kernel.run((&texels, held.map(index)), (&other, [0; 8])); + let want: Vec = held.iter().map(|&at| written(at)).collect(); + assert_eq!(got, want, "a kernel's reads of {held:?} after the writes"); + // Each of the three dispatches bound the texture buffer's second part. + let after = device.work_counts(); + assert!( + after.texel_buffer_parts_bound >= before.texel_buffer_parts_bound + 3, + "the parts bound: {} then {}", + before.texel_buffer_parts_bound, + after.texel_buffer_parts_bound + ); +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 55f86808a..059cd7e08 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -869,6 +869,7 @@ struct CommandCounters { ycbcr_planes_bound: AtomicU64, ycbcr_planes_images_bound: AtomicU64, texel_rows_bound: AtomicU64, + texel_buffer_parts_bound: AtomicU64, residual_form_draws: AtomicU64, residual_form_makings: AtomicU64, draws_unkept: AtomicU64, @@ -1423,6 +1424,12 @@ impl Counting<'_> { self.0.add(|counts| &counts.texel_rows_bound, 1); } + /// A texel buffer view of a part past the first of a texture buffer wider than one view holds + /// was written (`binding.rs`, `metal2vulkan::bind::texel_buffer_parts`). + pub(crate) fn texel_buffer_parts_bound(&self) { + self.0.add(|counts| &counts.texel_buffer_parts_bound, 1); + } + /// A binding of a two-plane YCbCr texture's planes image was written (`binding.rs`). pub(crate) fn ycbcr_planes_image_bound(&self) { self.0.add(|counts| &counts.ycbcr_planes_images_bound, 1); @@ -7196,6 +7203,12 @@ pub struct WorkCounts { pub texel_rows_textures: u64, /// Bindings of such textures' rows written into descriptor sets. pub texel_rows_bound: u64, + /// Texel buffer views of the parts past the first of texture buffers of more texels than the + /// device's `maxTexelBufferElements` written into descriptor sets, one per such part + /// (`metal2vulkan::bind::texel_buffer_parts`): a slot whose function reads, writes, updates + /// or asks the width of such a texture buffer binds an array of views of its parts, where one + /// view would be refused (`BindError::TexelBufferTooLarge`). + pub texel_buffer_parts_bound: u64, /// Two-plane YCbCr textures whose planes read in place are also an image the device's own /// sampler Y′CbCr conversion samples, a linear image of the multi-planar 4:2:0 format over /// their bytes (`texture/ycbcr_planes.rs`): a slot whose every sample the device's sampler @@ -11592,6 +11605,7 @@ impl Device { ycbcr_planes_bound: commands(|counts| &counts.ycbcr_planes_bound), texel_rows_textures: counters.texel_rows_textures.load(Ordering::Relaxed), texel_rows_bound: commands(|counts| &counts.texel_rows_bound), + texel_buffer_parts_bound: commands(|counts| &counts.texel_buffer_parts_bound), ycbcr_planes_images: counters.ycbcr_planes_images.load(Ordering::Relaxed), fd_blocks_awaited: counters.fd_blocks_awaited.load(Ordering::Relaxed), fd_blocks_refused: counters.fd_blocks_refused.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/candidate/engine/resources.rs b/crates/metal2vulkan-validation/src/candidate/engine/resources.rs index 2599a1936..9997a2394 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/resources.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/resources.rs @@ -166,6 +166,7 @@ pub fn bound_texture(texture: &LiteralTexture) -> Result { bytes_per_row: length, resource_id: None, swizzle: metal2vulkan::metal::TextureSwizzleChannels::DEFAULT, + parts: 1, }); } let layout = texture.layout()?; diff --git a/crates/metal2vulkan/src/bind/dispatch/tests.rs b/crates/metal2vulkan/src/bind/dispatch/tests.rs index 62984f8be..511d6e939 100644 --- a/crates/metal2vulkan/src/bind/dispatch/tests.rs +++ b/crates/metal2vulkan/src/bind/dispatch/tests.rs @@ -1189,6 +1189,8 @@ fn dispatch_reads_names_the_slot_values_the_commands_read() { max_elements: 1 << 20, block_size: 4, texels_per_block: 1, + parts: 1, + part_texels: 1 << 20, }); let plan = compute_plan(&t, VariantKey::new()); assert!(plan.dispatch_reads(SlotClass::Texture)); @@ -1200,6 +1202,7 @@ fn dispatch_reads_names_the_slot_values_the_commands_read() { bytes_per_row: 256, resource_id: None, swizzle: TextureSwizzleChannels::default(), + parts: 1, }; let (a, b) = (with(&[(1, texels(0))], 3), with(&[(1, texels(64))], 3)); assert_eq!(a.shape(), b.shape(), "one shape"); diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 503dadd63..168b962db 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -334,8 +334,8 @@ use crate::bind::plan::slots::{ address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots, check_sparse_textures, cross_variant, cubic_variant, heap_raw, heap_ycbcr_writes, large_view_candidates, mark_disjoint, plan_buffer, psb_variant, range_variant, record_noted, - record_specialized, snapshot_forms, srgb_variant, storage_view_variant, used_uses, - ycbcr_in_place_variant, ycbcr_planes_sampled_variant, + record_specialized, snapshot_forms, srgb_variant, storage_view_variant, + texel_buffer_parts_variant, used_uses, ycbcr_in_place_variant, ycbcr_planes_sampled_variant, }; use crate::bind::plan::{ AccessClass, BindingPlan, BoundKind, ByteRange, DescriptorWrite, FactorSite, FactorTemplate, @@ -1995,10 +1995,10 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result 1 { - let views = resources.level_views(set.set, b.binding, b.ty, slot, b.count)?; + let views = resources.slot_views(set.set, b.binding, b.ty, slot, b.count)?; descriptors.extend(views.into_iter().zip(0..).map(|(source, i)| { DescriptorWrite { set: set.set, @@ -2583,6 +2583,7 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result ranges.push(DescriptorRange { set, binding, + element: 0, range, }), (None, None) => {} diff --git a/crates/metal2vulkan/src/bind/heap/tests.rs b/crates/metal2vulkan/src/bind/heap/tests.rs index 707358ca4..c1ce918a8 100644 --- a/crates/metal2vulkan/src/bind/heap/tests.rs +++ b/crates/metal2vulkan/src/bind/heap/tests.rs @@ -140,6 +140,7 @@ fn fit_is_shape_samples_numeric_type_usage_and_aspect() { &TextureShape::Buffer { pixel_format: rgba, swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts: 1, }, &f2d ), @@ -242,6 +243,7 @@ fn members_are_used_then_bound_image_textures_reaching_a_table() { let buffer = TextureShape::Buffer { pixel_format: PixelFormat::R32Float, swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts: 1, }; let mut shape_ = BindShape::default(); shape_ @@ -1691,6 +1693,7 @@ fn a_texture_buffer_is_held_by_the_texel_buffer_class_of_its_numeric_type() { let bound = TextureShape::Buffer { pixel_format: rgba, swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts: 1, }; let read = shape(TextureType::TextureBuffer, rgba, 1, READ); let write = shape(TextureType::TextureBuffer, rgba, 1, WRITE); diff --git a/crates/metal2vulkan/src/bind/instantiate.rs b/crates/metal2vulkan/src/bind/instantiate.rs index f55df74ac..bccef4fc4 100644 --- a/crates/metal2vulkan/src/bind/instantiate.rs +++ b/crates/metal2vulkan/src/bind/instantiate.rs @@ -181,13 +181,20 @@ pub struct BufferRange { /// `WriteSource::InlineBytes`, from the start of the consumer's upload of the bytes, which the /// consumer places at an offset aligned to the descriptor type's `min*BufferOffsetAlignment`. /// The consumer binds exactly this range, never more. It is at least 16 bytes, inside the -/// allocation padded to 16 bytes, and its offset is a multiple of the alignment. +/// allocation padded to 16 bytes, and its offset is a multiple of the alignment. For a +/// `WriteSource::TexelBuffer`, the bytes the texel buffer view of the binding's array element +/// `element` views in the bound texture buffer's `VkBuffer` (`texel_ranges`): element 0 for one +/// view, and element `k` for part `k` of a texture buffer bound through its parts +/// (`bind::texel_parts`). #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct DescriptorRange { pub set: u32, pub binding: u32, + /// The binding's array element the range is bound at: 0 but for a texture buffer's parts. + #[cfg_attr(feature = "serde", serde(default))] + pub element: u32, pub range: BufferRange, } @@ -801,6 +808,7 @@ pub(crate) fn bind_buffers( descriptor_ranges.push(DescriptorRange { set, binding, + element: 0, range, }); out.residuals.push(pb.slot, residual); @@ -1030,7 +1038,7 @@ pub(crate) fn put( Ok(()) } -/// The texel-buffer view range of every bound texture buffer the plan writes: the view starts at +/// The texel-buffer view ranges of every bound texture buffer the plan writes: the view starts at /// the texture buffer's offset, which must be a multiple of `minTexelBufferOffsetAlignment` (the /// shader indexes from element 0 of the view; an unaligned offset is `Unsupported{TexelBuffer, /// NotRepresentable}`), and spans the whole texel blocks of its length @@ -1038,7 +1046,10 @@ pub(crate) fn put( /// past the last whole block hold no texel). Its element count, `⌊length / block size⌋ × texels per /// block`, must be at most `maxTexelBufferElements` (`VUID-VkBufferViewCreateInfo-range-00930`), /// else `TexelBufferTooLarge`; a view without a whole block is `Unsupported{TexelBuffer, -/// NotRepresentable}`. +/// NotRepresentable}`. A texture buffer the plan binds through its parts (`PlannedTexel::parts`, +/// `bind::texel_parts`) takes one range per part, at its array element: part `k` from the +/// offset plus `k · P` texels, `P` texels long but the last, which holds the rest; one of a +/// format of blocks of several texels is `TexelBufferTooLarge` too. pub(crate) fn texel_ranges( t: &ResourceTemplate, state: &BindState, @@ -1060,28 +1071,49 @@ pub(crate) fn texel_ranges( Feature::TexelBuffer, ))); } - let blocks = length / pt.block_size.max(1); + let block = pt.block_size.max(1); + let blocks = length / block; if blocks == 0 { return Err(BindError::Unsupported(Unsupported::not_representable( Feature::TexelBuffer, ))); } let elements = blocks.saturating_mul(pt.texels_per_block); - if elements > pt.max_elements { - return Err(BindError::TexelBufferTooLarge { - slot: pt.slot, - elements, - limit: pt.max_elements, - }); - } - out.push(DescriptorRange { + let too_large = BindError::TexelBufferTooLarge { + slot: pt.slot, + elements, + limit: pt.max_elements, + }; + let range = |element: u32, offset: u64, range: u64| DescriptorRange { set: pt.set, binding: pt.binding, - range: BufferRange { - offset, - range: blocks * pt.block_size.max(1), - }, - }); + element, + range: BufferRange { offset, range }, + }; + if pt.parts <= 1 { + if elements > pt.max_elements { + return Err(too_large); + } + out.push(range(0, offset, blocks * block)); + continue; + } + // Parts of `P` texels of one block each: every part but the last full, the last holding + // at least one texel. + let (part, parts) = (pt.part_texels, u64::from(pt.parts)); + if pt.texels_per_block != 1 || part == 0 { + return Err(too_large); + } + if elements > part.saturating_mul(parts) || elements <= part.saturating_mul(parts - 1) { + return Err(internal(format!( + "{elements} texels of a texture buffer at {:?} in {parts} parts of {part}", + pt.slot + ))); + } + for k in 0..pt.parts { + let first = part * u64::from(k); + let texels = part.min(elements - first); + out.push(range(k, offset + first * block, texels * block)); + } } Ok(out) } diff --git a/crates/metal2vulkan/src/bind/instantiate/tests.rs b/crates/metal2vulkan/src/bind/instantiate/tests.rs index e11f39b52..c2183c5d8 100644 --- a/crates/metal2vulkan/src/bind/instantiate/tests.rs +++ b/crates/metal2vulkan/src/bind/instantiate/tests.rs @@ -546,6 +546,8 @@ fn texel_views_count_whole_blocks_against_the_element_limit() { max_elements: 100, block_size: u64::from(block.size), texels_per_block: u64::from(block.texels), + parts: 1, + part_texels: 96, }], ..ResourceTemplate::default() }; @@ -560,6 +562,7 @@ fn texel_views_count_whole_blocks_against_the_element_limit() { bytes_per_row: length, resource_id: None, swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts: 1, }, ); let mut s = BindState::default(); @@ -600,6 +603,108 @@ fn texel_views_count_whole_blocks_against_the_element_limit() { ); } +/// A texture buffer bound through its parts (`bind::texel_parts`) takes one range per part at its +/// array element: part `k` from the offset plus `k · P` texels, `P` long but the last, which +/// holds the rest; past one view's limit, the same buffer bound as one view is +/// `TexelBufferTooLarge`. A format of blocks of several texels takes no parts, and texels the +/// parts do not hold are the bind state's disagreement with the plan's shape. +#[test] +fn texel_parts_view_the_limit_s_texels_each() { + use crate::bind::plan::PlannedTexel; + use crate::bind::state::StageTable; + use crate::pipeline::sym::{SlotClass, Stage}; + let slot = SlotRef { + stage: Stage::Kernel, + class: SlotClass::Texture, + index: 2, + }; + // `R32_UINT` texels, 100 to a view, parts of 96 (100 rounded down to the 16-byte alignment's + // 16 texels). + let planned = |parts| ResourceTemplate { + texel_buffers: vec![PlannedTexel { + set: 0, + binding: 4, + slot, + alignment: 16, + max_elements: 100, + block_size: 4, + texels_per_block: 1, + parts, + part_texels: 96, + }], + ..ResourceTemplate::default() + }; + let state = |length: u64| { + let mut t = StageTable::default(); + t.textures.insert( + 2, + BoundTexture::Buffer { + pixel_format: crate::metal::PixelFormat::R32Uint, + offset: 64, + length, + bytes_per_row: length, + resource_id: None, + swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts: 2, + }, + ); + let mut s = BindState::default(); + s.stages.insert(Stage::Kernel, t); + s + }; + let at = |element, offset, range| DescriptorRange { + set: 0, + binding: 4, + element, + range: BufferRange { offset, range }, + }; + // 150 texels: 96 in part 0, 54 in part 1 from texel 96. + assert_eq!( + texel_ranges(&planned(2), &state(600)), + Ok(vec![at(0, 64, 384), at(1, 64 + 384, 216)]) + ); + // 192 texels: two full parts; a ragged tail past the last whole texel is no texel. + assert_eq!( + texel_ranges(&planned(2), &state(770)), + Ok(vec![at(0, 64, 384), at(1, 64 + 384, 384)]) + ); + // 97 texels: one past the first part, the last holding one. + assert_eq!( + texel_ranges(&planned(2), &state(388)), + Ok(vec![at(0, 64, 384), at(1, 64 + 384, 4)]) + ); + // The same buffer as one view: past the limit. + assert_eq!( + texel_ranges(&planned(1), &state(600)), + Err(BindError::TexelBufferTooLarge { + slot, + elements: 150, + limit: 100 + }) + ); + // Blocks of two texels take no parts. + let mut blocks = planned(2); + blocks.texel_buffers[0].texels_per_block = 2; + assert_eq!( + texel_ranges(&blocks, &state(600)), + Err(BindError::TexelBufferTooLarge { + slot, + elements: 300, + limit: 100 + }) + ); + // Texels two parts do not hold, too many or too few. + for length in [772, 384] { + assert!( + matches!( + texel_ranges(&planned(2), &state(length)), + Err(BindError::Internal(_)) + ), + "{length} bytes" + ); + } +} + /// A push field's bytes are the bytes it was made of, however they were made: held in place up /// to `FieldBytes::INLINE` bytes, past it on the heap, a collect that crosses the bound included. #[test] diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index d9da60d65..bbaf00406 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -184,6 +184,7 @@ pub(crate) mod state; pub(crate) mod status; pub(crate) mod table; pub(crate) mod tessellation_scan; +pub(crate) mod texel_parts; pub(crate) mod texel_rows; pub(crate) mod tile_map; pub(crate) mod tiled_texels; @@ -344,6 +345,7 @@ pub use table::{FunctionTableSnapshot, FunctionTableWords}; pub use tessellation_scan::{ tessellation_scan_module, TessellationScanKernel, TessellationScanModule, }; +pub use texel_parts::{part_texels, texel_buffer_parts}; pub use texel_rows::TexelRows; pub use tile_map::{SparseTileMap, TileMapError, TileMapping}; pub use tiled_texels::{tiled_texels_module, TiledLevelMove, TiledTexelsModule}; diff --git a/crates/metal2vulkan/src/bind/plan.rs b/crates/metal2vulkan/src/bind/plan.rs index d357713a8..06adac2bf 100644 --- a/crates/metal2vulkan/src/bind/plan.rs +++ b/crates/metal2vulkan/src/bind/plan.rs @@ -524,6 +524,20 @@ pub(crate) struct PlannedTexel { /// The view format's texel block: bytes and texels per block (`vk::Format::block`). pub block_size: u64, pub texels_per_block: u64, + /// The views the binding holds, the elements of its descriptor array: 1, or the parts of a + /// texture buffer bound under its parts variant (`VariantKey::texel_buffer_parts`, + /// `bind::texel_parts`). + #[cfg_attr(feature = "serde", serde(default = "one_view"))] + pub parts: u32, + /// The texels of each part but the last (`bind::part_texels`). + #[cfg_attr(feature = "serde", serde(default))] + pub part_texels: u64, +} + +/// The views of a planned texel buffer stated without them: one. +#[cfg(feature = "serde")] +fn one_view() -> u32 { + 1 } /// One statically used buffer slot of a compute plan. diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index a72e9b06b..eb9837bcd 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -64,7 +64,8 @@ use super::slots::{ address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots, check_sparse_textures, cross_variant, cubic_variant, heap_raw, heap_ycbcr_writes, mark_disjoint, plan_buffer, psb_variant, record_noted, record_specialized, srgb_variant, - storage_view_variant, used_uses, ycbcr_in_place_variant, ycbcr_planes_sampled_variant, + storage_view_variant, texel_buffer_parts_variant, used_uses, ycbcr_in_place_variant, + ycbcr_planes_sampled_variant, }; use super::{ BindingPlan, BoundKind, ComputeTemplate, DescriptorWrite, FieldLocation, LocalRules, @@ -550,10 +551,10 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result 1 { - let views = resources.level_views(set.set, b.binding, b.ty, slot, b.count)?; + let views = resources.slot_views(set.set, b.binding, b.ty, slot, b.count)?; descriptors.extend(views.into_iter().zip(0..).map(|(source, i)| { DescriptorWrite { set: set.set, @@ -861,6 +862,7 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result { Ok(self.texture_write(set, binding, ty, slot)?.0) } + /// The writes of texture slot `slot`'s binding `(set, binding)` of type `ty`, an array of + /// `count` descriptors: a texture buffer's parts where it is a texel buffer + /// ([`texel_parts`](Self::texel_parts)), else a storage slot's level views + /// ([`level_views`](Self::level_views)). + pub fn slot_views( + &mut self, + set: u32, + binding: u32, + ty: vk::DescriptorType, + slot: SlotRef, + count: u32, + ) -> Result, BindError> { + match ty { + vk::DescriptorType::UNIFORM_TEXEL_BUFFER | vk::DescriptorType::STORAGE_TEXEL_BUFFER => { + self.texel_parts(set, binding, ty, slot, count) + } + _ => self.level_views(set, binding, ty, slot, count), + } + } + + /// The writes of texture-buffer slot `slot`'s `count` parts, binding `(set, binding)` of type + /// `ty`, under its parts variant (`RuntimeFact::TexelBufferParts`, + /// `VariantKey::texel_buffer_parts`, `bind::texel_parts`): element `k` views part `k` of the + /// bound texture buffer in the format its one view would take, the range of each its + /// template's (`PlannedTexel::parts`, `texel_ranges`); every element is the neutral of the + /// declared type where the slot binds the neutral. + fn texel_parts( + &mut self, + set: u32, + binding: u32, + ty: vk::DescriptorType, + slot: SlotRef, + count: u32, + ) -> Result, BindError> { + if !self.has_fact(RuntimeFact::TexelBufferParts { slot }) { + return Err(internal(format!( + "a {ty:?} binding of {count} descriptors at {slot:?} without texel buffer parts" + ))); + } + let (write, _) = self.texture_write(set, binding, ty, slot)?; + match write { + WriteSource::TexelBuffer { .. } => { + let planned = self + .template + .texel_buffers + .last_mut() + .filter(|pt| (pt.set, pt.binding, pt.slot) == (set, binding, slot)) + .ok_or_else(|| internal(format!("texel buffer parts at {slot:?} unplanned")))?; + planned.parts = count; + } + WriteSource::Neutral(_) => {} + other => return Err(internal(format!("texel buffer parts of {other:?}"))), + } + Ok(vec![write; count as usize]) + } + /// The writes of storage slot `slot`'s `count` level views, binding `(set, binding)` of type /// `ty` (`RuntimeFact::StorageTextureLevelViews`): element `i` views level `i` of the bound /// texture alone, and every element past its last level is the neutral of the declared type, as @@ -1203,6 +1259,7 @@ impl ResourcePlanner<'_> { TextureShape::Buffer { pixel_format, swizzle, + .. } => { // Metal applies a texture buffer's swizzle to a function's reads, and a texel // buffer view has none: the function applies it where its stage states so @@ -1287,6 +1344,8 @@ impl ResourcePlanner<'_> { max_elements: u64::from(l.max_texel_buffer_elements), block_size: u64::from(block.size), texels_per_block: u64::from(block.texels), + parts: 1, + part_texels: crate::bind::part_texels(l), }); let write = WriteSource::TexelBuffer { slot, diff --git a/crates/metal2vulkan/src/bind/plan/resources/tests.rs b/crates/metal2vulkan/src/bind/plan/resources/tests.rs index de4490359..24c61e84a 100644 --- a/crates/metal2vulkan/src/bind/plan/resources/tests.rs +++ b/crates/metal2vulkan/src/bind/plan/resources/tests.rs @@ -127,6 +127,7 @@ fn compatibility_is_type_samples_numeric_type_and_depth() { &TextureShape::Buffer { pixel_format: PixelFormat::RGBA8Unorm, swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts: 1, }, &t, &class @@ -217,6 +218,7 @@ fn a_ulong_slot_binds_only_rg32uint_textures() { let buffer = |pixel_format| TextureShape::Buffer { pixel_format, swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts: 1, }; assert!(compatible(&buffer(PixelFormat::RG32Uint), &tb, &class)); assert!(!compatible(&buffer(PixelFormat::RGBA16Uint), &tb, &class)); @@ -1202,6 +1204,7 @@ fn texel_format_follows_the_bound_format() { plan(Some(TextureShape::Buffer { pixel_format: pf, swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts: 1, })), u64::from(texel_format(pf).0), "{pf:?}" @@ -1397,6 +1400,7 @@ fn an_a8_texture_buffer_without_a8_unorm_views_its_bytes_in_red() { let buffer = TextureShape::Buffer { pixel_format, swizzle, + parts: 1, }; stage.textures.insert(index, buffer); } diff --git a/crates/metal2vulkan/src/bind/plan/slots.rs b/crates/metal2vulkan/src/bind/plan/slots.rs index 026e610f0..9f05c9144 100644 --- a/crates/metal2vulkan/src/bind/plan/slots.rs +++ b/crates/metal2vulkan/src/bind/plan/slots.rs @@ -596,6 +596,30 @@ pub(crate) fn ycbcr_in_place_variant( .collect() } +/// The texture-buffer slots whose function reads the texture buffer bound there through its parts +/// (`RuntimeFact::TexelBufferParts`) at which `shape` binds a texture buffer of more texels than +/// one view holds (`TextureShape::Buffer::parts` past 1), each with those parts: the plan's +/// `VariantKey::texel_buffer_parts` (`bind::texel_parts`). A texture buffer one view holds adds +/// nothing, so its draws keep their key; any other slot binds one view, which +/// `maxTexelBufferElements` bounds. The variant's compile states the same facts, so its plan for +/// the same shape states the same key. +pub(crate) fn texel_buffer_parts_variant( + dependencies: &[RuntimeDependency], + shape: &BindShape, +) -> BTreeMap { + dependencies + .iter() + .filter_map(|d| match d.fact { + RuntimeFact::TexelBufferParts { slot } => Some(slot), + _ => None, + }) + .filter_map(|slot| match bound_texture(shape, slot) { + Some(&TextureShape::Buffer { parts, .. }) if parts > 1 => Some((slot, parts)), + _ => None, + }) + .collect() +} + /// The slots of `in_place` (the plan's `VariantKey::ycbcr_in_place`) whose function's every sample /// the device's own sampler Y′CbCr conversion takes (`RuntimeFact::YCbCrInPlace`'s `device`), at /// which `shape` binds a texture whose planes are also held as an image it samples diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index 7c1858469..a7d6c0832 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -1322,10 +1322,12 @@ impl BoundTexture { BoundTexture::Buffer { pixel_format, swizzle, + parts, .. } => TextureShape::Buffer { pixel_format, swizzle, + parts, }, } } @@ -1520,6 +1522,13 @@ pub enum BoundTexture { /// `MTLTexture.swizzle`: the source of each channel a function's reads of it return. #[cfg_attr(feature = "serde", serde(default))] swizzle: metal::TextureSwizzleChannels, + /// The texel buffer views its texels take on the device + /// ([`texel_buffer_parts`](crate::bind::texel_buffer_parts) of its texels): 1 within the + /// device's `maxTexelBufferElements`, else its parts (`bind::texel_parts`), which a slot + /// whose function reads them so binds through its parts variant + /// (`VariantKey::texel_buffer_parts`). + #[cfg_attr(feature = "serde", serde(default = "one_part"))] + parts: u32, }, } @@ -2310,6 +2319,12 @@ fn one_level() -> u32 { 1 } +/// The views of a texture buffer stated without them: one. +#[cfg(feature = "serde")] +fn one_part() -> u32 { + 1 +} + /// The shape of a bound texture. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -2372,6 +2387,11 @@ pub enum TextureShape { /// specializes on it (`SpecKey::TextureSwizzle`). #[cfg_attr(feature = "serde", serde(default))] swizzle: metal::TextureSwizzleChannels, + /// The texel buffer views its texels take (`BoundTexture::Buffer`'s): past 1, a slot whose + /// function reads them through its parts (`RuntimeFact::TexelBufferParts`) takes the + /// parts variant (`VariantKey::texel_buffer_parts`). + #[cfg_attr(feature = "serde", serde(default = "one_part"))] + parts: u32, }, } diff --git a/crates/metal2vulkan/src/bind/texel_parts.rs b/crates/metal2vulkan/src/bind/texel_parts.rs new file mode 100644 index 000000000..5fd13d08f --- /dev/null +++ b/crates/metal2vulkan/src/bind/texel_parts.rs @@ -0,0 +1,99 @@ +//! A texture buffer wider than one texel buffer view holds, read and written through several +//! views of its bytes, its parts. +//! +//! **Where.** Metal makes a texture buffer of up to 2^28 texels on every Mac. One texel buffer +//! view holds at most the device's `maxTexelBufferElements` texels +//! (`VUID-VkBufferViewCreateInfo-range-00930`): 2^27 on ANV and lavapipe, 2^26 on MoltenVK. The +//! consumer states with a texture buffer's binding how many parts its texels take +//! ([`texel_buffer_parts`], `BoundTexture::Buffer::parts`), which its shape carries +//! (`TextureShape::Buffer::parts`): one for every texture buffer within the limit, which binds one +//! view as it always has. +//! +//! **The views.** Part `k` views the texels from `k · P`, `P` the device's [`part_texels`] (its +//! `maxTexelBufferElements` rounded down to a multiple of its `minTexelBufferOffsetAlignment`, so +//! each part starts on that alignment where the texture buffer does): `P` texels for every part +//! but the last, which holds the rest. Each is a view of the device's own in the format one view +//! would take, so a read converts its texel as that view does, the device's conversion +//! (Uniform Texel Buffer, Storage Texel Buffer). +//! +//! **What a function reads.** A slot whose function reads, writes, updates by an atomic or asks +//! the width of the texture buffer bound there, and does nothing else with it +//! (`RuntimeFact::TexelBufferParts`), on a device that indexes arrays of its kind of texel buffer +//! by a `NonUniform` value, takes the parts variant where the shape binds more than one part +//! there (`VariantKey::texel_buffer_parts`). Under it the slot is declared as an array of its +//! parts, and texel `i` is texel `i − k · P` of part `k = min(⌊i / P⌋, parts − 1)`. A texel past +//! the last lies past the last part's end, so its read is Metal's out-of-bounds texel and its +//! write is dropped, by the device's robustness or the function's own check as through one view. +//! The width is `(parts − 1) · P` plus the last part's. Any other slot binds one view, which +//! `maxTexelBufferElements` bounds (`BindError::TexelBufferTooLarge`). + +use crate::device::Limits; + +/// The texels of each part but the last of a texture buffer of more texels than one texel buffer +/// view holds, which binds through views of its parts (part `k` from texel `k · P`, the last +/// holding the rest): the device's `maxTexelBufferElements` rounded down to a multiple of its +/// `minTexelBufferOffsetAlignment`, so that a part starts on that alignment wherever the texture +/// buffer does (a texel is at least a byte). 0 on a device whose limit is below its alignment, +/// which binds no parts. +pub fn part_texels(limits: &Limits) -> u64 { + let max = u64::from(limits.max_texel_buffer_elements); + let alignment = limits.min_texel_buffer_offset_alignment.max(1); + max - max % alignment +} + +/// The texel buffer views the texels of a texture buffer of `texels` texels +/// (`⌊length / bytes per texel⌋`) take on a device of `limits`, which a consumer states with its +/// binding (`BoundTexture::Buffer::parts`): 1 within the device's `maxTexelBufferElements`, which +/// one view holds, else `⌈texels / P⌉` parts of [`part_texels`] `P` each (saturated at +/// `u32::MAX`). A slot whose function only reads, writes, updates by an atomic or asks the width +/// of such a texture buffer binds an array of views of its parts (`VariantKey::texel_buffer_parts`). +pub fn texel_buffer_parts(limits: &Limits, texels: u64) -> u32 { + let part = part_texels(limits); + if texels <= u64::from(limits.max_texel_buffer_elements) || part == 0 { + return 1; + } + u32::try_from(texels.div_ceil(part)).unwrap_or(u32::MAX) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn limits(max: u32, alignment: u64) -> Limits { + Limits { + max_texel_buffer_elements: max, + min_texel_buffer_offset_alignment: alignment, + ..Limits::default() + } + } + + /// A texture buffer within the limit takes one part, at the limit too; past it, parts of the + /// limit's texels, the last holding the rest: 2^28 texels take two parts of 2^27 on lavapipe's + /// limits and four of 2^26 on MoltenVK's. + #[test] + fn parts_hold_the_limit_s_texels_each() { + let lavapipe = limits(1 << 27, 16); + assert_eq!(part_texels(&lavapipe), 1 << 27); + assert_eq!(texel_buffer_parts(&lavapipe, 1), 1); + assert_eq!(texel_buffer_parts(&lavapipe, 1 << 27), 1); + assert_eq!(texel_buffer_parts(&lavapipe, (1 << 27) + 1), 2); + assert_eq!(texel_buffer_parts(&lavapipe, 1 << 28), 2); + assert_eq!(texel_buffer_parts(&limits(1 << 26, 256), 1 << 28), 4); + assert_eq!(texel_buffer_parts(&limits(1 << 28, 16), 1 << 28), 1); + } + + /// A limit off the offset alignment: each part holds the limit rounded down to it, so the next + /// starts on it. + #[test] + fn parts_start_on_the_offset_alignment() { + let odd = limits(1000, 64); + assert_eq!(part_texels(&odd), 960); + assert_eq!(texel_buffer_parts(&odd, 1000), 1); + assert_eq!(texel_buffer_parts(&odd, 1001), 2); + assert_eq!(texel_buffer_parts(&odd, 1920), 2); + assert_eq!(texel_buffer_parts(&odd, 1921), 3); + // A limit below the alignment holds no aligned part: one view, which the limit bounds. + assert_eq!(part_texels(&limits(32, 64)), 0); + assert_eq!(texel_buffer_parts(&limits(32, 64), 100), 1); + } +} diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 9ad0cb902..6d3cc82dd 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1324,6 +1324,7 @@ codec_enum! { PartialThreadgroups, TexelRows { slot }, UnitAxes { axes, relief }, + TexelBufferParts { slot }, } UniformViewChoice { Viewed, Spare, Kept } Mechanism { diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 1a4e1b7dc..ee76a6ea2 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,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 = 2122; +pub const SEMANTICS_VERSION: u32 = 2123; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2348; +pub const RUNTIME_VERSION: u32 = 2349; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles @@ -250,6 +250,17 @@ pub struct VariantKey { /// bytes alone (`bind::TexelRows`). The plan of a pipeline compiled under it states it. #[cfg_attr(feature = "serde", serde(default))] pub texel_rows: BTreeSet, + /// Texture-buffer slots whose function reads it through its parts, each with the parts of the + /// texture buffer the shape binds there: every slot of a `RuntimeFact::TexelBufferParts` the + /// shape binds a texture buffer of more texels than one view holds at + /// (`TextureShape::Buffer::parts`). Each such slot binds an array of that many texel buffer + /// views (`bind::texel_parts`). A texture buffer one view holds adds nothing, so its draws + /// keep their key. The plan of a pipeline compiled under it states it. + #[cfg_attr( + feature = "serde", + serde(default, with = "crate::pipeline::serde_pairs") + )] + pub texel_buffer_parts: BTreeMap, /// Texture slots a constexpr sampler samples, each with the address-mode map of the texture /// the shape binds there where it is not the identity: every slot of a /// `RuntimeFact::ConstexprSampled` the shape binds such a texture at. The function's constexpr @@ -595,6 +606,7 @@ impl VariantKey { && self.ycbcr_in_place.is_empty() && self.ycbcr_planes_sampled.is_empty() && self.texel_rows.is_empty() + && self.texel_buffer_parts.is_empty() && self.address_maps.is_empty() && !self.flat_grid && !self.call_threadgroups @@ -737,6 +749,12 @@ impl VariantKey { .filter(|s| s.stage == stage) .copied() .collect(); + out.texel_buffer_parts = self + .texel_buffer_parts + .iter() + .filter(|(s, _)| s.stage == stage) + .map(|(s, parts)| (*s, *parts)) + .collect(); out.address_maps = self .address_maps .iter() diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index ffd28dcf5..220f6c11a 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -200,6 +200,8 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { RuntimeFact::YCbCrInPlace { .. } => Mechanism::Variant, // Keyed by the slots bound to a texture whose rows are read and written in place. RuntimeFact::TexelRows { .. } => Mechanism::Variant, + // Keyed by the slots bound to a texture buffer of more texels than one view holds. + RuntimeFact::TexelBufferParts { .. } => Mechanism::Variant, // The function marks the `ExecutionStatus` buffer its `ExecutionStatus` fact binds; the // consumer reads the bit after the command buffer. RuntimeFact::AbsentArgumentRead { .. } => Mechanism::None, diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 675354c13..5363283d7 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -133,6 +133,7 @@ fn every_fact() -> Vec { RuntimeFact::RowLockstep, RuntimeFact::OneRow, RuntimeFact::UnitAxes { axes: 0, relief: 2 }, + RuntimeFact::TexelBufferParts { slot }, RuntimeFact::FlatGrid, RuntimeFact::CallThreadgroups, RuntimeFact::SparseTextureWrites { @@ -405,6 +406,7 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::TexelRows { .. } => 99, RuntimeFact::HeapStorageReads { .. } => 100, RuntimeFact::UnitAxes { .. } => 101, + RuntimeFact::TexelBufferParts { .. } => 102, } } @@ -412,7 +414,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..102).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..103).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -496,6 +498,7 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::RegionViewports | RuntimeFact::YCbCrInPlace { .. } | RuntimeFact::TexelRows { .. } + | RuntimeFact::TexelBufferParts { .. } | RuntimeFact::ZeroedColor { .. } | RuntimeFact::DroppedColor { .. } | RuntimeFact::DepthClampRange diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 9f3176334..bf2e23f5a 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -2210,7 +2210,11 @@ pub enum BindError { needed: u64, limit: u64, }, - /// A texel buffer exceeds `maxTexelBufferElements`. + /// A texture buffer bound through one texel buffer view exceeds `maxTexelBufferElements`: + /// one wider than that view binds through views of its parts (`bind::texel_parts`) except at + /// a slot whose function reads it through a sampler, on a device that indexes no array of + /// the slot's kind of texel buffer by a `NonUniform` value, or in a format whose block holds + /// several texels. TexelBufferTooLarge { slot: SlotRef, elements: u64, diff --git a/crates/metal2vulkan/src/lower/access/tile.rs b/crates/metal2vulkan/src/lower/access/tile.rs index f55118063..a6e54766b 100644 --- a/crates/metal2vulkan/src/lower/access/tile.rs +++ b/crates/metal2vulkan/src/lower/access/tile.rs @@ -1049,6 +1049,7 @@ fn image_decl(s: &TileSlot) -> ImageDecl { in_place: false, planes_sampler: None, rows: false, + parts: None, } } diff --git a/crates/metal2vulkan/src/lower/sampler/mod.rs b/crates/metal2vulkan/src/lower/sampler/mod.rs index 2f1782874..d36dee09d 100644 --- a/crates/metal2vulkan/src/lower/sampler/mod.rs +++ b/crates/metal2vulkan/src/lower/sampler/mod.rs @@ -1375,6 +1375,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { in_place: false, planes_sampler: None, rows: false, + parts: None, }; let symbol = ResourceSlot { stage: cx.stage, diff --git a/crates/metal2vulkan/src/lower/texture/atomic.rs b/crates/metal2vulkan/src/lower/texture/atomic.rs index f2a9af1ca..1a26db602 100644 --- a/crates/metal2vulkan/src/lower/texture/atomic.rs +++ b/crates/metal2vulkan/src/lower/texture/atomic.rs @@ -57,8 +57,8 @@ use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::BResult; use crate::spirv::ids::{DemoteTy, Value as SValue}; use crate::spirv::ir::{ - AtomicOp, BinOp, ConstBits, Constant, ConvOp, ImageQuery, MemAccess, MemoryOrder, Scope, - Semantics, Type as SType, UnOp, + AtomicOp, BinOp, ConstBits, Constant, ConvOp, MemAccess, MemoryOrder, Scope, Semantics, + Type as SType, UnOp, }; use super::{ @@ -238,6 +238,12 @@ pub(super) fn emit( }; let ptr = fb.module().global_value(g)?; let coord = super::emit::coordinate(cx, fb, &decl, &a.at)?; + // A texture buffer's parts: the part that holds the texel, at its index there; the guard + // tests the texel against the whole width. + let (part, at) = match decl.parts { + Some(p) => super::emit::part_pointer(fb, ptr, p, coord)?, + None => (ptr, coord), + }; let u32_ = fb.module().ty(SType::Int { width: 32, signed: false, @@ -298,7 +304,7 @@ pub(super) fn emit( let access = move |fb: &mut FunctionBuilder<'_>| -> BResult> { let zero = fb.u32_const(0)?; let sample = fb.module().const_value(zero)?; - let p = fb.image_texel_pointer(ptr, coord, sample)?; + let p = fb.image_texel_pointer(part, at, sample)?; Ok(match (op, x, comparator) { (AirOp::Load, _, _) => vec![fb.atomic_load(p, Scope::Device, sem)?], // A store is an exchange whose old texel is never read: the same relaxed write. @@ -328,8 +334,16 @@ pub(super) fn emit( let expected_n = usize::from(returns) + usize::from(comparator.is_some()); let compare = comparator.is_some(); let out = if a.guard || compare { - let img = fb.load(ptr, MemAccess::default())?; - let size = fb.query(ImageQuery::Size, img)?; + let img = match decl.parts { + Some(p) => { + let last = fb.u32_const(p.count.saturating_sub(1))?; + let last = fb.module().const_value(last)?; + let element = fb.access_chain(ptr, &[last])?; + fb.load(element, MemAccess::default())? + } + None => fb.load(ptr, MemAccess::default())?, + }; + let size = super::emit::texel_width(fb, &decl, img)?; let lt = fb.binary(BinOp::ULessThan, coord, size)?; let inb = if super::emit::coord_len(&decl) == 1 { lt diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index bfc42c482..e5c6a9509 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -18,6 +18,7 @@ use crate::spirv::ir::{ use super::half::{TexelLanes, TexelOrigin}; use super::slice::Slice; +use super::slot::Parts; use super::{ Coord, ImageDecl, ImageRef, QueryKind, QueryOp, Read, TexelClass, TexelConv, TexelForm, }; @@ -461,6 +462,18 @@ fn image_in( return Err(cx.fail(format!("texture slot {index} is not declared"))); }; let ptr = fb.module().global_value(g)?; + // A texture buffer's parts: the last part, whose size its width adds ([`texel_width`]); an + // access reads the part that holds its texel ([`part_image`]). + if let (Some(p), None) = (decl.parts, level) { + let img = last_part(fb, ptr, p)?; + return Ok(Loaded { + decl, + img, + live: None, + within: None, + flagged: None, + }); + } let Some(n) = decl.level_views else { if level.is_some() { return Err(cx.fail(format!( @@ -530,6 +543,69 @@ fn level_element( Ok((img, within)) } +/// The last of the `p.count` parts `ptr` points to, a texture-buffer slot's +/// ([`ImageDecl::parts`], `bind::texel_parts`), loaded. +fn last_part(fb: &mut FunctionBuilder<'_>, ptr: SValue, p: Parts) -> BResult { + let last = u32s(fb, 1, p.count.saturating_sub(1))?; + let element = fb.access_chain(ptr, &[last])?; + fb.load(element, MemAccess::default()) +} + +/// The width of texture-buffer image `img` of `decl`: its size, or, for a slot's parts +/// ([`ImageDecl::parts`]), whose `img` is its last part ([`last_part`]), the texels of the parts +/// before it, `(count − 1) · texels`, plus that part's size. +pub(super) fn texel_width( + fb: &mut FunctionBuilder<'_>, + decl: &ImageDecl, + img: SValue, +) -> BResult { + let size = fb.query(ImageQuery::Size, img)?; + let Some(p) = decl.parts else { + return Ok(size); + }; + let before = u32s(fb, 1, p.count.saturating_sub(1).saturating_mul(p.texels))?; + fb.binary(BinOp::IAdd, before, size) +} + +/// The part of the `p.count` parts `ptr` points to, a texture-buffer slot's +/// ([`ImageDecl::parts`], `bind::texel_parts`), that holds texel `coord`, as a `NonUniform` pointer +/// to it, and the texel's index in it: part `k = min(⌊coord / texels⌋, count − 1)`, index +/// `coord − k · texels`. A texel past the last lies past the last part's end, where the access's +/// own check or the device's robustness answers it as one view's. +pub(super) fn part_pointer( + fb: &mut FunctionBuilder<'_>, + ptr: SValue, + p: Parts, + coord: SValue, +) -> BResult<(SValue, SValue)> { + let texels = u32s(fb, 1, p.texels)?; + let whole = fb.binary(BinOp::UDiv, coord, texels)?; + let last = u32s(fb, 1, p.count.saturating_sub(1))?; + let k = fb.glsl(GlslOp::UMin, &[whole, last])?; + let first = fb.binary(BinOp::IMul, k, texels)?; + let index = fb.binary(BinOp::ISub, coord, first)?; + Ok((fb.access_chain_non_uniform(ptr, k)?, index)) +} + +/// [`part_pointer`]'s part of texture slot `image`, loaded, and the texel's index in it. +fn part_image( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + image: &ImageRef, + p: Parts, + coord: SValue, +) -> BResult<(SValue, SValue)> { + let ImageRef::Slot(index) = *image else { + return Err(cx.fail("texel buffer parts of a heap element")); + }; + let Some((g, _)) = cx.decl.families.texture.images.get(&index).copied() else { + return Err(cx.fail(format!("texture slot {index} is not declared"))); + }; + let ptr = fb.module().global_value(g)?; + let (element, at) = part_pointer(fb, ptr, p, coord)?; + Ok((fb.load(element, MemAccess::default())?, at)) +} + /// A heap element. pub(crate) struct HeapElement { pub decl: ImageDecl, @@ -2481,7 +2557,7 @@ fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BR } fb.query(ImageQuery::SizeLod(clamped), img)? } - (None, _) => fb.query(ImageQuery::Size, img)?, + (None, _) => texel_width(fb, &decl, img)?, }; let n = coord_len(&decl); let lt = fb.binary(BinOp::ULessThan, coord, size)?; @@ -2516,6 +2592,11 @@ fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BR (true, None) => in_range, (false, w) => w, }; + // A texture buffer's parts: the part that holds the texel, at its index there. + let (img, coord) = match decl.parts { + Some(p) => part_image(cx, fb, &r.image, p, coord)?, + None => (img, coord), + }; let ops = ImageOperands { lod: level, sample, @@ -2534,6 +2615,7 @@ fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BR ImageRef::Slot(index) => { let plain = sampled && !decl.rows + && decl.parts.is_none() && spec.is_none() && sample.is_none() && r.through.is_none() @@ -3069,6 +3151,12 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul (volume, _) => volume, }; let coord = volume.map_or(coord, |(at, _)| at); + // A texture buffer's parts: the part that holds the texel, at its index there; the check + // below tests the texel against the whole width. + let (part, at) = match decl.parts { + Some(p) => part_image(cx, fb, &w.image, p, coord)?, + None => (img, coord), + }; let v = cx.operand(fb, w.value)?; // A texture of another numeric class: the declared lanes as its own class's texel. let v = match w.cross { @@ -3136,19 +3224,19 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul if !w.guard { // A write through the null heap element, or at a level the texture lacks, is dropped. let cond = match (live, within) { - (None, None) => return fb.write(img, coord, texel, &ImageOperands::default(), mem), + (None, None) => return fb.write(part, at, texel, &ImageOperands::default(), mem), (Some(c), None) | (None, Some(c)) => c, (Some(a), Some(b)) => fb.binary(BinOp::LogicalAnd, a, b)?, }; let then: ArmFn<'_, ()> = Box::new(move |fb, _| { - fb.write(img, coord, texel, &ImageOperands::default(), mem)?; + fb.write(part, at, texel, &ImageOperands::default(), mem)?; Ok(ArmEnd::FallThrough(Vec::new())) }); fb.if_(&mut (), cond, then, None)?; return Ok(()); } let n = coord_len(&decl); - let size = fb.query(ImageQuery::Size, img)?; + let size = texel_width(fb, &decl, img)?; let lt = fb.binary(BinOp::ULessThan, coord, size)?; let mut inb = if n == 1 { lt } else { fb.unary(UnOp::All, lt)? }; if let Some(live) = live { @@ -3158,7 +3246,7 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul inb = fb.binary(BinOp::LogicalAnd, inb, within)?; } let then: ArmFn<'_, ()> = Box::new(move |fb, _| { - fb.write(img, coord, texel, &ImageOperands::default(), mem)?; + fb.write(part, at, texel, &ImageOperands::default(), mem)?; Ok(ArmEnd::FallThrough(Vec::new())) }); fb.if_(&mut (), inb, then, None)?; @@ -3482,7 +3570,7 @@ fn query_value( let zero = u32s(fb, 1, 0)?; fb.query(ImageQuery::SizeLod(zero), img) } - false => fb.query(ImageQuery::Size, img), + false => texel_width(fb, decl, img), } }; let level = match q.level { diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index 6763c3edb..16a064735 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -1224,8 +1224,9 @@ pub fn declare( for (index, s) in &plan.families.texture.slots { if let Some(decl) = &s.decl { let image = decl.declare(mb)?; - // A slot's level views are one descriptor array of single-level views. - let ty = match decl.level_views { + // A slot's level views are one descriptor array of single-level views, and a texture + // buffer's parts one of texel buffers. + let ty = match decl.level_views.or(decl.parts.map(|p| p.count)) { Some(n) => { let u32_ = mb.ty(SType::Int { width: 32, @@ -2878,6 +2879,14 @@ pub(crate) fn not_rows(cx: &mut SelectCx<'_>, index: u32) { } } +/// Mark texture slot `index` as accessed in a way a texture buffer's parts do not answer +/// (`slot::SlotPlan::not_parts`): the slot takes no parts variant. +pub(crate) fn not_parts(cx: &mut SelectCx<'_>, index: u32) { + if let Some(s) = cx.families.texture.slots.get_mut(&index) { + s.not_parts = true; + } +} + /// Whether the function observes any of texture call `at`'s status word. pub(crate) fn observes_status(cx: &mut SelectCx<'_>, at: InstId) -> bool { status_use(cx, at).is_some() @@ -3082,6 +3091,19 @@ fn select_image( ) { not_rows(cx, index); } + // A texture buffer's parts read, write and update a texel by its index, and answer the + // width, the presence and a fence; nothing else. + if !matches!( + t.op, + TexOp::Read + | TexOp::Write + | TexOp::Atomic(_) + | TexOp::Fence + | TexOp::IsNull + | TexOp::Query(Query::Width) + ) { + not_parts(cx, index); + } } let texel = match t.texel { Some(x) if matches!(t.op, TexOp::Read | TexOp::Write | TexOp::Atomic(_)) => Some( @@ -3291,6 +3313,7 @@ fn select_read_as( select_through(cx, image, texel, t)?; if let ImageRef::Slot(index) = image { not_rows(cx, index); + not_parts(cx, index); } } let residency = residency(cx, at, image)?; diff --git a/crates/metal2vulkan/src/lower/texture/slot.rs b/crates/metal2vulkan/src/lower/texture/slot.rs index 5675fbfa3..0f78a114b 100644 --- a/crates/metal2vulkan/src/lower/texture/slot.rs +++ b/crates/metal2vulkan/src/lower/texture/slot.rs @@ -148,6 +148,18 @@ pub struct ImageDecl { /// uniform for a sampled slot and storage for a storage one, texel `(x, y)` its texel /// `first + y · row + x` and the texture's size the push field's. pub rows: bool, + /// A texture-buffer slot under its parts variant (`LoweringInputs::texel_buffer_parts`, + /// `bind::texel_parts`), declared as an array of its parts' texel buffers. + pub parts: Option, +} + +/// The parts of a texture-buffer slot under its parts variant (`bind::texel_parts`): `count` +/// texel buffers, each of `texels` texels but the last, the device's `bind::part_texels`. Texel `i` +/// is texel `i − k · texels` of part `k = min(⌊i / texels⌋, count − 1)`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Parts { + pub count: u32, + pub texels: u32, } impl ImageDecl { @@ -261,6 +273,10 @@ pub struct SlotPlan { /// but a read or write of a texel by its coordinate, a query of the width, the height or the /// level count, and a presence test. The uses rule out the rest ([`rows_reads`]). pub not_rows: bool, + /// An access a texture buffer's parts do not answer (`bind::texel_parts`): anything but a + /// read of a texel by its index (not through a sampler), a write, an atomic, a width query, a + /// presence test and a fence. The uses rule out the rest ([`parts_reads`]). + pub not_parts: bool, /// The declaration, set by [`finish`] for a slot that is read, written, or queried, or /// whose faces are fetched. pub decl: Option, @@ -290,6 +306,7 @@ impl SlotPlan { offset_base: false, in_place: InPlaceReads::default(), not_rows: false, + not_parts: false, decl: None, } } @@ -604,6 +621,7 @@ fn declare_heap( in_place: false, planes_sampler: None, rows: false, + parts: None, }; Ok((class, decl)) } @@ -1082,6 +1100,7 @@ fn declare_slot( in_place: true, planes_sampler: Some(sampler), rows: false, + parts: None, }); } // A slot under its in-place variant is the uniform texel buffer of its texture's planes, of @@ -1105,6 +1124,7 @@ fn declare_slot( in_place: true, planes_sampler: None, rows: false, + parts: None, }); } // A slot under its rows variant is the texel buffer of its texture's rows, with the field of @@ -1152,6 +1172,7 @@ fn declare_slot( in_place: false, planes_sampler: None, rows: true, + parts: None, }); } // A slot bound in an extended-range format holds its raw texels in an unsigned integer @@ -1257,11 +1278,22 @@ fn declare_slot( if shape.dim == ImageDim::Buffer { facts.push(RuntimeFact::TexelBufferRange { slot: s.slot }); } + // A texture-buffer slot under its parts variant is an array of its parts, one texel buffer + // each (`bind::texel_parts`). + let texels = crate::bind::part_texels(&cx.profile.fields().limits); + let parts = match cx.inputs.texel_buffer_parts.get(&s.slot) { + Some(&count) if count > 1 && parts_reads(cx, s) => match u32::try_from(texels) { + Ok(texels) if texels > 0 => Some(Parts { count, texels }), + _ => return Err(cx.invariant("texel buffer parts on a device without them")), + }, + Some(_) => return Err(cx.invariant("a parts slot whose accesses its parts do not answer")), + None => None, + }; + let n = views.or(parts.map(|p| p.count)).unwrap_or(1); if storage { - let n = views.unwrap_or(1); counts.storage_images = counts.storage_images.saturating_add(n); } else { - counts.sampled_images = counts.sampled_images.saturating_add(1); + counts.sampled_images = counts.sampled_images.saturating_add(n); } Ok(ImageDecl { dim, @@ -1283,6 +1315,7 @@ fn declare_slot( in_place: false, planes_sampler: None, rows: false, + parts, }) } @@ -1320,6 +1353,24 @@ fn rows_reads(s: &SlotPlan) -> bool { ) } +/// Whether every access of texture-buffer slot `s` is one its parts answer (`bind::texel_parts`), +/// on a profile that indexes an array of its kind of texel buffer (storage where the function +/// writes or updates it, else uniform) by a `NonUniform` value: read, written, updated by an +/// atomic or asked its width, and nothing read through a sampler or its residency observed; no +/// access blocked ([`SlotPlan::not_parts`]). +fn parts_reads(cx: &SelectCx<'_>, s: &SlotPlan) -> bool { + let u = &s.uses; + let d = &cx.profile.fields().descriptors; + let indexed = match s.storage() { + true => d.non_uniform_storage_texel_buffer, + false => d.non_uniform_uniform_texel_buffer, + }; + (u.read || u.write || u.query || u.atomic) + && !(u.sample || u.compare || u.level_views || u.residency || u.faces || s.not_parts) + && s.shape.is_some_and(|x| x.dim == ImageDim::Buffer) + && indexed +} + /// Whether a slot of `shape` can have a tile map: a single-sample 2D, 2D array, or 3D color texture /// (`bind::SparseTileMap`), the sparse types the case model measures. fn tiled_shape(shape: ImageShape) -> bool { @@ -1416,6 +1467,13 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { facts.push(RuntimeFact::TexelRows { slot: s.slot }); } } + // The texture-buffer slots whose every access their parts answer: their compile under the + // parts variant states the same, which its plan holds to. + for s in cx.families.texture.slots.values() { + if parts_reads(cx, s) { + facts.push(RuntimeFact::TexelBufferParts { slot: s.slot }); + } + } let mut heap = Vec::new(); for (group, h) in &cx.families.texture.heap { let used = h.uses.read || h.uses.write || h.uses.query || h.uses.sample; diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index c545f1ede..dca8a65bb 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -224,6 +224,7 @@ mod serde_round_trips { planes_sampler(), )]), texel_rows: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 9)]), + texel_buffer_parts: BTreeMap::from([(slot(Stage::Kernel, SlotClass::Texture, 11), 2)]), flat_grid: true, call_threadgroups: true, replay_bindings: true, @@ -365,6 +366,10 @@ mod serde_round_trips { planes_sampler(), )]), texel_rows: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 10)]), + texel_buffer_parts: BTreeMap::from([( + slot(Stage::Fragment, SlotClass::Texture, 11), + 4, + )]), viewport_index_varying: true, // An emulated post-tessellation vertex function's state. tessellation: Some(crate::pipeline::TessellationDescriptor { diff --git a/crates/metal2vulkan/src/pipeline/compile/key.rs b/crates/metal2vulkan/src/pipeline/compile/key.rs index 18bb9de53..83ea22302 100644 --- a/crates/metal2vulkan/src/pipeline/compile/key.rs +++ b/crates/metal2vulkan/src/pipeline/compile/key.rs @@ -266,6 +266,11 @@ pub fn function_key( .bytes(format!("{:?}", inputs.texel_rows).as_bytes()); } // Appended only when set, as `storage_view_slots`. + if !inputs.texel_buffer_parts.is_empty() { + h.bytes(b"texel-buffer-parts") + .bytes(format!("{:?}", inputs.texel_buffer_parts).as_bytes()); + } + // Appended only when set, as `storage_view_slots`. if !inputs.extended_range.is_empty() { h.bytes(b"extended-range") .bytes(format!("{:?}", inputs.extended_range).as_bytes()); diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index 1d0daad41..e6178d59b 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -694,6 +694,7 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() { .replace(", ycbcr_in_place: {}", "") .replace(", ycbcr_planes_sampled: {}", "") .replace(", texel_rows: {}", "") + .replace(", texel_buffer_parts: {}", "") .replace(", viewport_index_varying: false", "") .replace(", max_call_stack_depth: None", "") .replace(", open_cl_mode: false", "") diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index e0c8b4d7c..e71fd8767 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -854,6 +854,16 @@ pub enum RuntimeFact { /// threadgroups runs at the call's threadgroup size alone. Its plans state the variant, and /// plan such a dispatch so. PartialThreadgroups, + /// The function only reads, writes, updates by a texture atomic or asks the width of the + /// texture buffer bound to the slot (`bind::texel_parts`): `read` (not through a sampler), + /// `write`, an atomic, `get_width`, `is_null` and a texture fence, on a device that indexes an + /// array of the slot's kind of texel buffer by a `NonUniform` value. Where the binder binds a + /// texture buffer of more texels than one view holds there (`TextureShape::Buffer::parts` + /// past 1), the slot joins the plan's variant (`VariantKey::texel_buffer_parts`, + /// `LoweringInputs::texel_buffer_parts`), under which its binding is an array of the texture + /// buffer's parts, one texel buffer view each. Elsewhere the slot binds one view, which + /// `maxTexelBufferElements` bounds (`TexelBufferRange`). + TexelBufferParts { slot: SlotRef }, } /// What one compile made of a slot of a `RuntimeFact::UniformViewRange`. diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index 4360dc988..3c44424db 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -201,6 +201,17 @@ pub struct LoweringInputs { /// queries reading the slot's push field (`bind::TexelRows`). #[cfg_attr(feature = "serde", serde(default))] pub texel_rows: BTreeSet, + /// Texture-buffer slots bound to a texture buffer of more texels than one view holds, each + /// with its parts (`VariantKey::texel_buffer_parts`, `RuntimeFact::TexelBufferParts`): each is + /// declared as an array of that many texel buffers, texel `i` of its reads, writes and atomics + /// texel `i − k · P` of part `k = min(⌊i / P⌋, parts − 1)`, `P` the device's + /// `bind::part_texels`, and its width `(parts − 1) · P` plus the last part's + /// (`bind::texel_parts`). + #[cfg_attr( + feature = "serde", + serde(default, with = "crate::pipeline::serde_pairs") + )] + pub texel_buffer_parts: BTreeMap, /// The fragment function's render pipeline has a vertex function that writes /// `[[viewport_array_index]]`. That function stores `ViewportIndex` as 0 for an index at or /// past the draw's viewport count, where Metal draws through viewport 0 and its fragment diff --git a/crates/metal2vulkan/src/tests/engine_graphics_binder.rs b/crates/metal2vulkan/src/tests/engine_graphics_binder.rs index 87b8d6183..e93b79791 100644 --- a/crates/metal2vulkan/src/tests/engine_graphics_binder.rs +++ b/crates/metal2vulkan/src/tests/engine_graphics_binder.rs @@ -1803,6 +1803,7 @@ fn a_swizzled_texel_buffer_specializes_the_slot_that_reads_it() { bytes_per_row: 1024, resource_id: None, swizzle, + parts: 1, }; let read = slot(Stage::Kernel, SlotClass::Texture, 0); let id = p @@ -1909,6 +1910,7 @@ fn cube_views_and_texel_buffers() { bytes_per_row: 1024, resource_id: None, swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts: 1, }; let s = kernel_state(&[(0, tb(0)), (1, tb(256))], &[], false); // Vulkan 1.2 requires `R32G32B32A32_SFLOAT` uniform texel buffers. @@ -1944,6 +1946,7 @@ fn cube_views_and_texel_buffers() { bytes_per_row: length, resource_id: None, swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts: 1, }; let ragged = kernel_state(&[(0, sized(1030)), (1, tb(256))], &[], false); let cmds = plan.instantiate_dispatch(&ragged, &d).expect("ragged"); @@ -2056,6 +2059,7 @@ fn a_written_texel_buffer_follows_its_buffer_features() { bytes_per_row: 16, resource_id: None, swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts: 1, }; let state = |textures: &[(u32, BoundTexture)]| { let mut s = kernel_state(textures, &[], true); @@ -2120,6 +2124,179 @@ fn a_written_texel_buffer_follows_its_buffer_features() { assert!(formatless.contains("lavapipe"), "{formatless:?}"); } +/// A texture buffer of more texels than one view holds binds through views of its parts +/// (`bind::texel_parts`) where its slot's function reads, writes or asks the width of it, on a +/// device that indexes texel buffer arrays by a `NonUniform` value: the plan asks for the parts +/// variant (`VariantKey::texel_buffer_parts`), whose pipeline declares the slot an array of its +/// parts and plans to itself, one write per part, the range of each part at its element. A +/// texture buffer one view holds asks for no parts: the pipeline the plan binds keeps its compile +/// key and its layout's one texel buffer at the slot. +#[test] +fn texture_buffers_past_the_limit_bind_their_parts() { + use crate::pipeline::facts::RuntimeFact; + let Some(bc) = fixture("ob1_texel_buffer") else { + return; + }; + let entry = "ob1_texel_buffer"; + let (src, dst) = ( + slot(Stage::Kernel, SlotClass::Texture, 0), + slot(Stage::Kernel, SlotClass::Texture, 1), + ); + let tb = |texels: u64, parts: u32| BoundTexture::Buffer { + pixel_format: PixelFormat::R32Uint, + offset: 0, + length: texels * 4, + bytes_per_row: texels * 4, + resource_id: None, + swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts, + }; + let state = |a: BoundTexture, b: BoundTexture| { + let mut s = kernel_state(&[(0, a), (1, b)], &[], true); + if let Some(t) = s.stages.get_mut(&Stage::Kernel) { + t.buffers.insert(1, buffer(4096, 0, None)); + } + s + }; + let d = Dispatch::Threadgroups { + groups: [1, 1, 1], + threads_per_group: [8, 1, 1], + }; + let counts = |p: &ComputePipeline| -> Vec<(u32, vk::DescriptorType)> { + let set = &p.layout.sets[0]; + [src, dst] + .iter() + .map(|&at| { + let b = set + .bindings + .iter() + .find(|b| b.source == BindingSource::Texture(at)); + let b = b.expect("the slot's binding"); + (b.count, b.ty) + }) + .collect() + }; + let mut parted = BTreeSet::new(); + for (stem, dev) in devices() { + let Ok(p) = kernel(&dev, &bc, entry) else { + continue; + }; + let limits = dev.profile().fields().limits; + let limit = u64::from(limits.max_texel_buffer_elements); + let part = crate::bind::part_texels(&limits); + let indexed = dev.profile().fields().descriptors; + let stated = |p: &ComputePipeline, at| { + p.dependencies + .iter() + .any(|d| d.fact == RuntimeFact::TexelBufferParts { slot: at }) + }; + assert_eq!( + stated(&p, src), + indexed.non_uniform_uniform_texel_buffer, + "{stem}" + ); + assert_eq!( + stated(&p, dst), + indexed.non_uniform_storage_texel_buffer, + "{stem}" + ); + // One view: no parts; the pipeline's bindings hold one texel buffer each. + let one = state(tb(limit, 1), tb(64, 1)); + let plan = p + .plan(&dev, &one.shape()) + .unwrap_or_else(|e| panic!("{stem}: {e}")); + assert!(plan.variant.texel_buffer_parts.is_empty(), "{stem}"); + let single = vec![ + (1, vk::DescriptorType::UNIFORM_TEXEL_BUFFER), + (1, vk::DescriptorType::STORAGE_TEXEL_BUFFER), + ]; + assert_eq!(counts(&p), single, "{stem}"); + if plan.variant.is_empty() { + assert!(plan.instantiate_dispatch(&one, &d).is_ok(), "{stem}"); + } + if !stated(&p, src) || !stated(&p, dst) || part == 0 { + continue; + } + // Past the limit: the source one texel past it (two parts on every committed profile), + // the destination in three. + let src_parts = crate::bind::texel_buffer_parts(&limits, limit + 1); + assert_eq!(src_parts, 2, "{stem}"); + let past = state(tb(limit + 1, src_parts), tb(2 * part + 7, 3)); + let plan = p + .plan(&dev, &past.shape()) + .unwrap_or_else(|e| panic!("{stem}: {e}")); + let want = std::collections::BTreeMap::from([(src, 2), (dst, 3)]); + assert_eq!(plan.variant.texel_buffer_parts, want, "{stem}"); + let lib = Library::from_air(&bc).expect("library"); + let f = lib.function(entry).expect("entry"); + let compiled = dev + .compile_function( + &FunctionDescriptor::new(f), + &plan.variant.lowering_inputs(Stage::Kernel), + &Budget::standard(), + ) + .unwrap_or_else(|e| panic!("{stem}: {e}")); + let variant = dev + .compile_compute_pipeline( + &ComputePipelineDescriptor::new(StageSource::Compiled(compiled)), + &Budget::standard(), + ) + .unwrap_or_else(|e| panic!("{stem}: {e}")); + assert_ne!(variant.key, p.key, "{stem}: a pipeline of its own"); + let arrays = vec![ + (2, vk::DescriptorType::UNIFORM_TEXEL_BUFFER), + (3, vk::DescriptorType::STORAGE_TEXEL_BUFFER), + ]; + assert_eq!(counts(&variant), arrays, "{stem}"); + let again = variant + .plan(&dev, &past.shape()) + .unwrap_or_else(|e| panic!("{stem}: {e}")); + assert_eq!(again.variant, plan.variant, "{stem}: a fixed point"); + let elements: Vec<(SlotRef, u32)> = again + .descriptors + .iter() + .filter_map(|w| match w.source { + WriteSource::TexelBuffer { slot, .. } => Some((slot, w.array_element)), + _ => None, + }) + .collect(); + assert_eq!( + elements, + vec![(src, 0), (src, 1), (dst, 0), (dst, 1), (dst, 2)], + "{stem}" + ); + let cmds = again + .instantiate_dispatch(&past, &d) + .unwrap_or_else(|e| panic!("{stem}: {e}")); + let texel_bindings: BTreeSet = (variant.layout.sets[0].bindings.iter()) + .filter(|b| matches!(b.source, BindingSource::Texture(_))) + .map(|b| b.binding) + .collect(); + let ranges: Vec<(u32, u64, u64)> = cmds + .descriptor_ranges + .iter() + .filter(|r| r.set == 0 && texel_bindings.contains(&r.binding)) + .map(|r| (r.element, r.range.offset, r.range.range)) + .collect(); + let tail = (limit + 1 - part) * 4; + assert_eq!( + ranges, + vec![ + (0, 0, part * 4), + (1, part * 4, tail), + (0, 0, part * 4), + (1, part * 4, part * 4), + (2, 2 * part * 4, 28), + ], + "{stem}" + ); + parted.insert(stem.clone()); + } + for stem in ["lavapipe", "swiftshader", "moltenvk-m3"] { + assert!(parted.contains(stem), "{stem}: {parted:?}"); + } +} + /// The value `plan` specializes constant `id` to (a `bool`'s low byte). fn spec_value(plan: &BindingPlan, id: u32) -> u8 { let e = plan @@ -2154,6 +2331,7 @@ fn out_of_bounds_alpha_follows_the_bound_format() { bytes_per_row: 1024, resource_id: None, swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts: 1, }; let (mut kernels, mut fragments) = (0, 0); for (stem, dev) in devices() { diff --git a/crates/metal2vulkan/src/tests/engine_texture_interp.rs b/crates/metal2vulkan/src/tests/engine_texture_interp.rs index bf9246449..35b25d136 100644 --- a/crates/metal2vulkan/src/tests/engine_texture_interp.rs +++ b/crates/metal2vulkan/src/tests/engine_texture_interp.rs @@ -387,6 +387,152 @@ fn a_swizzled_texel_buffer_reads_metals_out_of_bounds_alpha_in_any_lane() { assert!(ran > 0); } +/// `stem` with texel buffer views of at most `limit` texels and the robustness features in `drop` +/// removed. +fn limited(stem: &str, limit: u32, drop: &[VkFeature]) -> DeviceProfile { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/profiles") + .join(format!("{stem}.json")); + let text = std::fs::read_to_string(path).expect("profile"); + let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); + desc.limits.max_texel_buffer_elements = limit; + for f in drop { + desc.features.remove(f); + } + Device::new(desc, crate::device::DevicePolicy::default()) + .expect("device") + .profile() + .clone() +} + +/// A texture buffer of more texels than one view holds, read and written through its parts +/// (`bind::texel_parts`, `LoweringInputs::texel_buffer_parts`), on lavapipe's profile with views +/// of 1024 texels: `ob1_texel_buffer` reads texels on both sides of each part's end, each its own, +/// and writes texels on both sides of each part's end, each in its own place and nowhere else. +/// Without robustness the shader checks the reads and guards the writes against the whole width: +/// a read past the last texel is Metal's zero and a write there is dropped. The interpreter traps +/// any access outside an image, so no access leaves its part. +#[test] +fn a_texture_buffer_s_parts_hold_every_texel() { + use crate::lower::select::LowerInputs; + use crate::pipeline::facts::RuntimeFact; + use crate::pipeline::sym::{SlotClass, SlotRef}; + use crate::pipeline::testing::typed_module_with; + let bc = match llvm_assemble(&engine_dir().join("ob1_texel_buffer.ll")) { + Ok(b) => b, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return; + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected ob1_texel_buffer: {why}"), + }; + let slot = |index| SlotRef { + stage: Stage::Kernel, + class: SlotClass::Texture, + index, + }; + let (read, write) = (slot(0), slot(1)); + const PART: u32 = 1024; + let word = |i: u32| 0x5000_0000 ^ i; + let all = [ + VkFeature::RobustImageAccess, + VkFeature::RobustImageAccess2, + VkFeature::RobustBufferAccess, + VkFeature::RobustBufferAccess2, + ]; + let mut inputs = LowerInputs::new(); + inputs.texel_buffer_parts.insert(read, 2); + inputs.texel_buffer_parts.insert(write, 3); + // The source's 1033 texels in parts of 1024 and 9; the destination's 2053 in 1024, 1024, 5. + let (src_n, dst_n) = (PART + 9, 2 * PART + 5); + for (stem, p) in [ + ("lavapipe", limited("lavapipe", PART, &[])), + ("lavapipe unrobust", limited("lavapipe", PART, &all)), + ] { + assert_eq!( + crate::bind::part_texels(&p.fields().limits), + u64::from(PART) + ); + let contained = contains_texel_buffers(&p); + assert_eq!(contained, stem.ends_with("unrobust"), "{stem}"); + let (plan, m) = typed_module_with(&bc, "ob1_texel_buffer", &p, &inputs) + .unwrap_or_else(|e| panic!("{stem}: {e}")); + for at in [read, write] { + let fact = RuntimeFact::TexelBufferParts { slot: at }; + assert!(plan.facts.contains(&fact), "{stem}: {fact:?}"); + } + // An `R32Uint` texel `(v, 0, 0, 1)`; the parts in their elements. + let part = |index: u32, element: u32, first: u32, n: u32, held: bool| { + let mut img = Image::new(texture(index), [n, 1, 1], 1, 1, 1).at_element(element); + if held { + for (i, t) in img.texels.iter_mut().enumerate() { + *t = [word(first + i as u32), 0, 0, 1]; + } + } + img + }; + let images = vec![ + part(0, 0, 0, PART, true), + part(0, 1, PART, src_n - PART, true), + part(1, 0, 0, PART, false), + part(1, 1, PART, PART, false), + part(1, 2, 2 * PART, dst_n - 2 * PART, false), + ]; + // Past the last texel only where the shader checks the access; the device's robustness + // answers such an access elsewhere, which the interpreter traps. + let (past, far) = match contained { + true => (src_n, u32::MAX), + false => (1, 2), + }; + let reads = [0, PART - 1, PART, src_n - 1, past, far, 5, PART + 3]; + let (past, far) = match contained { + true => (dst_n, u32::MAX), + false => (7, 8), + }; + let writes = [ + PART - 1, + PART, + 2 * PART - 1, + 2 * PART, + dst_n - 1, + past, + far, + 3, + ]; + let idx: Vec = reads + .iter() + .chain(&writes) + .flat_map(|i| i.to_le_bytes()) + .collect(); + let mut res = resources(&plan, &[idx, vec![0u8; 32]]); + let identity = crate::metal::TextureSwizzleChannels::DEFAULT.word(); + res.spec + .insert(SpecKey::TextureSwizzle(read), u64::from(identity)); + res.spec.insert(SpecKey::OutOfBoundsAlpha(read), 1); + let (bufs, imgs) = + run_both(&m, &res, &images, [8, 1, 1]).unwrap_or_else(|e| panic!("{stem}: {e:?}")); + let want: Vec = (reads.iter()) + .map(|&i| if i < src_n { word(i) } else { 0 }) + .collect(); + assert_eq!(words(&bufs[1]), want, "{stem}: reads of {reads:?}"); + // The destination's texels, by index across its parts. + let mut written = vec![0u32; dst_n as usize]; + for (t, &i) in writes.iter().enumerate() { + if i < dst_n { + written[i as usize] = 0xA000_0000 | t as u32; + } + } + let got: Vec = (imgs.iter()) + .filter(|img| img.slot == texture(1)) + .flat_map(|img| img.texels.iter().map(|t| t[0])) + .collect(); + assert_eq!( + got, written, + "{stem}: the destination after the writes of {writes:?}" + ); + } +} + /// `t = 2 * (t + (1, 2, 3, 4))` per texel of a 2x2 read_write texture; on a profile that contains /// images, a 4x3 grid checks its reads and drops its writes outside the texture. #[test] diff --git a/crates/metal2vulkan/src/tests/engine_texture_ulong.rs b/crates/metal2vulkan/src/tests/engine_texture_ulong.rs index 782b106cc..897305432 100644 --- a/crates/metal2vulkan/src/tests/engine_texture_ulong.rs +++ b/crates/metal2vulkan/src/tests/engine_texture_ulong.rs @@ -844,6 +844,7 @@ fn a_swizzled_texture_buffer_read_as_ulong_is_refused() { bytes_per_row: 256, resource_id: None, swizzle, + parts: 1, }, ); t @@ -921,6 +922,7 @@ fn the_binder_views_an_atomically_updated_ulong_texture_as_r64() { bytes_per_row: 256, resource_id: None, swizzle: crate::metal::TextureSwizzleChannels::DEFAULT, + parts: 1, }, ); let plan = all.plan(&dev, &t.shape()).expect("plan"); diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 7c1764f79..d2e81c931 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3703,6 +3703,7 @@ field metal2vulkan-runtime::WorkCounts.submit_stalls_on_work pub submit_stalls_o field metal2vulkan-runtime::WorkCounts.submits_behind_idle_stalls pub submits_behind_idle_stalls: u64 field metal2vulkan-runtime::WorkCounts.sync_files_after_host_copies pub sync_files_after_host_copies: u64 field metal2vulkan-runtime::WorkCounts.sync_files_exported pub sync_files_exported: u64 +field metal2vulkan-runtime::WorkCounts.texel_buffer_parts_bound pub texel_buffer_parts_bound: u64 field metal2vulkan-runtime::WorkCounts.texel_rows_bound pub texel_rows_bound: u64 field metal2vulkan-runtime::WorkCounts.texel_rows_textures pub texel_rows_textures: u64 field metal2vulkan-runtime::WorkCounts.texel_shadow_bytes pub texel_shadow_bytes: u64 @@ -3949,6 +3950,7 @@ field metal2vulkan::bind::DescriptorBytes.binding pub binding: u32 field metal2vulkan::bind::DescriptorBytes.bytes pub bytes: Vec field metal2vulkan::bind::DescriptorBytes.set pub set: u32 field metal2vulkan::bind::DescriptorRange.binding pub binding: u32 +field metal2vulkan::bind::DescriptorRange.element pub element: u32 field metal2vulkan::bind::DescriptorRange.range pub range: BufferRange field metal2vulkan::bind::DescriptorRange.set pub set: u32 field metal2vulkan::bind::DescriptorWrite.array_element pub array_element: u32 @@ -4502,6 +4504,7 @@ field metal2vulkan::cache::VariantKey.srgb_textures pub srgb_textures: BTreeSet< field metal2vulkan::cache::VariantKey.storage_images pub storage_images: BTreeMap field metal2vulkan::cache::VariantKey.storage_view_slots pub storage_view_slots: BTreeSet field metal2vulkan::cache::VariantKey.swizzled_storage pub swizzled_storage: BTreeSet +field metal2vulkan::cache::VariantKey.texel_buffer_parts pub texel_buffer_parts: BTreeMap field metal2vulkan::cache::VariantKey.texel_rows pub texel_rows: BTreeSet field metal2vulkan::cache::VariantKey.unit_axes pub unit_axes: u8 field metal2vulkan::cache::VariantKey.viewport_compensation pub viewport_compensation: Option @@ -5125,6 +5128,7 @@ field metal2vulkan::pipeline::LoweringInputs.storage_images pub storage_images: field metal2vulkan::pipeline::LoweringInputs.storage_view_slots pub storage_view_slots: BTreeSet field metal2vulkan::pipeline::LoweringInputs.swizzled_storage pub swizzled_storage: BTreeSet field metal2vulkan::pipeline::LoweringInputs.tessellation pub tessellation: Option +field metal2vulkan::pipeline::LoweringInputs.texel_buffer_parts pub texel_buffer_parts: BTreeMap field metal2vulkan::pipeline::LoweringInputs.texel_rows pub texel_rows: BTreeSet field metal2vulkan::pipeline::LoweringInputs.texture_write_rounding pub texture_write_rounding: metal::TextureWriteRoundingMode field metal2vulkan::pipeline::LoweringInputs.threadgroup_size_matches_tile_size pub threadgroup_size_matches_tile_size: bool @@ -5553,6 +5557,7 @@ fn metal2vulkan::bind::mesh_scan_module pub fn mesh_scan_module(device: &Device) fn metal2vulkan::bind::metal_object_grid pub fn metal_object_grid(groups: [u32; 3], threads: [u32; 3], direct: bool) -> Option<([u32; 3], [u32; 3])> fn metal2vulkan::bind::mipmap_filter_module pub fn mipmap_filter_module(device: &Device, kernel: MipmapFilterKernel) -> Result fn metal2vulkan::bind::pages_copy_module pub fn pages_copy_module(device: &Device, copy: PagesCopy) -> Result +fn metal2vulkan::bind::part_texels pub fn part_texels(limits: &Limits) -> u64 fn metal2vulkan::bind::plane_bytes_copy_module pub fn plane_bytes_copy_module(device: &Device) -> Result fn metal2vulkan::bind::plane_copy_module pub fn plane_copy_module(device: &Device) -> Result fn metal2vulkan::bind::plane_words_module pub fn plane_words_module(device: &Device) -> Result @@ -5574,6 +5579,7 @@ fn metal2vulkan::bind::shadow_merge_kept_image_module pub fn shadow_merge_kept_i fn metal2vulkan::bind::shadow_merge_module pub fn shadow_merge_module(device: &Device, stores: ShadowMergeStores) -> Result fn metal2vulkan::bind::stencil_split_module pub fn stencil_split_module(device: &Device, feature: Feature) -> Result fn metal2vulkan::bind::tessellation_scan_module pub fn tessellation_scan_module(device: &Device, kernel: &TessellationScanKernel) -> Result +fn metal2vulkan::bind::texel_buffer_parts pub fn texel_buffer_parts(limits: &Limits, texels: u64) -> u32 fn metal2vulkan::bind::tiled_texels_module pub fn tiled_texels_module(device: &Device) -> Result fn metal2vulkan::bind::two_plane_texels_module pub fn two_plane_texels_module(device: &Device) -> Result fn metal2vulkan::bind::visibility_combine_module pub fn visibility_combine_module(device: &Device) -> Result @@ -13376,7 +13382,7 @@ variant metal2vulkan::bind::AstcTexels::Half Half variant metal2vulkan::bind::AstcTexels::Unorm8 Unorm8 variant metal2vulkan::bind::BoundBuffer::Buffer Buffer { length: u64, offset: u64, gpu_address: u64, device_address: Option, attribute_stride: Option } variant metal2vulkan::bind::BoundBuffer::Bytes Bytes { len: u32, attribute_stride: Option } -variant metal2vulkan::bind::BoundTexture::Buffer Buffer { pixel_format: metal::PixelFormat, offset: u64, length: u64, bytes_per_row: u64, resource_id: Option, swizzle: metal::TextureSwizzleChannels } +variant metal2vulkan::bind::BoundTexture::Buffer Buffer { pixel_format: metal::PixelFormat, offset: u64, length: u64, bytes_per_row: u64, resource_id: Option, swizzle: metal::TextureSwizzleChannels, parts: u32 } variant metal2vulkan::bind::BoundTexture::Texture Texture { facts: TextureFacts, resource_id: Option } variant metal2vulkan::bind::BufferShape::Buffer Buffer { attribute_stride: Option, device_address: bool, length_class: u8, offset_alignment: u32 } variant metal2vulkan::bind::BufferShape::Bytes Bytes { attribute_stride: Option } @@ -13619,7 +13625,7 @@ variant metal2vulkan::bind::StatusWord::SeqCstFences SeqCstFences variant metal2vulkan::bind::StatusWord::Status Status variant metal2vulkan::bind::TessellationRecords::Exact Exact { records: u32 } variant metal2vulkan::bind::TessellationRecords::Pool Pool -variant metal2vulkan::bind::TextureShape::Buffer Buffer { pixel_format: metal::PixelFormat, swizzle: metal::TextureSwizzleChannels } +variant metal2vulkan::bind::TextureShape::Buffer Buffer { pixel_format: metal::PixelFormat, swizzle: metal::TextureSwizzleChannels, parts: u32 } variant metal2vulkan::bind::TextureShape::Texture Texture { texture_type: metal::TextureType, pixel_format: metal::PixelFormat, sample_count: u32, usage: metal::TextureUsage, mipmap_level_count: u32, sparse: bool, swizzle: metal::TextureSwizzleChannels, address_modes: metal::sampler::AddressModeMap, offset_base_axes: u8, ycbcr_in_place: bool, ycbcr_planes_sampler: Option, texel_rows: bool } variant metal2vulkan::bind::TileMapError::Region Region { level: u32, slice: u32, origin: [u32; 3], size: [u32; 3] } variant metal2vulkan::bind::TileMapError::Shape Shape @@ -15209,6 +15215,7 @@ variant metal2vulkan::pipeline::RuntimeFact::StorageTextureNumericType StorageTe variant metal2vulkan::pipeline::RuntimeFact::StorageTextureWriteRounding StorageTextureWriteRounding { slot: SlotRef, halves: bool } variant metal2vulkan::pipeline::RuntimeFact::SynthesizedGeometry SynthesizedGeometry { weights: bool, layer: bool, viewport: bool } variant metal2vulkan::pipeline::RuntimeFact::TestedStorageWrites TestedStorageWrites { early_tests: bool, early_variant: bool } +variant metal2vulkan::pipeline::RuntimeFact::TexelBufferParts TexelBufferParts { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::TexelBufferRange TexelBufferRange { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::TexelFormat TexelFormat { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::TexelRows TexelRows { slot: SlotRef } diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index b614e27bf..70b93e87e 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -755,6 +755,8 @@ surface! { struct YCbCrInPlace N; struct YCbCrPlanesSampler N; struct TexelRows N; + fn part_texels; + fn texel_buffer_parts; struct YCbCrConversion N; struct YCbCrCodes N; enum YCbCrOutput N; diff --git a/docs/API.md b/docs/API.md index 93b38f6ce..053c4ca27 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1491,6 +1491,30 @@ for dependency in &pipeline.dependencies { conversion as an image's do, so the reads and writes are the image route's, bit for bit (the runtime's `texel_rows_device` tests compare every `RGBA8Unorm` and `RGBA16Float` code), and no precision note is recorded. Any other slot, and any texture without the fact, binds the image. +- A texture buffer of more texels than the device's `maxTexelBufferElements` (Metal makes them up + to 2^28 texels on every Mac; one texel buffer view holds 2^27 on ANV and lavapipe and 2^26 on + MoltenVK) is bound through views of its parts. State with its binding the views its texels take + (`BoundTexture::Buffer::parts`, `bind::texel_buffer_parts(limits, texels)`: 1 within the limit, + which binds one view as before and keeps the pipeline and its key). Each part but the last holds + `bind::part_texels(limits)` texels, the limit rounded down to a multiple of + `minTexelBufferOffsetAlignment`, so every part starts on that alignment where the texture buffer + does; the last holds the rest. A slot whose function only reads (not through a sampler), writes, + updates by an atomic or asks the width of the texture buffer, on a device that indexes an array + of the slot's kind of texel buffer by a `NonUniform` value (`RuntimeFact::TexelBufferParts`), + takes the pipeline's parts variant (`VariantKey::texel_buffer_parts`) where the shape binds more + than one part there: the slot is an array of the parts' texel buffers, one `WriteSource::TexelBuffer` + per array element, each element's view the bytes of the instance's `DescriptorRange` at that + `element`. The function reads texel `i` as texel `i - k · P` of part `k = min(⌊i / P⌋, parts - 1)`; + a texel past the last lies past the last part's end, so its read is Metal's out-of-bounds texel + and its write is dropped, as through one view, and the width is `(parts - 1) · P` plus the last + part's. Each part is the device's own view in the format one view takes, so a read converts its + texel as that view does, and no precision note is recorded. Still refused with + `BindError::TexelBufferTooLarge`: a slot that reads the texture buffer through a sampler, a device + without `shaderUniformTexelBufferArrayNonUniformIndexing` (or + `shaderStorageTexelBufferArrayNonUniformIndexing` for a slot that writes), and a format whose + block holds several texels; parts past a stage's sampled or storage image descriptors are the + link's descriptor-count refusal. A texture buffer past the limit in an argument buffer is the + heap class's neutral (`metal2vulkan-degrade-unnamed-texture-unviewable`). - `interface.reaches_command_buffers` and `interface.texture_writing_stages` say, provably, which pipelines may touch an indirect command buffer and which stages may write a texture. `interface.command_writes` (`CommandWrites`) says what its functions may write into the diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index c3e326d23..78573333a 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -286,7 +286,7 @@ Columns: | Variant | What it blocks | Where | Basis | Sites | Reach | |---|---|---|---|---|---| | `DescriptorRangeExceeded` | A descriptor-form slot's window exceeds the descriptor range limit (Profile F) | at the device's limit | `device` | 2: `crates/metal2vulkan/src/bind/graphics.rs (rebind_with)`, `crates/metal2vulkan/src/bind/instantiate.rs (bind_buffers)` | `app`: a buffer window past a device's descriptor range | -| `TexelBufferTooLarge` | A texel buffer exceeds `maxTexelBufferElements` | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/instantiate.rs (texel_ranges)` | `rare`: a texture buffer past maxTexelBufferElements | +| `TexelBufferTooLarge` | A texture buffer bound through one texel buffer view exceeds `maxTexelBufferElements` | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/instantiate.rs (texel_ranges)` | `rare`: a texture buffer past maxTexelBufferElements its parts do not bind | | `HeapTooLarge` | The set-1 heap's elements (one per resident texture a handle can name, plus the null element) exceed the pipeline's heap capacity | at the device's limit | `device` | 7: `crates/metal2vulkan/src/bind/heap.rs (directory_bytes)`, `crates/metal2vulkan/src/bind/heap.rs (heap_elements)` (+3) | `rare`: more resident textures than the pipeline's heap holds (bindless at scale) | | `TessellationFactorRange` | The tessellation factors a draw reads span more bytes (`needed`) than one storage-buffer descriptor can bind (`limit`, `maxStorageBufferRange`),... | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding)` | `rare`: tessellation factors past one storage descriptor | | `PatchIndexRange` | The patch indices a draw reads span more bytes (`needed`) than one storage-buffer descriptor can bind (`limit`, `maxStorageBufferRange`) | at the device's limit | `device` | 1: `crates/metal2vulkan/src/bind/graphics.rs (patch_binding)` | `rare`: patch indices past one storage descriptor | diff --git a/scripts/refusal-surface/reach.tsv b/scripts/refusal-surface/reach.tsv index 92f43167e..73014d264 100644 --- a/scripts/refusal-surface/reach.tsv +++ b/scripts/refusal-surface/reach.tsv @@ -202,7 +202,7 @@ apple DepthCleared none Apple-private (no public header) apple StencilCleared none Apple-private (no public header) apple SurfaceClientDirection none an IOSurface key in no public header bind DescriptorRangeExceeded app a buffer window past a device's descriptor range -bind TexelBufferTooLarge rare a texture buffer past maxTexelBufferElements +bind TexelBufferTooLarge rare a texture buffer past maxTexelBufferElements its parts do not bind bind HeapTooLarge rare more resident textures than the pipeline's heap holds (bindless at scale) bind TessellationFactorRange rare tessellation factors past one storage descriptor bind PatchIndexRange rare patch indices past one storage descriptor