WIP orphans: the viewport compensation, the slot rebinds and the dead code the deletions left
This commit is contained in:
1 parent
4847983473
commit
8bf93f30f8
46 files changed
+49
-4373
No files matched your search
@@ -9,7 +9,7 @@
|
||||
//! says where each argument goes, by its Metal argument index (`[[id(n)]]`), so an encoder over it
|
||||
//! writes exactly the bytes the function reads.
|
||||
//!
|
||||
//! A layout comes from one of three sources, each Metal's own rule:
|
||||
//! A layout comes from a function's argument buffer, by Metal's own rule:
|
||||
//!
|
||||
//! - **A function's argument buffer** (`newArgumentEncoderWithBufferIndex:`,
|
||||
//! [`Function::argument_buffer_layout`](crate::library::Function::argument_buffer_layout)): the
|
||||
@@ -23,44 +23,6 @@
|
||||
//! pointer to a struct that holds arguments is a nested argument buffer
|
||||
//! (`newArgumentEncoderForBufferAtIndex:`), with the pointee's layout; a pointer to any other
|
||||
//! struct is a plain buffer, for which Metal answers no nested encoder.
|
||||
//! - **Argument descriptors** (`newArgumentEncoderWithArguments:`,
|
||||
//! [`ArgumentBufferLayout::from_descriptors`]): the descriptors in the order given (not by
|
||||
//! index), each at the next offset its type's alignment allows, as a C struct of MSL types. A
|
||||
//! run of consecutive constants is a constant block: its first constant may set
|
||||
//! `constantBlockAlignment`, which then aligns it as `(offset + a - 1) & !(a - 1)` for `a` the
|
||||
//! larger of the alignment set and its type's. The encoder's `alignment` is the largest type
|
||||
//! alignment (never the block alignment), and `encodedLength` the end rounded up to it. Every
|
||||
//! rule here is measured on an M3 Max and an M4 (probes).
|
||||
//! - **A reflected buffer binding** (`newArgumentEncoderWithBufferBinding:`,
|
||||
//! [`ArgumentBufferLayout::from_buffer_binding`]): the binding's struct type as its reflection
|
||||
//! states it, not the function's AIR, by one of two rules. Each member sits at its `offset`,
|
||||
//! element `k` of an array at `k` times the array's `stride` further and `k` times its
|
||||
//! `argumentIndexStride` more ids, and a struct member's members at their ids plus the
|
||||
//! struct's; `encodedLength` is the end of the last element rounded up to the alignment, a
|
||||
//! struct element's size being its members' end rounded up to their largest alignment.
|
||||
//! - An argument buffer's: a constant takes its MSL size and alignment (as above), the
|
||||
//! alignment is the binding's `bufferAlignment`, and a pointer to an argument buffer nests
|
||||
//! by the same rule at the pointer's alignment. A library's binding thus gives the function's
|
||||
//! layout, while a pipeline's, whose arrays of textures, samplers and pointers, and of structs
|
||||
//! of them only, reflect stride 0, gives an encoder that writes every element of such an array at element
|
||||
//! 0's place, in fewer bytes.
|
||||
//! - A plain buffer's (a struct pointee that is no argument buffer): every constant takes 8
|
||||
//! bytes aligned to 8, whatever its type; the alignment is the members' largest; an array
|
||||
//! whose `argumentIndexStride` is 0 gives element `k` the ids `k` times the element's span;
|
||||
//! every member's id is 0, so index 0 is the last member's.
|
||||
//! - A binding that states no struct type (a plain buffer of a scalar, vector or matrix) has
|
||||
//! no arguments: an encoder of no bytes, alignment 1.
|
||||
//!
|
||||
//! These are Metal's answers on an M3 Max (macOS 26.7) and an M4 (macOS 27.0.1) over
|
||||
//! `validation/fixtures/public/reflection/`'s `argument_buffers`, `buffers`, `encoders` and
|
||||
//! `encoder_types` (every scalar, vector, matrix and atomic type alone in a plain buffer and
|
||||
//! after a texture in an argument buffer), and API validation lets every one of these encoders be
|
||||
//! made. They differ in one rule: in a plain buffer the M4 gives an integer or `bool` scalar its
|
||||
//! own size aligned to 1. This takes the M3 Max's, whose encoder is never shorter or less
|
||||
//! aligned, so memory sized and aligned by it holds the encoder under either.
|
||||
//!
|
||||
//! An index that two descriptors claim (the same index, or one inside another's array) is
|
||||
//! resolved to the later descriptor, as Metal's encoder resolves it.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
@@ -71,7 +33,7 @@ use crate::air::error::{AbiError, DiagName, InputError, InputErrorKind, Location
|
||||
use crate::budget::Meter;
|
||||
use crate::error::{Error, Feature, Limit, Unsupported};
|
||||
use crate::metal::{BindingAccess, DataType, TextureType};
|
||||
use crate::reflection::{BufferBinding, PointerType, StructType};
|
||||
use crate::reflection::{PointerType, StructType};
|
||||
|
||||
/// Bytes of every argument that is no constant: an address or a resource ID.
|
||||
pub const ARGUMENT_HANDLE_BYTES: u64 = 8;
|
||||
@@ -233,85 +195,6 @@ impl From<Error> for ArgumentLayoutError {
|
||||
}
|
||||
}
|
||||
|
||||
/// `(offset + a - 1) & !(a - 1)`: Metal's alignment step, which equals rounding up to a multiple
|
||||
/// of `a` when `a` is a power of two (a probe measured other values too).
|
||||
fn metal_align(offset: u64, a: u64) -> Option<u64> {
|
||||
let a = a.max(1);
|
||||
Some(offset.checked_add(a - 1)? & !(a - 1))
|
||||
}
|
||||
|
||||
/// The bytes and alignment of one element of `ty` in an argument buffer: 8 for every handle,
|
||||
/// and for a constant its MSL size and alignment (a 3-vector as a 4-vector; a matrix its columns'
|
||||
/// vectors). `None` for a type no argument has.
|
||||
fn type_size_align(ty: DataType) -> Option<(u64, u64, ArgumentType)> {
|
||||
use DataType as D;
|
||||
let handle = |t| Some((ARGUMENT_HANDLE_BYTES, ARGUMENT_HANDLE_BYTES, t));
|
||||
let (scalar, columns, rows) = match ty {
|
||||
D::Pointer => return handle(ArgumentType::Buffer),
|
||||
D::Texture => return handle(ArgumentType::Texture),
|
||||
D::Sampler => return handle(ArgumentType::Sampler),
|
||||
D::IndirectCommandBuffer => return handle(ArgumentType::IndirectCommandBuffer),
|
||||
D::ComputePipeline => return handle(ArgumentType::ComputePipelineState),
|
||||
D::RenderPipeline => return handle(ArgumentType::RenderPipelineState),
|
||||
D::VisibleFunctionTable => return handle(ArgumentType::VisibleFunctionTable),
|
||||
D::IntersectionFunctionTable => return handle(ArgumentType::IntersectionFunctionTable),
|
||||
D::PrimitiveAccelerationStructure | D::InstanceAccelerationStructure => {
|
||||
return handle(ArgumentType::AccelerationStructure)
|
||||
}
|
||||
D::DepthStencilState => return handle(ArgumentType::DepthStencilState),
|
||||
D::Float => (4, 1, 1),
|
||||
D::Float2 => (4, 1, 2),
|
||||
D::Float3 => (4, 1, 3),
|
||||
D::Float4 => (4, 1, 4),
|
||||
D::Float2x2 => (4, 2, 2),
|
||||
D::Float2x3 => (4, 2, 3),
|
||||
D::Float2x4 => (4, 2, 4),
|
||||
D::Float3x2 => (4, 3, 2),
|
||||
D::Float3x3 => (4, 3, 3),
|
||||
D::Float3x4 => (4, 3, 4),
|
||||
D::Float4x2 => (4, 4, 2),
|
||||
D::Float4x3 => (4, 4, 3),
|
||||
D::Float4x4 => (4, 4, 4),
|
||||
D::Half => (2, 1, 1),
|
||||
D::Half2 => (2, 1, 2),
|
||||
D::Half3 => (2, 1, 3),
|
||||
D::Half4 => (2, 1, 4),
|
||||
D::Half2x2 => (2, 2, 2),
|
||||
D::Half2x3 => (2, 2, 3),
|
||||
D::Half2x4 => (2, 2, 4),
|
||||
D::Half3x2 => (2, 3, 2),
|
||||
D::Half3x3 => (2, 3, 3),
|
||||
D::Half3x4 => (2, 3, 4),
|
||||
D::Half4x2 => (2, 4, 2),
|
||||
D::Half4x3 => (2, 4, 3),
|
||||
D::Half4x4 => (2, 4, 4),
|
||||
D::BFloat => (2, 1, 1),
|
||||
D::BFloat2 => (2, 1, 2),
|
||||
D::BFloat3 => (2, 1, 3),
|
||||
D::BFloat4 => (2, 1, 4),
|
||||
D::Int | D::UInt => (4, 1, 1),
|
||||
D::Int2 | D::UInt2 => (4, 1, 2),
|
||||
D::Int3 | D::UInt3 => (4, 1, 3),
|
||||
D::Int4 | D::UInt4 => (4, 1, 4),
|
||||
D::Short | D::UShort => (2, 1, 1),
|
||||
D::Short2 | D::UShort2 => (2, 1, 2),
|
||||
D::Short3 | D::UShort3 => (2, 1, 3),
|
||||
D::Short4 | D::UShort4 => (2, 1, 4),
|
||||
D::Char | D::UChar | D::Bool => (1, 1, 1),
|
||||
D::Char2 | D::UChar2 | D::Bool2 => (1, 1, 2),
|
||||
D::Char3 | D::UChar3 | D::Bool3 => (1, 1, 3),
|
||||
D::Char4 | D::UChar4 | D::Bool4 => (1, 1, 4),
|
||||
D::Long | D::ULong => (8, 1, 1),
|
||||
D::Long2 | D::ULong2 => (8, 1, 2),
|
||||
D::Long3 | D::ULong3 => (8, 1, 3),
|
||||
D::Long4 | D::ULong4 => (8, 1, 4),
|
||||
_ => return None,
|
||||
};
|
||||
// A vector of 3 takes the room of 4; a vector is aligned to its size.
|
||||
let vector = scalar * if rows == 3 { 4 } else { rows };
|
||||
Some((vector * columns, vector, ArgumentType::Constant))
|
||||
}
|
||||
|
||||
impl ArgumentBufferLayout {
|
||||
/// Where argument `index` lands: in the last member whose indices hold it, inside a struct
|
||||
/// member's element as that element's layout says. `None` when no member holds it.
|
||||
@@ -360,186 +243,6 @@ impl ArgumentBufferLayout {
|
||||
|
||||
impl ArgumentBufferLayout {}
|
||||
|
||||
/// Which of Metal's two rules lays out a reflected struct (the module docs).
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Rule {
|
||||
/// An argument buffer's: a constant takes its MSL size and alignment, and the encoder the
|
||||
/// binding's alignment.
|
||||
ArgumentBuffer,
|
||||
/// A plain buffer's: every constant takes [`PLAIN_CONSTANT_BYTES`] bytes at that alignment,
|
||||
/// and the encoder its members' largest alignment. An array whose `argumentIndexStride` is 0
|
||||
/// gives element `k` the ids `k` times the element's span.
|
||||
PlainBuffer,
|
||||
}
|
||||
|
||||
/// The bytes, and the alignment, a plain buffer's encoder gives each constant member whatever its
|
||||
/// type: Metal's answer on an M3 Max (macOS 26.7) for every scalar, vector, matrix and atomic
|
||||
/// type measured. An M4 (macOS 27.0.1) gives an integer or `bool` scalar its own size aligned to 1
|
||||
/// instead, and so never a longer or more aligned encoder: a buffer sized and aligned by this rule
|
||||
/// holds the encoder under either.
|
||||
const PLAIN_CONSTANT_BYTES: u64 = 8;
|
||||
|
||||
/// One element of a reflected member: what it holds, its bytes and alignment, and the layout a
|
||||
/// struct element or a pointer to an argument buffer has.
|
||||
struct ReflectedElement {
|
||||
ty: ArgumentType,
|
||||
size: u64,
|
||||
alignment: u64,
|
||||
layout: Option<Arc<ArgumentBufferLayout>>,
|
||||
}
|
||||
|
||||
/// Struct `st` as an encoder's arguments by `rule`, aligned to `alignment` (its members' largest
|
||||
/// alignment when `None`): its members, and the end of its last element rounded up to the
|
||||
/// alignment.
|
||||
fn reflected_layout(
|
||||
st: &StructType,
|
||||
alignment: Option<u64>,
|
||||
rule: Rule,
|
||||
) -> Result<ArgumentBufferLayout, ArgumentLayoutError> {
|
||||
let (members, end, natural) = reflected_members(st, rule)?;
|
||||
let alignment = alignment.unwrap_or(natural);
|
||||
let encoded_length = metal_align(end, alignment).ok_or(ArgumentLayoutError::TooLarge)?;
|
||||
Ok(ArgumentBufferLayout {
|
||||
encoded_length,
|
||||
alignment,
|
||||
members,
|
||||
})
|
||||
}
|
||||
|
||||
/// The members of reflected struct `st` by `rule`, the end of its last element, and its members'
|
||||
/// largest alignment. The recursion is as deep as the struct type, which the reflection built
|
||||
/// from a decoded layout under the nesting cap.
|
||||
fn reflected_members(
|
||||
st: &StructType,
|
||||
rule: Rule,
|
||||
) -> Result<(Vec<ArgumentMember>, u64, u64), ArgumentLayoutError> {
|
||||
let mut members = Vec::with_capacity(st.members().len());
|
||||
let (mut end, mut alignment) = (0u64, 1u64);
|
||||
for m in st.members() {
|
||||
let id = m.argument_index();
|
||||
let (element, count, stride, ids_per_element) = match m.array_type() {
|
||||
Some(a) => {
|
||||
if a.element_array_type().is_some() {
|
||||
return Err(ArgumentLayoutError::ArrayOfArrays { id });
|
||||
}
|
||||
let element = reflected_element(
|
||||
m.name(),
|
||||
a.element_type(),
|
||||
a.element_struct_type(),
|
||||
a.element_pointer_type(),
|
||||
rule,
|
||||
)?;
|
||||
let ids = match (a.argument_index_stride(), rule) {
|
||||
(0, Rule::ArgumentBuffer) if element.ty == ArgumentType::Struct => {
|
||||
return Err(unmeasured(m.name()));
|
||||
}
|
||||
(0, _) => element_ids(&element),
|
||||
(ids, _) => ids,
|
||||
};
|
||||
(element, a.array_length(), a.stride(), ids)
|
||||
}
|
||||
None => {
|
||||
let element = reflected_element(
|
||||
m.name(),
|
||||
m.data_type(),
|
||||
m.struct_type(),
|
||||
m.pointer_type(),
|
||||
rule,
|
||||
)?;
|
||||
let ids = element_ids(&element);
|
||||
let size = element.size;
|
||||
(element, 1, size, ids)
|
||||
}
|
||||
};
|
||||
let last = stride
|
||||
.checked_mul(u64::from(count.saturating_sub(1)))
|
||||
.and_then(|bytes| bytes.checked_add(m.offset()))
|
||||
.and_then(|start| start.checked_add(element.size))
|
||||
.ok_or(ArgumentLayoutError::TooLarge)?;
|
||||
end = end.max(last);
|
||||
alignment = alignment.max(element.alignment);
|
||||
members.push(ArgumentMember {
|
||||
id,
|
||||
count,
|
||||
ids_per_element,
|
||||
offset: m.offset(),
|
||||
stride,
|
||||
size: element.size,
|
||||
ty: element.ty,
|
||||
layout: element.layout,
|
||||
});
|
||||
}
|
||||
Ok((members, end, alignment))
|
||||
}
|
||||
|
||||
/// The ids one element takes: a struct all its members', anything else one.
|
||||
fn element_ids(element: &ReflectedElement) -> u32 {
|
||||
match (element.ty, &element.layout) {
|
||||
(ArgumentType::Struct, Some(l)) => l.id_span(),
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// One element of reflected type `data_type` (with its struct or pointer type) of member `name`,
|
||||
/// by `rule`.
|
||||
fn reflected_element(
|
||||
name: &str,
|
||||
data_type: DataType,
|
||||
st: Option<&StructType>,
|
||||
pointer: Option<&PointerType>,
|
||||
rule: Rule,
|
||||
) -> Result<ReflectedElement, ArgumentLayoutError> {
|
||||
if let Some(st) = st {
|
||||
let (members, end, alignment) = reflected_members(st, rule)?;
|
||||
let size = metal_align(end, alignment).ok_or(ArgumentLayoutError::TooLarge)?;
|
||||
return Ok(ReflectedElement {
|
||||
ty: ArgumentType::Struct,
|
||||
size,
|
||||
alignment,
|
||||
layout: Some(Arc::new(ArgumentBufferLayout {
|
||||
encoded_length: size,
|
||||
alignment: 1,
|
||||
members,
|
||||
})),
|
||||
});
|
||||
}
|
||||
let (size, alignment, ty) = type_size_align(data_type).ok_or_else(|| unmeasured(name))?;
|
||||
match rule {
|
||||
Rule::ArgumentBuffer => {
|
||||
let nested = match pointer {
|
||||
Some(p) if ty == ArgumentType::Buffer && p.element_is_argument_buffer() => p
|
||||
.element_struct_type()
|
||||
.map(|st| {
|
||||
reflected_layout(st, Some(p.alignment()), Rule::ArgumentBuffer)
|
||||
.map(Arc::new)
|
||||
})
|
||||
.transpose()?,
|
||||
_ => None,
|
||||
};
|
||||
Ok(ReflectedElement {
|
||||
ty,
|
||||
size,
|
||||
alignment,
|
||||
layout: nested,
|
||||
})
|
||||
}
|
||||
Rule::PlainBuffer if ty == ArgumentType::Constant => Ok(ReflectedElement {
|
||||
ty,
|
||||
size: PLAIN_CONSTANT_BYTES,
|
||||
alignment: PLAIN_CONSTANT_BYTES,
|
||||
layout: None,
|
||||
}),
|
||||
Rule::PlainBuffer => Err(unmeasured(name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The refusal of a reflected member whose encoder Metal's answer was not measured for.
|
||||
fn unmeasured(name: &str) -> ArgumentLayoutError {
|
||||
ArgumentLayoutError::Compile(Error::Unsupported(
|
||||
Unsupported::not_implemented(Feature::Reflection).naming(DiagName::new(name)),
|
||||
))
|
||||
}
|
||||
|
||||
/// Why a decoded entry's argument buffer needs the specialized entry: an index or count the AIR
|
||||
/// states through a function constant, or a parameter at the index that a function constant
|
||||
/// gates (or two such alternatives).
|
||||
|
||||
@@ -97,7 +97,6 @@
|
||||
//! ([`IndirectArgs::ClampScratch`]).
|
||||
|
||||
use crate::bind::graphics::zeroed;
|
||||
use crate::bind::heap::HeapSource;
|
||||
use crate::bind::indirect_clamp::IndirectClamp;
|
||||
use crate::bind::instantiate::{
|
||||
bind_buffers, put, slot_field, texel_ranges, BufferExtent, DescriptorBytes, DescriptorRange,
|
||||
|
||||
@@ -89,13 +89,6 @@
|
||||
//! (`RuntimeFact::ViewportCount`) stores `ViewportIndex` as 0 for an index at or past its
|
||||
//! `PushField::ViewportCount`, the encoder's viewport count (`BindState::viewport_count`), which
|
||||
//! each draw writes: Metal draws such an index through viewport 0.
|
||||
//! - **Viewport compensation**. A draw through a viewport Vulkan's cannot be (a negative width, or
|
||||
//! a depth range past `[0, 1]` the device does not take; `BindShape::viewport_compensation`) runs
|
||||
//! the variant whose vertex function compensates its position
|
||||
//! (`VariantKey::viewport_compensation`), from the draw's `PushField::ViewportCompensation`
|
||||
//! (`BindState::viewport_compensation`); the plan of the pipeline compiled under another
|
||||
//! compensation is `BindError::NeedsVariant`. A mesh pipeline has no vertex function to
|
||||
//! compensate: not implemented.
|
||||
//! - **Zeroed colors**. A draw into a pass with color attachments its pipeline has no pixel format
|
||||
//! for (`BindShape::zeroed_colors`), where plain Metal stores zero bytes at every sample the draw
|
||||
//! covers, runs the variant whose pipeline has them, written whole and unblended, and whose
|
||||
@@ -193,7 +186,7 @@
|
||||
//! at a time: the plan's variant says which. A draw of a rate-mapped pass's triangles fanned
|
||||
//! out to their regions (`BindShape::region_fan_out`) runs the variant whose triangle stage does
|
||||
//! so (`VariantKey::region_fan_out`) where its pipeline is such a pipeline of no amplification,
|
||||
//! drawn without a viewport compensation, whose stages synthesize no geometry stage of their own
|
||||
//! whose stages synthesize no geometry stage of their own
|
||||
//! (`RuntimeFact::SynthesizedGeometry`), draw no band and choose no slice or viewport; it binds
|
||||
//! the region table (`WriteSource::RateMapRegions`) and, for a probe, the flags
|
||||
//! (`WriteSource::RateMapFlags`), and a probe pushes its flag's index to the geometry stage. A
|
||||
@@ -367,7 +360,7 @@ use crate::pipeline::sym::{
|
||||
Axis, DispatchKeys, PushField, SlotClass, SlotRef, SpecKey, Stage, SyntheticBinding,
|
||||
};
|
||||
use crate::pipeline::vertex::{VertexAttribute, VertexStride};
|
||||
use crate::pipeline::{AmplificationDraws, RegionFanOut, ViewportCompensation};
|
||||
use crate::pipeline::{AmplificationDraws, RegionFanOut};
|
||||
use crate::vk;
|
||||
|
||||
/// A Metal draw call.
|
||||
@@ -467,8 +460,7 @@ pub struct DrawCommands {
|
||||
/// One write per stage with push fields, covering the stage's whole push range.
|
||||
pub push_constants: Vec<PushConstantWrite>,
|
||||
/// Each stage's `ArgumentTable` contents, then the plan's heap tables (its handle tables,
|
||||
/// sampler tables and function-table directories), which
|
||||
/// [`BindingPlan::instantiate_draw_apart_into`] leaves out.
|
||||
/// sampler tables and function-table directories).
|
||||
pub descriptor_bytes: Vec<DescriptorBytes>,
|
||||
/// Vertex-buffer offsets by Vulkan vertex binding (`vkCmdBindVertexBuffers`).
|
||||
pub buffer_offsets: Vec<(u32, u64)>,
|
||||
@@ -1209,7 +1201,7 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
|
||||
&& views.view_mask == 0;
|
||||
// A draw of a rate-mapped pass's triangles once, the variant's triangle stage fanning each out
|
||||
// to the regions it touches, where the pipeline is such a vertex pipeline of no amplification,
|
||||
// drawn without a compensation, whose stages synthesize no geometry stage of their own, draw
|
||||
// whose stages synthesize no geometry stage of their own, draw
|
||||
// no band and choose no slice or viewport; it draws no regions several at a time.
|
||||
let synthesized =
|
||||
(p.dependencies.iter()).any(|d| matches!(d.fact, RuntimeFact::SynthesizedGeometry { .. }));
|
||||
@@ -1219,7 +1211,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
|
||||
&& amplification_draws.is_none()
|
||||
&& views.view_mask == 0
|
||||
&& p.graphics.max_vertex_amplification_count <= 1
|
||||
&& shape.viewport_compensation.is_none()
|
||||
&& shape.line_band.is_none()
|
||||
&& !synthesized
|
||||
&& !p.graphics.writes_viewport_index
|
||||
@@ -1269,29 +1260,8 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
|
||||
// `Layer` output there, and only there. A mesh function writes `Layer` in every variant.
|
||||
let dropped_vertex_layer =
|
||||
vertex_layer.is_some() && !mesh && shape.render_target_array_length <= 1;
|
||||
// A viewport Vulkan's cannot be: the vertex function compensates its position, and the
|
||||
// pipeline compiled under another compensation (or none) is the other variant.
|
||||
let viewport_compensation = shape.viewport_compensation;
|
||||
let compiled_compensation = p.dependencies.iter().find_map(|d| match d.fact {
|
||||
RuntimeFact::ViewportCompensation {
|
||||
depth,
|
||||
point_guard,
|
||||
mirrors,
|
||||
vertex_clamp,
|
||||
} => Some(
|
||||
ViewportCompensation::new(depth)
|
||||
.with_point_guard(point_guard)
|
||||
.with_mirrors(mirrors)
|
||||
.with_vertex_clamp(vertex_clamp),
|
||||
),
|
||||
_ => None,
|
||||
});
|
||||
let profile = device.profile();
|
||||
let limits = &profile.fields().limits;
|
||||
// A mesh pipeline has no vertex function to compensate.
|
||||
if viewport_compensation.is_some() && !stages.contains(&Stage::Vertex) {
|
||||
return Err(not_implemented(Feature::MeshShading));
|
||||
}
|
||||
// The pass's colors the pipeline lacks, which plain Metal zeroes where the draw covers them:
|
||||
// the variant whose pipeline has them and whose fragment function writes the zero. A mesh
|
||||
// pipeline's is not built; a pipeline without a fragment function rasterizes into no color,
|
||||
@@ -1820,15 +1790,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
|
||||
// A folded object function's region record (`bind::mesh_arguments`): the
|
||||
// consumer's hole.
|
||||
PushField::ReplayRegionAddress if stage == Stage::Object => {}
|
||||
// The draw's viewport compensation, which instantiation reads from the state.
|
||||
PushField::ViewportCompensation if stage == Stage::Vertex => {}
|
||||
// The draw's point guard band, which instantiation reads from the state.
|
||||
PushField::PointGuard if stage == Stage::Vertex => {}
|
||||
// The draw's mirrored viewports, which instantiation reads from the state.
|
||||
PushField::ViewportMirrors if stage == Stage::Vertex => {}
|
||||
// The draw's clamp of each vertex's depth, which instantiation reads from the
|
||||
// state.
|
||||
PushField::VertexDepthClamp if stage == Stage::Vertex => {}
|
||||
// The draw's depth clamp range, which instantiation reads from the state.
|
||||
PushField::DepthClampRange if stage == Stage::Fragment => {}
|
||||
// The encoder's alpha test reference, which instantiation reads from the state.
|
||||
@@ -2624,7 +2585,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
|
||||
variant.pulled_vertex_buffers = pulled_vertex_buffers;
|
||||
variant.dropped_vertex_layer = dropped_vertex_layer;
|
||||
variant.amplification_draws = amplification_draws;
|
||||
variant.viewport_compensation = viewport_compensation;
|
||||
// A pipeline compiled for a draw replay's bindings states its variant.
|
||||
variant.replay_bindings = replayed;
|
||||
variant.merged_draws = p
|
||||
@@ -2693,7 +2653,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
|
||||
other_layer_variant: vertex_layer
|
||||
.is_some_and(|dropped| dropped != dropped_vertex_layer)
|
||||
|| compiled_draws != amplification_draws
|
||||
|| compiled_compensation != viewport_compensation
|
||||
|| other_colors
|
||||
|| compiled_range != depth_clamp_range
|
||||
|| compiled_rotated != rotated_weights
|
||||
@@ -2913,7 +2872,7 @@ impl BindingPlan {
|
||||
draw: &DrawCall,
|
||||
commands: &mut DrawCommands,
|
||||
) -> Result<(), BindError> {
|
||||
instantiate(self.drawn(draw)?, state, draw, commands, Heap::Written)
|
||||
instantiate(self.drawn(draw)?, state, draw, commands)
|
||||
}
|
||||
|
||||
/// The render template `draw` instantiates: this plan's, where the draw runs on its variant.
|
||||
@@ -2943,20 +2902,6 @@ impl BindingPlan {
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
/// [`slot_rebinds`](Self::slot_rebinds) of `slots`, made in `into` in place of what it held,
|
||||
/// keeping its lists' room: whether the plan rebinds them so (`into` then holds the same
|
||||
/// rebinds `slot_rebinds` answers), else `into` serves no rebind. A caller that makes rebinds
|
||||
/// again for other slots or another plan allocates nothing where `into` had room for them.
|
||||
pub fn slot_rebinds_into(&self, slots: &[SlotRef], into: &mut SlotRebinds) -> bool {
|
||||
match self.graphics.as_ref() {
|
||||
Some(t) if !t.other_layer_variant => rebinds_into(t, slots, into),
|
||||
_ => {
|
||||
into.slots.clear();
|
||||
into.slots.extend_from_slice(slots);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Vulkan draw of a Metal draw, and the base vertex and first instance the
|
||||
@@ -4389,23 +4334,14 @@ fn deindexed_draw(
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a draw's commands hold the plan's heap tables (`BindingPlan::instantiate_draw_into`)
|
||||
/// or leave them to the consumer (`BindingPlan::instantiate_draw_apart_into`).
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Heap {
|
||||
Written,
|
||||
Apart,
|
||||
}
|
||||
|
||||
/// The commands of `draw` of `state`, written over `out` (`BindingPlan::instantiate_draw_into`):
|
||||
/// each of its fields set, its vectors cleared or their values overwritten in place, never
|
||||
/// replaced; the heap tables among its descriptor bytes where `heap` writes them.
|
||||
/// replaced; the heap tables among its descriptor bytes.
|
||||
fn instantiate(
|
||||
t: &GraphicsTemplate,
|
||||
state: &BindState,
|
||||
draw: &DrawCall,
|
||||
out: &mut DrawCommands,
|
||||
heap: Heap,
|
||||
) -> Result<(), BindError> {
|
||||
let DrawCommands {
|
||||
push_constants,
|
||||
@@ -4451,10 +4387,7 @@ fn instantiate(
|
||||
extents.clear();
|
||||
let bound = bind_buffers(&t.buffers, state, descriptor_ranges, extents)?;
|
||||
descriptor_ranges.extend(crate::bind::instantiate::texel_ranges(&t.resources, state)?);
|
||||
let tables = match heap {
|
||||
Heap::Written => crate::bind::heap::table_bytes(&t.resources, state)?,
|
||||
Heap::Apart => Vec::new(),
|
||||
};
|
||||
let tables = crate::bind::heap::table_bytes(&t.resources, state)?;
|
||||
// A patch draw: a native pipeline's control stage's writes, or an emulated one's scan.
|
||||
let (control, scan) = match t.tessellation.map(|t| t.site) {
|
||||
Some(FactorSite::Scan { kernel, .. }) => {
|
||||
@@ -4572,34 +4505,6 @@ fn instantiate(
|
||||
PushField::RenderTargetArrayLength => {
|
||||
FieldBytes::of(&state.render_target_array_length.to_le_bytes())
|
||||
}
|
||||
// The identity where the state holds none: a plan states its variant, so
|
||||
// instantiation under another shape asks for the other one first.
|
||||
PushField::ViewportCompensation => state
|
||||
.viewport_compensation
|
||||
.map_or([1.0, 0.0, 1.0, 0.0], |c| c.values)
|
||||
.iter()
|
||||
.flat_map(|v| v.to_le_bytes())
|
||||
.collect(),
|
||||
PushField::PointGuard => state
|
||||
.viewport_compensation
|
||||
.map_or([1.0, 1.0], |c| c.guard)
|
||||
.iter()
|
||||
.flat_map(|v| v.to_le_bytes())
|
||||
.collect(),
|
||||
// No viewport mirrored where the state holds none.
|
||||
PushField::ViewportMirrors => FieldBytes::of(
|
||||
&state
|
||||
.viewport_compensation
|
||||
.map_or(0, |c| c.mirrors)
|
||||
.to_le_bytes(),
|
||||
),
|
||||
// No vertex's depth clamped where the state holds none.
|
||||
PushField::VertexDepthClamp => state
|
||||
.viewport_compensation
|
||||
.map_or([f32::NEG_INFINITY, f32::INFINITY], |c| c.vertex_clamp)
|
||||
.iter()
|
||||
.flat_map(|v| v.to_le_bytes())
|
||||
.collect(),
|
||||
// Metal's own `[0, 1]` where the state holds none.
|
||||
PushField::DepthClampRange => state
|
||||
.depth_clamp_range
|
||||
@@ -4910,437 +4815,6 @@ fn pulled_stride(
|
||||
Ok(FieldBytes::of(&stride.to_le_bytes()))
|
||||
}
|
||||
|
||||
/// Where a push field a slot rebind writes lies: its stage's push write among the commands'
|
||||
/// (`DrawCommands::push_constants`), that write's range start, and the field's place.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct FieldAt {
|
||||
push: usize,
|
||||
push_start: u32,
|
||||
loc: PushLoc,
|
||||
}
|
||||
|
||||
/// One changed buffer slot of a [`SlotRebinds`]: its place among the template's buffer slots, its
|
||||
/// descriptor range's place among the commands' and its `(set, binding)` where the plan binds it
|
||||
/// a descriptor-form buffer, and the ranges of [`SlotRebinds::words`] that hold the push fields
|
||||
/// reading its residual (`SlotBindOffset`) and its guest address (`SlotGuestBase`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct SlotRebind {
|
||||
buffer: usize,
|
||||
place: Option<(usize, (u32, u32))>,
|
||||
offsets: (usize, usize),
|
||||
bases: (usize, usize),
|
||||
}
|
||||
|
||||
/// A push field of a changed slot that no changed buffer slot of the template holds: its word is
|
||||
/// worked out apart.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum LooseWord {
|
||||
/// `SlotBindOffset`: no residual, 0.
|
||||
Offset,
|
||||
/// `SlotGuestBase` of the slot.
|
||||
Base(SlotRef),
|
||||
/// `VertexBufferStride` of the pulled layout.
|
||||
Stride(u32),
|
||||
}
|
||||
|
||||
/// What [`BindingPlan::rebind_draw_slots_into`] of some slots works out of a render plan alone
|
||||
/// ([`BindingPlan::slot_rebinds`]): each changed buffer slot's descriptor range place, the push
|
||||
/// fields that read the slots and where they lie, and the fixed-function vertex buffers they bind.
|
||||
/// Made once for a plan and its slots, it serves each rebind of them
|
||||
/// ([`BindingPlan::rebind_draw_slots_with`]), which looks at the state and the commands alone;
|
||||
/// made again in place for other slots or another plan
|
||||
/// ([`BindingPlan::slot_rebinds_into`]), it keeps its lists' room, so a rebinds made again of no
|
||||
/// more slots and fields allocates nothing. Its default is made of nothing. Opaque.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SlotRebinds {
|
||||
/// The slots they were made for.
|
||||
slots: Vec<SlotRef>,
|
||||
/// Each changed buffer slot, in the template's order of buffer slots.
|
||||
buffers: Vec<SlotRebind>,
|
||||
/// The push fields of the entries of `buffers`, each entry's at its ranges.
|
||||
words: Vec<FieldAt>,
|
||||
/// The push fields of changed slots no entry of `buffers` holds, in placement order.
|
||||
loose: Vec<(FieldAt, LooseWord)>,
|
||||
/// Each changed fixed-function vertex buffer's place among the template's.
|
||||
vertex: Vec<usize>,
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
thread_local! {
|
||||
/// The rebinds [`BindingPlan::rebind_draw_slots_with`] makes again to check those it is given
|
||||
/// (builds with debug assertions), kept with their lists' room.
|
||||
static REBINDS_MADE_AGAIN: std::cell::RefCell<SlotRebinds> =
|
||||
std::cell::RefCell::new(SlotRebinds::default());
|
||||
}
|
||||
|
||||
impl SlotRebinds {
|
||||
/// The slots they were made for.
|
||||
pub fn slots(&self) -> &[SlotRef] {
|
||||
&self.slots
|
||||
}
|
||||
}
|
||||
|
||||
/// Each push field of the template `t` that reads a slot `changed` answers for, with that slot,
|
||||
/// its word and where it lies, in placement order; an item `None` where such a field cannot be
|
||||
/// rewritten alone (a changed texture's in-place planes, a field of a stage with no push range).
|
||||
fn changed_fields<'a>(
|
||||
t: &'a GraphicsTemplate,
|
||||
slots: &'a [SlotRef],
|
||||
changed: impl Fn(SlotRef) -> bool + Copy + 'a,
|
||||
) -> impl Iterator<Item = Option<(SlotRef, LooseWord, FieldAt)>> + 'a {
|
||||
let pushes = t.stages.iter().scan(0, |pushes, st| {
|
||||
let (push_start, push_size) = st.push_range.unwrap_or((0, 0));
|
||||
let push = (push_size != 0).then(|| {
|
||||
*pushes += 1;
|
||||
*pushes - 1
|
||||
});
|
||||
Some((st, push, push_start))
|
||||
});
|
||||
pushes.flat_map(move |(st, push, push_start)| {
|
||||
st.fields.iter().filter_map(move |f| {
|
||||
let (slot, word) = match f.field {
|
||||
PushField::SlotBindOffset(slot) if changed(slot) => (slot, LooseWord::Offset),
|
||||
PushField::SlotGuestBase(slot) if changed(slot) => (slot, LooseWord::Base(slot)),
|
||||
PushField::VertexBufferStride(layout) => {
|
||||
let slot = SlotRef {
|
||||
stage: Stage::Vertex,
|
||||
class: SlotClass::Buffer,
|
||||
index: layout,
|
||||
};
|
||||
if !changed(slot) {
|
||||
return None;
|
||||
}
|
||||
(slot, LooseWord::Stride(layout))
|
||||
}
|
||||
// A changed texture's in-place planes or rows, and a changed buffer's length past
|
||||
// its bind offset.
|
||||
PushField::YCbCrInPlace(slot)
|
||||
| PushField::TexelRows(slot)
|
||||
| PushField::SlotBounds(slot)
|
||||
if slots.contains(&slot) =>
|
||||
{
|
||||
return Some(None)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let field = push.map(|push| FieldAt {
|
||||
push,
|
||||
push_start,
|
||||
loc: f.loc,
|
||||
});
|
||||
Some(field.map(|field| (slot, word, field)))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// [`BindingPlan::slot_rebinds_into`] of a render plan's template `t`.
|
||||
fn rebinds_into(t: &GraphicsTemplate, slots: &[SlotRef], into: &mut SlotRebinds) -> bool {
|
||||
into.slots.clear();
|
||||
into.slots.extend_from_slice(slots);
|
||||
into.buffers.clear();
|
||||
into.words.clear();
|
||||
into.loose.clear();
|
||||
into.vertex.clear();
|
||||
let changed = |slot: SlotRef| slot.class == SlotClass::Buffer && slots.contains(&slot);
|
||||
// What the slots decide some other way than below: a stage's argument or root table, a mesh
|
||||
// or patch draw's own reads, a de-indexed draw's layout, and a uniform view a written slot
|
||||
// may alias.
|
||||
let other_reads = t
|
||||
.stages
|
||||
.iter()
|
||||
.any(|st| st.root_first.is_some() || st.table.is_some())
|
||||
|| t.mesh.is_some()
|
||||
|| t.tessellation.is_some()
|
||||
|| t.deindexed.is_some()
|
||||
|| (t.buffers.iter().any(|b| b.disjoint) && t.buffers.iter().any(|b| b.access.write));
|
||||
// A texture slot's texels a texture buffer's range bounds, which the commands hold.
|
||||
let texel_range = |slot: &SlotRef| t.resources.texel_buffers.iter().any(|pt| pt.slot == *slot);
|
||||
let texels = slots
|
||||
.iter()
|
||||
.any(|slot| slot.class == SlotClass::Texture && texel_range(slot));
|
||||
if other_reads || texels || changed_fields(t, slots, changed).any(|f| f.is_none()) {
|
||||
return false;
|
||||
}
|
||||
// Each changed slot, with its descriptor-form range's place among the bound ones' (in
|
||||
// `bind_buffers`' order). What the plan's shape binds at a slot is what the state binds there
|
||||
// (`bound_buffer` holds the state to it): a bound descriptor-form slot takes its place.
|
||||
let mut at = 0;
|
||||
for (index, pb) in t.buffers.iter().enumerate() {
|
||||
let descriptor = match (pb.form, pb.binding) {
|
||||
(BufferForm::Descriptor(_), Some(key)) => Some(key),
|
||||
_ => None,
|
||||
};
|
||||
let bound = pb.bound != BoundKind::Unbound;
|
||||
let place = match (bound, descriptor) {
|
||||
(true, Some(key)) => {
|
||||
at += 1;
|
||||
Some((at - 1, key))
|
||||
}
|
||||
// A device-address slot's root entry.
|
||||
(true, None) if changed(pb.slot) => return false,
|
||||
_ => None,
|
||||
};
|
||||
if changed(pb.slot) {
|
||||
// The push fields that read its residual, then those that read its guest address.
|
||||
let fields = || changed_fields(t, slots, changed).flatten();
|
||||
let from = into.words.len();
|
||||
let offsets = fields()
|
||||
.filter(|(slot, word, _)| *slot == pb.slot && matches!(word, LooseWord::Offset));
|
||||
into.words.extend(offsets.map(|(_, _, field)| field));
|
||||
let middle = into.words.len();
|
||||
let bases = fields()
|
||||
.filter(|(slot, word, _)| *slot == pb.slot && matches!(word, LooseWord::Base(_)));
|
||||
into.words.extend(bases.map(|(_, _, field)| field));
|
||||
into.buffers.push(SlotRebind {
|
||||
buffer: index,
|
||||
place,
|
||||
offsets: (from, middle),
|
||||
bases: (middle, into.words.len()),
|
||||
});
|
||||
}
|
||||
}
|
||||
// The push fields of changed slots no changed buffer slot of the template holds, or not as
|
||||
// its residual or guest address, in placement order.
|
||||
let buffers = &into.buffers;
|
||||
let held = |slot: SlotRef| (buffers.iter()).any(|e| t.buffers[e.buffer].slot == slot);
|
||||
let loose = changed_fields(t, slots, changed)
|
||||
.flatten()
|
||||
.filter(|(slot, word, _)| matches!(word, LooseWord::Stride(_)) || !held(*slot));
|
||||
into.loose
|
||||
.extend(loose.map(|(_, word, field)| (field, word)));
|
||||
// Each changed fixed-function vertex buffer, at its binding's place (bound in
|
||||
// `t.vertex_buffers`' order); a per-bind stride's binding, whose extent and stride may move
|
||||
// with it, is written whole.
|
||||
for (place, vb) in t.vertex_buffers.iter().enumerate() {
|
||||
if !changed(vb.slot) {
|
||||
continue;
|
||||
}
|
||||
if matches!(vb.stride, VertexStride::PerBind) {
|
||||
return false;
|
||||
}
|
||||
into.vertex.push(place);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Write `word` at `field` of the commands' push writes: whether they hold its write.
|
||||
fn put_word<const N: usize>(
|
||||
out: &mut DrawCommands,
|
||||
field: FieldAt,
|
||||
word: [u8; N],
|
||||
) -> Result<bool, BindError> {
|
||||
let Some(write) = out.push_constants.get_mut(field.push) else {
|
||||
return Ok(false);
|
||||
};
|
||||
put(
|
||||
&mut write.bytes,
|
||||
field.push_start,
|
||||
&mut [],
|
||||
field.loc,
|
||||
&word,
|
||||
)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// [`BindingPlan::rebind_draw_slots_with`] of a render plan's template `t`.
|
||||
fn rebind_with(
|
||||
t: &GraphicsTemplate,
|
||||
rebinds: &SlotRebinds,
|
||||
state: &BindState,
|
||||
out: &mut DrawCommands,
|
||||
) -> Result<bool, BindError> {
|
||||
// An argument table's bytes or a root table: what the slots decide some other way.
|
||||
if !out.descriptor_bytes.is_empty() || !out.root_tables.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let other_plan = || internal("slot rebinds another plan made");
|
||||
// Each changed buffer slot's range and residual, and the push fields that read them.
|
||||
for entry in &rebinds.buffers {
|
||||
let pb = t.buffers.get(entry.buffer).ok_or_else(other_plan)?;
|
||||
let bound = crate::bind::instantiate::bound_buffer(state, pb.slot, pb.bound)?;
|
||||
let (bind_offset, length, base) = match bound {
|
||||
Some(&BoundBuffer::Buffer {
|
||||
length,
|
||||
offset,
|
||||
gpu_address,
|
||||
..
|
||||
}) => (offset, length, gpu_address.wrapping_add(offset)),
|
||||
Some(&BoundBuffer::Bytes { len, .. }) => (0, u64::from(len.max(1)), 0),
|
||||
None => (0, 0, 0),
|
||||
};
|
||||
let base = guest_word(base, t.resources.biased_slot_words);
|
||||
// An unbound slot has no residual: its `SlotBindOffset` reads 0.
|
||||
let mut residual = 0;
|
||||
if let (Some((place, key)), Some(_)) = (entry.place, bound) {
|
||||
let views = state.uniform_views_at_residual;
|
||||
let (range, slot_residual) =
|
||||
crate::bind::instantiate::planned_range(pb, bind_offset, length, views).map_err(
|
||||
|e| match e {
|
||||
RangeError::TooLarge { needed } => BindError::DescriptorRangeExceeded {
|
||||
slot: pb.slot,
|
||||
needed,
|
||||
limit: pb.max_range,
|
||||
},
|
||||
RangeError::Empty => BindError::Unsupported(
|
||||
Unsupported::not_representable(Feature::BufferRange),
|
||||
),
|
||||
},
|
||||
)?;
|
||||
let Some(written) =
|
||||
(out.descriptor_ranges.get_mut(place)).filter(|r| (r.set, r.binding) == key)
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
written.range = range;
|
||||
residual = slot_residual;
|
||||
}
|
||||
let (offsets, bases) = (entry.offsets, entry.bases);
|
||||
for &field in &rebinds.words[offsets.0..offsets.1] {
|
||||
if !put_word(out, field, residual.to_le_bytes())? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
for &field in &rebinds.words[bases.0..bases.1] {
|
||||
if !put_word(out, field, base.to_le_bytes())? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
for &(field, word) in &rebinds.loose {
|
||||
let written = match word {
|
||||
LooseWord::Offset => put_word(out, field, 0u32.to_le_bytes())?,
|
||||
LooseWord::Base(slot) => put_word(
|
||||
out,
|
||||
field,
|
||||
slot_guest_base(state, slot, t.resources.biased_slot_words),
|
||||
)?,
|
||||
LooseWord::Stride(layout) => {
|
||||
let stride = pulled_stride(t, state, layout)?;
|
||||
let Some(write) = out.push_constants.get_mut(field.push) else {
|
||||
return Ok(false);
|
||||
};
|
||||
put(
|
||||
&mut write.bytes,
|
||||
field.push_start,
|
||||
&mut [],
|
||||
field.loc,
|
||||
&stride,
|
||||
)?;
|
||||
true
|
||||
}
|
||||
};
|
||||
if !written {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
// Each changed fixed-function vertex buffer's offset, at its binding's place.
|
||||
let vertex = state.stages.get(&Stage::Vertex);
|
||||
for &place in &rebinds.vertex {
|
||||
let vb = t.vertex_buffers.get(place).ok_or_else(other_plan)?;
|
||||
let offset = match vertex.and_then(|v| v.buffers.get(&vb.slot.index)) {
|
||||
Some(&BoundBuffer::Buffer { offset, .. }) => offset,
|
||||
Some(&BoundBuffer::Bytes { .. }) => 0,
|
||||
None => return Err(BindError::UnboundVertexBuffer { slot: vb.slot }),
|
||||
};
|
||||
if !fetchable(vb, &t.vertex_strides, offset_alignment(offset, 0), None) {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(written) = out
|
||||
.buffer_offsets
|
||||
.get_mut(place)
|
||||
.filter(|(binding, _)| *binding == vb.binding)
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
written.1 = offset;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// [`BindingPlan::redraw_apart_into`] of a render plan's template `t`.
|
||||
fn redraw_with(
|
||||
t: &GraphicsTemplate,
|
||||
state: &BindState,
|
||||
(from, draw): (&DrawCall, &DrawCall),
|
||||
out: &mut DrawCommands,
|
||||
) -> Result<bool, BindError> {
|
||||
// What the arguments decide some other way: a stage's argument or root table, a mesh or
|
||||
// patch draw's own reads, a de-indexed draw's layout and indices.
|
||||
let other_reads = t
|
||||
.stages
|
||||
.iter()
|
||||
.any(|st| st.root_first.is_some() || st.table.is_some())
|
||||
|| t.mesh.is_some()
|
||||
|| t.tessellation.is_some()
|
||||
|| t.deindexed.is_some();
|
||||
// Direct draws with or without indices, of any index type and buffer: the arguments decide
|
||||
// their Vulkan draw, overrun and index use, written below. A draw with indices and one without
|
||||
// differ too in the vertices per primitive a vertex function divides by, which a plan that
|
||||
// reads them takes from the draw (`vertices_per_primitive`).
|
||||
let direct = |draw: &DrawCall| match draw {
|
||||
DrawCall::Primitives { .. } => Some(false),
|
||||
DrawCall::Indexed { .. } => Some(true),
|
||||
_ => None,
|
||||
};
|
||||
let per_primitive = || {
|
||||
(t.stages.iter().flat_map(|st| &st.fields))
|
||||
.any(|f| f.field == PushField::VerticesPerPrimitive)
|
||||
};
|
||||
let pair = match (direct(from), direct(draw)) {
|
||||
(Some(from), Some(draw)) => from == draw || !per_primitive(),
|
||||
_ => false,
|
||||
};
|
||||
if other_reads || !pair {
|
||||
return Ok(false);
|
||||
}
|
||||
// Each fixed-function vertex buffer's fetch window, which its slot's extent holds: the two
|
||||
// draws' the same, so the extents are. Inline bytes take no window.
|
||||
let vertex = state.stages.get(&Stage::Vertex);
|
||||
for vb in &t.vertex_buffers {
|
||||
let stride = match (
|
||||
vb.stride,
|
||||
vertex.and_then(|v| v.buffers.get(&vb.slot.index)),
|
||||
) {
|
||||
(VertexStride::Static(s), Some(BoundBuffer::Buffer { .. })) => s,
|
||||
(
|
||||
VertexStride::PerBind,
|
||||
Some(&BoundBuffer::Buffer {
|
||||
attribute_stride, ..
|
||||
}),
|
||||
) => attribute_stride.unwrap_or(0),
|
||||
(_, Some(BoundBuffer::Bytes { .. })) => continue,
|
||||
(_, None) => return Err(BindError::UnboundVertexBuffer { slot: vb.slot }),
|
||||
};
|
||||
if fetch_window(vb, stride, from) != fetch_window(vb, stride, draw) {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
multiview_instances(t.multiview_instance_limit, draw)?;
|
||||
let overrun = index_overrun(t.robust_index_fetch, draw);
|
||||
let (command, base) = vk_draw(draw, overrun);
|
||||
// The `BaseVertexInstance` fields, each at its place in its stage's push write.
|
||||
let mut pushes = 0;
|
||||
for st in &t.stages {
|
||||
let (push_start, push_size) = st.push_range.unwrap_or((0, 0));
|
||||
let push = (push_size != 0).then(|| {
|
||||
pushes += 1;
|
||||
pushes - 1
|
||||
});
|
||||
for f in (st.fields.iter()).filter(|f| f.field == PushField::BaseVertexInstance) {
|
||||
let Some(write) = push.and_then(|push| out.push_constants.get_mut(push)) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let bytes = FieldBytes::words(base);
|
||||
put(&mut write.bytes, push_start, &mut [], f.loc, &bytes)?;
|
||||
}
|
||||
}
|
||||
out.uses.clear();
|
||||
draw_uses(&mut out.uses, draw, overrun, None);
|
||||
out.draw = command;
|
||||
out.index_overrun = overrun;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The `at`th value of `list`, which holds at least `at`: the one a draw before left there, else
|
||||
/// `made`, pushed.
|
||||
fn reused<T>(list: &mut Vec<T>, at: usize, made: impl FnOnce() -> T) -> &mut T {
|
||||
|
||||
@@ -20,22 +20,13 @@ fn instantiate(
|
||||
draw: &DrawCall,
|
||||
) -> Result<DrawCommands, BindError> {
|
||||
let mut fresh = DrawCommands::default();
|
||||
let made = super::instantiate(t, state, draw, &mut fresh, Heap::Written).map(|()| fresh);
|
||||
let made = super::instantiate(t, state, draw, &mut fresh).map(|()| fresh);
|
||||
KEPT.with(|kept| {
|
||||
let mut kept = kept.borrow_mut();
|
||||
let over =
|
||||
super::instantiate(t, state, draw, &mut kept, Heap::Written).map(|()| kept.clone());
|
||||
super::instantiate(t, state, draw, &mut kept).map(|()| kept.clone());
|
||||
assert_eq!(over, made, "the commands written over those before");
|
||||
});
|
||||
// Apart from the heap tables (`BindingPlan::instantiate_draw_apart_into`), the same commands
|
||||
// but for those, which follow the stage tables.
|
||||
if let Ok(made) = &made {
|
||||
let mut apart = DrawCommands::default();
|
||||
super::instantiate(t, state, draw, &mut apart, Heap::Apart).expect("the commands apart");
|
||||
let heap = crate::bind::heap::table_bytes(&t.resources, state).expect("the heap tables");
|
||||
apart.descriptor_bytes.extend(heap);
|
||||
assert_eq!(&apart, made, "the commands apart from their heap tables");
|
||||
}
|
||||
made
|
||||
}
|
||||
|
||||
@@ -905,198 +896,6 @@ fn draws_bind_vertex_buffers_at_aligned_offsets_with_their_windows() {
|
||||
assert!(instantiate(&t, &state((64, 6), 12), &draw).is_ok());
|
||||
}
|
||||
|
||||
/// The commands of `draw` that [`redraw_with`] writes over the commands of `from` (each
|
||||
/// [`super::instantiate`]'s apart from the heap tables): `None` where it answers `Ok(false)`,
|
||||
/// else the commands, which must be `draw`'s own (and an error the one `draw`'s answers).
|
||||
fn redrawn(
|
||||
t: &GraphicsTemplate,
|
||||
state: &BindState,
|
||||
(from, draw): (&DrawCall, &DrawCall),
|
||||
) -> Result<Option<DrawCommands>, BindError> {
|
||||
let mut commands = DrawCommands::default();
|
||||
super::instantiate(t, state, from, &mut commands, Heap::Apart).expect("the first draw");
|
||||
let own = || {
|
||||
let mut own = DrawCommands::default();
|
||||
super::instantiate(t, state, draw, &mut own, Heap::Apart).map(|()| own)
|
||||
};
|
||||
match redraw_with(t, state, (from, draw), &mut commands) {
|
||||
Ok(true) => {
|
||||
let own = own().expect("the draw's own commands");
|
||||
assert_eq!(commands, own, "{draw:?} redrawn over {from:?}");
|
||||
Ok(Some(commands))
|
||||
}
|
||||
Ok(false) => Ok(None),
|
||||
Err(error) => {
|
||||
assert_eq!(own().err(), Some(error.clone()), "{draw:?}'s error");
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A draw that differs from the one before only in its arguments, redrawn over that one's
|
||||
/// commands, writes the commands every step writes for it: its Vulkan draw, its overrun, its
|
||||
/// `BaseVertexInstance` field and its index buffer's use; and none where a fixed-function vertex
|
||||
/// buffer's fetch window moves with them (a draw's vertices, a per-instance buffer's instances),
|
||||
/// where the plan reads them some other way (a de-indexed draw, a vertices-per-primitive field of
|
||||
/// a draw with indices and one without). Another index type or buffer, or indices read or not, is
|
||||
/// redrawn. Past a multiview plan's instance limit it answers every step's error.
|
||||
#[test]
|
||||
fn draws_of_other_arguments_redraw_what_every_step_writes() {
|
||||
use crate::pipeline::interface::PlacedField;
|
||||
let template = |vertex_buffers| GraphicsTemplate {
|
||||
buffers: Vec::new(),
|
||||
stages: vec![StageTemplate {
|
||||
stage: Stage::Vertex,
|
||||
flags: vk::ShaderStageFlags::VERTEX,
|
||||
fields: vec![PlacedField {
|
||||
field: PushField::BaseVertexInstance,
|
||||
loc: PushLoc::Push { offset: 8 },
|
||||
size: 8,
|
||||
}],
|
||||
push_range: Some((0, 16)),
|
||||
table: None,
|
||||
table_size: 0,
|
||||
root_first: None,
|
||||
}],
|
||||
vertex_buffers,
|
||||
pulled_strides: Vec::new(),
|
||||
resources: ResourceTemplate::default(),
|
||||
vertex_strides: rules(None, true),
|
||||
multiview_instance_limit: None,
|
||||
other_layer_variant: false,
|
||||
amplifications: Vec::new(),
|
||||
tessellation: None,
|
||||
indirect_first_instance_missing: false,
|
||||
robust_index_fetch: true,
|
||||
shadow_stencil: None,
|
||||
mesh: None,
|
||||
shader_tests: None,
|
||||
deindexed: None,
|
||||
private_list: false,
|
||||
storage_kept: 0,
|
||||
line_band: None,
|
||||
region_probe: None,
|
||||
};
|
||||
let state = {
|
||||
let buffer = |attribute_stride| BoundBuffer::Buffer {
|
||||
length: 4096,
|
||||
offset: 64,
|
||||
gpu_address: 0x1_0000,
|
||||
device_address: None,
|
||||
attribute_stride,
|
||||
};
|
||||
let mut t = StageTable::default();
|
||||
t.buffers.insert(1, buffer(None));
|
||||
t.buffers.insert(2, buffer(Some(8)));
|
||||
let mut s = BindState::default();
|
||||
s.stages.insert(Stage::Vertex, t);
|
||||
s
|
||||
};
|
||||
let indexed =
|
||||
|index_count, index_offset, base_vertex, instances: (u32, u32)| DrawCall::Indexed {
|
||||
index_type: vk::IndexType::UINT16,
|
||||
index_buffer: IndexBufferRef::new(7, 4096),
|
||||
index_count,
|
||||
index_offset,
|
||||
instance_count: instances.1,
|
||||
base_vertex,
|
||||
base_instance: instances.0,
|
||||
};
|
||||
let t = template(vertex_buffers());
|
||||
let first = indexed(6, 64, 5, (1, 5));
|
||||
// Another first index, count and base vertex: the per-vertex buffer's window is the whole
|
||||
// buffer for both, the per-instance one's the same instances'.
|
||||
for draw in [
|
||||
indexed(6, 128, 5, (1, 5)),
|
||||
indexed(9, 0, -3, (1, 5)),
|
||||
// Indices past the buffer's end, which the robust fetch draws.
|
||||
indexed(12, 4090, 5, (1, 5)),
|
||||
] {
|
||||
let commands = redrawn(&t, &state, (&first, &draw)).expect("redrawn");
|
||||
assert!(commands.is_some(), "{draw:?} redrawn");
|
||||
}
|
||||
let base = redrawn(&t, &state, (&first, &indexed(6, 128, 9, (1, 5))))
|
||||
.expect("redrawn")
|
||||
.expect("redrawn at another base vertex");
|
||||
assert_eq!(base.push_constants[0].bytes[8..12], 9u32.to_le_bytes());
|
||||
// Other instances move the per-instance buffer's window, and so do vertices without indices
|
||||
// after indices, whose per-vertex window is the whole buffer; another index type or index
|
||||
// buffer is redrawn.
|
||||
let moved = indexed(6, 64, 5, (2, 5));
|
||||
assert_eq!(redrawn(&t, &state, (&first, &moved)), Ok(None));
|
||||
let wide = DrawCall::Indexed {
|
||||
index_type: vk::IndexType::UINT32,
|
||||
index_buffer: IndexBufferRef::new(7, 4096),
|
||||
index_count: 6,
|
||||
index_offset: 64,
|
||||
instance_count: 5,
|
||||
base_vertex: 5,
|
||||
base_instance: 1,
|
||||
};
|
||||
let other_buffer = DrawCall::Indexed {
|
||||
index_type: vk::IndexType::UINT16,
|
||||
index_buffer: IndexBufferRef::new(8, 4096),
|
||||
index_count: 6,
|
||||
index_offset: 64,
|
||||
instance_count: 5,
|
||||
base_vertex: 5,
|
||||
base_instance: 1,
|
||||
};
|
||||
for draw in [wide, other_buffer] {
|
||||
let commands = redrawn(&t, &state, (&first, &draw)).expect("redrawn");
|
||||
assert!(commands.is_some(), "{draw:?} redrawn");
|
||||
}
|
||||
let unindexed = primitives(0, 6, (1, 5));
|
||||
assert_eq!(redrawn(&t, &state, (&first, &unindexed)), Ok(None));
|
||||
// With no fixed-function vertex buffer, a draw without indices after one with them, and the
|
||||
// other way, is redrawn, its index use gone or made; but not where a vertex function divides
|
||||
// by the vertices per primitive, which a draw with indices and one without set apart.
|
||||
let pulled = template(Vec::new());
|
||||
for (from, draw) in [(&first, &unindexed), (&unindexed, &first)] {
|
||||
let commands = redrawn(&pulled, &state, (from, draw)).expect("redrawn");
|
||||
let uses = commands.map(|commands| commands.uses.len());
|
||||
assert_eq!(uses, Some(usize::from(draw == &first)), "{draw:?} redrawn");
|
||||
}
|
||||
let mut per_primitive = template(Vec::new());
|
||||
per_primitive.stages[0].fields.push(PlacedField {
|
||||
field: PushField::VerticesPerPrimitive,
|
||||
loc: PushLoc::Push { offset: 0 },
|
||||
size: 4,
|
||||
});
|
||||
let mut triangles = state.clone();
|
||||
triangles.primitive_type = Some(metal::PrimitiveType::Triangle);
|
||||
let kinds = (&unindexed, &first);
|
||||
assert_eq!(redrawn(&per_primitive, &triangles, kinds), Ok(None));
|
||||
let more = (&unindexed, &primitives(3, 6, (1, 5)));
|
||||
let commands = redrawn(&per_primitive, &triangles, more).expect("redrawn");
|
||||
assert!(commands.is_some(), "more vertices redrawn");
|
||||
// Draws without indices of other vertices move the per-vertex buffer's window; with no
|
||||
// fixed-function vertex buffer, every argument is the commands' alone.
|
||||
let vertices = primitives(2, 3, (1, 5));
|
||||
assert_eq!(
|
||||
redrawn(&t, &state, (&vertices, &primitives(4, 3, (1, 5)))),
|
||||
Ok(None)
|
||||
);
|
||||
let pulled = template(Vec::new());
|
||||
for draw in [primitives(4, 3, (1, 5)), primitives(0, 30, (3, 2))] {
|
||||
let commands = redrawn(&pulled, &state, (&vertices, &draw)).expect("redrawn");
|
||||
assert!(commands.is_some(), "{draw:?} redrawn");
|
||||
}
|
||||
// A de-indexed draw reads its indices and layout itself.
|
||||
let mut deindexed = template(Vec::new());
|
||||
deindexed.deindexed = Some(metal::IndexType::UInt16);
|
||||
let mut primitive = state.clone();
|
||||
primitive.primitive_type = Some(metal::PrimitiveType::Triangle);
|
||||
let indices = (&first, &indexed(6, 128, 5, (1, 5)));
|
||||
assert_eq!(redrawn(&deindexed, &primitive, indices), Ok(None));
|
||||
// Instances past a multiview plan's limit: every step's error.
|
||||
let mut multiview = template(Vec::new());
|
||||
multiview.multiview_instance_limit = Some(4);
|
||||
let past = primitives(2, 3, (1, 5));
|
||||
let redrawn_past = redrawn(&multiview, &state, (&primitives(2, 3, (0, 1)), &past));
|
||||
assert!(redrawn_past.is_err(), "{redrawn_past:?}");
|
||||
}
|
||||
|
||||
/// Inline vertex bytes at a per-bind layout read at their bind's stride, 0 without one, as plain
|
||||
/// Metal reads them (`setVertexBytes:length:atIndex:` read vertex 0 for every
|
||||
/// vertex, the stride form at 0, 4 and 8 its stride); and a stride fixed function cannot fetch is
|
||||
|
||||
@@ -230,7 +230,7 @@ pub use extended_canonical::{
|
||||
pub use extended_shadow::{extended_shadow_module, ExtendedShadowModule};
|
||||
pub use graphics::{
|
||||
alpha_test_code, DrawCall, DrawCommands, IndexOverrun, MeshDispatch, MeshGroups,
|
||||
MeshRecordsRegion, SlotRebinds, TessellationDispatch, TessellationRecords,
|
||||
MeshRecordsRegion, TessellationDispatch, TessellationRecords,
|
||||
};
|
||||
pub use heap::{
|
||||
handle_entry, handle_entry_flags, heap_classes, heap_element, heap_raw_form, HeapElement,
|
||||
@@ -302,11 +302,11 @@ pub use replay::{
|
||||
pub use state::{
|
||||
ArgumentFunctionTable, ArgumentSampler, ArgumentSamplersShape, BindShape, BindState,
|
||||
BoundAccelerationStructure, BoundBuffer, BoundSampler, BoundSamplerShape, BoundTexture,
|
||||
BufferRanges, BufferShape, CompensatedViewport, FragmentTests, FunctionTablesShape,
|
||||
HeapPlacement, ImageblockSize, ResourceClass, SamplerDescriptor, SamplerShape, StageInRegion,
|
||||
StageShape, StageTable, TessellationFactorBuffer, TessellationFactors, TextureFacts,
|
||||
TextureShape, TileThreadgroupArgument, TileThreadgroupMemory, UsedClass, UsedResource,
|
||||
UsedShape, VertexAmplification, ViewMapping, ZERO_OFFSET_CLASS, ZERO_OFFSET_TOLD,
|
||||
BufferRanges, BufferShape, FragmentTests, FunctionTablesShape, HeapPlacement, ImageblockSize,
|
||||
ResourceClass, SamplerDescriptor, SamplerShape, StageInRegion, StageShape, StageTable,
|
||||
TessellationFactorBuffer, TessellationFactors, TextureFacts, TextureShape,
|
||||
TileThreadgroupArgument, TileThreadgroupMemory, UsedClass, UsedResource, UsedShape,
|
||||
VertexAmplification, ViewMapping, ZERO_OFFSET_CLASS, ZERO_OFFSET_TOLD,
|
||||
};
|
||||
// How `BindState::shape` classes a buffer: the crate reads it from `state`, and a consumer takes
|
||||
// shapes from `BindState::shape`; only the crate's tests and validation reach it here.
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
//! texel buffers), except typed storage images, which must use exactly their declared format and
|
||||
//! are listed only where the profile's format table supports it.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::device::profile::DeviceProfile;
|
||||
use crate::device::requirements::FormatUsage;
|
||||
@@ -251,52 +250,6 @@ pub fn image_classes(profile: &DeviceProfile) -> Vec<ImageHandleClass> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The image classes a texture slot of Metal's `ulong` texel can declare on `profile` (never a heap
|
||||
/// class): 1D, 1D array, 2D, 2D array, 3D, and buffer, sampled, or storage of the `RG32` unsigned
|
||||
/// format Metal binds (declared, or formatless as a binder's class names it), and storage
|
||||
/// `R64_UINT`, the view of a slot a `ulong` atomic updates, where the profile has what such a slot
|
||||
/// needs (`DeviceProfile::ulong_atomic_gaps`).
|
||||
pub fn ulong_classes(profile: &DeviceProfile) -> Vec<ImageHandleClass> {
|
||||
let shapes = [
|
||||
(ImageDim::D1, false),
|
||||
(ImageDim::D1, true),
|
||||
(ImageDim::D2, false),
|
||||
(ImageDim::D2, true),
|
||||
(ImageDim::D3, false),
|
||||
(ImageDim::Buffer, false),
|
||||
];
|
||||
let mut out = Vec::new();
|
||||
for (dim, arrayed) in shapes {
|
||||
let atomic = profile
|
||||
.ulong_atomic_gaps(dim == ImageDim::Buffer)
|
||||
.is_empty()
|
||||
.then_some((
|
||||
ImageAccess::Storage,
|
||||
StorageFormatClass::Format(vk::Format::R64_UINT),
|
||||
));
|
||||
let classes = [
|
||||
(ImageAccess::Sampled, StorageFormatClass::NotStorage),
|
||||
(ImageAccess::Storage, StorageFormatClass::Unknown),
|
||||
(
|
||||
ImageAccess::Storage,
|
||||
StorageFormatClass::Format(vk::Format::R32G32_UINT),
|
||||
),
|
||||
];
|
||||
for (access, format) in classes.into_iter().chain(atomic) {
|
||||
out.push(ImageHandleClass {
|
||||
dim,
|
||||
arrayed,
|
||||
multisampled: false,
|
||||
sampled_type: SampledType::Uint64,
|
||||
depth_compare: false,
|
||||
access,
|
||||
format,
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Device {}
|
||||
|
||||
/// Bytes of the `ZeroBuffer` neutral on `profile`: large enough for any uniform-buffer view
|
||||
|
||||
@@ -1,31 +1,12 @@
|
||||
//! The neutral resources: a `ulong` atomic's neutral is listed exactly where its slot compiles,
|
||||
//! the zero buffer covers any uniform view, an undeclarable type has none, and their formats follow
|
||||
//! the declared type and the registry's numeric formats.
|
||||
//! The neutral resources: the zero buffer covers any uniform view, an undeclarable type has none,
|
||||
//! and their formats follow the declared type and the registry's numeric formats.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::*;
|
||||
use crate::device::{DeviceDescription, DevicePolicy};
|
||||
use crate::spirv::testing::is_moltenvk_capture;
|
||||
|
||||
/// Formats whose use here is guaranteed by Vulkan's mandatory format support.
|
||||
const MANDATORY: &[(vk::Format, FormatUsage)] = &[
|
||||
(vk::Format::R8G8B8A8_UNORM, FormatUsage::SampledImage),
|
||||
(vk::Format::R8G8B8A8_SINT, FormatUsage::SampledImage),
|
||||
(vk::Format::R8G8B8A8_UINT, FormatUsage::SampledImage),
|
||||
(vk::Format::D16_UNORM, FormatUsage::SampledImage),
|
||||
(vk::Format::R32_SFLOAT, FormatUsage::StorageImage),
|
||||
(vk::Format::R32_SINT, FormatUsage::StorageImage),
|
||||
(vk::Format::R32_UINT, FormatUsage::StorageImage),
|
||||
(vk::Format::R32_SFLOAT, FormatUsage::UniformTexelBuffer),
|
||||
(vk::Format::R32_SINT, FormatUsage::UniformTexelBuffer),
|
||||
(vk::Format::R32_UINT, FormatUsage::UniformTexelBuffer),
|
||||
(vk::Format::R32_SFLOAT, FormatUsage::StorageTexelBuffer),
|
||||
(vk::Format::R32_SINT, FormatUsage::StorageTexelBuffer),
|
||||
(vk::Format::R32_UINT, FormatUsage::StorageTexelBuffer),
|
||||
];
|
||||
|
||||
/// A device for every committed profile (`validation/profiles/`, read-only), sorted by stem.
|
||||
fn committed_devices() -> Vec<(String, Device)> {
|
||||
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles");
|
||||
@@ -47,145 +28,6 @@ fn committed_devices() -> Vec<(String, Device)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `profile` supports `usage` on `format`: its format table decides when it lists the
|
||||
/// format; otherwise only Vulkan's mandatory support counts.
|
||||
fn supported(profile: &DeviceProfile, format: vk::Format, usage: FormatUsage) -> bool {
|
||||
let f = profile.fields();
|
||||
let table = match usage {
|
||||
FormatUsage::StorageImage | FormatUsage::StorageTexelBuffer => &f.storage_formats,
|
||||
_ => &f.image_formats,
|
||||
};
|
||||
match table.formats.get(&format) {
|
||||
Some(usages) => usages.contains(&usage),
|
||||
None => MANDATORY.contains(&(format, usage)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The view type an image of `dim`/`arrayed` must be viewed as (VUID-vkCmdDraw-viewType-07752).
|
||||
fn view_type_for(dim: ImageDim, arrayed: bool) -> vk::ImageViewType {
|
||||
match (dim, arrayed) {
|
||||
(ImageDim::D1, false) => vk::ImageViewType::TYPE_1D,
|
||||
(ImageDim::D1, true) => vk::ImageViewType::TYPE_1D_ARRAY,
|
||||
(ImageDim::D2, false) => vk::ImageViewType::TYPE_2D,
|
||||
(ImageDim::D2, true) => vk::ImageViewType::TYPE_2D_ARRAY,
|
||||
(ImageDim::D3, false) => vk::ImageViewType::TYPE_3D,
|
||||
(ImageDim::Cube, false) => vk::ImageViewType::CUBE,
|
||||
(ImageDim::Cube, true) => vk::ImageViewType::CUBE_ARRAY,
|
||||
other => panic!("no view type for {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks the Vulkan compatibility rules between a declared image type and its neutral.
|
||||
fn assert_compatible(stem: &str, class: &ImageHandleClass, n: &NeutralResource, p: &DeviceProfile) {
|
||||
let ctx = format!("{stem}: {class:?} -> {n:?}");
|
||||
let format = n.format().unwrap_or_else(|| panic!("{ctx}: no format"));
|
||||
// The view format's numeric type matches the declared sampled type
|
||||
// (VUID-vkCmdDraw-format-07753); a `ulong` slot's image is `RG32` unsigned.
|
||||
assert!(serves(format, class.sampled_type), "{ctx}");
|
||||
assert_eq!(
|
||||
numeric_type(format),
|
||||
Some(match class.sampled_type {
|
||||
SampledType::Uint64 => SampledType::Uint,
|
||||
other => other,
|
||||
}),
|
||||
"{ctx}"
|
||||
);
|
||||
let storage = class.access == ImageAccess::Storage;
|
||||
// A typed storage image is viewed with exactly its declared format
|
||||
// (VUID-vkCmdDraw-OpTypeImage-07027/07028); formatless ones need a storage-capable format.
|
||||
if let StorageFormatClass::Format(declared) = class.format {
|
||||
assert_eq!(format, declared, "{ctx}");
|
||||
}
|
||||
match *n {
|
||||
NeutralResource::TexelBuffer { .. } => {
|
||||
assert_eq!(class.dim, ImageDim::Buffer, "{ctx}");
|
||||
let usage = if storage {
|
||||
FormatUsage::StorageTexelBuffer
|
||||
} else {
|
||||
FormatUsage::UniformTexelBuffer
|
||||
};
|
||||
assert!(supported(p, format, usage), "{ctx}: {usage:?}");
|
||||
}
|
||||
NeutralResource::Image {
|
||||
view_type,
|
||||
depth_compare,
|
||||
samples,
|
||||
storage_format,
|
||||
..
|
||||
} => {
|
||||
assert_ne!(class.dim, ImageDim::Buffer, "{ctx}");
|
||||
assert_eq!(view_type, view_type_for(class.dim, class.arrayed), "{ctx}");
|
||||
// MS=1 needs a multisampled view and MS=0 a single-sampled one
|
||||
// (VUID-vkCmdDraw-MS-07288 and friends).
|
||||
assert_eq!(samples > 1, class.multisampled, "{ctx}");
|
||||
assert_eq!(storage_format.is_some(), storage, "{ctx}");
|
||||
assert_eq!(depth_compare, class.depth_compare, "{ctx}");
|
||||
if depth_compare {
|
||||
assert_eq!(format, vk::Format::D16_UNORM, "{ctx}: depth format");
|
||||
// Depth formats are guaranteed (and Metal depth textures exist) only for 2D and
|
||||
// cube images, so a depth neutral of another shape could fail image creation.
|
||||
assert!(
|
||||
matches!(
|
||||
view_type,
|
||||
vk::ImageViewType::TYPE_2D
|
||||
| vk::ImageViewType::TYPE_2D_ARRAY
|
||||
| vk::ImageViewType::CUBE
|
||||
| vk::ImageViewType::CUBE_ARRAY
|
||||
),
|
||||
"{ctx}: depth view type"
|
||||
);
|
||||
}
|
||||
if view_type == vk::ImageViewType::CUBE_ARRAY {
|
||||
assert!(p.fields().images.cube_array, "{ctx}: imageCubeArray");
|
||||
}
|
||||
if storage && samples > 1 {
|
||||
assert!(p.fields().images.storage_multisample, "{ctx}");
|
||||
}
|
||||
let usage = if storage {
|
||||
FormatUsage::StorageImage
|
||||
} else {
|
||||
FormatUsage::SampledImage
|
||||
};
|
||||
assert!(supported(p, format, usage), "{ctx}: {usage:?}");
|
||||
}
|
||||
_ => panic!("{ctx}: not an image or texel buffer"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A `ulong` slot that a `ulong` atomic updates is declared `R64ui`: its `R64_UINT` neutral is
|
||||
/// listed exactly where the profile has what that slot needs, image and texel buffer apart, and
|
||||
/// never on MoltenVK, which has no 64-bit image atomics.
|
||||
#[test]
|
||||
fn a_ulong_atomic_neutral_is_listed_exactly_where_its_slot_compiles() {
|
||||
let r64 = |c: &ImageHandleClass| {
|
||||
c.sampled_type == SampledType::Uint64
|
||||
&& c.format == StorageFormatClass::Format(vk::Format::R64_UINT)
|
||||
};
|
||||
let mut listed = 0;
|
||||
for (stem, device) in committed_devices() {
|
||||
let profile = device.profile();
|
||||
for buffer in [false, true] {
|
||||
let compiles = profile.ulong_atomic_gaps(buffer).is_empty();
|
||||
let n = ulong_classes(profile)
|
||||
.iter()
|
||||
.filter(|c| r64(c) && (c.dim == ImageDim::Buffer) == buffer)
|
||||
.count();
|
||||
// Five image shapes (1D, 1D array, 2D, 2D array, 3D), or the texture buffer.
|
||||
let shapes = if buffer { 1 } else { 5 };
|
||||
assert_eq!(
|
||||
n,
|
||||
if compiles { shapes } else { 0 },
|
||||
"{stem}: buffer {buffer}"
|
||||
);
|
||||
listed += n;
|
||||
}
|
||||
if is_moltenvk_capture(&stem) {
|
||||
assert!(!ulong_classes(profile).iter().any(r64), "{stem}");
|
||||
}
|
||||
}
|
||||
assert!(listed > 0, "no committed profile lists an R64_UINT neutral");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_buffer_covers_any_uniform_view_and_is_padded() {
|
||||
for (stem, device) in committed_devices() {
|
||||
|
||||
@@ -825,13 +825,6 @@ fn unmeasured_descriptors_are_refused() {
|
||||
.contains("3 layers"));
|
||||
}
|
||||
|
||||
/// FNV-1a, 64 bits, of `bytes`: a short name for Metal's measured parameter data.
|
||||
fn fnv(bytes: &[u8]) -> u64 {
|
||||
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, &byte| {
|
||||
(hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
|
||||
})
|
||||
}
|
||||
|
||||
/// An axis of no screen pixels has one tile of no screen and no physical pixels, whatever its
|
||||
/// quality samples, so the layer's physical extent on it is 0 and the map compiles (Metal's API
|
||||
/// validation stops the descriptor; plain Metal compiles it, and `apple_tests` holds its bytes).
|
||||
|
||||
@@ -96,64 +96,6 @@ fn coalesce(out: &mut Vec<RootEntry>, mut e: RootEntry) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// [`resident_set`] of the allocations of `parts` in their order, each part `(sorted, set)`: its
|
||||
/// allocations as [`sorted`] gives them and their resident set. Where no part's allocations sort
|
||||
/// before another's ahead of it, the parts' sets are joined as they are, each coalesced with the
|
||||
/// ones before it only at its head: an entry of a part's set that goes in whole leaves the rest of
|
||||
/// that set whole too, as the set is sorted and disjoint. Parts whose allocations interleave are
|
||||
/// sorted and coalesced together again, as one.
|
||||
pub(crate) fn joined<'a>(
|
||||
parts: impl IntoIterator<Item = (&'a [RootEntry], &'a [RootEntry])>,
|
||||
) -> Vec<RootEntry> {
|
||||
let parts: Vec<(&[RootEntry], &[RootEntry])> = parts
|
||||
.into_iter()
|
||||
.filter(|(sorted, _)| !sorted.is_empty())
|
||||
.collect();
|
||||
// Runs of parts, each `(first, end, greatest)`: its parts, and its greatest allocation in
|
||||
// `order`, at or below every allocation of the runs after it.
|
||||
let mut runs: Vec<(usize, usize, RootEntry)> = Vec::with_capacity(parts.len());
|
||||
for (at, (sorted, _)) in parts.iter().enumerate() {
|
||||
let (Some(&least), Some(&greatest)) = (sorted.first(), sorted.last()) else {
|
||||
continue;
|
||||
};
|
||||
let mut run = (at, at + 1, greatest);
|
||||
while let Some(&(first, _, before)) = runs.last() {
|
||||
if order(&before, &least) != Ordering::Greater {
|
||||
break;
|
||||
}
|
||||
runs.pop();
|
||||
run.0 = first;
|
||||
if order(&before, &run.2) == Ordering::Greater {
|
||||
run.2 = before;
|
||||
}
|
||||
}
|
||||
runs.push(run);
|
||||
}
|
||||
let len = parts.iter().map(|(_, set)| set.len()).sum();
|
||||
let mut out: Vec<RootEntry> = Vec::with_capacity(len);
|
||||
for (first, end, _) in runs {
|
||||
let merged;
|
||||
let set = match end - first {
|
||||
1 => parts[first].1,
|
||||
_ => {
|
||||
let all = parts[first..end]
|
||||
.iter()
|
||||
.flat_map(|(sorted, _)| sorted.iter());
|
||||
let mut together: Vec<RootEntry> = all.copied().collect();
|
||||
together.sort_by(order);
|
||||
merged = coalesced_of_sorted(&together);
|
||||
&merged[..]
|
||||
}
|
||||
};
|
||||
let whole = set
|
||||
.iter()
|
||||
.position(|&e| coalesce(&mut out, e))
|
||||
.map_or(set.len(), |at| at + 1);
|
||||
out.extend_from_slice(&set[whole..]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The coalesced resident set of `state`: every bound buffer with a device address (every stage)
|
||||
/// and every `Buffer`/`Heap` used resource with both addresses, at their padded sizes.
|
||||
pub(crate) fn resident_entries(state: &BindState) -> Vec<RootEntry> {
|
||||
|
||||
@@ -460,36 +460,3 @@ fn a_state_resident_apart_keeps_the_used_resources_out_of_its_tables() {
|
||||
assert_eq!(apart.shape(), state.shape());
|
||||
}
|
||||
}
|
||||
|
||||
/// Ranges of every shape a list of buffers holds, in an order a list may take: clustered so that
|
||||
/// nesting, partial overlap, one start shared at different lengths and hosts, empty ones and
|
||||
/// records past `RECORDS_ADDRESS_BASE` all occur; sorted by Metal address where `sorted`, else
|
||||
/// with some starting below the ones before them, as a no-copy buffer's range starts below its
|
||||
/// address.
|
||||
fn list_ranges(rng: &mut Rng, sorted: bool) -> Vec<crate::bind::ResidentRange> {
|
||||
use crate::bind::ResidentRange;
|
||||
let n = rng.below(120) as usize;
|
||||
let mut ranges: Vec<ResidentRange> = (0..n)
|
||||
.map(|_| {
|
||||
let base = match rng.below(8) {
|
||||
0 => RECORDS_ADDRESS_BASE,
|
||||
_ => 0x1_0000,
|
||||
};
|
||||
let guest = base + 8 * rng.below(512);
|
||||
let length = match rng.below(6) {
|
||||
0 => 0,
|
||||
1 => 8 * rng.below(400),
|
||||
_ => 1 + rng.below(96),
|
||||
};
|
||||
let host = match rng.below(3) {
|
||||
0 => rng.next(),
|
||||
_ => guest.wrapping_add(0x40_0000),
|
||||
};
|
||||
ResidentRange::new(host, guest, length)
|
||||
})
|
||||
.collect();
|
||||
if sorted {
|
||||
ranges.sort_by_key(|range| range.guest);
|
||||
}
|
||||
ranges
|
||||
}
|
||||
@@ -5,17 +5,13 @@
|
||||
//! from a table is unbound. [`BindShape`] is the hashable projection that can change a plan;
|
||||
//! offsets, addresses, and lengths only change per-draw bytes ([`BindState::shape`]).
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use crate::bind::ResidentRange;
|
||||
use crate::device::profile::Limits;
|
||||
use crate::metal;
|
||||
use crate::pipeline::artifact::RuntimeDependency;
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::pipeline::lower_inputs::ViewportCompensation;
|
||||
use crate::pipeline::sym::{SlotClass, Stage};
|
||||
use crate::pipeline::sym::Stage;
|
||||
use crate::spirv::ir::intern::FxHasher;
|
||||
|
||||
/// Everything bound for one draw or dispatch.
|
||||
@@ -227,12 +223,6 @@ pub struct BindState {
|
||||
/// outside a render encoder.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub tile_threadgroup: TileThreadgroupMemory,
|
||||
/// The draw's viewport compensation (`PushField::ViewportCompensation`): `None` where the
|
||||
/// draw's viewport is Vulkan's, as it is unless it has a negative width or a depth range past
|
||||
/// `[0, 1]` the device does not take. Its variant is part of the shape
|
||||
/// (`BindShape::viewport_compensation`), its values only of the draw's bytes.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub viewport_compensation: Option<CompensatedViewport>,
|
||||
/// The color attachments of the draw's render pass its render pipeline has no pixel format
|
||||
/// for, the pass's pixel format of each by color index: plain Metal stores zero bytes into
|
||||
/// each at every sample the draw covers (Metal's validation stops the draw). Its variant is
|
||||
@@ -479,102 +469,6 @@ impl FragmentTests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A draw's viewport compensation (`BindState::viewport_compensation`): the variant its pipeline's
|
||||
/// vertex function compiles under, and the `[sx, a, b, clip]` it applies to the position, `(sx x,
|
||||
/// y, a w + b z, w)`, clipping at `z` and `w - z` where `clip` is 1. Under
|
||||
/// `ViewportCompensation::point_guard`, `guard` is the `[gx, gy]` it scales `x` and `y` by
|
||||
/// (`PushField::PointGuard`). Under `ViewportCompensation::mirrors`, `mirrors` has bit `i` set
|
||||
/// where viewport `i` is mirrored (`PushField::ViewportMirrors`). Under
|
||||
/// `ViewportCompensation::vertex_clamp`, `vertex_clamp` is the `[lo, hi]` the function clamps each
|
||||
/// vertex's normalized depth `z / w` to (`PushField::VertexDepthClamp`).
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct CompensatedViewport {
|
||||
pub compensation: ViewportCompensation,
|
||||
pub values: [f32; 4],
|
||||
#[cfg_attr(feature = "serde", serde(default = "unit_guard"))]
|
||||
pub guard: [f32; 2],
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub mirrors: u32,
|
||||
#[cfg_attr(
|
||||
feature = "serde",
|
||||
serde(default = "unclamped", with = "vertex_clamp_bounds")
|
||||
)]
|
||||
pub vertex_clamp: [f32; 2],
|
||||
}
|
||||
|
||||
/// The point guard band's identity, `[1, 1]`.
|
||||
#[cfg(feature = "serde")]
|
||||
fn unit_guard() -> [f32; 2] {
|
||||
[1.0, 1.0]
|
||||
}
|
||||
|
||||
/// The vertex depth clamp's identity, `[-inf, +inf]`: no vertex's depth clamped.
|
||||
const UNCLAMPED: [f32; 2] = [f32::NEG_INFINITY, f32::INFINITY];
|
||||
|
||||
/// [`UNCLAMPED`], serde's default.
|
||||
#[cfg(feature = "serde")]
|
||||
fn unclamped() -> [f32; 2] {
|
||||
UNCLAMPED
|
||||
}
|
||||
|
||||
/// serde of [`CompensatedViewport::vertex_clamp`]: each bound, or none where that side is
|
||||
/// unbounded (`-inf` below, `+inf` above, as clip mode's `[0, +inf]` and [`UNCLAMPED`] are),
|
||||
/// since a format without infinities cannot hold one (`serde_json` writes `null`, which reads back
|
||||
/// as no `f32`).
|
||||
#[cfg(feature = "serde")]
|
||||
mod vertex_clamp_bounds {
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
pub(super) fn serialize<S: Serializer>(
|
||||
bounds: &[f32; 2],
|
||||
serializer: S,
|
||||
) -> Result<S::Ok, S::Error> {
|
||||
let [lo, hi] = *bounds;
|
||||
[
|
||||
(lo != f32::NEG_INFINITY).then_some(lo),
|
||||
(hi != f32::INFINITY).then_some(hi),
|
||||
]
|
||||
.serialize(serializer)
|
||||
}
|
||||
|
||||
pub(super) fn deserialize<'de, D: Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<[f32; 2], D::Error> {
|
||||
let [lo, hi] = <[Option<f32>; 2]>::deserialize(deserializer)?;
|
||||
Ok([lo.unwrap_or(f32::NEG_INFINITY), hi.unwrap_or(f32::INFINITY)])
|
||||
}
|
||||
}
|
||||
|
||||
impl CompensatedViewport {
|
||||
/// The compensation `values` under the variant `compensation`, scaling no point (a `guard`
|
||||
/// of `[1, 1]`).
|
||||
pub fn new(compensation: ViewportCompensation, values: [f32; 4]) -> CompensatedViewport {
|
||||
CompensatedViewport {
|
||||
compensation,
|
||||
values,
|
||||
guard: [1.0, 1.0],
|
||||
mirrors: 0,
|
||||
vertex_clamp: UNCLAMPED,
|
||||
}
|
||||
}
|
||||
|
||||
/// This compensation, bit `i` of `mirrors` set where viewport `i` is mirrored.
|
||||
pub fn with_mirrors(self, mirrors: u32) -> CompensatedViewport {
|
||||
CompensatedViewport { mirrors, ..self }
|
||||
}
|
||||
|
||||
/// This compensation, clamping each vertex's normalized depth `z / w` to `vertex_clamp`'s
|
||||
/// `[lo, hi]` under `ViewportCompensation::vertex_clamp`.
|
||||
pub fn with_vertex_clamp(self, vertex_clamp: [f32; 2]) -> CompensatedViewport {
|
||||
CompensatedViewport {
|
||||
vertex_clamp,
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a command's heap arrays (set 1) hold its heap members and its argument samplers. A plan
|
||||
/// writes member `i` of every image array, and listed argument sampler `i` of every sampler array,
|
||||
/// at its planned element `i + 1` (element 0 is each array's neutral); the command's handle and
|
||||
@@ -751,7 +645,6 @@ impl BindState {
|
||||
argument_samplers: ArgumentSamplersShape::of(&self.argument_samplers),
|
||||
function_tables: FunctionTablesShape::of(&self.function_tables),
|
||||
tile_threadgroup: self.tile_threadgroup.clone(),
|
||||
viewport_compensation: self.viewport_compensation.map(|c| c.compensation),
|
||||
zeroed_colors: self.zeroed_colors.clone(),
|
||||
dropped_colors: self.dropped_colors.clone(),
|
||||
kept_imageblock_bytes: self.kept_imageblock_bytes,
|
||||
@@ -841,7 +734,6 @@ impl BindState {
|
||||
argument_samplers,
|
||||
function_tables,
|
||||
tile_threadgroup,
|
||||
viewport_compensation,
|
||||
zeroed_colors,
|
||||
dropped_colors,
|
||||
kept_imageblock_bytes,
|
||||
@@ -873,7 +765,6 @@ impl BindState {
|
||||
&& argument_samplers.is_of(&self.argument_samplers)
|
||||
&& FunctionTablesShape::of(&self.function_tables) == *function_tables
|
||||
&& self.tile_threadgroup == *tile_threadgroup
|
||||
&& self.viewport_compensation.map(|c| c.compensation) == *viewport_compensation
|
||||
&& self.zeroed_colors == *zeroed_colors
|
||||
&& self.dropped_colors == *dropped_colors
|
||||
&& self.kept_imageblock_bytes == *kept_imageblock_bytes
|
||||
@@ -1859,10 +1750,6 @@ pub struct BindShape {
|
||||
/// specialization.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub tile_threadgroup: TileThreadgroupMemory,
|
||||
/// `BindState.viewport_compensation`'s variant: the vertex function a draw through a viewport
|
||||
/// Vulkan's cannot be runs (`VariantKey::viewport_compensation`).
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub viewport_compensation: Option<ViewportCompensation>,
|
||||
/// `BindState.zeroed_colors`: the variant whose pipeline has those attachments and whose
|
||||
/// fragment function writes zero to them (`VariantKey::zeroed_colors`).
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
@@ -1944,68 +1831,6 @@ pub struct BindShape {
|
||||
|
||||
impl BindShape {}
|
||||
|
||||
/// One stage's slots into a shape key ([`BindShape::key_beside_used`]): the stage, then each
|
||||
/// class's count and its slots' shapes in index order, as a state's table and a shape's give them.
|
||||
fn key_stage(
|
||||
key: &mut FxHasher,
|
||||
stage: Stage,
|
||||
(buffers, textures, samplers): (
|
||||
impl ExactSizeIterator<Item = (u32, BufferShape)>,
|
||||
impl ExactSizeIterator<Item = (u32, TextureShape)>,
|
||||
impl ExactSizeIterator<Item = (u32, BoundSamplerShape)>,
|
||||
),
|
||||
) {
|
||||
stage.hash(key);
|
||||
key.write_usize(buffers.len());
|
||||
buffers.for_each(|slot| slot.hash(key));
|
||||
key.write_usize(textures.len());
|
||||
textures.for_each(|slot| slot.hash(key));
|
||||
key.write_usize(samplers.len());
|
||||
samplers.for_each(|slot| slot.hash(key));
|
||||
}
|
||||
|
||||
/// An argument sampler shape's part of a shape key: the samplers' parts are or-ed, so the
|
||||
/// shape's set of them and a state's list, which may repeat one, have one key
|
||||
/// ([`BindShape::key_beside_used`]).
|
||||
fn sampler_key(shape: &SamplerShape) -> u64 {
|
||||
let mut key = FxHasher::default();
|
||||
shape.hash(&mut key);
|
||||
key.finish()
|
||||
}
|
||||
|
||||
/// The fields of a shape beside its stages that its key holds, of the types the shape holds them
|
||||
/// in (the argument samplers as their class and their shapes' or-ed parts), so a state's key and
|
||||
/// a shape's hash them alike ([`BindShape::key_beside_used`]).
|
||||
#[derive(Hash)]
|
||||
struct KeyRest<'a> {
|
||||
vertex_amplification: &'a VertexAmplification,
|
||||
imageblock_size: ImageblockSize,
|
||||
render_target_array_length: u32,
|
||||
tessellation_factor_buffer: bool,
|
||||
render_area: [u32; 2],
|
||||
argument_samplers: (u8, u64),
|
||||
function_tables: FunctionTablesShape,
|
||||
tile_threadgroup: &'a TileThreadgroupMemory,
|
||||
viewport_compensation: Option<ViewportCompensation>,
|
||||
zeroed_colors: &'a BTreeMap<u32, metal::PixelFormat>,
|
||||
dropped_colors: &'a BTreeSet<u32>,
|
||||
kept_imageblock_bytes: Option<u32>,
|
||||
depth_clamp_range: bool,
|
||||
rotated_weights: bool,
|
||||
mesh_last_first: bool,
|
||||
line_band: Option<crate::pipeline::BandPrimitive>,
|
||||
interlocked_colors: &'a BTreeSet<u32>,
|
||||
fragment_tests: FragmentTests,
|
||||
extended_shadows: &'a BTreeSet<u32>,
|
||||
snapshot_textures: &'a BTreeSet<u32>,
|
||||
primitive_id_indices: Option<metal::IndexType>,
|
||||
quad_primitive_ids: bool,
|
||||
private_list: bool,
|
||||
far_vertex_buffers: &'a BTreeSet<u32>,
|
||||
region_viewports: bool,
|
||||
region_fan_out: Option<crate::pipeline::RegionFanOut>,
|
||||
}
|
||||
|
||||
/// The projection of `BindState::argument_samplers` that can change a plan: the capacity class of
|
||||
/// the list's length, and the distinct shapes of its samplers. A plan holds
|
||||
/// [`ArgumentSamplersShape::entries`] entries in each sampler table and sampler array, so a
|
||||
|
||||
-5
@@ -897,11 +897,7 @@ codec_enum! {
|
||||
ShadowStencilState, IndexCapacity, ViewportCount, RenderTargetArrayLength,
|
||||
PatchIndexOffset, PatchIndexBound, ControlPointIndexOffset, StageInStride(f0),
|
||||
AmplificationId, AmplificationLayerOffset, AmplificationViewportOffset,
|
||||
ViewportCompensation,
|
||||
PointGuard,
|
||||
DepthClampRange,
|
||||
ViewportMirrors,
|
||||
VertexDepthClamp,
|
||||
ShaderTestsState,
|
||||
CaptureLayout,
|
||||
CaptureIndexAddress,
|
||||
@@ -1292,7 +1288,6 @@ codec_enum! {
|
||||
TextureSwizzle { slot },
|
||||
TileImageblock { data_size, alignment },
|
||||
AmplificationDraws { layered, viewports },
|
||||
ViewportCompensation { depth, point_guard, mirrors, vertex_clamp },
|
||||
FoldedGroups,
|
||||
ReplayBindings,
|
||||
AbsentArgumentRead { stage },
|
||||
|
||||
Vendored
+2
-12
@@ -72,7 +72,7 @@ pub const SEMANTICS_VERSION: u32 = 2207;
|
||||
/// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag
|
||||
/// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that
|
||||
/// bumps it says what changed; this comment keeps no history.
|
||||
pub const ARTIFACT_FORMAT_VERSION: u32 = 556;
|
||||
pub const ARTIFACT_FORMAT_VERSION: u32 = 557;
|
||||
|
||||
/// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding
|
||||
/// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle
|
||||
@@ -301,12 +301,6 @@ pub struct VariantKey {
|
||||
/// it.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub amplification_draws: Option<crate::pipeline::AmplificationDraws>,
|
||||
/// The vertex function compensates its position for a viewport Vulkan's cannot be
|
||||
/// (`LoweringInputs::viewport_compensation`): the variant a shape whose viewport has a
|
||||
/// negative width, or a depth range past `[0, 1]` the device does not take, asks for
|
||||
/// (`BindShape::viewport_compensation`). The plan of a pipeline compiled under it states it.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub viewport_compensation: Option<crate::pipeline::ViewportCompensation>,
|
||||
/// The kernel folds Metal's group counts into one dispatch within the device's limits
|
||||
/// (`LoweringInputs::folded_groups`): the variant a threadgroup dispatch whose group counts
|
||||
/// are GPU data runs on, for a kernel that observes its threadgroup partition, reading its
|
||||
@@ -612,7 +606,6 @@ impl VariantKey {
|
||||
&& !self.replay_bindings
|
||||
&& !self.merged_draws
|
||||
&& self.amplification_draws.is_none()
|
||||
&& self.viewport_compensation.is_none()
|
||||
&& !self.folded_groups
|
||||
&& !self.partial_threadgroups
|
||||
&& self.extended_range.is_empty()
|
||||
@@ -650,7 +643,7 @@ impl VariantKey {
|
||||
/// the fragment function the colors it writes zero to and those it drops, its depth's clamp
|
||||
/// range and whether its draws' tests are read-only, for a tile function the imageblock bytes
|
||||
/// its pass keeps, and for the vertex function the
|
||||
/// dropped `Layer` output, the viewport compensation and the window depth
|
||||
/// dropped `Layer` output and the window depth
|
||||
/// (a vertex function's projection is
|
||||
/// derived from the vertex descriptor and
|
||||
/// [`pulled_vertex_buffers`](VariantKey::pulled_vertex_buffers) when the pipeline compiles,
|
||||
@@ -705,9 +698,6 @@ impl VariantKey {
|
||||
out.amplification_draws = self
|
||||
.amplification_draws
|
||||
.filter(|_| stage != crate::pipeline::sym::Stage::Kernel);
|
||||
out.viewport_compensation = self
|
||||
.viewport_compensation
|
||||
.filter(|_| stage == crate::pipeline::sym::Stage::Vertex);
|
||||
out.region_viewports =
|
||||
self.region_viewports && stage == crate::pipeline::sym::Stage::Vertex;
|
||||
out.region_copies = self.region_fan_out
|
||||
|
||||
@@ -183,9 +183,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
|
||||
// A separate compile of the pipeline, which an amplification multiview does not express
|
||||
// asks for; the binder writes each amplification's words before its draw.
|
||||
RuntimeFact::AmplificationDraws { .. } => Mechanism::Variant,
|
||||
// A separate compile of the pipeline, which a viewport Vulkan's cannot be asks for; the
|
||||
// binder writes the draw's compensation.
|
||||
RuntimeFact::ViewportCompensation { .. } => Mechanism::Variant,
|
||||
// A pipeline compiled under the folded-groups variant; its plans state it.
|
||||
RuntimeFact::FoldedGroups => Mechanism::Variant,
|
||||
// A render pipeline compiled under the replay-bindings variant; its plans state it.
|
||||
|
||||
@@ -153,12 +153,6 @@ fn every_fact() -> Vec<RuntimeFact> {
|
||||
layered: true,
|
||||
viewports: false,
|
||||
},
|
||||
RuntimeFact::ViewportCompensation {
|
||||
depth: true,
|
||||
point_guard: true,
|
||||
mirrors: true,
|
||||
vertex_clamp: true,
|
||||
},
|
||||
RuntimeFact::FoldedGroups,
|
||||
RuntimeFact::ReplayBindings,
|
||||
RuntimeFact::MergedDraws,
|
||||
@@ -362,7 +356,6 @@ fn variant(f: &RuntimeFact) -> usize {
|
||||
RuntimeFact::TextureSwizzle { .. } => 52,
|
||||
RuntimeFact::TileImageblock { .. } => 53,
|
||||
RuntimeFact::AmplificationDraws { .. } => 54,
|
||||
RuntimeFact::ViewportCompensation { .. } => 55,
|
||||
RuntimeFact::FoldedGroups => 56,
|
||||
RuntimeFact::AbsentArgumentRead { .. } => 57,
|
||||
RuntimeFact::ZeroedColor { .. } => 59,
|
||||
@@ -497,7 +490,6 @@ fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
| RuntimeFact::OneRow
|
||||
| RuntimeFact::UnitAxes { .. }
|
||||
| RuntimeFact::AmplificationDraws { .. }
|
||||
| RuntimeFact::ViewportCompensation { .. }
|
||||
| RuntimeFact::FoldedGroups
|
||||
| RuntimeFact::ReplayBindings
|
||||
| RuntimeFact::MergedDraws
|
||||
|
||||
@@ -74,7 +74,6 @@ use crate::device::requirements::{
|
||||
ApiVersion, FormatUsage, VkExtension, VkFeature, VkLimit, VkProperty,
|
||||
};
|
||||
use crate::device::DriverWorkaround;
|
||||
use crate::metal::PixelFormat;
|
||||
use crate::pipeline::sym::{Axis, SlotRef, SpecKey, Stage};
|
||||
use crate::vk;
|
||||
|
||||
@@ -885,11 +884,6 @@ pub enum RuntimeDriverDefect {
|
||||
/// depth/stencil attachment's stencil a fragment function writes without stencil export
|
||||
/// (`Feature::StencilExport`).
|
||||
MultisampledDepthStencilColourCopies,
|
||||
/// A primitive whose normalized depths reach past `[0, 1]` rasterizes inexact depths, where
|
||||
/// Metal's own viewport of the same depth range draws them exactly. The runtime draws a
|
||||
/// viewport depth range past `[0, 1]` that the device does not take natively through such
|
||||
/// depths (the vertex stage's compensation, `Feature::ViewportDepthRange`).
|
||||
NormalizedDepthPastUnitRange,
|
||||
/// A compressed image's memory requirements answer a size short of the memory the GPU
|
||||
/// writes its compression data through, so a resource bound right after the image loses what
|
||||
/// a command buffer that also writes the image writes into its first bytes. Nothing is
|
||||
@@ -1601,10 +1595,6 @@ pub enum Feature {
|
||||
HeapTextureTiling {
|
||||
missing: LinearNeed,
|
||||
},
|
||||
/// A viewport depth range past `[0, 1]` (`setViewport:`), which Metal takes and the runtime
|
||||
/// draws natively (`VK_EXT_depth_range_unrestricted`) or through the vertex stage's
|
||||
/// compensation.
|
||||
ViewportDepthRange,
|
||||
/// A shader write to a texture made without `ShaderWrite` (or `ShaderAtomic`), or a read of
|
||||
/// one made without `ShaderRead`, which plain Metal runs, where the texture's image lacks the
|
||||
/// storage or sampled usage: the runtime adds it only where it costs the image nothing (the
|
||||
|
||||
@@ -11,7 +11,6 @@ pub use host::{BindingError, CommandBuffer, CommandBufferError, RecordView, Reso
|
||||
|
||||
use std::fmt;
|
||||
use std::num::NonZeroU64;
|
||||
use std::ops::Range;
|
||||
|
||||
/// Buffer namespace of an encoded command.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
|
||||
@@ -667,159 +667,3 @@ fn buffer_slots_hold_the_answers_of_metal_s_getters() {
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
/// A small deterministic generator for the field tests (xorshift64*).
|
||||
struct Draws(u64);
|
||||
|
||||
impl Draws {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 >> 12;
|
||||
self.0 ^= self.0 << 25;
|
||||
self.0 ^= self.0 >> 27;
|
||||
self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
|
||||
/// A word that is often 0, else small or anything.
|
||||
fn word(&mut self) -> u32 {
|
||||
match self.below(4) {
|
||||
0 => 0,
|
||||
1 => self.below(8) as u32,
|
||||
_ => self.next() as u32,
|
||||
}
|
||||
}
|
||||
|
||||
fn words<const N: usize>(&mut self) -> [u32; N] {
|
||||
std::array::from_fn(|_| self.word())
|
||||
}
|
||||
|
||||
fn action(&mut self) -> Action {
|
||||
match self.below(9) {
|
||||
0 => Action::Empty,
|
||||
1 => Action::DispatchThreadgroups {
|
||||
grid: self.words(),
|
||||
local_size: self.words(),
|
||||
},
|
||||
2 => Action::DispatchThreads {
|
||||
grid: self.words(),
|
||||
local_size: self.words(),
|
||||
},
|
||||
3 => Action::DrawPrimitives {
|
||||
primitive_type: self.word(),
|
||||
vertex_start: self.word(),
|
||||
vertex_count: self.word(),
|
||||
instance_count: self.word(),
|
||||
base_instance: self.word(),
|
||||
},
|
||||
4 => Action::DrawIndexedPrimitives {
|
||||
primitive_type: self.word(),
|
||||
index_count: self.word(),
|
||||
index_type: self.word(),
|
||||
index_buffer: self.next(),
|
||||
instance_count: self.word(),
|
||||
base_vertex: self.word() as i32,
|
||||
base_instance: self.word(),
|
||||
},
|
||||
5 => Action::DrawPatches {
|
||||
control_points: self.word(),
|
||||
patch_start: self.word(),
|
||||
patch_count: self.word(),
|
||||
patch_index_buffer: self.next(),
|
||||
instance_count: self.word(),
|
||||
base_instance: self.word(),
|
||||
factor_buffer: self.next(),
|
||||
factor_instance_stride: self.word(),
|
||||
factor_scale: self.word(),
|
||||
},
|
||||
6 => Action::DrawIndexedPatches {
|
||||
control_points: self.word(),
|
||||
patch_start: self.word(),
|
||||
patch_count: self.word(),
|
||||
patch_index_buffer: self.next(),
|
||||
control_point_index_buffer: self.next(),
|
||||
instance_count: self.word(),
|
||||
base_instance: self.word(),
|
||||
factor_buffer: self.next(),
|
||||
factor_instance_stride: self.word(),
|
||||
factor_scale: self.word(),
|
||||
},
|
||||
7 => Action::DrawMeshThreadgroups {
|
||||
threadgroups: self.words(),
|
||||
object_threads: self.words(),
|
||||
mesh_threads: self.words(),
|
||||
},
|
||||
_ => Action::DrawMeshThreads {
|
||||
threads: self.words(),
|
||||
object_threads: self.words(),
|
||||
mesh_threads: self.words(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn binding(&mut self) -> Option<BufferBinding> {
|
||||
match self.below(4) {
|
||||
0 => None,
|
||||
_ => Some(BufferBinding {
|
||||
address: match self.below(2) {
|
||||
0 => u64::from(self.word()),
|
||||
_ => self.next(),
|
||||
},
|
||||
attribute_stride: match self.below(3) {
|
||||
0 => None,
|
||||
1 => Some(u64::from(self.word())),
|
||||
// All ones is reserved: the encoder refuses it.
|
||||
_ => Some(self.next() | (u64::from(self.below(2) == 0) * u64::MAX)),
|
||||
},
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn stage(&mut self) -> BufferStage {
|
||||
[
|
||||
BufferStage::Kernel,
|
||||
BufferStage::Vertex,
|
||||
BufferStage::Fragment,
|
||||
BufferStage::Object,
|
||||
BufferStage::Mesh,
|
||||
][self.below(5) as usize]
|
||||
}
|
||||
|
||||
/// A record `encode_into` takes: random fields, a stage-in region only beside an action that
|
||||
/// leaves its words, the first two lengths 0 beside an indexed patch draw, and a pipeline
|
||||
/// set or retained, not both, a kernel's or not.
|
||||
fn record(&mut self) -> CommandRecord {
|
||||
let action = self.action();
|
||||
let mut record = CommandRecord {
|
||||
action,
|
||||
barrier: self.below(2) == 0,
|
||||
..Default::default()
|
||||
};
|
||||
let pipeline = NonZeroU64::new(self.next() * self.below(2));
|
||||
match self.below(2) {
|
||||
0 => record.bindings.pipeline = pipeline,
|
||||
_ => record.retained_pipeline = pipeline,
|
||||
}
|
||||
record.kernel_pipeline = pipeline.is_some() && self.below(2) == 0;
|
||||
for stage in BufferStage::of(false) {
|
||||
for slot in record.bindings.buffers_mut(stage).iter_mut() {
|
||||
*slot = self
|
||||
.binding()
|
||||
.filter(|b| b.attribute_stride != Some(u64::MAX));
|
||||
}
|
||||
}
|
||||
for length in record.threadgroup_memory_lengths.iter_mut() {
|
||||
*length = self.word();
|
||||
}
|
||||
if matches!(action, Action::DrawIndexedPatches { .. }) {
|
||||
record.threadgroup_memory_lengths[..2].fill(0);
|
||||
}
|
||||
if !action.takes_stage_in_words() {
|
||||
record.stage_in_region = self.words();
|
||||
}
|
||||
record.imageblock_size = [self.word() as u16, self.word() as u16];
|
||||
record
|
||||
}
|
||||
}
|
||||
@@ -76,30 +76,12 @@ pub struct CompiledFunction(Arc<FunctionArtifact>, Arc<LastRelocation>);
|
||||
#[derive(Default)]
|
||||
pub(crate) struct LastRelocation(std::sync::Mutex<Option<Relocated>>);
|
||||
|
||||
/// One relocation: what link assigned, the words that came out, and a digest of those words a
|
||||
/// caller asked for.
|
||||
/// One relocation: what link assigned, and the words that came out.
|
||||
struct Relocated {
|
||||
/// The value link assigned to each of the module's relocation slots, in `relocs` order: the
|
||||
/// whole of what the words depend on besides the module itself.
|
||||
assigned: Vec<u32>,
|
||||
words: Arc<[u32]>,
|
||||
/// The digest of `words`, with the function that derived it: a caller that hashes words some
|
||||
/// other way derives again rather than reading a digest its own function did not make
|
||||
/// ([`CompiledFunction::relocated_words_digest`]). Cleared with the words it describes, so
|
||||
/// it can never name another relocation's.
|
||||
digest: Option<(fn(&[u32]) -> Hash256, Hash256)>,
|
||||
}
|
||||
|
||||
/// What a relocation slot can say about a digest of some words by some function
|
||||
/// ([`LastRelocation::digest_of`]).
|
||||
enum DigestOf {
|
||||
/// It holds those very words and that function's digest of them.
|
||||
Kept(Hash256),
|
||||
/// It holds those very words and no digest of them by that function, so one derived now
|
||||
/// belongs in it.
|
||||
Wanted,
|
||||
/// The words are not the ones it holds, so it has nothing to say about them.
|
||||
Other,
|
||||
}
|
||||
|
||||
impl LastRelocation {
|
||||
@@ -110,47 +92,15 @@ impl LastRelocation {
|
||||
(kept.assigned == assigned).then(|| Arc::clone(&kept.words))
|
||||
}
|
||||
|
||||
/// Keep `words` as the relocation that assigned `assigned`, replacing what the slot held
|
||||
/// (and the digest of the words it held).
|
||||
/// Keep `words` as the relocation that assigned `assigned`, replacing what the slot held.
|
||||
pub(crate) fn keep(&self, assigned: Vec<u32>, words: &Arc<[u32]>) {
|
||||
let mut slot = self.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
*slot = Some(Relocated {
|
||||
assigned,
|
||||
words: Arc::clone(words),
|
||||
digest: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// What the slot has for a digest of `words` by `derive` ([`DigestOf`]). The words are the
|
||||
/// slot's only if they are the same allocation: a relocation hands back the very `Arc` it
|
||||
/// kept, so an equal copy of the words is a different caller's and answers `Other`.
|
||||
fn digest_of(&self, words: &Arc<[u32]>, derive: fn(&[u32]) -> Hash256) -> DigestOf {
|
||||
let slot = self.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some(kept) = slot.as_ref() else {
|
||||
return DigestOf::Other;
|
||||
};
|
||||
if !Arc::ptr_eq(&kept.words, words) {
|
||||
return DigestOf::Other;
|
||||
}
|
||||
match kept.digest {
|
||||
Some((made_by, digest)) if std::ptr::fn_addr_eq(made_by, derive) => {
|
||||
DigestOf::Kept(digest)
|
||||
}
|
||||
_ => DigestOf::Wanted,
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep `digest`, which `derive` produced over `words`, if the slot still holds those very
|
||||
/// words; drop it if the slot has moved on, since a digest only ever describes the words
|
||||
/// beside it.
|
||||
fn keep_digest(&self, words: &Arc<[u32]>, derive: fn(&[u32]) -> Hash256, digest: Hash256) {
|
||||
let mut slot = self.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(kept) = slot.as_mut() {
|
||||
if Arc::ptr_eq(&kept.words, words) {
|
||||
kept.digest = Some((derive, digest));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A clone of a compiled function shares its slot, so the `Debug`, equality and hashing of a
|
||||
|
||||
@@ -164,19 +164,12 @@ pub const fn shape(f: PushField) -> FieldShape {
|
||||
// Region base `xyz` and grid `xyz`, one 4-vector each (`w` unused); a stage-in region's
|
||||
// origin and size the same way.
|
||||
PushField::DispatchRegion | PushField::StageInRegion => FieldShape::UVec4Array(2),
|
||||
// A draw's viewport compensation, four `f32`s' bits.
|
||||
PushField::ViewportCompensation => FieldShape::UVec4Array(1),
|
||||
// A draw's point guard band, two `f32`s' bits.
|
||||
PushField::PointGuard => FieldShape::UVec2,
|
||||
// A draw's depth clamp range, two `f32`s' bits.
|
||||
PushField::DepthClampRange => FieldShape::UVec2,
|
||||
// A draw's mirrored viewports, one bit each.
|
||||
PushField::ViewportMirrors => FieldShape::U32,
|
||||
// Which of a snapshot variant's draws runs.
|
||||
PushField::SnapshotPhase => FieldShape::U32,
|
||||
// The alpha test reference's code.
|
||||
PushField::AlphaTestReference => FieldShape::U32,
|
||||
// A draw's clamp of each vertex's depth, two `f32`s' bits.
|
||||
PushField::VertexDepthClamp => FieldShape::UVec2,
|
||||
// The blend color and one minus it, four `f32`s' bits each.
|
||||
// The blend color as the encoder set it, four `f32`s' bits.
|
||||
PushField::HalfBlendColor => FieldShape::UVec4Array(1),
|
||||
@@ -942,7 +935,6 @@ mod tests {
|
||||
PushField::AmplificationLayerOffset,
|
||||
PushField::AmplificationViewportOffset,
|
||||
PushField::BaseVertexInstance,
|
||||
PushField::ViewportCompensation,
|
||||
PushField::CaptureLayout,
|
||||
]);
|
||||
for i in 0..31 {
|
||||
|
||||
@@ -468,8 +468,6 @@ pub struct StageIoPlan {
|
||||
/// The word attachments whose `float` or `half` output each return stores as the word Metal
|
||||
/// stores (`word_color::encode`), with each word's layout.
|
||||
pub words_written: BTreeMap<u32, crate::metal::format::WordAttachment>,
|
||||
/// A vertex function's viewport compensation (`LoweringInputs::viewport_compensation`).
|
||||
pub compensation: Option<Compensation>,
|
||||
/// A fragment function's depth output, which each return gives Metal's answer
|
||||
/// (`clamp_depth`).
|
||||
pub depth_clamp: Option<DepthClamp>,
|
||||
@@ -598,7 +596,7 @@ const PRIMITIVE_ID_WORDS: u64 = 56;
|
||||
|
||||
/// How a vertex function compiled under `LoweringInputs::window_depth_varying` writes its
|
||||
/// window depth: at each return, the `z / w` of the value it stores to its `Position` object
|
||||
/// (`position`, after any compensation or clamp) to its `IoRole::WindowDepth` varying
|
||||
/// (`position`, after any clamp) to its `IoRole::WindowDepth` varying
|
||||
/// (`object`), for a fragment function that computes each sample's depth from it
|
||||
/// (`lower::fragment`'s `depth_test`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -679,23 +677,6 @@ pub struct DepthClamp {
|
||||
pub range: bool,
|
||||
}
|
||||
|
||||
/// How a vertex function compiled under `LoweringInputs::viewport_compensation` stores its
|
||||
/// position: its `Position` object, whose value it compensates by
|
||||
/// `PushField::ViewportCompensation` before storing it, and, where it compensates the depth, its
|
||||
/// `ClipDistance` object and the first of the two elements it writes there after its own. Under
|
||||
/// Metal's guard band for points, `guard` names the object and the first of the four elements it
|
||||
/// writes after those. Under `mirrors` it negates `x` where the viewport it selects is mirrored
|
||||
/// (`PushField::ViewportMirrors`). Under `vertex_clamp`, which only a compensated depth takes, it
|
||||
/// clamps that depth by `PushField::VertexDepthClamp`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Compensation {
|
||||
pub position: usize,
|
||||
pub clip: Option<(usize, u32)>,
|
||||
pub guard: Option<(usize, u32)>,
|
||||
pub mirrors: bool,
|
||||
pub vertex_clamp: bool,
|
||||
}
|
||||
|
||||
impl StageIoPlan {
|
||||
/// The index of an object equal to `o`, adding it when there is none.
|
||||
fn object(&mut self, o: IoObject) -> usize {
|
||||
@@ -1886,7 +1867,6 @@ pub fn emit_return(
|
||||
let plan = &cx.plan.families.stage_io;
|
||||
let (outputs, returned, point) = (plan.outputs.clone(), plan.returned, plan.point_size_default);
|
||||
let seconds = plan.rotated_seconds.clone();
|
||||
let compensation = plan.compensation;
|
||||
let region_copy = plan.region_copy;
|
||||
let depth_clamp = plan.depth_clamp;
|
||||
let window_depth = plan.window_depth;
|
||||
@@ -1910,11 +1890,6 @@ pub fn emit_return(
|
||||
(Some(_), _) if outputs.is_empty() => {}
|
||||
(Some(v), _) => {
|
||||
let x = cx.operand(fb, v)?;
|
||||
// The viewport the function selects, which a compensation of mirrors reads.
|
||||
let selected = match compensation.filter(|c| c.mirrors) {
|
||||
Some(_) => Some(selected_viewport(cx, fb, x, returned, &outputs)?),
|
||||
None => None,
|
||||
};
|
||||
for o in &outputs {
|
||||
let part = output_part(cx, fb, x, returned, o)?;
|
||||
let part =
|
||||
@@ -1922,10 +1897,6 @@ pub fn emit_return(
|
||||
true => metal_point_size(fb, part)?,
|
||||
false => part,
|
||||
};
|
||||
let part = match compensation.filter(|c| c.position == o.link.object) {
|
||||
Some(c) => compensate(cx, fb, c, part, selected)?,
|
||||
None => part,
|
||||
};
|
||||
let part = match region_copy.filter(|r| r.position == o.link.object) {
|
||||
Some(r) => store_region_copy(cx, fb, r, part)?,
|
||||
None => part,
|
||||
@@ -2480,187 +2451,6 @@ fn rotated_second(
|
||||
fb.vector_shuffle(first, constants, &lanes)
|
||||
}
|
||||
|
||||
/// The viewport a vertex function returning `x` selects, as Vulkan reads it: the `ViewportIndex`
|
||||
/// it stores (`output_part`) or the `IoRole::SelectedViewport` varying the synthesized geometry
|
||||
/// stages store it from, else the one an amplification stores (`StageIoPlan::amplified`), else
|
||||
/// the first.
|
||||
fn selected_viewport(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
x: SValue,
|
||||
returned: Returned,
|
||||
outputs: &[PlannedOutput],
|
||||
) -> BResult<SValue> {
|
||||
let sp = &cx.plan.families.stage_io;
|
||||
// The `ViewportIndex` the function stores, or the varying the synthesized geometry stages
|
||||
// store it from (`IoRole::SelectedViewport`): either holds the index below the count.
|
||||
let selected_key = crate::pipeline::sym::VaryingKey::selected_viewport();
|
||||
let is_index = |o: &IoObject| match o {
|
||||
IoObject::Builtin {
|
||||
builtin: crate::spv::BuiltIn::ViewportIndex,
|
||||
dir: IoDir::Output,
|
||||
..
|
||||
} => true,
|
||||
IoObject::User {
|
||||
key,
|
||||
dir: IoDir::Output,
|
||||
..
|
||||
} => *key == selected_key,
|
||||
_ => false,
|
||||
};
|
||||
let object = sp.objects.iter().position(is_index);
|
||||
let amplified = sp
|
||||
.amplified
|
||||
.iter()
|
||||
.find(|a| Some(a.link.object) == object)
|
||||
.copied();
|
||||
if let Some(o) = outputs.iter().find(|o| Some(o.link.object) == object) {
|
||||
return output_part(cx, fb, x, returned, o);
|
||||
}
|
||||
match amplified {
|
||||
Some(a) => {
|
||||
let offset = cx.push_field(fb, a.offset)?;
|
||||
below_count(cx, fb, offset, a.below)
|
||||
}
|
||||
None => {
|
||||
let zero = fb.u32_const(0)?;
|
||||
fb.module().const_value(zero)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `position`, a vertex function's `float4` position, compensated for the draw's viewport by
|
||||
/// `PushField::ViewportCompensation`'s `[sx, a, b, clip]`
|
||||
/// (`LoweringInputs::viewport_compensation`): `(sx x, y, a w + b z, w)`, or `(sx x, y, z, w)` where
|
||||
/// only `x` is compensated. Where the depth is, the two clip distances `c.clip` names are stored
|
||||
/// too: `z` and `w - z` where `clip` is 1, which clip at Metal's near and far planes as the Vulkan
|
||||
/// viewport's no longer do, and 1 where it is 0 (depth clamp mode, which clips at neither). Under
|
||||
/// the point guard band (`c.guard`) `x` and `y` are scaled by `PushField::PointGuard`'s `[gx, gy]`
|
||||
/// too, and the four clip distances `c.guard` names are stored: `1.5 w - x`, `1.5 w + x`, `1.5 w -
|
||||
/// y` and `1.5 w + y` of the function's own `x` and `y`, which cull a point where Metal does. Under
|
||||
/// `c.mirrors` `x` is negated too where the `selected` viewport's bit of
|
||||
/// `PushField::ViewportMirrors` is set. Under `c.vertex_clamp` the compensated depth is clamped to
|
||||
/// `[lo w, hi w]` of `PushField::VertexDepthClamp`'s `[lo, hi]` where `w` is positive, as Metal
|
||||
/// clamps each vertex's depth before the interpolation; a NaN depth takes the bound.
|
||||
fn compensate(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
c: Compensation,
|
||||
position: SValue,
|
||||
selected: Option<SValue>,
|
||||
) -> BResult<SValue> {
|
||||
let field = cx.push_field(fb, PushField::ViewportCompensation)?;
|
||||
let f32_ = fb.module().ty(SType::Float { width: 32 })?;
|
||||
let lane = |fb: &mut FunctionBuilder<'_>, i: u32| -> BResult<SValue> {
|
||||
let bits = fb.composite_extract(field, &[0, i])?;
|
||||
fb.convert(ConvOp::Bitcast, bits, f32_)
|
||||
};
|
||||
let x = fb.composite_extract(position, &[0])?;
|
||||
let y = fb.composite_extract(position, &[1])?;
|
||||
let z = fb.composite_extract(position, &[2])?;
|
||||
let w = fb.composite_extract(position, &[3])?;
|
||||
let sx = lane(fb, 0)?;
|
||||
let sxx = fb.binary(BinOp::FMul, sx, x)?;
|
||||
// Mirrored and unmirrored viewports in one draw: `x` negated where the selected viewport's
|
||||
// bit is set.
|
||||
let sxx = match selected.filter(|_| c.mirrors) {
|
||||
None => sxx,
|
||||
Some(index) => {
|
||||
let mirrors = cx.push_field(fb, PushField::ViewportMirrors)?;
|
||||
let bits = fb.binary(BinOp::ShiftRightLogical, mirrors, index)?;
|
||||
let one = fb.u32_const(1)?;
|
||||
let one = fb.module().const_value(one)?;
|
||||
let bit = fb.binary(BinOp::BitwiseAnd, bits, one)?;
|
||||
let zero = fb.u32_const(0)?;
|
||||
let zero = fb.module().const_value(zero)?;
|
||||
let mirrored = fb.binary(BinOp::INotEqual, bit, zero)?;
|
||||
let negated = fb.unary(UnOp::FNegate, sxx)?;
|
||||
fb.select(mirrored, negated, sxx)?
|
||||
}
|
||||
};
|
||||
let f32_const = |fb: &mut FunctionBuilder<'_>, v: f32| -> BResult<SValue> {
|
||||
let k = fb.module().constant(Constant::Scalar {
|
||||
ty: f32_,
|
||||
bits: ConstBits(u64::from(v.to_bits())),
|
||||
})?;
|
||||
fb.module().const_value(k)
|
||||
};
|
||||
// Metal's guard band for points: the position scaled into the widened Vulkan viewports,
|
||||
// and the four planes at `1.5 w` of the function's own `x` and `y`.
|
||||
let (sxx, y_out) = match c.guard {
|
||||
None => (sxx, y),
|
||||
Some((object, first)) => {
|
||||
let guard = cx.push_field(fb, PushField::PointGuard)?;
|
||||
let scale = |fb: &mut FunctionBuilder<'_>, i: u32| -> BResult<SValue> {
|
||||
let bits = fb.composite_extract(guard, &[i])?;
|
||||
fb.convert(ConvOp::Bitcast, bits, f32_)
|
||||
};
|
||||
let (gx, gy) = (scale(fb, 0)?, scale(fb, 1)?);
|
||||
let band = f32_const(fb, 1.5)?;
|
||||
let band = fb.binary(BinOp::FMul, band, w)?;
|
||||
let g = global(cx, object)?;
|
||||
let base = fb.module().global_value(g)?;
|
||||
let mut k = first;
|
||||
for v in [x, y] {
|
||||
for op in [BinOp::FSub, BinOp::FAdd] {
|
||||
let d = fb.binary(op, band, v)?;
|
||||
let kc = fb.u32_const(k)?;
|
||||
let kc = fb.module().const_value(kc)?;
|
||||
let p = fb.access_chain(base, &[kc])?;
|
||||
fb.store(p, d, MemAccess::default())?;
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
(
|
||||
fb.binary(BinOp::FMul, gx, sxx)?,
|
||||
fb.binary(BinOp::FMul, gy, y)?,
|
||||
)
|
||||
}
|
||||
};
|
||||
let depth = match c.clip {
|
||||
None => z,
|
||||
Some((object, first)) => {
|
||||
let (a, b, clip) = (lane(fb, 1)?, lane(fb, 2)?, lane(fb, 3)?);
|
||||
let aw = fb.binary(BinOp::FMul, a, w)?;
|
||||
let bz = fb.binary(BinOp::FMul, b, z)?;
|
||||
let depth = fb.binary(BinOp::FAdd, aw, bz)?;
|
||||
let (half, one) = (f32_const(fb, 0.5)?, f32_const(fb, 1.0)?);
|
||||
let clips = fb.binary(BinOp::FOrdGreaterThan, clip, half)?;
|
||||
let far = fb.binary(BinOp::FSub, w, z)?;
|
||||
let g = global(cx, object)?;
|
||||
let base = fb.module().global_value(g)?;
|
||||
for (k, distance) in [(first, z), (first + 1, far)] {
|
||||
let d = fb.select(clips, distance, one)?;
|
||||
let kc = fb.u32_const(k)?;
|
||||
let kc = fb.module().const_value(kc)?;
|
||||
let p = fb.access_chain(base, &[kc])?;
|
||||
fb.store(p, d, MemAccess::default())?;
|
||||
}
|
||||
// Metal clamps each vertex's depth before the interpolation: `z / w` to the draw's
|
||||
// `[lo, hi]` where `w` is positive.
|
||||
match c.vertex_clamp {
|
||||
false => depth,
|
||||
true => {
|
||||
let range = cx.push_field(fb, PushField::VertexDepthClamp)?;
|
||||
let bound = |fb: &mut FunctionBuilder<'_>, i: u32| -> BResult<SValue> {
|
||||
let bits = fb.composite_extract(range, &[i])?;
|
||||
let v = fb.convert(ConvOp::Bitcast, bits, f32_)?;
|
||||
fb.binary(BinOp::FMul, v, w)
|
||||
};
|
||||
let (low, high) = (bound(fb, 0)?, bound(fb, 1)?);
|
||||
let raised = fb.glsl(GlslOp::NMax, &[depth, low])?;
|
||||
let clamped = fb.glsl(GlslOp::NMin, &[raised, high])?;
|
||||
let zero = f32_const(fb, 0.0)?;
|
||||
let positive = fb.binary(BinOp::FOrdGreaterThan, w, zero)?;
|
||||
fb.select(positive, clamped, depth)?
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let vec4 = fb.module().ty(SType::Vector { elem: f32_, len: 4 })?;
|
||||
fb.composite_construct(vec4, &[sxx, y_out, depth, w])
|
||||
}
|
||||
|
||||
/// `position`, a vertex function's `float4` position, as its region's copy (`r`,
|
||||
/// `LoweringInputs::region_copies`): the region of segments `(x0 + DrawIndex, y0)` of the region
|
||||
/// table, `[x0, y0]` its `PushField::RegionBox` (a draw of a row's regions in order), its position
|
||||
|
||||
@@ -16,14 +16,12 @@ use crate::lower::arith::legal::{form_on, refuse_bfloat_color, refuse_int64_inte
|
||||
use crate::lower::arith::{FloatFmt, Form, Held};
|
||||
use crate::lower::select::SelectCx;
|
||||
use crate::lower::stage_io::{
|
||||
fetch, not_lowered, AmplifiedOutput, Compensation, DepthClamp, IoObject, MergedRead,
|
||||
MergedValue, PlannedOutput, PlannedParam, Returned, RotatedSecond, Source, StageIoPlan,
|
||||
fetch, not_lowered, AmplifiedOutput, DepthClamp, IoObject, MergedRead, MergedValue,
|
||||
PlannedOutput, PlannedParam, Returned, RotatedSecond, Source, StageIoPlan,
|
||||
};
|
||||
use crate::pipeline::artifact::PrecisionNote;
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::pipeline::lower_inputs::{
|
||||
FactorLane, RotatedBlendForm, VertexFetch, ViewportCompensation,
|
||||
};
|
||||
use crate::pipeline::lower_inputs::{FactorLane, RotatedBlendForm, VertexFetch};
|
||||
use crate::pipeline::stage_io::{
|
||||
DepthMode, Interpolation, IoNumeric, IoRole, IoType, IoVariable, Sampling, StageBuiltin,
|
||||
};
|
||||
@@ -1237,7 +1235,7 @@ fn amplified_output(cx: &mut SelectCx<'_>, index: AmplifiedIndex) -> Result<(),
|
||||
/// first vertex. So does a draw replay's of one draw per command (`replay_bindings`), whose
|
||||
/// buffers are in the slot table at its push: its draws' indices are their own. A function that
|
||||
/// writes its own viewport or slice index, and one under another field that moves its indices or
|
||||
/// position (`amplification_draws`, `viewport_compensation`), or that runs behind the
|
||||
/// position (`amplification_draws`), or that runs behind the
|
||||
/// tessellator, is `NotImplemented(RasterizationRateMap)`: the runtime draws those region by
|
||||
/// region. A device that cannot store `ViewportIndex` from a vertex function,
|
||||
/// read `DrawIndex` or take several viewports refuses it, naming the three features. A function
|
||||
@@ -1255,11 +1253,7 @@ fn region_viewport(
|
||||
)
|
||||
});
|
||||
let tessellated = matches!(cx.entry.ep.stage, AirStage::Vertex { patch: Some(_) });
|
||||
if indexed
|
||||
|| tessellated
|
||||
|| i.amplification_draws.is_some()
|
||||
|| i.viewport_compensation.is_some()
|
||||
{
|
||||
if indexed || tessellated || i.amplification_draws.is_some() {
|
||||
return Err(Unsupported::not_implemented(Feature::RasterizationRateMap).into());
|
||||
}
|
||||
let f = cx.profile.fields();
|
||||
@@ -2705,14 +2699,6 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
if cx.inputs.region_copies && cx.stage == Stage::Vertex {
|
||||
region_copy(cx, &outputs, returned)?;
|
||||
}
|
||||
// A viewport Vulkan's cannot be: the position compensated for it.
|
||||
if let Some(c) = cx
|
||||
.inputs
|
||||
.viewport_compensation
|
||||
.filter(|_| cx.stage == Stage::Vertex)
|
||||
{
|
||||
compensate(cx, c)?;
|
||||
}
|
||||
// The window depth of the position the function stores, for a fragment function that
|
||||
// computes each sample's depth from it. A function that writes no position rasterizes
|
||||
// nothing.
|
||||
@@ -2997,58 +2983,6 @@ pub(crate) fn finish_merged(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Plan a vertex function's viewport compensation `c` (`LoweringInputs::viewport_compensation`):
|
||||
/// its `Position` is stored compensated by `PushField::ViewportCompensation`, and under
|
||||
/// [`ViewportCompensation::depth`] two `ClipDistance` elements follow the function's own, which
|
||||
/// Metal's near and far planes clip at. Under [`ViewportCompensation::point_guard`] the position
|
||||
/// is scaled by `PushField::PointGuard` too, and four more elements follow, Metal's guard band
|
||||
/// for points. Under [`ViewportCompensation::vertex_clamp`] the compensated depth is clamped by
|
||||
/// `PushField::VertexDepthClamp` before the interpolation. A function that writes no position
|
||||
/// rasterizes nothing and is compensated in nothing. Refused: the clip distances on a device
|
||||
/// without `shaderClipDistance`, or past its `maxClipDistances` or
|
||||
/// `maxCombinedClipAndCullDistances`.
|
||||
fn compensate(cx: &mut SelectCx<'_>, c: ViewportCompensation) -> Result<(), Error> {
|
||||
cx.facts.insert(RuntimeFact::ViewportCompensation {
|
||||
depth: c.depth,
|
||||
point_guard: c.point_guard,
|
||||
mirrors: c.mirrors,
|
||||
vertex_clamp: c.vertex_clamp,
|
||||
});
|
||||
let is = |o: &IoObject, b| matches!(o, IoObject::Builtin { builtin, dir: IoDir::Output, .. } if *builtin == b);
|
||||
let sp = &cx.families.stage_io;
|
||||
let Some(position) = sp.objects.iter().position(|o| is(o, B::Position)) else {
|
||||
return Ok(());
|
||||
};
|
||||
cx.push.insert(PushField::ViewportCompensation);
|
||||
if c.point_guard {
|
||||
cx.push.insert(PushField::PointGuard);
|
||||
}
|
||||
if c.mirrors {
|
||||
cx.push.insert(PushField::ViewportMirrors);
|
||||
}
|
||||
// Each vertex's depth clamped, which only a compensated depth takes.
|
||||
if c.vertex_clamp && c.depth {
|
||||
cx.push.insert(PushField::VertexDepthClamp);
|
||||
}
|
||||
let added = 2 * u32::from(c.depth) + 4 * u32::from(c.point_guard);
|
||||
let clips = match added {
|
||||
0 => None,
|
||||
_ => Some(added_clip_distances(cx, added, Feature::ClipDistance)?),
|
||||
};
|
||||
let clip = clips.filter(|_| c.depth);
|
||||
let guard = clips
|
||||
.filter(|_| c.point_guard)
|
||||
.map(|(object, first)| (object, first + 2 * u32::from(c.depth)));
|
||||
cx.families.stage_io.compensation = Some(Compensation {
|
||||
position,
|
||||
clip,
|
||||
guard,
|
||||
mirrors: c.mirrors,
|
||||
vertex_clamp: c.vertex_clamp && c.depth,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add `added` clip distances past a vertex function's own, for `feature`: its `ClipDistance`
|
||||
/// object, `added` elements longer, or a new one, and the first of the added elements. Refused as
|
||||
/// `feature` where the device writes no clip distances or the count passes its limits.
|
||||
@@ -3127,7 +3061,7 @@ fn added_clip_distances(
|
||||
/// from their own first vertex, and its region its `DrawIndex`'s; so does a draw replay's of one
|
||||
/// draw per command (`replay_bindings`), whose buffers are in the slot table at its push. A
|
||||
/// function that writes its own viewport or slice index, one under another field that moves its
|
||||
/// indices or position (`amplification_draws`, `viewport_compensation`), runs behind the
|
||||
/// indices or position (`amplification_draws`), runs behind the
|
||||
/// tessellator or returns no outputs is `NotImplemented(RasterizationRateMap)`: the runtime draws those through each
|
||||
/// region's viewport. A device that cannot store `ViewportIndex` from a vertex function, read
|
||||
/// `DrawIndex` or write four more clip distances refuses it.
|
||||
@@ -3159,12 +3093,7 @@ fn region_copy(
|
||||
Some(p) if returned != Returned::Void => p,
|
||||
_ => return Err(Unsupported::not_implemented(Feature::RasterizationRateMap).into()),
|
||||
};
|
||||
if indexed
|
||||
|| tessellated
|
||||
|| i.amplification_draws.is_some()
|
||||
|| i.viewport_compensation.is_some()
|
||||
|| i.region_viewports
|
||||
{
|
||||
if indexed || tessellated || i.amplification_draws.is_some() || i.region_viewports {
|
||||
return Err(Unsupported::not_implemented(Feature::RasterizationRateMap).into());
|
||||
}
|
||||
let f = cx.profile.fields();
|
||||
@@ -3665,7 +3594,6 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
// The alpha test: the alpha's extracts, its clamp and code, the reference, the
|
||||
// comparison and the kill.
|
||||
+ 40 * u64::from(sp.alpha_test.is_some())
|
||||
+ compensation_stores(sp.compensation)
|
||||
+ sp.depth_clamp.map_or(0, |d| match (d.range, d.clamps) {
|
||||
// The `[0, 1]` selects, the range's two clamps and the negative NaN's select.
|
||||
(true, _) => 14,
|
||||
@@ -3731,17 +3659,6 @@ fn float_color(e: &crate::air::Entry, ty: AirTypeId) -> bool {
|
||||
matches!(scalar, Some(Type::Float))
|
||||
}
|
||||
|
||||
/// The stores' worth of words a compensated position adds to each return: the field's lanes and
|
||||
/// `x`'s product, under the depth's compensation its sum of products and the two clip distances'
|
||||
/// selects and stores, and under the point guard band its two lanes and products, the band, and the
|
||||
/// four clip distances' sums and stores.
|
||||
fn compensation_stores(c: Option<Compensation>) -> u64 {
|
||||
let Some(c) = c else { return 0 };
|
||||
let depth = if c.clip.is_some() { 9 } else { 0 };
|
||||
let guard = if c.guard.is_some() { 13 } else { 0 };
|
||||
3 + depth + guard
|
||||
}
|
||||
|
||||
/// Whether a fragment function's depth output is clamped to `[0, 1]` as Metal stores it
|
||||
/// (`DepthClamp::clamps`; five stores' words with a positive NaN's kill, two for the kill
|
||||
/// alone): where the profile enables `VK_EXT_depth_range_unrestricted`, under which Vulkan no
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -26,7 +26,7 @@ use crate::device::requirements::{FormatUsage, VkFeature};
|
||||
use crate::device::DeviceProfile;
|
||||
use crate::error::{Capability, DescriptorError, Error, Feature, Unsupported};
|
||||
use crate::metal::{
|
||||
PixelFormat, TextureSwizzle, TextureSwizzleChannels, TextureType, TextureUsage,
|
||||
PixelFormat, TextureSwizzleChannels, TextureType, TextureUsage,
|
||||
};
|
||||
use crate::pipeline::lower_inputs::{
|
||||
AliasView, ChannelWrite, StorageImageChoice, StorageImageClass,
|
||||
@@ -548,57 +548,6 @@ impl ExtendedRange {
|
||||
}
|
||||
}
|
||||
|
||||
/// The code Metal's straight clear route ([`ClearRoute::Straight`]) stores in a `BGR10_XR`
|
||||
/// or `BGRA10_XR` channel, or its alpha where `alpha`, for the `float` `v` (an Apple M4 under
|
||||
/// macOS 27.0.1: every channel of 2,574 colors of each form; the consumer's M3 Max under 26.7
|
||||
/// alike). A linear channel's: `(v + 384/510) · 510`, each step a `float` rounded to nearest
|
||||
/// even, rounded to the nearest code with ties up, clamped to `[0, 1023]`, a NaN 0 (`0.25` is
|
||||
/// 511 and `-0.25` is 257, where a write stores 512 and 256); alpha's that of `v` clamped to
|
||||
/// `[0, 1]` first, a NaN 384. An `_sRGB` color channel's: the offset from code 384, toward the
|
||||
/// sign of `v`, of the thresholds of Metal's own encode of that sign at most `|v|`
|
||||
/// (`extended_srgb::STRAIGHT_SRGB_FIRST`), a NaN 384.
|
||||
fn straight_code(self, v: f32, alpha: bool) -> u32 {
|
||||
if self.srgb() && !alpha {
|
||||
let bits = v.abs().to_bits();
|
||||
let at = |thresholds: &[u32]| thresholds.partition_point(|&t| t <= bits) as u32;
|
||||
return match (v.is_nan(), v < 0.0) {
|
||||
(true, _) => 384,
|
||||
(false, true) => 384 - at(&extended_srgb::STRAIGHT_SRGB_FIRST_NEGATIVE),
|
||||
(false, false) => 384 + at(&extended_srgb::STRAIGHT_SRGB_FIRST),
|
||||
};
|
||||
}
|
||||
let v = match (v.is_nan(), alpha) {
|
||||
(true, true) => 0.0,
|
||||
(true, false) => return 0,
|
||||
(false, true) => v.clamp(0.0, 1.0),
|
||||
(false, false) => v,
|
||||
};
|
||||
let x = (v + 384.0 / 510.0) * 510.0;
|
||||
// Ties up, of the `float`: its sum with a half is exact in `f64`.
|
||||
(f64::from(x) + 0.5).floor().clamp(0.0, 1023.0) as u32
|
||||
}
|
||||
|
||||
/// The value a padded form's code `code` of a color channel, or of alpha where `alpha`, reads:
|
||||
/// `code / 1023`, `RGB10A2Unorm_sRGB`'s alpha `code / 3`, the color of `R10Unorm_X6_sRGB` and
|
||||
/// `RGB10A2Unorm_sRGB` through the sRGB transfer function (`RG10Unorm_X12_sRGB` reads its codes
|
||||
/// as `RG10Unorm_X12` does), in `f64` and then rounded to `f32`.
|
||||
fn padded_code_value(self, code: u32, alpha: bool) -> f32 {
|
||||
let linear = |d: f64| f64::from(code) / d;
|
||||
let v = match self {
|
||||
ExtendedRange::Rgb10A2Srgb if alpha => linear(3.0),
|
||||
ExtendedRange::R10X6Srgb | ExtendedRange::Rgb10A2Srgb => {
|
||||
let c = linear(1023.0);
|
||||
if c <= 0.04045 {
|
||||
c / 12.92
|
||||
} else {
|
||||
((c + 0.055) / 1.055).powf(2.4)
|
||||
}
|
||||
}
|
||||
_ => linear(1023.0),
|
||||
};
|
||||
v as f32
|
||||
}
|
||||
|
||||
/// The `float` value Metal reads from the code `code` (below 1024) of a color channel, or of
|
||||
/// alpha where `alpha`, of a `BGR10_XR`, `BGRA10_XR` or two-plane format or an `_sRGB` twin
|
||||
/// (an Apple M3 Max and an M4): `(code - 384) / 510` correctly rounded, an `_sRGB` color
|
||||
@@ -697,59 +646,6 @@ impl ExtendedRange {
|
||||
code.clamp(0, 1023) as u32
|
||||
}
|
||||
|
||||
/// The raw texel of the red, green, blue and alpha codes `rgba` (alpha the two-plane
|
||||
/// formats' byte there), with the bits Metal does not read as its writes write them:
|
||||
/// `BGR10_XR`'s bits 30 and 31 ones, plane 0's zero, `BGRA10_XR`'s low 6 bits of each field
|
||||
/// zero.
|
||||
fn texel(self, rgba: [u32; 4]) -> [u32; 4] {
|
||||
let word = rgba[0] << 20 | rgba[1] << 10 | rgba[2];
|
||||
match self {
|
||||
ExtendedRange::Bgr10 { .. } => [0xC000_0000 | word, 0, 0, 0],
|
||||
ExtendedRange::Planes { .. } => [word, rgba[3], 0, 0],
|
||||
ExtendedRange::Bgra10 { .. } => {
|
||||
[rgba[2] << 6, rgba[1] << 6, rgba[0] << 6, rgba[3] << 6]
|
||||
}
|
||||
// Each code in its word's top 10 bits, the low 6 bits zero.
|
||||
ExtendedRange::R10X6 | ExtendedRange::R10X6Srgb => [rgba[0] << 6, 0, 0, 0],
|
||||
ExtendedRange::Rgb10A2Srgb => [
|
||||
rgba[3] << 30 | rgba[2] << 20 | rgba[1] << 10 | rgba[0],
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
],
|
||||
ExtendedRange::Rg10X12 | ExtendedRange::Rg10X12Srgb => {
|
||||
[rgba[0] << 6, rgba[1] << 6, 0, 0]
|
||||
}
|
||||
// A bfloat code a word.
|
||||
ExtendedRange::R16Bfloat => [rgba[0], 0, 0, 0],
|
||||
ExtendedRange::Rg16Bfloat => [rgba[0], rgba[1], 0, 0],
|
||||
ExtendedRange::Rgba16Bfloat => rgba,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The bfloat code of `v` by [`ClearRoute::Straight`]: its `float` rounded to nearest even
|
||||
/// (Rust's conversion), then [`bfloat_nearest_even`]; a NaN the `float` NaN of its sign and top
|
||||
/// 23 payload bits, quieted, cut to its top 16 bits.
|
||||
fn bfloat_of_double(v: f64) -> u32 {
|
||||
if v.is_nan() {
|
||||
let bits = v.to_bits();
|
||||
let sign = ((bits >> 63) as u32) << 31;
|
||||
let payload = ((bits >> 29) & 0x7f_ffff) as u32;
|
||||
return (sign | 0x7fc0_0000 | payload) >> 16;
|
||||
}
|
||||
bfloat_nearest_even(v as f32)
|
||||
}
|
||||
|
||||
/// The bfloat code nearest `v`, ties to even (an overflow past the largest finite code the
|
||||
/// infinity), a NaN the quiet NaN `0x7fc0`.
|
||||
pub(crate) fn bfloat_nearest_even(v: f32) -> u32 {
|
||||
if v.is_nan() {
|
||||
return 0x7fc0;
|
||||
}
|
||||
// No sum passes `u32`: the largest non-NaN bits, `0xff80_0000`, plus `0x8000`.
|
||||
let b = v.to_bits();
|
||||
(b + 0x7fff + ((b >> 16) & 1)) >> 16
|
||||
}
|
||||
|
||||
/// The layout of a two-plane YCbCr format ([`ycbcr_format`]): Metal's texture over an IOSurface's
|
||||
@@ -1736,31 +1632,6 @@ pub fn vk_format(
|
||||
Err(Unsupported::needs_any_of(Feature::Format, alternatives).into())
|
||||
}
|
||||
|
||||
/// The swizzle that reads as component mapping `m` (in `TextureSwizzleChannels::compose`'s
|
||||
/// canonical form over a format's own channels): each channel from the one `m` names, from itself
|
||||
/// where `m` names none, or a constant.
|
||||
fn swizzle_of(m: vk::ComponentMapping) -> TextureSwizzleChannels {
|
||||
use crate::metal::TextureSwizzle as T;
|
||||
use vk::ComponentSwizzle as S;
|
||||
let named = [
|
||||
(S::ZERO, T::Zero),
|
||||
(S::ONE, T::One),
|
||||
(S::R, T::Red),
|
||||
(S::G, T::Green),
|
||||
(S::B, T::Blue),
|
||||
(S::A, T::Alpha),
|
||||
];
|
||||
let channel = |c: vk::ComponentSwizzle, own: T| {
|
||||
named.iter().find(|(s, _)| *s == c).map_or(own, |&(_, t)| t)
|
||||
};
|
||||
TextureSwizzleChannels::new(
|
||||
channel(m.r, T::Red),
|
||||
channel(m.g, T::Green),
|
||||
channel(m.b, T::Blue),
|
||||
channel(m.a, T::Alpha),
|
||||
)
|
||||
}
|
||||
|
||||
/// What `profile` lacks to make an image view whose component mapping is `components`:
|
||||
/// `imageViewFormatSwizzle`, where its portability subset withholds it and the mapping is not the
|
||||
/// identity (`VUID-VkImageViewCreateInfo-imageViewFormatSwizzle-04465`). A swizzled candidate's
|
||||
|
||||
@@ -2350,44 +2350,6 @@ fn a_pass_renders_only_the_ycbcr_formats_whose_store_is_matched() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The probe's clear colors: each 10-bit code's value and each tie between two
|
||||
/// codes, 512 values of its generator, and the specials; color `i` is values `i` to `i + 3`.
|
||||
fn straight_clear_colors() -> Vec<[f64; 4]> {
|
||||
let mut values = Vec::new();
|
||||
for k in 0..1024 {
|
||||
values.push((f64::from(k) - 384.0) / 510.0);
|
||||
values.push((f64::from(k) + 0.5 - 384.0) / 510.0);
|
||||
}
|
||||
let mut seed: u64 = 0x9e37_79b9_7f4a_7c15;
|
||||
for _ in 0..512 {
|
||||
seed = seed
|
||||
.wrapping_mul(6_364_136_223_846_793_005)
|
||||
.wrapping_add(1_442_695_040_888_963_407);
|
||||
let u = (seed >> 11) as f64 / (1u64 << 53) as f64;
|
||||
values.push(-0.9 + 2.3 * u);
|
||||
}
|
||||
values.extend([
|
||||
f64::NEG_INFINITY,
|
||||
-1e30,
|
||||
-65504.0,
|
||||
-2.0,
|
||||
-0.0,
|
||||
0.0,
|
||||
1e-40,
|
||||
6e-8,
|
||||
1e-30,
|
||||
65504.0,
|
||||
1e30,
|
||||
f64::INFINITY,
|
||||
f64::NAN,
|
||||
-f64::NAN,
|
||||
]);
|
||||
let n = values.len();
|
||||
(0..n)
|
||||
.map(|i| std::array::from_fn(|c| values[(i + c) % n]))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The table [`repr`] reads holds [`make_repr`]'s entry of every format, at its raw value.
|
||||
#[test]
|
||||
fn the_format_table_holds_each_format_s_entry() {
|
||||
|
||||
@@ -234,7 +234,6 @@ mod serde_round_trips {
|
||||
replay_bindings: true,
|
||||
merged_draws: true,
|
||||
amplification_draws: Some(AmplificationDraws::new(true, false)),
|
||||
viewport_compensation: Some(ViewportCompensation::new(true)),
|
||||
folded_groups: true,
|
||||
partial_threadgroups: true,
|
||||
extended_range: BTreeMap::from([(
|
||||
@@ -427,7 +426,6 @@ mod serde_round_trips {
|
||||
VaryingKey::viewport_index(),
|
||||
]),
|
||||
absent_varyings: BTreeSet::from([VaryingKey::user(b"generated(5colorDv4_f)")]),
|
||||
viewport_compensation: Some(ViewportCompensation::new(false)),
|
||||
folded_groups: true,
|
||||
partial_threadgroups: true,
|
||||
extended_range: BTreeMap::from([(
|
||||
@@ -1061,14 +1059,6 @@ mod bind_serde_round_trips {
|
||||
viewport_count: 3,
|
||||
function_tables: vec![crate::bind::ArgumentFunctionTable::new(0x7ab1_0001, 9)],
|
||||
tile_threadgroup: tile_threadgroup(),
|
||||
// Clip mode's vertex clamp, unbounded above, which JSON holds as `null`.
|
||||
viewport_compensation: Some(
|
||||
crate::bind::CompensatedViewport::new(
|
||||
ViewportCompensation::new(true).with_vertex_clamp(true),
|
||||
[-1.0, 0.5, 1.5, 1.0],
|
||||
)
|
||||
.with_vertex_clamp([0.0, f32::INFINITY]),
|
||||
),
|
||||
zeroed_colors: BTreeMap::from([(1, metal::PixelFormat::R32Uint)]),
|
||||
dropped_colors: BTreeSet::from([4]),
|
||||
kept_imageblock_bytes: Some(4),
|
||||
@@ -1143,7 +1133,6 @@ mod bind_serde_round_trips {
|
||||
crate::bind::ArgumentFunctionTable::new(3, 0),
|
||||
]),
|
||||
tile_threadgroup: tile_threadgroup(),
|
||||
viewport_compensation: Some(ViewportCompensation::new(false)),
|
||||
zeroed_colors: BTreeMap::from([(1, metal::PixelFormat::R32Uint)]),
|
||||
dropped_colors: BTreeSet::from([4]),
|
||||
kept_imageblock_bytes: Some(4),
|
||||
|
||||
@@ -13,7 +13,7 @@ use crate::pipeline::facts::{Mechanism, RuntimeFact};
|
||||
use crate::pipeline::graphics::GraphicsState;
|
||||
use crate::pipeline::interface::{LevelReads, PipelineInterface, SampledLevels, SnapshotRefusal};
|
||||
use crate::pipeline::layout::PipelineLayout;
|
||||
use crate::pipeline::sym::{SlotRef, SpecKey};
|
||||
use crate::pipeline::sym::SpecKey;
|
||||
use crate::pipeline::vertex::VertexInputState;
|
||||
use crate::vk;
|
||||
|
||||
|
||||
@@ -379,22 +379,6 @@ pub fn function_key(
|
||||
.bytes(format!("{:?}", inputs.absent_varyings).as_bytes());
|
||||
}
|
||||
// Appended only when set.
|
||||
if let Some(c) = inputs.viewport_compensation {
|
||||
h.bytes(b"viewport-compensation").u64(u64::from(c.depth));
|
||||
// Appended only when set.
|
||||
if c.point_guard {
|
||||
h.bytes(b"point-guard");
|
||||
}
|
||||
// Appended only when set.
|
||||
if c.mirrors {
|
||||
h.bytes(b"viewport-mirrors");
|
||||
}
|
||||
// Appended only when set.
|
||||
if c.vertex_clamp {
|
||||
h.bytes(b"viewport-vertex-clamp");
|
||||
}
|
||||
}
|
||||
// Appended only when set.
|
||||
if inputs.folded_groups {
|
||||
h.bytes(b"folded-groups");
|
||||
}
|
||||
|
||||
@@ -709,7 +709,6 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() {
|
||||
.replace(", color_writes: {}", "")
|
||||
.replace(", primitive_varyings: {}", "")
|
||||
.replace(", absent_varyings: {}", "")
|
||||
.replace(", viewport_compensation: None", "")
|
||||
.replace(", folded_groups: false", "")
|
||||
.replace(", partial_threadgroups: false", "")
|
||||
.replace(", extended_range: {}", "")
|
||||
|
||||
@@ -433,22 +433,6 @@ pub enum RuntimeFact {
|
||||
/// writes no viewport index of its own (a mapping offsets the viewport). Its plans state the
|
||||
/// variant the shape's amplification asks for.
|
||||
AmplificationDraws { layered: bool, viewports: bool },
|
||||
/// The vertex function was compiled under `VariantKey::viewport_compensation`
|
||||
/// (`LoweringInputs::viewport_compensation` of `depth`): it negates its position's `x` and,
|
||||
/// under `depth`, rewrites its depth and clips at Metal's planes by the draw's
|
||||
/// `PushField::ViewportCompensation`, which the binder writes from
|
||||
/// `BindState::viewport_compensation`. Its plans state the variant the shape asks for.
|
||||
/// Under `point_guard` it also scales its position by the draw's `PushField::PointGuard`
|
||||
/// and culls a point past Metal's guard band by four clip distances. Under `mirrors` it negates
|
||||
/// `x` by the selected viewport's bit of the draw's `PushField::ViewportMirrors`. Under
|
||||
/// `vertex_clamp` it clamps its compensated depth by the draw's `PushField::VertexDepthClamp`
|
||||
/// before the interpolation, as Metal clamps each vertex's depth.
|
||||
ViewportCompensation {
|
||||
depth: bool,
|
||||
point_guard: bool,
|
||||
mirrors: bool,
|
||||
vertex_clamp: bool,
|
||||
},
|
||||
/// The kernel was compiled under `VariantKey::folded_groups`
|
||||
/// (`LoweringInputs::folded_groups`): it runs a threadgroup dispatch of its own threadgroup
|
||||
/// size whose group counts it reads from the 32-byte region record at its
|
||||
|
||||
@@ -212,9 +212,7 @@ pub struct GraphicsState {
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub flat_fragment_inputs: bool,
|
||||
/// The elements of the vertex function's own `[[clip_distance]]` output, 0 for none (a mesh
|
||||
/// pipeline's too). A draw of points compiled under `ViewportCompensation::point_guard`
|
||||
/// writes four more after them, and two more again under `ViewportCompensation::depth`,
|
||||
/// within `maxClipDistances` and `maxCombinedClipAndCullDistances`.
|
||||
/// pipeline's too).
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub clip_distances: u32,
|
||||
/// Whether the fragment function writes its depth (`[[depth(...)]]`). A draw in depth clamp
|
||||
|
||||
@@ -911,18 +911,6 @@ pub enum PatchDomain {
|
||||
}
|
||||
|
||||
impl PipelineInterface {
|
||||
/// The buffer slots of `stage` (bit `i` for index `i`, below 64) whose form `takes`.
|
||||
fn buffers_where(&self, stage: Stage, takes: impl Fn(BufferForm) -> bool) -> u64 {
|
||||
let mut slots = 0;
|
||||
for (slot, interface) in &self.slots {
|
||||
if let SlotInterface::Buffer(b) = interface {
|
||||
if slot.stage == stage && slot.index < u64::BITS && takes(b.form) {
|
||||
slots |= 1 << slot.index;
|
||||
}
|
||||
}
|
||||
}
|
||||
slots
|
||||
}
|
||||
}
|
||||
|
||||
impl StageInterface {
|
||||
|
||||
@@ -439,21 +439,6 @@ pub struct LoweringInputs {
|
||||
/// attachments; empty for any other function.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub absent_varyings: BTreeSet<VaryingKey>,
|
||||
/// The vertex function's position is compensated for a viewport Vulkan's cannot be
|
||||
/// (`VariantKey::viewport_compensation`): a negative width, or, under
|
||||
/// [`ViewportCompensation::depth`], a depth range past `[0, 1]` on a device that does not take
|
||||
/// one. The function reads the draw's `[sx, a, b, clip]` from `PushField::ViewportCompensation`
|
||||
/// (four `f32`s' bits) and writes `Position` as `(sx x, y, a w + b z, w)`; under `depth` it
|
||||
/// also writes two `ClipDistance` elements after its own, `z` and `w - z` where `clip` is 1
|
||||
/// (Metal's near and far planes) and 1 where it is 0. Under
|
||||
/// [`ViewportCompensation::point_guard`] it reads the draw's `[gx, gy]` from
|
||||
/// `PushField::PointGuard` (two `f32`s' bits), writes `Position` as `(gx sx x, gy y, ..)`, and
|
||||
/// writes four `ClipDistance` elements after the others: `1.5 w - x`, `1.5 w + x`, `1.5 w - y`
|
||||
/// and `1.5 w + y`, of the function's own `x` and `y`. It states
|
||||
/// `RuntimeFact::ViewportCompensation`. A post-tessellation vertex function is compensated
|
||||
/// as a vertex function is; any other function compiles as without it.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub viewport_compensation: Option<ViewportCompensation>,
|
||||
/// The kernel runs a threadgroup dispatch whose group counts are GPU data
|
||||
/// (`dispatchThreadgroupsWithIndirectBuffer:`) as one Vulkan dispatch within the device's
|
||||
/// group-count limits, whatever the counts (`VariantKey::folded_groups`): Vulkan workgroup
|
||||
@@ -903,8 +888,8 @@ pub struct LoweringInputs {
|
||||
/// (`merged_draws`) takes it too, its corner from its `VertexIndex` and `InstanceIndex` as
|
||||
/// without it, and so does a draw replay's of one draw per command (`replay_bindings`). A
|
||||
/// function that writes its own `[[viewport_array_index]]` or
|
||||
/// `[[render_target_array_index]]`, one compiled under `amplification_draws` or
|
||||
/// `viewport_compensation`, and a post-tessellation vertex function, is
|
||||
/// `[[render_target_array_index]]`, one compiled under `amplification_draws`, and a
|
||||
/// post-tessellation vertex function, is
|
||||
/// `NotImplemented(RasterizationRateMap)` under it: the
|
||||
/// runtime draws those region by region. The vertex function states `RuntimeFact::RegionViewports`. A
|
||||
/// fragment function compiled under it (behind such a vertex function, where it reads
|
||||
@@ -931,7 +916,7 @@ pub struct LoweringInputs {
|
||||
/// `VertexIndex` and `InstanceIndex` as without it, and so does a draw replay's of one draw
|
||||
/// per command (`replay_bindings`). A function that writes its own
|
||||
/// `[[viewport_array_index]]` or `[[render_target_array_index]]`, one compiled under
|
||||
/// `amplification_draws` or `viewport_compensation`, a post-tessellation vertex function and
|
||||
/// `amplification_draws`, a post-tessellation vertex function and
|
||||
/// one that returns no outputs are `NotImplemented(RasterizationRateMap)` under it: the runtime draws those region by region
|
||||
/// through each region's viewport. Any other stage compiles as without it.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
@@ -1232,69 +1217,6 @@ impl AmplificationDraws {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a vertex function compiled for a viewport Vulkan's cannot be compensates its position
|
||||
/// (`LoweringInputs::viewport_compensation`, `VariantKey::viewport_compensation`).
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct ViewportCompensation {
|
||||
/// The depth too: the function rewrites `z` and writes the two clip distances, for a depth
|
||||
/// range past `[0, 1]` the Vulkan viewport cannot hold. Without it only `x` is negated (a
|
||||
/// negative width), and the function declares no clip distance of its own.
|
||||
pub depth: bool,
|
||||
/// Metal's guard band for points too: the function scales its position's `x` and `y` by the
|
||||
/// draw's `PushField::PointGuard`, for a draw of points through Vulkan viewports widened by the
|
||||
/// inverse scale about their centers, and writes four clip distances after the others, which
|
||||
/// cull a point where Metal does, its `|x|` or `|y|` past `1.5 w`.
|
||||
pub point_guard: bool,
|
||||
/// Mirrored and unmirrored viewports in one draw: the function negates its position's `x` where
|
||||
/// the viewport it selects (the `ViewportIndex` it stores, or the amplification's, else the
|
||||
/// first) has its bit set in the draw's `PushField::ViewportMirrors`, on top of `sx`.
|
||||
pub mirrors: bool,
|
||||
/// Metal's clamp of each vertex's depth before the interpolation, under `depth`: the function
|
||||
/// clamps its compensated depth `a w + b z` to `[lo w, hi w]` of the draw's
|
||||
/// `PushField::VertexDepthClamp` `[lo, hi]` where `w` is positive, so the device interpolates
|
||||
/// the vertices' clamped depths, as Metal does, where it would clamp each sample. The clip
|
||||
/// distances take the unclamped `z`.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub vertex_clamp: bool,
|
||||
}
|
||||
|
||||
impl ViewportCompensation {
|
||||
/// The compensation of the position's `x`, and of its depth where `depth`.
|
||||
pub fn new(depth: bool) -> ViewportCompensation {
|
||||
ViewportCompensation {
|
||||
depth,
|
||||
point_guard: false,
|
||||
mirrors: false,
|
||||
vertex_clamp: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// This compensation, with Metal's guard band for points where `point_guard`.
|
||||
pub fn with_point_guard(self, point_guard: bool) -> ViewportCompensation {
|
||||
ViewportCompensation {
|
||||
point_guard,
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// This compensation, negating `x` by the selected viewport's bit of the draw's mirrors where
|
||||
/// `mirrors`.
|
||||
pub fn with_mirrors(self, mirrors: bool) -> ViewportCompensation {
|
||||
ViewportCompensation { mirrors, ..self }
|
||||
}
|
||||
|
||||
/// This compensation, clamping each vertex's depth by the draw's
|
||||
/// `PushField::VertexDepthClamp` where `vertex_clamp`.
|
||||
pub fn with_vertex_clamp(self, vertex_clamp: bool) -> ViewportCompensation {
|
||||
ViewportCompensation {
|
||||
vertex_clamp,
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The render pipeline state a fragment function's interlocked framebuffer fetch depends on
|
||||
/// (`LoweringInputs::framebuffer_fetch`).
|
||||
#[non_exhaustive]
|
||||
|
||||
@@ -137,7 +137,6 @@ pub use lower_inputs::{
|
||||
AliasView, AmplificationDraws, BlendEquation, ChannelWrite, ColorGroup, ExtendedRangeColor,
|
||||
FactorLane, FetchedAttachment, FramebufferFetchInputs, LoweringInputs, RotatedBlendForm,
|
||||
StorageImageChoice, StorageImageClass, VertexFetch, VertexFetchProjection,
|
||||
ViewportCompensation,
|
||||
};
|
||||
pub use table::FunctionHandle;
|
||||
// The vocabulary the pipeline surface reaches: render-pipeline keys, runtime facts and their
|
||||
|
||||
@@ -1183,32 +1183,11 @@ pub enum PushField {
|
||||
/// `[[stage_in]]` layout of `MTLBufferLayoutStrideDynamic` fetches at
|
||||
/// (`RuntimeFact::StageInStride`).
|
||||
StageInStride(u32),
|
||||
/// The draw's viewport compensation for a vertex function compiled under
|
||||
/// `LoweringInputs::viewport_compensation` (`RuntimeFact::ViewportCompensation`): one
|
||||
/// `uvec4` holding the bits of four `f32`s, `[sx, a, b, clip]`, which the function applies to
|
||||
/// its position as `(sx x, y, a w + b z, w)`, clipping at `z` and `w - z` where `clip` is 1
|
||||
/// (`BindState::viewport_compensation`).
|
||||
ViewportCompensation,
|
||||
/// The draw's point guard band for a vertex function compiled under
|
||||
/// `ViewportCompensation::point_guard`: one `uvec2` holding the bits of two `f32`s,
|
||||
/// `[gx, gy]`, the inverse powers of two its Vulkan viewports are widened by, which the
|
||||
/// function scales its position's `x` and `y` by (`CompensatedViewport::guard`).
|
||||
PointGuard,
|
||||
/// The draw's depth clamp range for a fragment function compiled under
|
||||
/// `LoweringInputs::depth_clamp_range` (`RuntimeFact::DepthClampRange`): one `uvec2` holding
|
||||
/// the bits of two `f32`s, `[low, high]`, which the function clamps the depth it writes to
|
||||
/// after Metal's `[0, 1]` (`BindState::depth_clamp_range`).
|
||||
DepthClampRange,
|
||||
/// The draw's mirrored viewports for a vertex function compiled under
|
||||
/// `ViewportCompensation::mirrors`: one `u32` whose bit `i` is set where viewport `i` has a
|
||||
/// negative width, which the function negates its position's `x` by for the viewport it
|
||||
/// selects (`CompensatedViewport::mirrors`).
|
||||
ViewportMirrors,
|
||||
/// The draw's clamp of each vertex's depth for a vertex function compiled under
|
||||
/// `ViewportCompensation::vertex_clamp`: one `uvec2` holding the bits of two `f32`s,
|
||||
/// `[lo, hi]`, which the function clamps its compensated depth's `z / w`, the Vulkan
|
||||
/// viewport's normalized depth, to before the interpolation (`CompensatedViewport::vertex_clamp`).
|
||||
VertexDepthClamp,
|
||||
/// The draw's depth state for a fragment function that runs the draw's depth test itself
|
||||
/// (`RuntimeFact::ShaderTests`), a `uvec4`: word 0 holds the depth `MTLCompareFunction` in
|
||||
/// bits 0 to 2, whether depth writes are enabled in bit 3, and whether the encoder's depth
|
||||
|
||||
@@ -5,16 +5,13 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use super::{diff, fixture};
|
||||
use crate::bind::{ArgumentBufferLayout, ArgumentLayoutError, ArgumentType};
|
||||
use crate::bind::{ArgumentBufferLayout, ArgumentType};
|
||||
use crate::budget::Budget;
|
||||
use crate::error::{DiagName, Error, Feature};
|
||||
use crate::library::{FunctionConstantValues, Library};
|
||||
use crate::metal::{BindingAccess, DataType};
|
||||
use crate::pipeline::testing::{fixtures_dir, AssembleError};
|
||||
use crate::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource};
|
||||
use crate::reflection::{
|
||||
Binding, BufferBinding, PointerType, StructMember, StructType, TypeDetail,
|
||||
};
|
||||
use crate::reflection::Binding;
|
||||
|
||||
const FUNCTION: &str = "reflection_argument_buffers";
|
||||
|
||||
|
||||
@@ -27,10 +27,7 @@ use crate::cache::Hash256;
|
||||
use crate::device::{DeviceDescription, DevicePolicy};
|
||||
use crate::library::{FunctionConstantValues, Library};
|
||||
use crate::metal::PixelFormat;
|
||||
use crate::pipeline::{
|
||||
ColorAttachmentDescriptor, ComputePipelineDescriptor, FunctionDescriptor, PrivateRenderState,
|
||||
RenderPipelineDescriptor, StageSource, TileRenderPipelineDescriptor,
|
||||
};
|
||||
use crate::pipeline::FunctionDescriptor;
|
||||
|
||||
/// The device a runtime bundle's command compiles for, as `device.json` holds it and the command
|
||||
/// line's `--device` reads it: the description and policy the runtime's compile device was built
|
||||
@@ -114,56 +111,6 @@ impl<'a> ReproBundle<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The bundle of `library`'s bytes, which its content hash names.
|
||||
fn of_library(library: &'a Library) -> ReproBundle<'a> {
|
||||
let bytes = library.bytes();
|
||||
ReproBundle::hashed(input_name(bytes).to_owned(), bytes, *library.content_hash())
|
||||
}
|
||||
|
||||
/// The bundle of the stage `function`'s library, naming the function and its constant
|
||||
/// values, on the device of `device`.
|
||||
fn of_function(device: &[u8], function: &'a FunctionDescriptor) -> ReproBundle<'a> {
|
||||
let FunctionDescriptor {
|
||||
function,
|
||||
constants,
|
||||
specialized: _,
|
||||
linked,
|
||||
libraries,
|
||||
} = function;
|
||||
let mut bundle = ReproBundle::of_library(function.library())
|
||||
.device(device)
|
||||
.options(["--function", function.info().name]);
|
||||
let mut unreplayed = Unreplayed::default();
|
||||
bundle = bundle.options(constant_options(constants, &mut unreplayed));
|
||||
unreplayed.links(
|
||||
function.info().name,
|
||||
linked.is_empty(),
|
||||
libraries.is_empty(),
|
||||
);
|
||||
bundle.unreplayed.extend(unreplayed.0);
|
||||
bundle
|
||||
}
|
||||
|
||||
/// This bundle with `device` its `device.json`, which its command reads.
|
||||
fn device(self, device: &[u8]) -> ReproBundle<'a> {
|
||||
self.file("device.json", device.to_vec())
|
||||
.options(["--device", "device.json"])
|
||||
}
|
||||
|
||||
/// This bundle with `value` as JSON in the file `name`, which its command names with `flag`.
|
||||
fn json(self, flag: &str, name: &str, value: &impl serde::Serialize) -> ReproBundle<'a> {
|
||||
match serde_json::to_vec_pretty(value) {
|
||||
Ok(bytes) => self.file(name, bytes).options([flag, name]),
|
||||
Err(e) => {
|
||||
let mut bundle = self;
|
||||
bundle
|
||||
.unreplayed
|
||||
.push(format!("{flag}: not serialized: {e}"));
|
||||
bundle
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The command that replays the failure, run in the bundle's directory.
|
||||
pub fn command(&self) -> String {
|
||||
let mut words = vec![
|
||||
@@ -281,103 +228,6 @@ impl<'a> ReproBundle<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a command does not replay of a request.
|
||||
#[derive(Default)]
|
||||
struct Unreplayed(Vec<String>);
|
||||
|
||||
impl Unreplayed {
|
||||
/// `field`, where its `value` is not Metal's default `default`.
|
||||
fn field<T: PartialEq + std::fmt::Debug>(&mut self, field: &str, value: &T, default: &T) {
|
||||
if value != default {
|
||||
self.0.push(format!("{field}: {value:?}"));
|
||||
}
|
||||
}
|
||||
|
||||
fn note(&mut self, note: impl Into<String>) {
|
||||
self.0.push(note.into());
|
||||
}
|
||||
|
||||
/// The linked functions and dynamic libraries of the stage function `function`, where it has
|
||||
/// them: the command line links none.
|
||||
fn links(&mut self, function: &str, no_linked: bool, no_libraries: bool) {
|
||||
if !no_linked {
|
||||
self.note(format!("`{function}`'s linked functions"));
|
||||
}
|
||||
if !no_libraries {
|
||||
self.note(format!("`{function}`'s dynamic libraries"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The command line's `--constant` options of `constants`: `ID:TYPE:COMPONENTS`, each component
|
||||
/// its raw bits (`0x`). A value the option cannot state is noted in `unreplayed`.
|
||||
fn constant_options(
|
||||
constants: &FunctionConstantValues,
|
||||
unreplayed: &mut Unreplayed,
|
||||
) -> Vec<String> {
|
||||
let FunctionConstantValues { by_index, by_name } = constants;
|
||||
// The command line reads an ID of digits as an index: a name of digits is not stated.
|
||||
let ids = by_index
|
||||
.iter()
|
||||
.map(|(index, value)| (index.to_string(), value, false))
|
||||
.chain(
|
||||
by_name
|
||||
.iter()
|
||||
.map(|(name, value)| (name.clone(), value, name.parse::<u32>().is_ok())),
|
||||
);
|
||||
let mut options = Vec::new();
|
||||
for (id, value, named_as_index) in ids {
|
||||
let name = value.ty.name();
|
||||
let ty = name.strip_prefix("MTLDataType").unwrap_or(name);
|
||||
let lanes = match ty.as_bytes().last() {
|
||||
Some(digit @ b'2'..=b'4') => usize::from(digit - b'0'),
|
||||
_ => 1,
|
||||
};
|
||||
let width = value.bytes.len() / lanes;
|
||||
if named_as_index
|
||||
|| id.contains(':')
|
||||
|| value.bytes.len() != width * lanes
|
||||
|| !matches!(width, 1 | 2 | 4 | 8)
|
||||
{
|
||||
unreplayed.note(format!("constant `{id}`: {value:?}"));
|
||||
continue;
|
||||
}
|
||||
let components: Vec<String> = value
|
||||
.bytes
|
||||
.chunks(width)
|
||||
.map(|chunk| {
|
||||
let mut word = [0u8; 8];
|
||||
word[..width].copy_from_slice(chunk);
|
||||
format!("0x{:x}", u64::from_le_bytes(word))
|
||||
})
|
||||
.collect();
|
||||
options.push("--constant".to_owned());
|
||||
options.push(format!("{id}:{ty}:{}", components.join(",")));
|
||||
}
|
||||
options
|
||||
}
|
||||
|
||||
/// The command line's `INDEX:FORMAT` of color attachment `index`.
|
||||
fn color_format(index: usize, format: PixelFormat) -> String {
|
||||
format!("{index}:{}", format_name(format))
|
||||
}
|
||||
|
||||
/// A pixel format's Metal name without its `MTLPixelFormat` prefix.
|
||||
fn format_name(format: PixelFormat) -> &'static str {
|
||||
let name = format.name();
|
||||
name.strip_prefix("MTLPixelFormat").unwrap_or(name)
|
||||
}
|
||||
|
||||
/// The input file's name for `bytes`: a metallib's, AIR bitcode's (wrapped or raw), or other
|
||||
/// bytes'.
|
||||
fn input_name(bytes: &[u8]) -> &'static str {
|
||||
match bytes.get(..4) {
|
||||
Some(b"MTLB") => "input.metallib",
|
||||
Some([0xde, 0xc0, 0x17, 0x0b]) | Some([b'B', b'C', 0xc0, 0xde]) => "input.air",
|
||||
_ => "input.bin",
|
||||
}
|
||||
}
|
||||
|
||||
/// `args` as one shell command line, each quoted where it needs it.
|
||||
pub fn shell_join(args: &[String]) -> String {
|
||||
args.iter()
|
||||
|
||||
@@ -5,14 +5,13 @@
|
||||
|
||||
use crate::bind::{
|
||||
ArgumentFunctionTable, ArgumentSampler, BindState, BoundBuffer, BoundSampler, BoundTexture,
|
||||
BufferRanges, CompensatedViewport, FragmentTests, ImageblockSize, ResourceClass,
|
||||
SamplerDescriptor, StageTable, TessellationFactorBuffer, TessellationFactors, TextureFacts,
|
||||
TileThreadgroupArgument, TileThreadgroupMemory, UsedResource, VertexAmplification,
|
||||
BufferRanges, FragmentTests, ImageblockSize, ResourceClass, SamplerDescriptor, StageTable,
|
||||
TessellationFactorBuffer, TessellationFactors, TextureFacts, TileThreadgroupArgument,
|
||||
TileThreadgroupMemory, UsedResource, VertexAmplification,
|
||||
};
|
||||
use crate::metal::{
|
||||
CompareFunction, PixelFormat, RenderStages, ResourceUsage, SamplerMinMagFilter, TextureType,
|
||||
};
|
||||
use crate::pipeline::lower_inputs::ViewportCompensation;
|
||||
use crate::pipeline::sym::Stage;
|
||||
|
||||
/// A buffer of `length` bytes bound at `offset`.
|
||||
@@ -240,15 +239,6 @@ fn states() -> Vec<BindState> {
|
||||
.insert(0, TileThreadgroupArgument::new(64, 0));
|
||||
s.tile_threadgroup = memory;
|
||||
}),
|
||||
with(|s| {
|
||||
s.viewport_compensation = Some(CompensatedViewport {
|
||||
compensation: ViewportCompensation {
|
||||
depth: true,
|
||||
..ViewportCompensation::default()
|
||||
},
|
||||
..CompensatedViewport::default()
|
||||
});
|
||||
}),
|
||||
with(|s| {
|
||||
s.zeroed_colors.insert(1, PixelFormat::RGBA8Unorm);
|
||||
}),
|
||||
|
||||
@@ -627,17 +627,6 @@ fn inttoptr_resolves_addresses_of_large_sets() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The entries `(host, guest, size)` of a resident set uploaded apart from its root table.
|
||||
fn resident_entries(resident: &[(u64, u64, u64)]) -> Vec<u8> {
|
||||
let mut bytes = Vec::with_capacity(32 * resident.len());
|
||||
for &(h, g, s) in resident {
|
||||
for v in [h, g, s, 0] {
|
||||
bytes.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// A linked-list walk: the head is the `[[buffer(0)]]` parameter and each next pointer is loaded
|
||||
/// from the current node, so the loop's pointer phi merges the parameter with loaded pointers.
|
||||
/// The parameter's slot is reached through its root entry (`Psb`, `DeviceAddresses`) and the phi
|
||||
|
||||
@@ -72,20 +72,6 @@ const FORMATS: [(PixelFormat, ExtendedRange); 6] = [
|
||||
),
|
||||
];
|
||||
|
||||
/// A kernel writing `float4` `src[gid.x + 32 gid.y]` (buffer 0) to `texture2d<float,
|
||||
/// access::write>` slot 1 at `gid`.
|
||||
const WRITE: &str = r#"define void @k(ptr addrspace(1) %src, ptr addrspace(1) %w, <2 x i32> %gid) {
|
||||
%x = extractelement <2 x i32> %gid, i64 0
|
||||
%y = extractelement <2 x i32> %gid, i64 1
|
||||
%row = shl i32 %y, 5
|
||||
%n = add i32 %x, %row
|
||||
%i = zext i32 %n to i64
|
||||
%p = getelementptr inbounds <4 x float>, ptr addrspace(1) %src, i64 %i
|
||||
%v = load <4 x float>, ptr addrspace(1) %p, align 16
|
||||
call void @air.write_texture_2d.v4f32(ptr addrspace(1) %w, <2 x i32> %gid, <4 x float> %v, i32 0, i32 2)
|
||||
ret void
|
||||
}
|
||||
|
||||
declare void @air.write_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, <4 x float>, i32, i32)
|
||||
|
||||
!air.kernel = !{!0}
|
||||
@@ -97,23 +83,6 @@ declare void @air.write_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, <4 x float
|
||||
!5 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"gid"}
|
||||
"#;
|
||||
|
||||
/// The `half` bits of lane `l` of batch `b`: every fourth pattern from 0 to past 2.5, positive in
|
||||
/// the even batches and negative in the odd ones, the first lanes NaN, the infinities, the
|
||||
/// largest finite `half`s, zeros and one.
|
||||
fn half_lane(b: u32, l: u32) -> u16 {
|
||||
const SPECIAL: [u16; 10] = [
|
||||
0x7e00, 0x7c00, 0xfc00, 0x7bff, 0xfbff, 0x0000, 0x8000, 0x3c00, 0x3e00, 0x4000,
|
||||
];
|
||||
if b == 0 && (l as usize) < SPECIAL.len() {
|
||||
return SPECIAL[l as usize];
|
||||
}
|
||||
let bits = ((b / 2) * 4 * SIDE * SIDE + 4 * l + b % 4) as u16;
|
||||
match b % 2 {
|
||||
0 => bits,
|
||||
_ => bits | 0x8000,
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture() -> Option<Vec<u8>> {
|
||||
match llvm_assemble(&engine_dir().join("rt6_samples.ll")) {
|
||||
Ok(b) => Some(b),
|
||||
|
||||
@@ -29,7 +29,7 @@ use std::path::Path;
|
||||
use crate::bind::{
|
||||
sampler_desc, AccessClass, BindState, BindingPlan, BoundBuffer, BoundSampler, BoundTexture,
|
||||
Dispatch, DrawCall, DrawCommands, FieldLocation, ImageSource, IndexBufferRef, IndexOverrun,
|
||||
IndirectRef, NeutralResource, PlanDiagnostic, SamplerDescriptor, SamplerSource, SlotRebinds,
|
||||
IndirectRef, NeutralResource, PlanDiagnostic, SamplerDescriptor, SamplerSource,
|
||||
StageTable, TextureFacts, UseTarget, WriteSource,
|
||||
};
|
||||
use crate::budget::Budget;
|
||||
@@ -1471,7 +1471,7 @@ fn sampled_textures_and_runtime_samplers() {
|
||||
let plan = p.plan(&dev, &empty.shape()).expect("unbound");
|
||||
match combined(&plan)[0] {
|
||||
(
|
||||
ImageSource::Neutral(n @ NeutralResource::Image { view_type, .. }),
|
||||
ImageSource::Neutral(NeutralResource::Image { view_type, .. }),
|
||||
SamplerSource::Neutral(NeutralResource::Sampler { compare: false }),
|
||||
) => {
|
||||
assert_eq!(view_type, vk::ImageViewType::TYPE_2D, "{stem}");
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
//! What a kernel's `float` write to a storage texture records of the device's half-float and
|
||||
//! small-float conversion, under the key the runtime compiles it under for the texture it binds.
|
||||
//!
|
||||
//! The fixture `hsw_storage_writes`' `hsw_write` and `hsw_read_write` write texture slot 0, and
|
||||
//! `hsw_buffer` writes a texture buffer there. On a device that writes such a texture without a
|
||||
//! format, the binder names no storage choice for a half-float texture (the default formatless
|
||||
//! declaration serves it), so the dispatch runs the module compiled with none. That module records
|
||||
//! what the write leaves to the device under the class of the format bound at the slot
|
||||
//! (`SpecKey::BoundTexelFormat`), which the runtime reads at each dispatch
|
||||
//! (`StageModule::bound_format_clauses`): bound in a half-float format, the NaN
|
||||
//! (`PrecisionNote::DeviceNanEncoding`) and the rounding (`PrecisionNote::DeviceColorConversion`),
|
||||
//! on every profile, requiring no `VkProperty::MetalHalfStorage*`; bound in `RG11B10Float`, the
|
||||
//! NaN on every profile; bound in a format that holds no NaN, no NaN note.
|
||||
//!
|
||||
//! `llvm-as` assembles the fixture; without it the tests skip visibly.
|
||||
|
||||
use crate::bind::{BindState, BoundBuffer, BoundTexture, StageTable, TextureFacts};
|
||||
use crate::budget::Budget;
|
||||
use crate::device::requirements::VkProperty;
|
||||
use crate::device::{Device, DevicePolicy};
|
||||
use crate::error::Error;
|
||||
use crate::library::Library;
|
||||
use crate::metal::format::bound_texel_format;
|
||||
use crate::metal::{PixelFormat, TextureType, TextureUsage};
|
||||
use crate::pipeline::artifact::{PrecisionNote, StageModule};
|
||||
use crate::pipeline::sym::{SlotClass, SlotRef, Stage};
|
||||
use crate::pipeline::testing::{engine_dir, llvm_assemble, AssembleError};
|
||||
use crate::pipeline::{ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor};
|
||||
use crate::pipeline::{LoweringInputs, StageSource};
|
||||
use crate::spirv::testing::committed_descriptions;
|
||||
|
||||
/// The written texture's slot.
|
||||
const SLOT: SlotRef = SlotRef {
|
||||
stage: Stage::Kernel,
|
||||
class: SlotClass::Texture,
|
||||
index: 0,
|
||||
};
|
||||
|
||||
/// The half-float formats.
|
||||
const HALVES: [PixelFormat; 3] = [
|
||||
PixelFormat::R16Float,
|
||||
PixelFormat::RG16Float,
|
||||
PixelFormat::RGBA16Float,
|
||||
];
|
||||
|
||||
fn fixture() -> Option<Vec<u8>> {
|
||||
match llvm_assemble(&engine_dir().join("hsw_storage_writes.ll")) {
|
||||
Ok(b) => Some(b),
|
||||
Err(AssembleError::Missing(why)) => {
|
||||
eprintln!("SKIPPED: {why}");
|
||||
None
|
||||
}
|
||||
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected hsw_storage_writes: {why}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `entry` compiled into a compute pipeline for `dev` under `inputs`, or `None` where the device
|
||||
/// needs the storage slot's format as an input.
|
||||
fn pipeline(
|
||||
dev: &Device,
|
||||
bc: &[u8],
|
||||
entry: &str,
|
||||
inputs: &LoweringInputs,
|
||||
) -> Option<ComputePipeline> {
|
||||
let lib = Library::from_air(bc).expect("library");
|
||||
let f = lib.function(entry).expect("function");
|
||||
let compiled =
|
||||
match dev.compile_function(&FunctionDescriptor::new(f), inputs, &Budget::standard()) {
|
||||
Ok(c) => c,
|
||||
Err(Error::NeedsInput(_)) => return None,
|
||||
Err(e) => panic!("{entry}: {e}"),
|
||||
};
|
||||
Some(
|
||||
dev.compile_compute_pipeline(
|
||||
&ComputePipelineDescriptor::new(StageSource::Compiled(compiled)),
|
||||
&Budget::standard(),
|
||||
)
|
||||
.expect("pipeline"),
|
||||
)
|
||||
}
|
||||
|
||||
/// A kernel's state: texture slot 0 holding a writable texture of `pf` (a texture buffer where
|
||||
/// `buffer`), buffers 0 and 1.
|
||||
fn state(pf: PixelFormat, buffer: bool) -> BindState {
|
||||
let kind = match buffer {
|
||||
true => TextureType::TextureBuffer,
|
||||
false => TextureType::Type2D,
|
||||
};
|
||||
let mut facts = TextureFacts::new(kind, pf);
|
||||
facts.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE;
|
||||
let mut t = StageTable::default();
|
||||
t.textures.insert(
|
||||
0,
|
||||
BoundTexture::Texture {
|
||||
facts,
|
||||
resource_id: None,
|
||||
},
|
||||
);
|
||||
for (index, gpu_address) in [(0, 0x1_0000), (1, 0x2_0000)] {
|
||||
t.buffers.insert(
|
||||
index,
|
||||
BoundBuffer::Buffer {
|
||||
length: 65536,
|
||||
offset: 0,
|
||||
gpu_address,
|
||||
device_address: None,
|
||||
attribute_stride: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
let mut s = BindState::default();
|
||||
s.stages.insert(Stage::Kernel, t);
|
||||
s
|
||||
}
|
||||
@@ -13,7 +13,7 @@
|
||||
//! - A fragment function compiled under it that reads `[[viewport_array_index]]` reads 0 and
|
||||
//! declares no `ViewportIndex`.
|
||||
//! - A vertex function that selects its own viewport, a post-tessellation one, and one under
|
||||
//! draws of one amplification each or a viewport compensation is
|
||||
//! draws of one amplification each is
|
||||
//! `NotImplemented(RasterizationRateMap)`; a device without `shaderDrawParameters` names the
|
||||
//! three features the variant needs.
|
||||
//! - A render plan whose shape asks for it states the variant, which the pipeline compiled
|
||||
@@ -36,7 +36,7 @@ use crate::pipeline::descriptor::{
|
||||
};
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::pipeline::link::{link, LinkInputs};
|
||||
use crate::pipeline::lower_inputs::{AmplificationDraws, LoweringInputs, ViewportCompensation};
|
||||
use crate::pipeline::lower_inputs::{AmplificationDraws, LoweringInputs};
|
||||
use crate::pipeline::relocate::relocate;
|
||||
use crate::pipeline::stage_io::StageBuiltin;
|
||||
use crate::pipeline::testing::{compile_with, engine_dir, llvm_assemble, AssembleError};
|
||||
@@ -190,12 +190,6 @@ fn region_viewports_refuse_what_is_drawn_region_by_region() {
|
||||
viewports: true,
|
||||
});
|
||||
assert_eq!(refusal(&viewports, "rfb_full", &lified), not_implemented);
|
||||
let mut compensated = inputs(true);
|
||||
compensated.viewport_compensation = Some(ViewportCompensation::new(true));
|
||||
assert_eq!(
|
||||
refusal(&viewports, "rfb_full", &compensated),
|
||||
not_implemented
|
||||
);
|
||||
let mut desc = description("lavapipe");
|
||||
assert!(desc.features.remove(&F::ShaderDrawParameters));
|
||||
let without = profile_of(desc);
|
||||
|
||||
@@ -1,581 +0,0 @@
|
||||
//! A vertex function compiled for a viewport Vulkan's cannot be
|
||||
//! (`LoweringInputs::viewport_compensation`), over the owned fixtures `engine/rfb_viewports`
|
||||
//! (Metal's fullscreen triangle), `engine/stage_io` (a bare position return, and a position
|
||||
//! beside two clip distances of the function's own) and `engine/vertex_amplification` (a
|
||||
//! post-tessellation vertex function):
|
||||
//!
|
||||
//! - Compensated, the function states `RuntimeFact::ViewportCompensation` and reads
|
||||
//! `PushField::ViewportCompensation` in its push window. Under the depth's compensation it
|
||||
//! writes two `ClipDistance` elements after its own: two where it has none, four beside its
|
||||
//! two. Under Metal's guard band for points it reads `PushField::PointGuard` too and writes four
|
||||
//! more after those.
|
||||
//! - Every module passes L3 (`spirv-val` and requirements within the profile), and the words the
|
||||
//! compensation adds are bounded: measured, 73 to 91 for `x` alone and 179 to 211 with the
|
||||
//! depth (the push block's declaration among them where the function had none). The common
|
||||
//! path, compiled without it, is unchanged.
|
||||
//! - The depth's compensation needs `shaderClipDistance` and two clip distances beyond the
|
||||
//! function's own within `maxClipDistances` and `maxCombinedClipAndCullDistances`, and the
|
||||
//! point guard band four, refused typed otherwise; the negation of `x` alone needs neither.
|
||||
//! - A render plan whose shape asks for a compensation states its variant, which the pipeline
|
||||
//! compiled without it does not draw (`BindError::NeedsVariant`); compiled, the variant's
|
||||
//! modules pass L3, it states the fact, its plan settles on itself, and the draw's push data
|
||||
//! holds the state's four values at the vertex function's field, and the guard's two at its
|
||||
//! own.
|
||||
//! - Under the mirrors of viewports in one draw the function reads `PushField::ViewportMirrors`
|
||||
//! (one `u32`) too, through the viewport index it stores (`engine/rt6_viewports`'
|
||||
//! `rt6_select`) or the first where it stores none, and the draw's push data holds the state's
|
||||
//! bits there.
|
||||
//! - Under Metal's clamp of each vertex's depth a compensated depth reads
|
||||
//! `PushField::VertexDepthClamp` (two `f32`s) too, and the draw's push data holds the state's
|
||||
//! bounds there; without the depth's compensation nothing is clamped and nothing read.
|
||||
//!
|
||||
//! `llvm-as` assembles the fixtures; a missing tool skips visibly. No GPU is used.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::bind::{BindState, CompensatedViewport, DrawCall};
|
||||
use crate::budget::Budget;
|
||||
use crate::device::requirements::{VkFeature as F, VkLimit};
|
||||
use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile};
|
||||
use crate::error::{BindError, Capability, Error, Feature, Unsupported};
|
||||
use crate::library::{FunctionArtifact, Library};
|
||||
use crate::pipeline::descriptor::{FunctionDescriptor, RenderPipelineDescriptor, StageSource};
|
||||
use crate::pipeline::facts::RuntimeFact;
|
||||
use crate::pipeline::interface::PushLoc;
|
||||
use crate::pipeline::link::{link, LinkInputs};
|
||||
use crate::pipeline::lower_inputs::{LoweringInputs, ViewportCompensation};
|
||||
use crate::pipeline::relocate::relocate;
|
||||
use crate::pipeline::stage_io::StageBuiltin;
|
||||
use crate::pipeline::sym::{PushField, Stage};
|
||||
use crate::pipeline::testing::{compile_with, engine_dir, llvm_assemble, AssembleError};
|
||||
use crate::spirv::testing::check_words_valid;
|
||||
|
||||
/// The bitcode of the owned fixture `stem` (`engine/<stem>.ll`), or `None` (printed) where
|
||||
/// `llvm-as` is missing.
|
||||
fn fixture(stem: &str) -> Option<Vec<u8>> {
|
||||
match llvm_assemble(&engine_dir().join(format!("{stem}.ll"))) {
|
||||
Ok(b) => Some(b),
|
||||
Err(AssembleError::Missing(why)) => {
|
||||
eprintln!("SKIPPED: {why}");
|
||||
None
|
||||
}
|
||||
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {stem}.ll: {why}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn description(stem: &str) -> DeviceDescription {
|
||||
let 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");
|
||||
DeviceDescription::from_khronos_json(&text, None).expect("description")
|
||||
}
|
||||
|
||||
fn profile_of(desc: DeviceDescription) -> DeviceProfile {
|
||||
Device::from_queries(desc, DevicePolicy::default())
|
||||
.expect("device")
|
||||
.profile()
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// The lowering inputs of `compensation`.
|
||||
fn inputs(compensation: Option<ViewportCompensation>) -> LoweringInputs {
|
||||
let mut inputs = LoweringInputs::new();
|
||||
inputs.viewport_compensation = compensation;
|
||||
inputs
|
||||
}
|
||||
|
||||
/// Link `a` alone, relocate it, and run L3; its relocated words.
|
||||
fn validate(a: &FunctionArtifact, p: &DeviceProfile) -> Vec<u32> {
|
||||
let linked = link(&[a], &LinkInputs::standalone(), p).unwrap_or_else(|e| panic!("link: {e}"));
|
||||
let words = relocate(a, &linked.table).expect("relocate");
|
||||
check_words_valid(&words, &a.requirements, p).unwrap_or_else(|e| panic!("L3: {e}"));
|
||||
words
|
||||
}
|
||||
|
||||
/// The clip distances `a`'s stage interface declares.
|
||||
fn clip_distances(a: &FunctionArtifact) -> u32 {
|
||||
a.interface
|
||||
.io
|
||||
.builtins
|
||||
.iter()
|
||||
.find_map(|b| match b {
|
||||
StageBuiltin::ClipDistance { count } => Some(*count),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// `e` without the location an `Unsupported` carries.
|
||||
fn unlocated(e: Error) -> Error {
|
||||
match e {
|
||||
Error::Unsupported(u) => Error::Unsupported(Unsupported {
|
||||
location: None,
|
||||
..u
|
||||
}),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Each entry compiled without the compensation, with `x`'s alone and with the depth's: the
|
||||
/// fact, the push field in the vertex window, the clip distances, L3, and the words each adds
|
||||
/// (printed; bounded on `Device::from_queries`' profile, at most 129, 247, 276 and 375 words).
|
||||
#[test]
|
||||
fn a_compensated_vertex_function_states_its_compensation() {
|
||||
let entries = [
|
||||
("rfb_viewports", "rfb_full", 0),
|
||||
("stage_io", "stage_io_vertex_position", 0),
|
||||
("stage_io", "stage_io_vertex_clip", 2),
|
||||
("vertex_amplification", "amp_post_tessellation", 0),
|
||||
];
|
||||
let mut over = Vec::new();
|
||||
for stem in ["lavapipe", "moltenvk-m3", "intel-irisxe-rplp-anv"] {
|
||||
let p = profile_of(description(stem));
|
||||
for (fixture_stem, entry, own) in entries {
|
||||
let Some(bc) = fixture(fixture_stem) else {
|
||||
return;
|
||||
};
|
||||
let plain = compile_with(&bc, entry, &p, &inputs(None))
|
||||
.unwrap_or_else(|e| panic!("{stem} {entry}: {e}"));
|
||||
let plain_words = validate(&plain, &p).len();
|
||||
assert!(
|
||||
!plain
|
||||
.facts
|
||||
.iter()
|
||||
.any(|f| matches!(f, RuntimeFact::ViewportCompensation { .. })),
|
||||
"{stem} {entry}"
|
||||
);
|
||||
assert_eq!(clip_distances(&plain), own, "{stem} {entry}");
|
||||
for (depth, point_guard, bound) in [
|
||||
(false, false, 130),
|
||||
(true, false, 250),
|
||||
(false, true, 280),
|
||||
(true, true, 380),
|
||||
] {
|
||||
let compensation = ViewportCompensation::new(depth).with_point_guard(point_guard);
|
||||
let a = compile_with(&bc, entry, &p, &inputs(Some(compensation)))
|
||||
.unwrap_or_else(|e| panic!("{stem} {entry} {depth} {point_guard}: {e}"));
|
||||
let words = validate(&a, &p).len();
|
||||
assert!(
|
||||
a.facts.contains(&RuntimeFact::ViewportCompensation {
|
||||
depth,
|
||||
point_guard,
|
||||
mirrors: false,
|
||||
vertex_clamp: false
|
||||
}),
|
||||
"{stem} {entry} {depth}: {:?}",
|
||||
a.facts
|
||||
);
|
||||
let guard = a
|
||||
.interface
|
||||
.push
|
||||
.fields
|
||||
.iter()
|
||||
.find(|f| f.field == PushField::PointGuard);
|
||||
match point_guard {
|
||||
true => assert!(
|
||||
guard.is_some_and(|f| matches!(f.loc, PushLoc::Push { .. }) && f.size == 8),
|
||||
"{stem} {entry} {depth}: {guard:?}"
|
||||
),
|
||||
false => assert_eq!(guard, None, "{stem} {entry} {depth}"),
|
||||
}
|
||||
let field = a
|
||||
.interface
|
||||
.push
|
||||
.fields
|
||||
.iter()
|
||||
.find(|f| f.field == PushField::ViewportCompensation)
|
||||
.unwrap_or_else(|| panic!("{stem} {entry} {depth}: no compensation field"));
|
||||
assert!(
|
||||
matches!(field.loc, PushLoc::Push { .. }) && field.size == 16,
|
||||
"{stem} {entry} {depth}: {field:?}"
|
||||
);
|
||||
let expected = own + 2 * u32::from(depth) + 4 * u32::from(point_guard);
|
||||
assert_eq!(clip_distances(&a), expected, "{stem} {entry} {depth}");
|
||||
let added = words as i64 - plain_words as i64;
|
||||
println!(
|
||||
"{stem} {entry}: depth {depth} point guard {point_guard} adds {added} words \
|
||||
to {plain_words}"
|
||||
);
|
||||
if !(0..=bound).contains(&added) {
|
||||
over.push(format!(
|
||||
"{stem} {entry} {depth} {point_guard}: {added} words past {bound}"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(over.is_empty(), "{over:#?}");
|
||||
}
|
||||
|
||||
/// The depth's compensation needs `shaderClipDistance`, and its two clip distances beyond the
|
||||
/// function's own within the device's limits, and the point guard band its four; the negation
|
||||
/// of `x` alone needs neither.
|
||||
#[test]
|
||||
fn the_depth_compensation_needs_its_clip_distances() {
|
||||
let Some(stage_io) = fixture("stage_io") else {
|
||||
return;
|
||||
};
|
||||
let Some(viewports) = fixture("rfb_viewports") else {
|
||||
return;
|
||||
};
|
||||
let mut desc = description("moltenvk-m3");
|
||||
assert!(desc.features.remove(&F::ShaderClipDistance));
|
||||
let without = profile_of(desc);
|
||||
let x = inputs(Some(ViewportCompensation::new(false)));
|
||||
let depth = inputs(Some(ViewportCompensation::new(true)));
|
||||
let a = compile_with(&viewports, "rfb_full", &without, &x).expect("x alone");
|
||||
validate(&a, &without);
|
||||
assert_eq!(clip_distances(&a), 0);
|
||||
let refusal = compile_with(&viewports, "rfb_full", &without, &depth)
|
||||
.map(|_| ())
|
||||
.map_err(unlocated);
|
||||
assert_eq!(
|
||||
refusal,
|
||||
Err(Error::Unsupported(Unsupported::needs(
|
||||
Feature::ClipDistance,
|
||||
Capability::Feature(F::ShaderClipDistance)
|
||||
)))
|
||||
);
|
||||
// Three clip distances: the function's two and the compensation's two do not fit.
|
||||
let mut desc = description("moltenvk-m3");
|
||||
desc.limits.max_clip_distances = 3;
|
||||
let three = profile_of(desc);
|
||||
compile_with(&stage_io, "stage_io_vertex_clip", &three, &x).expect("x alone");
|
||||
let refusal = compile_with(&stage_io, "stage_io_vertex_clip", &three, &depth)
|
||||
.map(|_| ())
|
||||
.map_err(unlocated);
|
||||
assert_eq!(
|
||||
refusal,
|
||||
Err(Error::Unsupported(Unsupported::needs(
|
||||
Feature::ClipDistance,
|
||||
Capability::Limit {
|
||||
limit: VkLimit::MaxClipDistances,
|
||||
required: 4,
|
||||
available: 3,
|
||||
}
|
||||
)))
|
||||
);
|
||||
compile_with(&viewports, "rfb_full", &three, &depth).expect("two clip distances");
|
||||
let points = inputs(Some(
|
||||
ViewportCompensation::new(false).with_point_guard(true),
|
||||
));
|
||||
let refusal = compile_with(&viewports, "rfb_full", &without, &points)
|
||||
.map(|_| ())
|
||||
.map_err(unlocated);
|
||||
assert_eq!(
|
||||
refusal,
|
||||
Err(Error::Unsupported(Unsupported::needs(
|
||||
Feature::ClipDistance,
|
||||
Capability::Feature(F::ShaderClipDistance)
|
||||
)))
|
||||
);
|
||||
let refusal = compile_with(&viewports, "rfb_full", &three, &points)
|
||||
.map(|_| ())
|
||||
.map_err(unlocated);
|
||||
assert_eq!(
|
||||
refusal,
|
||||
Err(Error::Unsupported(Unsupported::needs(
|
||||
Feature::ClipDistance,
|
||||
Capability::Limit {
|
||||
limit: VkLimit::MaxClipDistances,
|
||||
required: 4,
|
||||
available: 3,
|
||||
}
|
||||
)))
|
||||
);
|
||||
}
|
||||
|
||||
/// A compensation of mirrored and unmirrored viewports in one draw: the function states it,
|
||||
/// reads `PushField::ViewportMirrors` (one `u32` in its push window), passes L3, and adds a
|
||||
/// bounded handful of words to the same compensation without it (printed): through the
|
||||
/// viewport index it stores (`rt6_select`), and through the first where it stores none.
|
||||
#[test]
|
||||
fn a_compensation_of_mirrors_reads_the_selected_viewports_bit() {
|
||||
let entries = [
|
||||
("rt6_viewports", "rt6_select"),
|
||||
("rfb_viewports", "rfb_full"),
|
||||
("vertex_amplification", "amp_post_tessellation"),
|
||||
];
|
||||
for stem in ["lavapipe", "moltenvk-m3", "intel-irisxe-rplp-anv"] {
|
||||
let p = profile_of(description(stem));
|
||||
for (fixture_stem, entry) in entries {
|
||||
let Some(bc) = fixture(fixture_stem) else {
|
||||
return;
|
||||
};
|
||||
for depth in [false, true] {
|
||||
let what = format!("{stem} {entry} {depth}");
|
||||
let one = ViewportCompensation::new(depth);
|
||||
let without = compile_with(&bc, entry, &p, &inputs(Some(one)))
|
||||
.unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
let without = validate(&without, &p).len();
|
||||
let a = compile_with(&bc, entry, &p, &inputs(Some(one.with_mirrors(true))))
|
||||
.unwrap_or_else(|e| panic!("{what} mirrors: {e}"));
|
||||
let words = validate(&a, &p).len();
|
||||
assert!(
|
||||
a.facts.contains(&RuntimeFact::ViewportCompensation {
|
||||
depth,
|
||||
point_guard: false,
|
||||
mirrors: true,
|
||||
vertex_clamp: false
|
||||
}),
|
||||
"{what}: {:?}",
|
||||
a.facts
|
||||
);
|
||||
let field = a
|
||||
.interface
|
||||
.push
|
||||
.fields
|
||||
.iter()
|
||||
.find(|f| f.field == PushField::ViewportMirrors)
|
||||
.unwrap_or_else(|| panic!("{what}: no mirrors field"));
|
||||
assert!(
|
||||
matches!(field.loc, PushLoc::Push { .. }) && field.size == 4,
|
||||
"{what}: {field:?}"
|
||||
);
|
||||
let added = words as i64 - without as i64;
|
||||
println!("{what}: the mirrors add {added} words to {without}");
|
||||
assert!((0..=160).contains(&added), "{what}: {added} words");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A compensation that clamps each vertex's depth as Metal does: under the depth's compensation
|
||||
/// the function states it, reads `PushField::VertexDepthClamp` (two `f32`s' bits in its push
|
||||
/// window), passes L3, and adds at most 120 words to the same compensation without it (printed;
|
||||
/// measured 82 for `rfb_span` on lavapipe); without the depth's compensation there is no depth
|
||||
/// to clamp, and no field.
|
||||
#[test]
|
||||
fn a_compensation_clamping_each_vertexs_depth_reads_its_bounds() {
|
||||
let entries = [
|
||||
("rfb_viewports", "rfb_span"),
|
||||
("rfb_viewports", "rfb_full"),
|
||||
("stage_io", "stage_io_vertex_clip"),
|
||||
("vertex_amplification", "amp_post_tessellation"),
|
||||
];
|
||||
for stem in ["lavapipe", "moltenvk-m3", "intel-irisxe-rplp-anv"] {
|
||||
let p = profile_of(description(stem));
|
||||
for (fixture_stem, entry) in entries {
|
||||
let Some(bc) = fixture(fixture_stem) else {
|
||||
return;
|
||||
};
|
||||
for depth in [false, true] {
|
||||
let what = format!("{stem} {entry} {depth}");
|
||||
let one = ViewportCompensation::new(depth);
|
||||
let without = compile_with(&bc, entry, &p, &inputs(Some(one)))
|
||||
.unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
let without = validate(&without, &p).len();
|
||||
let a = compile_with(&bc, entry, &p, &inputs(Some(one.with_vertex_clamp(true))))
|
||||
.unwrap_or_else(|e| panic!("{what} vertex clamp: {e}"));
|
||||
let words = validate(&a, &p).len();
|
||||
assert!(
|
||||
a.facts.contains(&RuntimeFact::ViewportCompensation {
|
||||
depth,
|
||||
point_guard: false,
|
||||
mirrors: false,
|
||||
vertex_clamp: true
|
||||
}),
|
||||
"{what}: {:?}",
|
||||
a.facts
|
||||
);
|
||||
let field = a
|
||||
.interface
|
||||
.push
|
||||
.fields
|
||||
.iter()
|
||||
.find(|f| f.field == PushField::VertexDepthClamp);
|
||||
let added = words as i64 - without as i64;
|
||||
println!("{what}: the vertex clamp adds {added} words to {without}");
|
||||
match depth {
|
||||
true => {
|
||||
let field = field.unwrap_or_else(|| panic!("{what}: no clamp field"));
|
||||
assert!(
|
||||
matches!(field.loc, PushLoc::Push { .. }) && field.size == 8,
|
||||
"{what}: {field:?}"
|
||||
);
|
||||
assert!((0..=120).contains(&added), "{what}: {added} words");
|
||||
}
|
||||
false => {
|
||||
assert!(field.is_none(), "{what}: {field:?}");
|
||||
assert_eq!(added, 0, "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A plan of the bare position return drawn through a compensated viewport: the variant, which
|
||||
/// the base pipeline does not draw; compiled, its modules, fact and settled plan, and the four
|
||||
/// values in the draw's push data at the vertex function's field.
|
||||
#[test]
|
||||
fn a_compensated_draw_runs_its_variant_with_the_states_values() {
|
||||
let Some(bc) = fixture("stage_io") else {
|
||||
return;
|
||||
};
|
||||
let budget = Budget::standard();
|
||||
let lib = Library::from_air(&bc).expect("library");
|
||||
let d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(
|
||||
lib.function("stage_io_vertex_position").expect("function"),
|
||||
)));
|
||||
let triangle = DrawCall::Primitives {
|
||||
vertex_start: 0,
|
||||
vertex_count: 3,
|
||||
instance_count: 1,
|
||||
base_instance: 0,
|
||||
};
|
||||
for stem in ["moltenvk-m3", "lavapipe"] {
|
||||
let dev = Device::from_queries(description(stem), DevicePolicy::default()).expect("device");
|
||||
let base = dev
|
||||
.compile_render_pipeline(&d, &budget)
|
||||
.unwrap_or_else(|e| panic!("{stem}: {e}"));
|
||||
for (depth, point_guard, mirrors, vertex_clamp) in [
|
||||
(false, false, false, false),
|
||||
(true, false, false, false),
|
||||
(true, true, false, false),
|
||||
(false, false, true, false),
|
||||
(true, true, true, false),
|
||||
(true, false, false, true),
|
||||
(true, false, true, true),
|
||||
] {
|
||||
let what = format!("{stem} {depth} {point_guard} {mirrors} {vertex_clamp}");
|
||||
let compensation = ViewportCompensation::new(depth)
|
||||
.with_point_guard(point_guard)
|
||||
.with_mirrors(mirrors)
|
||||
.with_vertex_clamp(vertex_clamp);
|
||||
let values = [-1.0f32, 0.5, 1.5, 1.0];
|
||||
let guard = [0.25f32, 0.5];
|
||||
let bits = 0b101u32;
|
||||
let clamp = [-0.5f32, 1.25];
|
||||
let state = BindState {
|
||||
viewport_compensation: Some(
|
||||
CompensatedViewport {
|
||||
guard,
|
||||
..CompensatedViewport::new(compensation, values)
|
||||
}
|
||||
.with_mirrors(bits)
|
||||
.with_vertex_clamp(clamp),
|
||||
),
|
||||
..Default::default()
|
||||
};
|
||||
let plan = base
|
||||
.plan(&dev, &state.shape())
|
||||
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
|
||||
assert_eq!(
|
||||
plan.variant.viewport_compensation,
|
||||
Some(compensation),
|
||||
"{what}"
|
||||
);
|
||||
assert_eq!(
|
||||
plan.instantiate_draw(&state, &triangle),
|
||||
Err(BindError::NeedsVariant {
|
||||
variant: Box::new(plan.variant.clone())
|
||||
}),
|
||||
"{what}"
|
||||
);
|
||||
let key = plan.variant.clone();
|
||||
let p = dev
|
||||
.compile_render_variant(&d, &key, &budget)
|
||||
.unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
for m in &p.stages {
|
||||
check_words_valid(&m.spirv, &p.requirements, dev.profile())
|
||||
.unwrap_or_else(|e| panic!("{what} {:?}: L3: {e}", m.stage));
|
||||
}
|
||||
assert!(
|
||||
p.dependencies.iter().any(|x| x.fact
|
||||
== RuntimeFact::ViewportCompensation {
|
||||
depth,
|
||||
point_guard,
|
||||
mirrors,
|
||||
vertex_clamp
|
||||
}),
|
||||
"{what}"
|
||||
);
|
||||
let plan = p
|
||||
.plan(&dev, &state.shape())
|
||||
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
|
||||
assert_eq!(plan.variant, key, "{what}");
|
||||
let commands = plan
|
||||
.instantiate_draw(&state, &triangle)
|
||||
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
|
||||
let offset_of = |field: PushField| {
|
||||
p.interface
|
||||
.push
|
||||
.iter()
|
||||
.filter(|pl| pl.stage == Stage::Vertex)
|
||||
.flat_map(|pl| pl.fields.iter())
|
||||
.find(|f| f.field == field)
|
||||
.map(|f| match f.loc {
|
||||
PushLoc::Push { offset } => offset as usize,
|
||||
other => panic!("{what}: {other:?}"),
|
||||
})
|
||||
};
|
||||
let mut pushed = vec![None; 256];
|
||||
for w in &commands.push_constants {
|
||||
for (i, b) in w.bytes.iter().enumerate() {
|
||||
if let Some(slot) = pushed.get_mut(w.offset as usize + i) {
|
||||
*slot = Some(*b);
|
||||
}
|
||||
}
|
||||
}
|
||||
let bytes = |v: &[f32]| -> Vec<Option<u8>> {
|
||||
v.iter().flat_map(|v| v.to_le_bytes()).map(Some).collect()
|
||||
};
|
||||
let offset = offset_of(PushField::ViewportCompensation)
|
||||
.unwrap_or_else(|| panic!("{what}: no compensation field"));
|
||||
assert_eq!(
|
||||
pushed.get(offset..offset + 16),
|
||||
Some(&bytes(&values)[..]),
|
||||
"{what}"
|
||||
);
|
||||
match offset_of(PushField::PointGuard) {
|
||||
Some(offset) => {
|
||||
assert!(point_guard, "{what}");
|
||||
assert_eq!(
|
||||
pushed.get(offset..offset + 8),
|
||||
Some(&bytes(&guard)[..]),
|
||||
"{what}"
|
||||
);
|
||||
}
|
||||
None => assert!(!point_guard, "{what}"),
|
||||
}
|
||||
match offset_of(PushField::ViewportMirrors) {
|
||||
Some(offset) => {
|
||||
assert!(mirrors, "{what}");
|
||||
let expected: Vec<Option<u8>> =
|
||||
bits.to_le_bytes().iter().copied().map(Some).collect();
|
||||
assert_eq!(
|
||||
pushed.get(offset..offset + 4),
|
||||
Some(&expected[..]),
|
||||
"{what}"
|
||||
);
|
||||
}
|
||||
None => assert!(!mirrors, "{what}"),
|
||||
}
|
||||
match offset_of(PushField::VertexDepthClamp) {
|
||||
Some(offset) => {
|
||||
assert!(vertex_clamp, "{what}");
|
||||
assert_eq!(
|
||||
pushed.get(offset..offset + 8),
|
||||
Some(&bytes(&clamp)[..]),
|
||||
"{what}"
|
||||
);
|
||||
}
|
||||
None => assert!(!vertex_clamp, "{what}"),
|
||||
}
|
||||
// Without the compensation the variant asks for the base again.
|
||||
let plan = p
|
||||
.plan(&dev, &BindState::default().shape())
|
||||
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
|
||||
assert_eq!(plan.variant.viewport_compensation, None, "{what}");
|
||||
assert!(
|
||||
matches!(
|
||||
plan.instantiate_draw(&BindState::default(), &triangle),
|
||||
Err(BindError::NeedsVariant { .. })
|
||||
),
|
||||
"{what}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,6 @@ mod engine_global_builtins;
|
||||
mod engine_graphics_binder;
|
||||
mod engine_half_hold;
|
||||
mod engine_half_moves;
|
||||
mod engine_half_storage_notes;
|
||||
mod engine_handles;
|
||||
mod engine_heap_binder;
|
||||
mod engine_heap_residency;
|
||||
@@ -210,7 +209,6 @@ mod engine_unread_attribute;
|
||||
mod engine_unspecialized;
|
||||
mod engine_vertex_fetch;
|
||||
mod engine_vertex_variants;
|
||||
mod engine_viewport_compensation;
|
||||
mod engine_volatile;
|
||||
mod engine_wide;
|
||||
mod engine_widest_pin;
|
||||
|
||||
@@ -425,7 +425,6 @@ surface! {
|
||||
enum StorageImageClass N;
|
||||
enum VertexFetch N;
|
||||
struct VertexFetchProjection N;
|
||||
struct ViewportCompensation N;
|
||||
struct FunctionHandle O;
|
||||
struct RenderPipelineKeys N;
|
||||
enum Mechanism N;
|
||||
@@ -478,7 +477,6 @@ surface! {
|
||||
struct MeshDispatch N;
|
||||
enum MeshGroups N;
|
||||
enum MeshRecordsRegion N;
|
||||
struct SlotRebinds O;
|
||||
struct TessellationDispatch N;
|
||||
enum TessellationRecords N;
|
||||
fn heap_classes;
|
||||
@@ -561,7 +559,6 @@ surface! {
|
||||
struct FunctionTablesShape N;
|
||||
struct TileThreadgroupMemory N;
|
||||
struct TileThreadgroupArgument N;
|
||||
struct CompensatedViewport N;
|
||||
enum FragmentTests N;
|
||||
struct ExecutionStatus E;
|
||||
struct MeshRecordsFault N;
|
||||
|
||||
Reference in new issue
Block a user