diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 0e44b0af4..169cba633 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1327,7 +1327,7 @@ pub enum RenderPipelineKind { /// function that is not post-tessellation is ignored, as Metal ignores it. Tessellation, /// Stages the translator synthesizes beside the functions' but a tessellation's: geometry - /// stages, lines drawn as bands of triangles, a rate map's fan-out, or mesh records. + /// stages, lines drawn as bands of triangles, or a rate map's fan-out. SynthesizedStages, /// A fragment function that reaches the render pass's imageblock. Imageblock, diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index c486cce6e..220859370 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -663,7 +663,6 @@ fn unbuilt(pipeline: &RenderPipeline, enabled: &EnabledCaps) -> Option= 3, "{}", linked.stages.len()); // The payload object under the mesh function that reads its payload, and that mesh diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 3986d3ab3..0e7820101 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -129,10 +129,7 @@ //! - **Rotated weights**. A draw of triangles drawn with Metal's last vertex first //! (`BindShape::rotated_weights`) of a pipeline whose fragment function reads //! `[[barycentric_coord]]` runs the variant that takes Metal's weights back from the drawn -//! triangle's (`VariantKey::rotated_weights`, `LoweringInputs::rotated_weights`). A mesh draw -//! drawn from each primitive's last index first (`BindShape::mesh_last_first`) of an emulated -//! mesh function's pipeline of lines or triangles runs the variant whose synthesized vertex -//! stage reads its corners so (`VariantKey::mesh_last_first`). +//! triangle's (`VariantKey::rotated_weights`, `LoweringInputs::rotated_weights`). //! - **Tested storage writes**. A fragment function that stores a color through the interlocked //! storage form and declares no early tests only because it discards //! (`RuntimeFact::TestedStorageWrites`), in a pipeline with a depth or stencil attachment, stores @@ -272,29 +269,6 @@ //! offset where the mesh function chooses its slice, is not implemented: the mesh function does //! not add it. A mesh pipeline draws with an amplification count of 1 (its //! `maxVertexAmplificationCount`). -//! -//! An emulated mesh pipeline (`GraphicsState::mesh_records`) is different in these ways: -//! - Its object and mesh functions are `COMPUTE` stages, the object function's first, and -//! their threadgroups are held to the compute limits, as is the object function's grid. -//! - Each draw's compute work is `DrawCommands::mesh_dispatch` (`MeshDispatch` states the -//! consumer contract), over a work buffer of the draw's own. A direct draw of `G` mesh -//! threadgroups without an object function is the host's: its dispatch is `G` folded into -//! rows of `maxComputeWorkGroupCount[0]`, its records hold `G · group_words` words (at -//! least 16 bytes; past `maxStorageBufferRange` refused, naming it), and its draw is a -//! `Draw` of `G · NP · k` vertices. A direct draw with an object function, and an indirect -//! draw without one, are scanned on the GPU (`MeshScanModule`): the mesh dispatch and the -//! draw are indirect from the work buffer, and the records lie in the command buffer's -//! records pool, where a draw that does not fit draws nothing and fails the command buffer -//! (`StatusReport::mesh_records_overflow`). Neither asks for its arguments on the CPU. -//! - An indirect draw of a pipeline with an object function, whose object threadgroups only the -//! GPU knows, runs an object arguments pass first (`mesh_object_arguments_module`, -//! `MeshDispatch::object_arguments`): it reads Metal's arguments, reserves the object -//! threadgroups' slots and offsets in the records pool (`lower::mesh::work::SLOTS`), and -//! writes the object dispatch, which reads its counts from the work buffer; then the scan as -//! above. Every threadgroup of a grid whose threads per grid wrap runs, reporting the wrapped -//! grid as Metal's (`lower::dispatch`'s object grid). A grid Metal's GPU discards, one past the -//! compute limits, and one whose slots the pool cannot hold draw nothing and say so in the -//! command buffer's `ExecutionStatus`. use std::collections::BTreeMap; @@ -321,9 +295,8 @@ use crate::bind::plan::slots::{ use crate::bind::plan::{ AccessClass, BindingPlan, BoundKind, ByteRange, DescriptorWrite, FactorTemplate, FieldLocation, GraphicsTemplate, GroupLimits, GroupStage, MeshTemplate, PlannedVertexBuffer, - PushFieldPlacement, PushTemplate, RecordsTemplate, ResourceUse, ShaderTestsTemplate, - ShadowTemplate, StageTemplate, StrideRules, UseTarget, VertexBufferBind, ViewSetup, - WriteSource, + PushFieldPlacement, PushTemplate, ResourceUse, ShaderTestsTemplate, ShadowTemplate, + StageTemplate, StrideRules, UseTarget, VertexBufferBind, ViewSetup, WriteSource, }; use crate::bind::resident::{stage_root_table, table_entries}; use crate::bind::state::{ @@ -508,10 +481,6 @@ pub struct DrawCommands { /// (`SpecKey::ObjectLocalSize`, `ObjectFlatLocalSize`, `ObjectMultiRegion`). The consumer creates the draw's /// `VkPipeline` with it. `None` for every other draw, whose pipeline takes the plan's. pub specialization: Option, - /// A mesh draw of an emulated mesh function's pipeline (`GraphicsState::mesh_records`): the - /// compute dispatch that runs its mesh threadgroups before `draw` draws their primitives - /// ([`MeshDispatch`] states the consumer contract). `None` for every other draw. - pub mesh_dispatch: Option, /// An indirect mesh draw on a device with `VK_EXT_mesh_shader`, whose first stage's group /// counts `vkCmdDrawMeshTasksIndirectEXT` requires within the device's limits: the form of the /// arguments pass the consumer records before the draw ([`MeshArguments`], which it makes with @@ -574,130 +543,10 @@ impl Default for DrawCommands { discards_command_buffer: false, amplifications: Vec::new(), specialization: None, - mesh_dispatch: None, } } } -/// The compute work of a mesh draw whose mesh function is emulated: its object threadgroups, where -/// the pipeline has an object function, set the mesh grids they launch; its mesh threadgroups write -/// their vertices and primitives to records, from which the pipeline's synthesized vertex stage -/// draws them. -/// -/// The draw's **work buffer** (`SyntheticBinding::MeshWork`) is the region of -/// [`work_bytes`](Self::work_bytes) that every step of the draw binds whole: its first words are -/// [`work`](Self::work), the rest zero. Its header holds the draw's object threadgroups and its -/// mesh threadgroups, where its records begin, the mesh dispatch's arguments -/// ([`DISPATCH_OFFSET`](Self::DISPATCH_OFFSET)) and the draw's ([`DRAW_OFFSET`](Self::DRAW_OFFSET)); -/// then each object threadgroup's slot (the grid it set and its payload) and each one's first -/// mesh threadgroup. -/// -/// The consumer, outside the render pass instance the draw records into, and after every command -/// of the pass that writes what the object or mesh function reads or reads what they write: -/// -/// - makes the work buffer and the records ([`records`](Self::records)), and writes them to the -/// plan's `WriteSource::MeshWork` and `WriteSource::MeshRecords` bindings of the draw's set 0; -/// for records in the command buffer's pool it writes the pool's words at word -/// [`POOL_WORDS`](Self::POOL_WORDS) of the work buffer, and, for any draw, its number for the -/// draw at word [`DRAW_ID`](Self::DRAW_ID), which a records fault reports -/// (`StatusReport::mesh_records_overflow`); -/// - creates a compute pipeline of each of the pipeline's `COMPUTE` modules (the object -/// function's first, where it has one), under the pipeline's layout and the draw's -/// `DrawCommands::specialization`; -/// - for an indirect draw with an object function ([`object_arguments`](Self::object_arguments)), -/// dispatches [`mesh_object_arguments_module`](crate::bind::mesh_object_arguments_module) (one -/// workgroup) under the scan's bindings first: it reads Metal's arguments, reserves the draw's -/// slots and offsets in the records pool, and writes the object dispatch's -/// `VkDispatchIndirectCommand` in the work buffer; -/// - with an object function, binds its pipeline and the draw's sets at the compute bind point, -/// records the push writes whose stages are `COMPUTE`, and `vkCmdDispatch` of -/// [`object_groups`](Self::object_groups), or, for an indirect draw, `vkCmdDispatchIndirect` -/// from the work buffer where the object arguments pass wrote it; -/// - for [`MeshGroups::Scanned`], dispatches [`MeshScanModule`](crate::bind::MeshScanModule) -/// (one workgroup) over the work buffer, the command buffer's `ExecutionStatus` buffer, the -/// arguments the variant names and the records; -/// - binds the mesh function's pipeline and the draw's sets, records the push writes whose -/// stages are `COMPUTE`, and dispatches its threadgroups: `vkCmdDispatch` of -/// [`MeshGroups::Direct`]'s counts (nothing where one is 0), or `vkCmdDispatchIndirect` from -/// the work buffer at [`DISPATCH_OFFSET`](Self::DISPATCH_OFFSET); -/// - between the steps, orders each one's writes before the next one's reads (a barrier from -/// compute shader writes to compute shader and indirect command reads), and after the last, -/// before the draw's vertex stage and indirect command reads; then records `DrawCommands::draw` -/// in the render pass instance as any draw, its indirect buffer (`DrawIndirect`, for -/// [`MeshGroups::Scanned`]) the work buffer. -/// -/// The object and mesh functions' resource uses are compute-stage uses (`ResourceUse`'s -/// stages). -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct MeshDispatch { - /// The work buffer's first words; its other words are zero. - pub work: Vec, - /// The work buffer's bytes, at least 16. - pub work_bytes: u64, - /// The object function's threadgroups, the object dispatch's group counts; `None` for a - /// pipeline without an object function, and for an indirect draw with one. - pub object_groups: Option<[u32; 3]>, - /// An indirect draw with an object function: the range of the Metal indirect buffer its - /// object arguments pass binds at `MeshScanModule::ARGUMENTS_BINDING`, from the arguments' - /// offset aligned down to `minStorageBufferOffsetAlignment` through their 12 bytes (the work - /// buffer's `OBJECT_ARGUMENTS` word names where they begin). `None` for any other draw. - pub object_arguments: Option, - /// The mesh threadgroups. - pub mesh: MeshGroups, - /// The records. - pub records: MeshRecordsRegion, -} - -impl MeshDispatch { - /// The work buffer's word where the consumer writes its records pool's words, for - /// [`MeshRecordsRegion::Pool`]. - pub const POOL_WORDS: usize = crate::lower::mesh::work::POOL_WORDS as usize; - /// The work buffer's word where the consumer writes its number for the draw. - pub const DRAW_ID: usize = crate::lower::mesh::work::DRAW_ID as usize; - /// The byte of the work buffer where the mesh dispatch's `VkDispatchIndirectCommand` lies. - pub const DISPATCH_OFFSET: u64 = 4 * crate::lower::mesh::work::DISPATCH as u64; - /// The byte of the work buffer where the draw's `VkDrawIndirectCommand` lies. - pub const DRAW_OFFSET: u64 = 4 * crate::lower::mesh::work::DRAW as u64; -} - -/// Where an emulated mesh draw's mesh threadgroups come from ([`MeshDispatch`]). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum MeshGroups { - /// The host knows them (a direct draw without an object function): the dispatch's group - /// counts, the draw's threadgroups folded into rows of `maxComputeWorkGroupCount[0]`. The - /// work buffer is complete, and the draw is a `Draw`. - Direct([u32; 3]), - /// The scan writes them (a draw with an object function, or an indirect draw): the mesh - /// dispatch is indirect, and the draw a `DrawIndirect`, both from the work buffer. - Scanned { - /// The range of the Metal indirect buffer the scan binds at - /// `MeshScanModule::ARGUMENTS_BINDING`, for an indirect draw: from the arguments' offset - /// aligned down to `minStorageBufferOffsetAlignment` through their 12 bytes. `None` for - /// any other draw, whose scan reads no argument (any 4 bytes bind there). - arguments: Option, - }, -} - -/// The records of an emulated mesh draw ([`MeshDispatch`]), which its mesh dispatch and its draw -/// bind whole. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum MeshRecordsRegion { - /// A region of the draw's own of this many bytes (at least 16), for - /// [`MeshGroups::Direct`]. - Exact(u64), - /// The command buffer's records pool, for [`MeshGroups::Scanned`]: storage of the - /// consumer's size (its budget for the command buffer's emulated mesh draws, within - /// `maxStorageBufferRange`), which the scans reserve from front to back - /// (`StatusWord::MeshRecordsCursor`). Its words need no initial value. - Pool, -} - /// How a direct indexed draw treats its index positions past the index buffer: the positions whose /// bytes do not lie wholly before where Metal's fetch stops reading it /// ([`IndexBufferRef::fetch_end`], the length rounded up to 4 bytes). Metal's API validation @@ -742,38 +591,29 @@ impl RenderPipeline { /// a Metal function, with its Vulkan stage: a tessellation pipeline's (`tessellated`) synthesized /// vertex and control stages run none, and its post-tessellation vertex function is its /// evaluation stage; a mesh render pipeline's object and mesh functions are its task and mesh -/// stages, and an emulated pipeline's (`emulated`) are its compute stages, the object function's -/// first where it has one, and its synthesized vertex stage runs none; the geometry stages link +/// stages; the geometry stages link /// generates (`link::geometry`: barycentric weights read as varyings, a selected slice or /// viewport) run none and bind nothing, nor do a band variant's (`banded`) control and evaluation /// stages (`link::band`). fn metal_stages( stages: impl ExactSizeIterator, (tessellated, banded): (bool, bool), - emulated: bool, ) -> Result, BindError> { - let stages: Vec = stages.collect(); let mut out = Vec::with_capacity(stages.len()); - for (i, &s) in stages.iter().enumerate() { - let compute = s == vk::ShaderStage::COMPUTE && emulated; - let object_first = compute && stages.get(i + 1) == Some(&vk::ShaderStage::COMPUTE); + for s in stages { let stage = if s == vk::ShaderStage::FRAGMENT { Stage::Fragment - } else if object_first { - Stage::Object - } else if s == vk::ShaderStage::MESH_EXT || compute { + } else if s == vk::ShaderStage::MESH_EXT { Stage::Mesh } else if s == vk::ShaderStage::TASK_EXT { Stage::Object - } else if s == vk::ShaderStage::VERTEX && emulated { - continue; } else if s == vk::ShaderStage::VERTEX && !tessellated || s == vk::ShaderStage::TESSELLATION_EVALUATION && tessellated { Stage::Vertex } else if tessellated && (s == vk::ShaderStage::VERTEX || s == vk::ShaderStage::TESSELLATION_CONTROL) - || s == vk::ShaderStage::GEOMETRY && !emulated + || s == vk::ShaderStage::GEOMETRY || banded && (s == vk::ShaderStage::TESSELLATION_CONTROL || s == vk::ShaderStage::TESSELLATION_EVALUATION) @@ -789,15 +629,10 @@ fn metal_stages( /// Whether a module of mesh render pipeline `p` other than its object function's declares /// threadgroup memory arguments (`SpecKey::TgLength`): a mesh function's, whose lengths no encoder -/// setter sets. The object module is the task stage, or, `emulated`, the first of the two compute -/// stages, as [`metal_stages`] names them. -fn other_stage_lengths(p: &RenderPipeline, emulated: bool) -> bool { - p.stages.iter().enumerate().any(|(i, m)| { - let object = m.stage == vk::ShaderStage::TASK_EXT - || emulated - && m.stage == vk::ShaderStage::COMPUTE - && p.stages.get(i + 1).map(|n| n.stage) == Some(vk::ShaderStage::COMPUTE); - !object +/// setter sets. The object module is the task stage, as [`metal_stages`] names it. +fn other_stage_lengths(p: &RenderPipeline) -> bool { + p.stages.iter().any(|m| { + m.stage != vk::ShaderStage::TASK_EXT && m.specialization .constants .iter() @@ -832,15 +667,6 @@ fn tessellated_pipeline_stage(stage: Stage) -> vk::PipelineStageFlags2 { } } -/// [`pipeline_stage`] of an emulated mesh function's pipeline, whose object and mesh functions -/// run in the draw's compute dispatches. -fn emulated_mesh_pipeline_stage(stage: Stage) -> vk::PipelineStageFlags2 { - match stage { - Stage::Object | Stage::Mesh => vk::PipelineStageFlags2::COMPUTE_SHADER, - other => pipeline_stage(other), - } -} - /// How a plan draws the shape's vertex amplification. #[derive(Clone, Debug, PartialEq, Eq)] enum Route { @@ -934,7 +760,6 @@ fn stores(a: crate::pipeline::graphics::ColorAttachmentState) -> bool { fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result { check_slots(shape)?; - let records = p.graphics.mesh_records.as_ref(); let tessellation = p.graphics.tessellation.is_some(); let modules = metal_stages( p.stages.iter().map(|m| m.stage), @@ -942,7 +767,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result = modules.iter().map(|(stage, _)| *stage).collect(); // A mesh render pipeline (`Device::compile_mesh_pipeline`) is drawn by mesh draws. @@ -1245,7 +1069,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result Result 1); - let compiled_last_first = p - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::MeshLastFirst); // A draw of lines, or of triangles' edges, as bands: the variant whose synthesized // tessellation stages draw them so, which its graphics state states. let line_band = shape.line_band; @@ -1451,15 +1262,9 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result mesh_layers - { + if mesh && vertex_layer.is_some() && shape.render_target_array_length > mesh_layers { return Err(BindError::Unsupported(Unsupported::needs( Feature::MeshShading, Capability::Limit { @@ -1476,12 +1281,10 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result vk::PipelineStageFlags2 = - match (&p.graphics.tessellation, records) { - (Some(_), _) => tessellated_pipeline_stage, - (None, Some(_)) => emulated_mesh_pipeline_stage, - (None, None) => pipeline_stage, - }; + let stage_flags: fn(Stage) -> vk::PipelineStageFlags2 = match &p.graphics.tessellation { + Some(_) => tessellated_pipeline_stage, + None => pipeline_stage, + }; let bindings = bindings(&p.layout); let stage_shape = |s: Stage| shape.stages.get(&s); @@ -1883,9 +1686,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result WriteSource::MeshRecords, - SyntheticBinding::MeshWork if records.is_some() => WriteSource::MeshWork, SyntheticBinding::HandleTable => { planner(&mut heap)?.table(stage, set.set, b.binding)? } @@ -2134,7 +1934,7 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result Some((static_bytes, payload)), _ => None, }); - if mesh && other_stage_lengths(p, records.is_some()) { + if mesh && other_stage_lengths(p) { // A mesh function's arguments, whose lengths no Metal setter sets. return Err(not_implemented(Feature::MeshShading)); } @@ -2211,32 +2011,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result GroupLimits { - size: limits.max_compute_work_group_size, - invocations: limits.max_compute_work_group_invocations, - count: limits.max_compute_work_group_count, - total: None, - stage: GroupStage::Compute, - }, - None => GroupLimits { - size: m.max_mesh_work_group_size, - invocations: m.max_mesh_work_group_invocations, - count: m.max_mesh_work_group_count, - total: Some(m.max_mesh_work_group_total_count), - stage: GroupStage::Mesh, - }, - }; - let records = records.map(|r| RecordsTemplate { - group_words: r.group_words(), - group_vertices: r.primitives.saturating_mul(r.corners), - max_range: limits.max_storage_buffer_range, - slot_words: r.slot_words, - row: limits.max_compute_work_group_count[0], - rows: limits.max_compute_work_group_count[1], - alignment: limits.min_storage_buffer_offset_alignment, - }); let mesh = mesh.then(|| MeshTemplate { multiples: p .dependencies @@ -2248,23 +2022,19 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result GroupLimits { - size: limits.max_compute_work_group_size, - invocations: limits.max_compute_work_group_invocations, - count: limits.max_compute_work_group_count, - total: None, - stage: GroupStage::Compute, - }, - None => GroupLimits { - size: m.max_task_work_group_size, - invocations: m.max_task_work_group_invocations, - count: m.max_task_work_group_count, - total: Some(m.max_task_work_group_total_count), - stage: GroupStage::Task, - }, + mesh: GroupLimits { + size: m.max_mesh_work_group_size, + invocations: m.max_mesh_work_group_invocations, + count: m.max_mesh_work_group_count, + total: m.max_mesh_work_group_total_count, + stage: GroupStage::Mesh, + }, + object: stages.contains(&Stage::Object).then_some(GroupLimits { + size: m.max_task_work_group_size, + invocations: m.max_task_work_group_invocations, + count: m.max_task_work_group_count, + total: m.max_task_work_group_total_count, + stage: GroupStage::Task, }), folded: p .dependencies @@ -2274,7 +2044,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result Result Result, mesh_region: [u8; 32], - /// An emulated mesh function's dispatch. - dispatch: Option, /// A direct draw's fold of its object grid, of a folded object function /// (`DrawCommands::object_fold`). fold: Option, @@ -2934,13 +2699,12 @@ fn mesh_limit(limit: VkLimit, required: u64, available: u32) -> BindError { } /// The limits that name a stage's threadgroup and grid: the task stage's for an object -/// function, the mesh stage's for a mesh function, and the compute stage's for an emulated mesh -/// function, whose grid has no total limit. +/// function and the mesh stage's for a mesh function. struct GroupLimitNames { size: fn(u8) -> VkLimit, invocations: VkLimit, count: fn(u8) -> VkLimit, - total: Option, + total: VkLimit, } impl GroupLimitNames { @@ -2950,19 +2714,13 @@ impl GroupLimitNames { size: VkLimit::MaxTaskWorkGroupSize, invocations: VkLimit::MaxTaskWorkGroupInvocations, count: VkLimit::MaxTaskWorkGroupCount, - total: Some(VkLimit::MaxTaskWorkGroupTotalCount), + total: VkLimit::MaxTaskWorkGroupTotalCount, }, GroupStage::Mesh => GroupLimitNames { size: VkLimit::MaxMeshWorkGroupSize, invocations: VkLimit::MaxMeshWorkGroupInvocations, count: VkLimit::MaxMeshWorkGroupCount, - total: Some(VkLimit::MaxMeshWorkGroupTotalCount), - }, - GroupStage::Compute => GroupLimitNames { - size: VkLimit::MaxComputeWorkGroupSize, - invocations: VkLimit::MaxComputeWorkGroupInvocations, - count: VkLimit::MaxComputeWorkGroupCount, - total: None, + total: VkLimit::MaxMeshWorkGroupTotalCount, }, } } @@ -3015,10 +2773,8 @@ fn check_grid(limits: &GroupLimits, g: [u32; 3]) -> Result<(), BindError> { )); } let total: u64 = g.iter().map(|&x| u64::from(x)).product(); - if let (Some(available), Some(limit)) = (limits.total, names.total) { - if total > u64::from(available) { - return Err(mesh_limit(limit, total, available)); - } + if total > u64::from(limits.total) { + return Err(mesh_limit(names.total, total, limits.total)); } Ok(()) } @@ -3163,24 +2919,13 @@ fn mesh_draw( if let Some(o) = &t.object { check_group(o, lo, flat(&object_keys), &t.multiples)?; } - // An emulated mesh function's threadgroups are folded into rows, so its direct grid is - // held to no axis limit. - match (groups, t.object.as_ref(), &t.records) { - (Some(_), Some(_), _) if folded => {} - (Some(g), Some(o), _) => check_grid(o, g)?, - (Some(g), None, None) => check_grid(&t.mesh, g)?, - (Some(_), None, Some(_)) | (None, _, _) => {} + match (groups, t.object.as_ref()) { + (Some(_), Some(_)) if folded => {} + (Some(g), Some(o)) => check_grid(o, g)?, + (Some(g), None) => check_grid(&t.mesh, g)?, + (None, _) => {} } } - // An emulated mesh function's threadgroups are a compute dispatch, and their primitives a - // draw of `NP · k` vertices each. - let (command, dispatch) = match &t.records { - None => (command, None), - Some(r) => { - let (command, dispatch) = emulated_draw(r, t.object.is_some(), draw, groups, launches)?; - (command, Some(dispatch)) - } - }; let object = t.object.is_some(); // A folded object function reads every grid builtin from its region record, and an unfolded // one whose wrapped grid leaves a partial threadgroup from its region (`MultiRegion` 1). @@ -3195,7 +2940,7 @@ fn mesh_draw( (true, Some(g), Some(o)) => { let task = MeshGridLimits { axes: o.count, - total: o.total.unwrap_or(u32::MAX), + total: o.total, }; let g = if launches { g } else { [0; 3] }; let fold = match asked.filter(|_| launches) { @@ -3268,198 +3013,11 @@ fn mesh_draw( specialization, object_region, mesh_region, - dispatch, fold, discards, }) } -/// The draw and the compute work of an emulated mesh draw `draw` under `r` ([`MeshDispatch`]), -/// of a pipeline with an object function where `object`: `groups` are the first stage's -/// threadgroups of a direct draw (`None` for an indirect one), `lo` the threads of an object -/// threadgroup, and a draw that `launches` nothing runs nothing and draws nothing. -/// -/// - A direct draw without an object function is the host's: `G` mesh threadgroups (refused as -/// a group count where they pass a `u32`), their records exactly (`maxStorageBufferRange`, -/// else `Unsupported{MeshShading}` naming it with the records' bytes), folded into rows of -/// `maxComputeWorkGroupCount[0]` (the rows within `maxComputeWorkGroupCount[1]`, else -/// refused naming it), and a draw of `G · NP · k` vertices (refused as a group count past a -/// `u32`). -/// - A direct draw with an object function dispatches its object threadgroups (`O`, whose -/// work buffer must be bindable whole, else refused naming `maxStorageBufferRange` with its -/// bytes), and an indirect draw without one reads Metal's arguments in the scan: both are -/// scanned, their records in the command buffer's pool. -/// - An indirect draw with an object function, of object threadgroups of `lo` threads, runs the -/// object arguments pass first (`MeshDispatch::object_arguments`), which reads Metal's -/// arguments, reserves the slots and offsets of its object threadgroups in the pool, and writes -/// the object dispatch, which reads its counts from the work buffer; then the scan, as above. -fn emulated_draw( - r: &RecordsTemplate, - object: bool, - draw: &DrawCall, - groups: Option<[u32; 3]>, - launches: bool, -) -> Result<(vk::DrawCommand, MeshDispatch), BindError> { - use crate::lower::mesh::work; - let group_vertices = r.group_vertices; - let over_range = |bytes: u64| mesh_limit(VkLimit::MaxStorageBufferRange, bytes, r.max_range); - let count_past = || { - BindError::Unsupported(Unsupported::not_representable(Feature::GroupCount { - axis: None, - })) - }; - let header = |objects: u32| { - let mut w = vec![0u32; work::HEADER as usize]; - w[work::OBJECT_GROUPS as usize] = objects; - w[work::SLOT_WORDS as usize] = r.slot_words; - // Within a `u32`: link sizes a threadgroup's records so (`lower::mesh::layout`). - w[work::GROUP_WORDS as usize] = r.group_words as u32; - w[work::GROUP_VERTICES as usize] = group_vertices; - w[work::ROW as usize] = r.row.max(1); - w - }; - let work_bytes = |objects: u64| -> Result { - let bytes = work::words(objects, r.slot_words).saturating_mul(4); - if bytes > u64::from(r.max_range) { - return Err(over_range(bytes)); - } - Ok(bytes) - }; - // The range of Metal's arguments at `offset` a pass binds, from the offset aligned down to - // `minStorageBufferOffsetAlignment`, and the arguments' byte in it. - let arguments_range = |offset: u64| { - let a = r.alignment.max(4); - let start = offset - offset % a; - let residual = offset - start; - let range = BufferRange { - offset: start, - range: residual + 12, - }; - (range, residual) - }; - let scanned = |objects: u32, object_groups, arguments| -> Result<_, BindError> { - let command = vk::DrawCommand::DrawIndirect { - offset: MeshDispatch::DRAW_OFFSET, - draw_count: 1, - stride: 16, - }; - let dispatch = MeshDispatch { - work: header(objects), - work_bytes: work_bytes(u64::from(objects))?, - object_groups, - object_arguments: None, - mesh: MeshGroups::Scanned { arguments }, - records: MeshRecordsRegion::Pool, - }; - Ok((command, dispatch)) - }; - match (object, groups.filter(|_| launches)) { - // The host's draw of `G` mesh threadgroups. - (false, Some(g)) => { - let total: u64 = g.iter().map(|&x| u64::from(x)).product(); - let t = u32::try_from(total).map_err(|_| count_past())?; - let bytes = total - .saturating_mul(r.group_words) - .saturating_mul(4) - .max(MIN_RECORDS_BYTES); - if bytes > u64::from(r.max_range) { - return Err(over_range(bytes)); - } - let vertices = t.checked_mul(group_vertices).ok_or_else(count_past)?; - let row = r.row.max(1); - let rows = t.div_ceil(row); - if rows > r.rows { - return Err(mesh_limit( - VkLimit::MaxComputeWorkGroupCount(1), - u64::from(rows), - r.rows, - )); - } - let folded = [t.min(row), rows, 1]; - let mut w = header(1); - w[work::MESH_GROUPS as usize] = t; - w[work::DISPATCH as usize..][..3].copy_from_slice(&folded); - w[work::DRAW as usize..][..4].copy_from_slice(&[vertices, 1, 0, 0]); - // Slot 0: the grid, then a zero payload; then the offsets 0 and `T`. - w.extend(g); - w.extend(std::iter::repeat_n( - 0, - r.slot_words.saturating_sub(3) as usize, - )); - w.extend([0, t]); - let command = vk::DrawCommand::Draw { - vertex_count: vertices, - instance_count: 1, - first_vertex: 0, - first_instance: 0, - }; - let dispatch = MeshDispatch { - work: w, - work_bytes: work_bytes(1)?, - object_groups: None, - object_arguments: None, - mesh: MeshGroups::Direct(folded), - records: MeshRecordsRegion::Exact(bytes), - }; - Ok((command, dispatch)) - } - // The object threadgroups set the mesh grids: scanned. - (true, Some(g)) => { - let objects: u64 = g.iter().map(|&x| u64::from(x)).product(); - let objects = u32::try_from(objects).map_err(|_| count_past())?; - scanned(objects, Some(g), None) - } - // Metal's arguments are the mesh grid: scanned from them. - (false, None) if launches => { - let DrawCall::MeshThreadgroupsIndirect { indirect, .. } = *draw else { - return Err(internal(format!("an indirect mesh draw of {draw:?}"))); - }; - let (range, residual) = arguments_range(indirect.offset); - let mut out = scanned(1, None, Some(range))?; - let word = u32::try_from(residual / 4 + 1).map_err(|_| count_past())?; - out.1.work[work::ARGUMENTS as usize] = word; - Ok(out) - } - // Metal's arguments are the object grid: the object arguments pass reads them, reserves - // the slots in the pool and writes the object dispatch; then the scan. - (true, None) if launches => { - let DrawCall::MeshThreadgroupsIndirect { indirect, .. } = *draw else { - return Err(internal(format!("an indirect mesh draw of {draw:?}"))); - }; - let range = arguments_range(indirect.offset); - let mut out = scanned(0, None, None)?; - let word = u32::try_from(range.1 / 4 + 1).map_err(|_| count_past())?; - out.1.work[work::OBJECT_ARGUMENTS as usize] = word; - out.1.object_arguments = Some(range.0); - Ok(out) - } - // A draw that launches nothing: no step runs, and nothing is drawn. - (_, _) => { - let command = vk::DrawCommand::Draw { - vertex_count: 0, - instance_count: 1, - first_vertex: 0, - first_instance: 0, - }; - let mut w = header(1); - w.extend(std::iter::repeat_n(0, r.slot_words as usize + 2)); - let dispatch = MeshDispatch { - work: w, - work_bytes: work_bytes(1)?, - object_groups: None, - object_arguments: None, - mesh: MeshGroups::Direct([0; 3]), - records: MeshRecordsRegion::Exact(MIN_RECORDS_BYTES), - }; - Ok((command, dispatch)) - } - } -} - -/// The fewest bytes of an emulated mesh function's records: a draw of no threadgroup still binds -/// them (the smallest binding). -const MIN_RECORDS_BYTES: u64 = 16; - /// What a patch draw of `p` instantiates ([`FactorTemplate`]), from the layout's factor, patch /// index and control-point index bindings and the device's `(minStorageBufferOffsetAlignment, /// maxStorageBufferRange)`: `None` for a pipeline that draws no patches. The control stage binds @@ -4042,7 +3600,6 @@ fn instantiate( index_bounds_pass, amplifications: amplifications_out, specialization: specialization_out, - mesh_dispatch: mesh_dispatch_out, mesh_arguments: mesh_arguments_out, object_fold: object_fold_out, discards_command_buffer: discards_out, @@ -4367,10 +3924,7 @@ fn instantiate( }; let index_unbounded = indirect_indices_unbounded(t.robust_index_fetch, draw); let amplifications = amplification_writes(t)?; - let (mesh_dispatch, specialization) = match mesh { - Some(m) => (m.dispatch, Some(m.specialization)), - None => (None, None), - }; + let specialization = mesh.map(|m| m.specialization); // The de-indexed form reads its indices in the vertex stage, by address, and binds no index // buffer. uses.clear(); @@ -4378,12 +3932,8 @@ fn instantiate( Some(indices) => uses.push(indices), None => draw_uses(uses, draw, overrun, t.tessellation.as_ref()), } - // An indirect mesh draw's arguments pass, or an emulated one's scan or object arguments pass, - // reads Metal's 12 bytes in the compute stage. - let scanned = mesh_dispatch.as_ref().is_some_and(|d| { - matches!(d.mesh, MeshGroups::Scanned { arguments: Some(_) }) || d.object_arguments.is_some() - }); - if scanned || mesh_arguments.is_some() { + // An indirect mesh draw's arguments pass reads Metal's 12 bytes in the compute stage. + if mesh_arguments.is_some() { uses.push(ResourceUse { resource: UseTarget::Indirect, access: AccessSet::READ, @@ -4400,7 +3950,6 @@ fn instantiate( *draw_command = command; *overrun_out = overrun; *amplifications_out = amplifications; - *mesh_dispatch_out = mesh_dispatch; *specialization_out = specialization; Ok(()) } diff --git a/crates/metal2vulkan/src/bind/graphics/tests.rs b/crates/metal2vulkan/src/bind/graphics/tests.rs index e42a66410..2570051af 100644 --- a/crates/metal2vulkan/src/bind/graphics/tests.rs +++ b/crates/metal2vulkan/src/bind/graphics/tests.rs @@ -1501,13 +1501,12 @@ fn mesh_template(flat: bool, multiples: Vec) -> GraphicsTemplate { size: [256; 3], invocations: 256, count: [65535; 3], - total: Some(1 << 22), + total: 1 << 22, stage: GroupStage::Mesh, }, object: None, folded: false, partial_groups: false, - records: None, }), shader_tests: None, deindexed: None, @@ -1566,7 +1565,7 @@ fn object_template() -> GraphicsTemplate { size: [128; 3], invocations: 128, count: [65535; 3], - total: Some(1 << 22), + total: 1 << 22, stage: crate::bind::plan::GroupStage::Task, }); t diff --git a/crates/metal2vulkan/src/bind/mesh_arguments.rs b/crates/metal2vulkan/src/bind/mesh_arguments.rs index c2da76c21..67d2d3f38 100644 --- a/crates/metal2vulkan/src/bind/mesh_arguments.rs +++ b/crates/metal2vulkan/src/bind/mesh_arguments.rs @@ -94,7 +94,6 @@ use std::sync::Arc; use crate::bind::instantiate::{BufferRange, IndirectRef}; -use crate::bind::mesh_scan::{div_ceil, for_range}; use crate::bind::replay::checked_mul; use crate::bind::status::{StatusBits, StatusWord}; use crate::budget::{Budget, Meter}; @@ -104,7 +103,7 @@ use crate::error::{Error, InternalError, InternalKind}; use crate::pipeline::sym::{ PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, Stage, Symbol, SyntheticBinding, }; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; +use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; use crate::spirv::error::BResult; use crate::spirv::ids::{GlobalId, TypeId, Value}; @@ -501,6 +500,43 @@ fn u32_value(f: &mut FunctionBuilder<'_>, v: u32) -> BResult { f.module().const_value(c) } +/// `a / b` rounded up (`b` not 0), without wrapping. +fn div_ceil(f: &mut FunctionBuilder<'_>, a: Value, b: Value) -> BResult { + let q = f.binary(BinOp::UDiv, a, b)?; + let r = f.binary(BinOp::UMod, a, b)?; + let zero = u32_value(f, 0)?; + let one = u32_value(f, 1)?; + let partial = f.binary(BinOp::INotEqual, r, zero)?; + let extra = f.select(partial, one, zero)?; + f.binary(BinOp::IAdd, q, extra) +} + +/// Run `each(f, i)` for `i` from `lo` below `hi`. +fn for_range<'a>( + f: &mut FunctionBuilder<'_>, + u32_: TypeId, + (lo, hi): (Value, Value), + each: impl FnOnce(&mut FunctionBuilder<'_>, Value) -> BResult<()> + 'a, +) -> BResult<()> { + let var = f.local_var(u32_, None)?; + let counter = f.var_ptr(var)?; + f.store(counter, lo, MemAccess::default())?; + let body: LoopFn<'a, ()> = Box::new(move |f, _, lc| { + let i = f.load(counter, MemAccess::default())?; + let done = f.binary(BinOp::UGreaterThanEqual, i, hi)?; + let exit: ArmFn<'_, ()> = Box::new(move |f, _| { + lc.break_(f)?; + Ok(ArmEnd::Exits) + }); + f.if_(&mut (), done, exit, None)?; + let one = u32_value(f, 1)?; + let next = f.binary(BinOp::IAdd, i, one)?; + f.store(counter, next, MemAccess::default())?; + each(f, i) + }); + f.loop_(&mut (), LoopSpec::default(), body) +} + /// Whether `v`'s product is at most `total`, without overflow and without a division: a zero /// count's product is 0, and otherwise the product is within where neither multiplication's high /// word is set and its low word is at most `total` (`checked_mul`, as `bind::replay`'s). diff --git a/crates/metal2vulkan/src/bind/mesh_scan.rs b/crates/metal2vulkan/src/bind/mesh_scan.rs deleted file mode 100644 index b5f9b6606..000000000 --- a/crates/metal2vulkan/src/bind/mesh_scan.rs +++ /dev/null @@ -1,749 +0,0 @@ -//! The mesh scan of an emulated mesh draw whose mesh threadgroups only the GPU knows: a draw of a -//! pipeline with an object function, whose object threadgroups each set the mesh grid they launch, -//! and an indirect draw, whose mesh grid is Metal's indirect arguments. -//! -//! One workgroup of [`MeshScanModule::LOCAL_SIZE`] invocations reads the draw's work buffer -//! (`SyntheticBinding::MeshWork`, [`MeshDispatch::work`](crate::bind::MeshDispatch::work)): the -//! grid each of its `O` object threadgroups set (slot 0's, of an indirect draw, from Metal's -//! arguments, held to Metal's limits on a mesh grid as an object function's grid is), and -//! writes, after the slots: -//! -//! - each object threadgroup's first mesh threadgroup, in object threadgroup order, and `T`, the -//! draw's mesh threadgroups (the offsets the mesh function's wrapper bisects); -//! - in the header, `T`, where the draw's records begin in the command buffer's records pool -//! (`RECORDS_BASE`), the mesh dispatch's `VkDispatchIndirectCommand` (`T` folded into rows of -//! the header's `ROW` workgroups) and the draw's `VkDrawIndirectCommand` (`T · NP · k` -//! vertices). -//! -//! The draw's records are reserved from the records pool's cursor -//! ([`StatusWord::MeshRecordsCursor`], 0 before the command buffer's first scan): `T` mesh -//! threadgroups' words. A draw whose records the rest of the pool cannot hold, or whose vertices -//! pass a `u32`, runs and draws nothing; the scan sets [`StatusBits::MESH_RECORDS_OVERFLOW`] and, -//! where it is the command buffer's first records fault, the consumer's number for the draw, its object threadgroups and the mesh threadgroups it needed -//! (saturated) in the fault words, which -//! [`ExecutionStatus::decode`](crate::bind::ExecutionStatus::decode) reports. Nothing is drawn -//! short silently. -//! -//! **Bindings** (set 0, storage buffers): [`MeshScanModule::WORK_BINDING`] (the draw's work -//! buffer, whole), `STATUS_BINDING` (the command buffer's `ExecutionStatus` buffer) and -//! `ARGUMENTS_BINDING` (for an indirect draw, the Metal indirect buffer's range from the -//! arguments' offset aligned down to `minStorageBufferOffsetAlignment`; for any other draw any 4 -//! bytes, which nothing reads). Every read of the arguments is contained. -//! -//! **Synchronization** (consumer): the object dispatch's writes, the arguments' writes and the -//! upload of the work buffer → `SHADER_READ` in `COMPUTE_SHADER` before the scan; scans one -//! after another (each reads and writes the pool's cursor); the scan's writes → -//! `INDIRECT_COMMAND_READ` in `DRAW_INDIRECT` and `SHADER_READ` in `COMPUTE_SHADER` before the -//! mesh dispatch, and in `VERTEX_SHADER` before the draw. - -use std::sync::Arc; - -use crate::bind::index_bounds::finished; -use crate::bind::mesh_arguments::{ - METAL_MESH_GRID_AXIS, METAL_MESH_GRID_TOTAL, METAL_OBJECT_GRID_TOTAL, -}; -use crate::bind::replay::checked_mul; -use crate::bind::status::{StatusBits, StatusWord}; -use crate::device::requirements::Requirements; -use crate::device::Device; -use crate::error::Error; -use crate::lower::mesh::work; -use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, Symbol, SyntheticBinding}; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, TypeId, Value}; -use crate::spirv::ir::{ - natural_layout, AtomicOp, BinOp, ConstBits, Constant, ExecMode, ExecModel, GlslOp, IoDir, - LayoutRule, MemAccess, MemoryOrder, Scope, Semantics, StorageClass, Type, TypedModule, UnOp, -}; - -/// The crate-owned mesh scan module of one device, validated like any output. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MeshScanModule { - /// SPIR-V 1.5 words, entry point `main`, bindings numbered as below in set 0. - pub spirv: Arc<[u32]>, - /// What the module needs from the device (within every Vulkan 1.2 device). - pub requirements: Requirements, -} - -impl MeshScanModule { - /// Descriptor set of every binding. - pub const SET: u32 = 0; - /// The draw's work buffer, a storage buffer. - pub const WORK_BINDING: u32 = 0; - /// The command buffer's `ExecutionStatus` buffer, a storage buffer. - pub const STATUS_BINDING: u32 = 1; - /// The Metal indirect buffer, a storage buffer. - pub const ARGUMENTS_BINDING: u32 = 2; - /// The draw's records, a storage buffer: the command buffer's records pool, where an indirect - /// draw with an object function keeps its slots and offsets (`MeshDispatch::object_arguments`). - pub const RECORDS_BINDING: u32 = 3; - /// Invocations of the one workgroup, along x. - pub const LOCAL_SIZE: u32 = 64; -} - -/// The work buffer's binding symbol in the typed module. -pub const WORK: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 0, -}; -/// The arguments' binding symbol ([`MeshScanModule::ARGUMENTS_BINDING`]). -pub const ARGUMENTS: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 1, -}; -/// The records' binding symbol ([`MeshScanModule::RECORDS_BINDING`]). -pub const RECORDS: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 2, -}; -/// The status buffer's binding symbol ([`MeshScanModule::STATUS_BINDING`]). -pub const STATUS: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Synthetic(SyntheticBinding::ExecutionStatus), - index: 0, -}; - -/// A `Block { u32 words[]; }` storage buffer bound at `sym`. -pub(crate) fn words_buffer( - b: &mut ModuleBuilder, - sym: ResourceSlot, - u32_: TypeId, -) -> BResult { - let rta = b.ty(Type::RuntimeArray { - elem: u32_, - stride: Some(4), - })?; - let layout = natural_layout(b.types(), LayoutRule::Std430, true, &[rta])?; - let block = b.ty(Type::Struct { - members: [rta].into(), - layout: Some(layout), - })?; - b.resource(sym, StorageClass::StorageBuffer, block) -} - -pub(crate) fn k(f: &mut FunctionBuilder<'_>, v: u32) -> BResult { - let c = f.u32_const(v)?; - f.module().const_value(c) -} - -/// The pointer to word `index` of `buffer`'s runtime array. -pub(crate) fn word_ptr(f: &mut FunctionBuilder<'_>, buffer: Value, index: Value) -> BResult { - let zero = k(f, 0)?; - f.access_chain(buffer, &[zero, index]) -} - -pub(crate) fn load(f: &mut FunctionBuilder<'_>, buffer: Value, index: Value) -> BResult { - let p = word_ptr(f, buffer, index)?; - f.load(p, MemAccess::default()) -} - -pub(crate) fn load_at(f: &mut FunctionBuilder<'_>, buffer: Value, index: u32) -> BResult { - let i = k(f, index)?; - load(f, buffer, i) -} - -pub(crate) fn store( - f: &mut FunctionBuilder<'_>, - buffer: Value, - index: Value, - v: Value, -) -> BResult<()> { - let p = word_ptr(f, buffer, index)?; - f.store(p, v, MemAccess::default()) -} - -pub(crate) fn store_at( - f: &mut FunctionBuilder<'_>, - buffer: Value, - index: u32, - v: Value, -) -> BResult<()> { - let i = k(f, index)?; - store(f, buffer, i, v) -} - -/// Word `index` of `buffer` where it lies inside the buffer's bound range, else 0 (contained). -fn contained(f: &mut FunctionBuilder<'_>, buffer: Value, index: Value) -> BResult { - let zero = k(f, 0)?; - let len = f.array_length(buffer, 0)?; - let inside = f.binary(BinOp::ULessThan, index, len)?; - let safe = f.select(inside, index, zero)?; - let loaded = load(f, buffer, safe)?; - f.select(inside, loaded, zero) -} - -/// `a + b`, or `u32::MAX` where it wraps. -pub(crate) fn saturating_add(f: &mut FunctionBuilder<'_>, a: Value, b: Value) -> BResult { - let sum = f.binary(BinOp::IAdd, a, b)?; - let wrapped = f.binary(BinOp::ULessThan, sum, a)?; - let max = k(f, u32::MAX)?; - f.select(wrapped, max, sum) -} - -/// `a / b` rounded up (`b` not 0), without wrapping. -pub(crate) fn div_ceil(f: &mut FunctionBuilder<'_>, a: Value, b: Value) -> BResult { - let q = f.binary(BinOp::UDiv, a, b)?; - let r = f.binary(BinOp::UMod, a, b)?; - let zero = k(f, 0)?; - let one = k(f, 1)?; - let partial = f.binary(BinOp::INotEqual, r, zero)?; - let extra = f.select(partial, one, zero)?; - f.binary(BinOp::IAdd, q, extra) -} - -/// The threadgroups of grid `g`: `x · y · z` where the grid lies within Metal's limits on a mesh -/// grid ([`METAL_MESH_GRID_AXIS`] along each axis, [`METAL_MESH_GRID_TOTAL`] in all, as an -/// emulated object function holds the grid it sets), else 0. The product compared wraps only -/// where an earlier test fails. -fn bounded_groups(f: &mut FunctionBuilder<'_>, [x, y, z]: [Value; 3]) -> BResult { - let one = k(f, 1)?; - let total = k(f, METAL_MESH_GRID_TOTAL)?; - let ny = f.glsl(GlslOp::UMax, &[y, one])?; - let room = f.binary(BinOp::UDiv, total, ny)?; - let mut all = f.binary(BinOp::ULessThanEqual, x, room)?; - let xy = f.binary(BinOp::IMul, x, y)?; - let nz = f.glsl(GlslOp::UMax, &[z, one])?; - let room = f.binary(BinOp::UDiv, total, nz)?; - let c = f.binary(BinOp::ULessThanEqual, xy, room)?; - all = f.binary(BinOp::LogicalAnd, all, c)?; - let axis = k(f, METAL_MESH_GRID_AXIS)?; - for v in [x, y, z] { - let c = f.binary(BinOp::ULessThanEqual, v, axis)?; - all = f.binary(BinOp::LogicalAnd, all, c)?; - } - let xyz = f.binary(BinOp::IMul, xy, z)?; - let zero = k(f, 0)?; - f.select(all, xyz, zero) -} - -/// Run `each(f, i)` for `i` from `lo` below `hi`. -pub(crate) fn for_range<'a>( - f: &mut FunctionBuilder<'_>, - u32_: TypeId, - (lo, hi): (Value, Value), - each: impl FnOnce(&mut FunctionBuilder<'_>, Value) -> BResult<()> + 'a, -) -> BResult<()> { - let var = f.local_var(u32_, None)?; - let counter = f.var_ptr(var)?; - f.store(counter, lo, MemAccess::default())?; - let body: LoopFn<'a, ()> = Box::new(move |f, _, lc| { - let i = f.load(counter, MemAccess::default())?; - let done = f.binary(BinOp::UGreaterThanEqual, i, hi)?; - let exit: ArmFn<'_, ()> = Box::new(move |f, _| { - lc.break_(f)?; - Ok(ArmEnd::Exits) - }); - f.if_(&mut (), done, exit, None)?; - let one = k(f, 1)?; - let next = f.binary(BinOp::IAdd, i, one)?; - f.store(counter, next, MemAccess::default())?; - each(f, i) - }); - f.loop_(&mut (), LoopSpec::default(), body) -} - -/// Where the draw's slots and offsets begin (`work::SLOTS`): whether in the records, and the word -/// of their first in the buffer that holds them. -#[derive(Clone, Copy)] -pub(crate) struct Slots { - work: Value, - records: Value, - pooled: Value, - start: Value, -} - -impl Slots { - pub(crate) fn of(f: &mut FunctionBuilder<'_>, work: Value, records: Value) -> BResult { - let word = load_at(f, work, work::SLOTS)?; - let zero = k(f, 0)?; - let one = k(f, 1)?; - let pooled = f.binary(BinOp::INotEqual, word, zero)?; - let in_pool = f.binary(BinOp::ISub, word, one)?; - let header = k(f, work::HEADER)?; - let start = f.select(pooled, in_pool, header)?; - Ok(Slots { - work, - records, - pooled, - start, - }) - } - - /// Word `at` of the slots and offsets (from their first). - pub(crate) fn load(self, f: &mut FunctionBuilder<'_>, at: Value) -> BResult { - let zero = k(f, 0)?; - let at = f.binary(BinOp::IAdd, self.start, at)?; - let in_work = f.select(self.pooled, zero, at)?; - let in_pool = f.select(self.pooled, at, zero)?; - let from_work = load(f, self.work, in_work)?; - let from_pool = load(f, self.records, in_pool)?; - f.select(self.pooled, from_pool, from_work) - } - - /// Store `v` at word `at` of the slots and offsets (from their first). - pub(crate) fn store(self, f: &mut FunctionBuilder<'_>, at: Value, v: Value) -> BResult<()> { - let at = f.binary(BinOp::IAdd, self.start, at)?; - let (records, work) = (self.records, self.work); - let pool: ArmFn<'_, ()> = Box::new(move |f, _| { - store(f, records, at, v)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - let local: ArmFn<'_, ()> = Box::new(move |f, _| { - store(f, work, at, v)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - f.if_(&mut (), self.pooled, pool, Some(local))?; - Ok(()) - } -} - -/// Run `then(f)` where `c` holds. -pub(crate) fn when<'a>( - f: &mut FunctionBuilder<'_>, - c: Value, - then: impl FnOnce(&mut FunctionBuilder<'_>) -> BResult<()> + 'a, -) -> BResult<()> { - let arm: ArmFn<'a, ()> = Box::new(move |f, _| { - then(f)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - f.if_(&mut (), c, arm, None)?; - Ok(()) -} - -/// The workgroup barrier over the partial sums. -pub(crate) fn barrier(f: &mut FunctionBuilder<'_>) -> BResult<()> { - let sem = Semantics { - order: MemoryOrder::AcquireRelease, - workgroup_memory: true, - ..Semantics::RELAXED - }; - f.control_barrier(Scope::Workgroup, Scope::Workgroup, sem) -} - -/// The scan as a typed module, before serialization: the module [`mesh_scan_module`] serializes, -/// which the CPU interpreter runs. Its bindings are the symbols [`WORK`], [`ARGUMENTS`] and -/// [`STATUS`]. -pub fn scan_typed_module() -> BResult { - let mut b = ModuleBuilder::new(); - let u32_ = b.ty(Type::Int { - width: 32, - signed: false, - })?; - let lanes = b.constant(Constant::Scalar { - ty: u32_, - bits: ConstBits(u64::from(MeshScanModule::LOCAL_SIZE)), - })?; - let partial_ty = b.ty(Type::Array { - elem: u32_, - len: lanes, - stride: None, - })?; - let partial = b.plain_global(StorageClass::Workgroup, partial_ty, None)?; - let total_var = b.plain_global(StorageClass::Workgroup, u32_, None)?; - let work = words_buffer(&mut b, WORK, u32_)?; - let arguments = words_buffer(&mut b, ARGUMENTS, u32_)?; - let status = words_buffer(&mut b, STATUS, u32_)?; - let records = words_buffer(&mut b, RECORDS, u32_)?; - let invocation = b.builtin( - crate::spv::BuiltIn::LocalInvocationIndex, - IoDir::Input, - u32_, - )?; - let void = b.ty(Type::Void)?; - let mut f = b.function(void)?; - let work = f.module().global_value(work)?; - let arguments = f.module().global_value(arguments)?; - let status = f.module().global_value(status)?; - let records = f.module().global_value(records)?; - let partial = f.module().global_value(partial)?; - let total_var = f.module().global_value(total_var)?; - let invocation = f.module().global_value(invocation)?; - let lin = f.load(invocation, MemAccess::default())?; - let zero = k(&mut f, 0)?; - let one = k(&mut f, 1)?; - let first = f.binary(BinOp::IEqual, lin, zero)?; - - let objects = load_at(&mut f, work, work::OBJECT_GROUPS)?; - let slot_words = load_at(&mut f, work, work::SLOT_WORDS)?; - let group_words = load_at(&mut f, work, work::GROUP_WORDS)?; - let group_vertices = load_at(&mut f, work, work::GROUP_VERTICES)?; - let pool_words = load_at(&mut f, work, work::POOL_WORDS)?; - let draw_id = load_at(&mut f, work, work::DRAW_ID)?; - let row = load_at(&mut f, work, work::ROW)?; - let argument_word = load_at(&mut f, work, work::ARGUMENTS)?; - let slots = Slots::of(&mut f, work, records)?; - - // An indirect draw's grid (slot 0, `O = 1`): Metal's arguments, read by every invocation. - let indirect = f.binary(BinOp::INotEqual, argument_word, zero)?; - let at = f.binary(BinOp::ISub, argument_word, one)?; - let mut grid = Vec::with_capacity(3); - for i in 0..3 { - let i = k(&mut f, i)?; - let w = f.binary(BinOp::IAdd, at, i)?; - let w = f.select(indirect, w, zero)?; - let v = contained(&mut f, arguments, w)?; - grid.push(f.select(indirect, v, zero)?); - } - let argued = bounded_groups(&mut f, [grid[0], grid[1], grid[2]])?; - let held = f.binary(BinOp::INotEqual, argued, zero)?; - let write_grid = f.binary(BinOp::LogicalAnd, indirect, first)?; - when(&mut f, write_grid, move |f| { - let zero = k(f, 0)?; - for (i, v) in grid.into_iter().enumerate() { - let v = f.select(held, v, zero)?; - let at = k(f, work::HEADER + i as u32)?; - store(f, work, at, v)?; - } - Ok(()) - })?; - // The mesh threadgroups object threadgroup `o` launches. - let groups = move |f: &mut FunctionBuilder<'_>, o: Value| -> BResult { - let slot = f.binary(BinOp::IMul, o, slot_words)?; - let mut g = [slot; 3]; - for (i, v) in g.iter_mut().enumerate() { - let off = k(f, i as u32)?; - let w = f.binary(BinOp::IAdd, slot, off)?; - *v = slots.load(f, w)?; - } - let set = bounded_groups(f, g)?; - f.select(indirect, argued, set) - }; - - // Each invocation's run of object threadgroups: `[lin · c, lin · c + c)` within `O`. - let lanes = k(&mut f, MeshScanModule::LOCAL_SIZE)?; - let chunk = div_ceil(&mut f, objects, lanes)?; - let start = f.binary(BinOp::IMul, lin, chunk)?; - let lo = f.glsl(GlslOp::UMin, &[start, objects])?; - let end = f.binary(BinOp::IAdd, lo, chunk)?; - let hi = f.glsl(GlslOp::UMin, &[end, objects])?; - let sum_var = f.local_var(u32_, None)?; - let sum = f.var_ptr(sum_var)?; - f.store(sum, zero, MemAccess::default())?; - for_range(&mut f, u32_, (lo, hi), move |f, o| { - let n = groups(f, o)?; - let s = f.load(sum, MemAccess::default())?; - let s = saturating_add(f, s, n)?; - f.store(sum, s, MemAccess::default()) - })?; - let mine = f.load(sum, MemAccess::default())?; - let own = f.access_chain(partial, &[lin])?; - f.store(own, mine, MemAccess::default())?; - barrier(&mut f)?; - // The first invocation turns the sums into each run's first mesh threadgroup. - when(&mut f, first, move |f| { - let zero = k(f, 0)?; - let lanes = k(f, MeshScanModule::LOCAL_SIZE)?; - f.store(sum, zero, MemAccess::default())?; - for_range(f, u32_, (zero, lanes), move |f, t| { - let p = f.access_chain(partial, &[t])?; - let part = f.load(p, MemAccess::default())?; - let running = f.load(sum, MemAccess::default())?; - f.store(p, running, MemAccess::default())?; - let next = saturating_add(f, running, part)?; - f.store(sum, next, MemAccess::default()) - })?; - let total = f.load(sum, MemAccess::default())?; - f.store(total_var, total, MemAccess::default()) - })?; - barrier(&mut f)?; - // The offsets of the run's object threadgroups. - let offsets = f.binary(BinOp::IMul, objects, slot_words)?; - let own = f.access_chain(partial, &[lin])?; - let base = f.load(own, MemAccess::default())?; - f.store(sum, base, MemAccess::default())?; - for_range(&mut f, u32_, (lo, hi), move |f, o| { - let running = f.load(sum, MemAccess::default())?; - let at = f.binary(BinOp::IAdd, offsets, o)?; - slots.store(f, at, running)?; - let n = groups(f, o)?; - let next = saturating_add(f, running, n)?; - f.store(sum, next, MemAccess::default()) - })?; - // The first invocation reserves the records and writes the dispatch and the draw. - when(&mut f, first, move |f| { - let zero = k(f, 0)?; - let one = k(f, 1)?; - let total = f.load(total_var, MemAccess::default())?; - let at = f.binary(BinOp::IAdd, offsets, objects)?; - slots.store(f, at, total)?; - let cursor_at = k(f, StatusWord::MeshRecordsCursor.index())?; - let cursor_ptr = word_ptr(f, status, cursor_at)?; - let cursor = f.load(cursor_ptr, MemAccess::default())?; - let used = f.glsl(GlslOp::UMin, &[cursor, pool_words])?; - let room = f.binary(BinOp::ISub, pool_words, used)?; - let gw = f.glsl(GlslOp::UMax, &[group_words, one])?; - let fit = f.binary(BinOp::UDiv, room, gw)?; - let fits = f.binary(BinOp::ULessThanEqual, total, fit)?; - // The draw's vertices fit a `u32` where the product's high word is 0 - // (`replay::checked_mul`, whose docs say why). - let gv = f.glsl(GlslOp::UMax, &[group_vertices, one])?; - let (_, past) = checked_mul(f, total, gv, zero)?; - let drawable = f.unary(UnOp::LogicalNot, past)?; - let ok = f.binary(BinOp::LogicalAnd, fits, drawable)?; - let t = f.select(ok, total, zero)?; - let words = f.binary(BinOp::IMul, t, group_words)?; - let next = f.binary(BinOp::IAdd, used, words)?; - let cursor_after = f.select(ok, next, cursor)?; - f.store(cursor_ptr, cursor_after, MemAccess::default())?; - let records_base = f.select(ok, used, zero)?; - let row = f.glsl(GlslOp::UMax, &[row, one])?; - let x = f.glsl(GlslOp::UMin, &[t, row])?; - let y = div_ceil(f, t, row)?; - let vertices = f.binary(BinOp::IMul, t, group_vertices)?; - for (at, v) in [ - (work::MESH_GROUPS, t), - (work::RECORDS_BASE, records_base), - (work::DISPATCH, x), - (work::DISPATCH + 1, y), - (work::DISPATCH + 2, one), - (work::DRAW, vertices), - (work::DRAW + 1, one), - (work::DRAW + 2, zero), - (work::DRAW + 3, zero), - ] { - store_at(f, work, at, v)?; - } - // A draw the pool cannot hold, or whose vertices pass a `u32`, draws nothing and says - // so; the command buffer's first such draw is named. - let over = f.unary(UnOp::LogicalNot, ok)?; - when(f, over, move |f| { - let zero = k(f, 0)?; - let word = k(f, StatusWord::Status.index())?; - let bit = k(f, StatusBits::MESH_RECORDS_OVERFLOW.0)?; - let p = word_ptr(f, status, word)?; - let old = f.atomic(AtomicOp::Or, p, Scope::Device, Semantics::RELAXED, bit)?; - let had = f.binary(BinOp::BitwiseAnd, old, bit)?; - let new = f.binary(BinOp::IEqual, had, zero)?; - when(f, new, move |f| { - for (w, v) in [ - (StatusWord::MeshFaultDraw, draw_id), - (StatusWord::MeshFaultObjects, objects), - (StatusWord::MeshFaultGroups, total), - ] { - store_at(f, status, w.index(), v)?; - } - Ok(()) - }) - }) - })?; - f.ret(None)?; - let id = f.finish()?; - b.entry( - ExecModel::GLCompute, - id, - vec![ExecMode::LocalSize { - x: MeshScanModule::LOCAL_SIZE, - y: 1, - z: 1, - }], - )?; - b.finalize() -} - -/// The object arguments pass as a typed module, before serialization: the module -/// [`mesh_object_arguments_module`] serializes for a device of `compute` -/// (`maxComputeWorkGroupCount`), which the CPU interpreter runs. One invocation reads Metal's -/// arguments, the object grid, at the header's `OBJECT_ARGUMENTS` word (the module docs), and: -/// -/// - a grid with a zero count runs nothing; -/// - one of more threadgroups than [`METAL_OBJECT_GRID_TOTAL`], which Metal's GPU discards, runs -/// nothing and sets [`StatusBits::MESH_GRID_DISCARDED`]; -/// - one with a count past `compute` on its axis runs nothing and sets -/// [`StatusBits::MESH_GRID_PAST_LIMITS`] (a grid whose threads per grid wrap along an axis runs: -/// the object function reports the wrapped grid, `lower::dispatch`'s object grid); -/// - else it reserves `O · S + O + 1` words of the records pool from its cursor for the slots and -/// offsets, and writes `O` (`OBJECT_GROUPS`), their first word plus 1 (`SLOTS`) and the object -/// dispatch (`OBJECT_DISPATCH`, the grid); where the rest of the pool cannot hold them it runs -/// nothing and sets [`StatusBits::MESH_RECORDS_OVERFLOW`], naming the draw and its object -/// threadgroups (and no mesh threadgroup) where it is the command buffer's first records fault. -/// -/// A grid that runs nothing writes 0 for `O`, `SLOTS` and the dispatch. Its bindings are the -/// scan's. -pub fn object_arguments_typed_module(compute: [u32; 3]) -> BResult { - let mut b = ModuleBuilder::new(); - let u32_ = b.ty(Type::Int { - width: 32, - signed: false, - })?; - let work = words_buffer(&mut b, WORK, u32_)?; - let arguments = words_buffer(&mut b, ARGUMENTS, u32_)?; - let status = words_buffer(&mut b, STATUS, u32_)?; - // The records are bound for the scan's layout; this pass only reserves from their cursor. - words_buffer(&mut b, RECORDS, u32_)?; - let void = b.ty(Type::Void)?; - let mut f = b.function(void)?; - let work = f.module().global_value(work)?; - let arguments = f.module().global_value(arguments)?; - let status = f.module().global_value(status)?; - let zero = k(&mut f, 0)?; - let one = k(&mut f, 1)?; - let argument_word = load_at(&mut f, work, work::OBJECT_ARGUMENTS)?; - let at = f.binary(BinOp::ISub, argument_word, one)?; - let mut grid = [zero; 3]; - let mut any_zero = boolean(&mut f, false)?; - let mut past = boolean(&mut f, false)?; - for (i, g) in grid.iter_mut().enumerate() { - let off = k(&mut f, i as u32)?; - let w = f.binary(BinOp::IAdd, at, off)?; - *g = contained(&mut f, arguments, w)?; - let z = f.binary(BinOp::IEqual, *g, zero)?; - any_zero = f.binary(BinOp::LogicalOr, any_zero, z)?; - let limit = k(&mut f, compute[i])?; - let over = f.binary(BinOp::UGreaterThan, *g, limit)?; - past = f.binary(BinOp::LogicalOr, past, over)?; - } - let some = f.unary(UnOp::LogicalNot, any_zero)?; - let (xy, wraps_xy) = checked_mul(&mut f, grid[0], grid[1], zero)?; - let (n, wraps_n) = checked_mul(&mut f, xy, grid[2], zero)?; - let mut many = f.binary(BinOp::LogicalOr, wraps_xy, wraps_n)?; - let most = k(&mut f, METAL_OBJECT_GRID_TOTAL)?; - let over = f.binary(BinOp::UGreaterThan, n, most)?; - many = f.binary(BinOp::LogicalOr, many, over)?; - let discarded = f.binary(BinOp::LogicalAnd, some, many)?; - let kept = f.unary(UnOp::LogicalNot, many)?; - let past = f.binary(BinOp::LogicalAnd, past, kept)?; - let past = f.binary(BinOp::LogicalAnd, past, some)?; - // The slots and offsets: `n · S + n + 1` words, held below 2^29 · 2^17 by the grid's bound - // and the slot's (a payload of at most 16 KiB); counted without wrapping all the same. - let slot_words = load_at(&mut f, work, work::SLOT_WORDS)?; - let pool_words = load_at(&mut f, work, work::POOL_WORDS)?; - let draw_id = load_at(&mut f, work, work::DRAW_ID)?; - let (slots, wraps_slots) = checked_mul(&mut f, n, slot_words, zero)?; - let offsets = f.binary(BinOp::IAdd, n, one)?; - let words = saturating_add(&mut f, slots, offsets)?; - let cursor_at = k(&mut f, StatusWord::MeshRecordsCursor.index())?; - let cursor_ptr = word_ptr(&mut f, status, cursor_at)?; - let cursor = f.load(cursor_ptr, MemAccess::default())?; - let used = f.glsl(GlslOp::UMin, &[cursor, pool_words])?; - let room = f.binary(BinOp::ISub, pool_words, used)?; - let fits = f.binary(BinOp::ULessThanEqual, words, room)?; - let wraps_slots = f.unary(UnOp::LogicalNot, wraps_slots)?; - let fits = f.binary(BinOp::LogicalAnd, fits, wraps_slots)?; - let launched = f.binary(BinOp::LogicalOr, discarded, past)?; - let launched = f.unary(UnOp::LogicalNot, launched)?; - let launched = f.binary(BinOp::LogicalAnd, launched, some)?; - let runs = f.binary(BinOp::LogicalAnd, launched, fits)?; - let short = f.unary(UnOp::LogicalNot, fits)?; - let overflow = f.binary(BinOp::LogicalAnd, launched, short)?; - let next = f.binary(BinOp::IAdd, used, words)?; - let cursor_after = f.select(runs, next, cursor)?; - f.store(cursor_ptr, cursor_after, MemAccess::default())?; - let first_word = f.binary(BinOp::IAdd, used, one)?; - let objects = f.select(runs, n, zero)?; - let slots_word = f.select(runs, first_word, zero)?; - store_at(&mut f, work, work::OBJECT_GROUPS, objects)?; - store_at(&mut f, work, work::SLOTS, slots_word)?; - for (i, g) in grid.into_iter().enumerate() { - let v = f.select(runs, g, zero)?; - store_at(&mut f, work, work::OBJECT_DISPATCH + i as u32, v)?; - } - // What runs nothing says why: Metal's discard, the device's limits, or the pool. - let discard_bit = k(&mut f, StatusBits::MESH_GRID_DISCARDED.0)?; - let past_bit = k(&mut f, StatusBits::MESH_GRID_PAST_LIMITS.0)?; - let discard_bit = f.select(discarded, discard_bit, zero)?; - let past_bit = f.select(past, past_bit, zero)?; - let bits = f.binary(BinOp::BitwiseOr, discard_bit, past_bit)?; - let set = f.binary(BinOp::INotEqual, bits, zero)?; - when(&mut f, set, move |f| { - let word = k(f, StatusWord::Status.index())?; - let p = word_ptr(f, status, word)?; - f.atomic(AtomicOp::Or, p, Scope::Device, Semantics::RELAXED, bits)?; - Ok(()) - })?; - when(&mut f, overflow, move |f| { - let zero = k(f, 0)?; - let word = k(f, StatusWord::Status.index())?; - let bit = k(f, StatusBits::MESH_RECORDS_OVERFLOW.0)?; - let p = word_ptr(f, status, word)?; - let old = f.atomic(AtomicOp::Or, p, Scope::Device, Semantics::RELAXED, bit)?; - let had = f.binary(BinOp::BitwiseAnd, old, bit)?; - let new = f.binary(BinOp::IEqual, had, zero)?; - when(f, new, move |f| { - let zero = k(f, 0)?; - for (w, v) in [ - (StatusWord::MeshFaultDraw, draw_id), - (StatusWord::MeshFaultObjects, n), - (StatusWord::MeshFaultGroups, zero), - ] { - store_at(f, status, w.index(), v)?; - } - Ok(()) - }) - })?; - f.ret(None)?; - let id = f.finish()?; - b.entry( - ExecModel::GLCompute, - id, - vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }], - )?; - b.finalize() -} - -/// The `bool` constant `v`. -fn boolean(f: &mut FunctionBuilder<'_>, v: bool) -> BResult { - let ty = f.module().ty(Type::Bool)?; - let c = f.module().constant(Constant::Scalar { - ty, - bits: ConstBits(u64::from(v)), - })?; - f.module().const_value(c) -} - -/// The fixed binding numbers of the scan's symbols. -fn binding_of(sym: &Symbol) -> Option { - match sym { - Symbol::DescriptorSet(_) => Some(MeshScanModule::SET), - Symbol::Binding(s) if *s == WORK => Some(MeshScanModule::WORK_BINDING), - Symbol::Binding(s) if *s == ARGUMENTS => Some(MeshScanModule::ARGUMENTS_BINDING), - Symbol::Binding(s) if *s == STATUS => Some(MeshScanModule::STATUS_BINDING), - Symbol::Binding(s) if *s == RECORDS => Some(MeshScanModule::RECORDS_BINDING), - _ => None, - } -} - -/// The object arguments pass of `device`, which an emulated indirect draw with an object function -/// dispatches (one workgroup of one invocation) before its object dispatch, under the scan's -/// bindings (`MeshDispatch::object_arguments`): it reads Metal's arguments, reserves the object -/// threadgroups' slots in the records pool, and writes the object dispatch, or runs nothing and -/// sets the status bit that says why (`MESH_GRID_DISCARDED`, `MESH_GRID_PAST_LIMITS` past the -/// device's `maxComputeWorkGroupCount`, `MESH_RECORDS_OVERFLOW`). Built with the typed builder, -/// verified, serialized, and numbered with the fixed bindings of [`MeshScanModule`]. -pub fn mesh_object_arguments_module(device: &Device) -> Result { - let compute = device - .profile() - .fields() - .limits - .max_compute_work_group_count; - let (spirv, requirements) = finished( - device, - object_arguments_typed_module(compute)?, - binding_of, - "the mesh object arguments pass", - )?; - Ok(MeshScanModule { - spirv, - requirements, - }) -} - -/// The mesh scan module of `device`: built with the typed builder, verified, serialized, and -/// numbered with the fixed bindings of [`MeshScanModule`]. -pub fn mesh_scan_module(device: &Device) -> Result { - let (spirv, requirements) = - finished(device, scan_typed_module()?, binding_of, "the mesh scan")?; - Ok(MeshScanModule { - spirv, - requirements, - }) -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/mesh_scan/tests.rs b/crates/metal2vulkan/src/bind/mesh_scan/tests.rs deleted file mode 100644 index 0f1f8c9d1..000000000 --- a/crates/metal2vulkan/src/bind/mesh_scan/tests.rs +++ /dev/null @@ -1,565 +0,0 @@ -//! The mesh scan: valid on every committed profile (L3, `G-val`), and, on the CPU interpreter, -//! each object threadgroup's first mesh threadgroup, the draw's `T`, its reservation in the -//! records pool, its dispatch folded into rows and its draw; an indirect draw's grid from Metal's -//! arguments, held to Metal's limit; and a draw the pool cannot hold draws nothing, sets -//! `MESH_RECORDS_OVERFLOW` and names itself, the first such draw only. Slots in the records pool -//! (`work::SLOTS`) scan as slots in the work buffer do. The object arguments pass: valid on every -//! committed profile, and on the interpreter it reserves an indirect draw's slots and writes its -//! object dispatch, or runs nothing and says why. - -use super::*; -use crate::bind::status::{ExecutionStatus, MeshRecordsFault, StatusReport}; -use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; -use crate::spirv::testing::{assert_valid, committed_profiles}; - -fn words(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|c| u32::from_le_bytes(*c)) - .collect() -} - -fn bytes(words: &[u32]) -> Vec { - words.iter().flat_map(|w| w.to_le_bytes()).collect() -} - -/// A draw's work buffer before the scan: `grids` of the object threadgroups, slots of -/// `slot_words`, the records of `group_words` words and `group_vertices` vertices per mesh -/// threadgroup, a pool of `pool_words`, draw number 7, rows of `row`, and Metal's arguments at -/// word `arguments - 1` where it is not 0; the slots and offsets at word `pooled` of the pool -/// where it is `Some`, else after the header. -struct Draw { - grids: Vec<[u32; 3]>, - slot_words: u32, - group_words: u32, - group_vertices: u32, - pool_words: u32, - row: u32, - arguments: u32, - pooled: Option, -} - -impl Draw { - fn of(grids: &[[u32; 3]]) -> Draw { - Draw { - grids: grids.to_vec(), - slot_words: 6, - group_words: 10, - group_vertices: 3, - pool_words: 1000, - row: 4, - arguments: 0, - pooled: None, - } - } - - /// The slots and the offsets before the scan. - fn slots(&self) -> Vec { - let mut w = Vec::new(); - for g in &self.grids { - let mut slot = vec![0xAAAA_AAAA; self.slot_words as usize]; - slot[..3].copy_from_slice(g); - slot[3] = 0; - w.extend(slot); - } - // The offsets, which the scan writes. - w.extend(std::iter::repeat_n(0xEEEE_EEEE, self.grids.len() + 1)); - w - } - - /// The pool's words before the scan: `len` words, the slots at `pooled`. - fn pool(&self, len: usize) -> Vec { - let mut w = vec![0x5555_5555; len]; - if let Some(at) = self.pooled { - let slots = self.slots(); - w[at as usize..][..slots.len()].copy_from_slice(&slots); - } - w - } - - fn words(&self) -> Vec { - let o = self.grids.len() as u32; - let mut w = vec![0u32; work::HEADER as usize]; - w[work::OBJECT_GROUPS as usize] = o; - w[work::SLOT_WORDS as usize] = self.slot_words; - w[work::GROUP_WORDS as usize] = self.group_words; - w[work::GROUP_VERTICES as usize] = self.group_vertices; - w[work::POOL_WORDS as usize] = self.pool_words; - w[work::DRAW_ID as usize] = 7; - w[work::ROW as usize] = self.row; - w[work::ARGUMENTS as usize] = self.arguments; - match self.pooled { - Some(at) => { - w[work::SLOTS as usize] = at + 1; - w.push(0xEEEE_EEEE); - } - None => w.extend(self.slots()), - } - w - } -} - -/// What a scan left: the work words, the status report, the pool's cursor, and the pool. -struct Scanned { - work: Vec, - report: StatusReport, - cursor: u32, - pool: Vec, -} - -/// The pool's words in the tests. -const POOL: usize = 4096; - -/// Run the scan of `draw` over `arguments` (bound whole) with the pool's cursor at `cursor` and -/// the status bits `bits`, in both invocation orders. -fn scan(draw: &Draw, arguments: &[u32], cursor: u32, bits: u32) -> Scanned { - let module = scan_typed_module().expect("scan"); - let mut status = [0u32; 8]; - status[StatusWord::Status.index() as usize] = bits; - status[StatusWord::MeshRecordsCursor.index() as usize] = cursor; - let mut ran = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let res = Resources { - buffers: vec![ - Buffer { - slot: Some(WORK), - address: None, - bytes: bytes(&draw.words()), - }, - Buffer { - slot: Some(ARGUMENTS), - address: None, - bytes: bytes(arguments), - }, - Buffer { - slot: Some(STATUS), - address: None, - bytes: bytes(&status), - }, - Buffer { - slot: Some(RECORDS), - address: None, - bytes: bytes(&draw.pool(POOL)), - }, - ], - push: Vec::new(), - spec: Default::default(), - }; - let cfg = Config { - order, - ..Config::default() - }; - ran.push(run(&module, &cfg, res).expect("scan run").buffers); - } - assert_eq!(ran[0], ran[1], "order independent"); - let after = &ran[0]; - let status_bytes: [u8; 32] = after[2].as_slice().try_into().expect("status"); - let status = words(&after[2]); - Scanned { - work: words(&after[0]), - report: ExecutionStatus::decode(&status_bytes), - cursor: status[StatusWord::MeshRecordsCursor.index() as usize], - pool: words(&after[3]), - } -} - -/// The offsets after `draw`'s slots, where they lie. -fn offsets(draw: &Draw, s: &Scanned) -> Vec { - let slots = draw.grids.len() * draw.slot_words as usize; - match draw.pooled { - Some(at) => s.pool[at as usize + slots..][..draw.grids.len() + 1].to_vec(), - None => s.work[work::HEADER as usize + slots..].to_vec(), - } -} - -fn header(work: &[u32], at: u32, n: usize) -> Vec { - work[at as usize..at as usize + n].to_vec() -} - -#[test] -fn the_scan_is_valid_on_every_committed_profile() { - for (_, p) in committed_profiles().expect("profiles") { - assert_valid(scan_typed_module().expect("scan"), &p); - } -} - -/// Each object threadgroup's first mesh threadgroup in object order, and `T`; the records -/// reserved after the cursor; `T` folded into rows of `ROW`; `T · NP · k` vertices. A grid with -/// an axis of 0 launches none, and one past Metal's limits none (65,536 along an axis, or 2^20 in -/// all: the object function holds it so; the scan holds it again). -#[test] -fn the_scan_places_each_object_threadgroups_mesh_threadgroups() { - let draw = Draw::of(&[ - [2, 1, 1], - [0, 5, 1], - [3, 2, 1], - [1, 1, 1], - [1 << 20, 2, 1], - [1, 65536, 1], - [1024, 1024, 1], - ]); - let s = scan(&draw, &[0], 40, 0); - assert_eq!(offsets(&draw, &s), vec![0, 2, 2, 8, 9, 9, 9, 9]); - assert_eq!(s.work[work::MESH_GROUPS as usize], 9); - assert_eq!(s.work[work::RECORDS_BASE as usize], 40); - assert_eq!(s.cursor, 40 + 9 * 10); - assert_eq!(header(&s.work, work::DISPATCH, 3), vec![4, 3, 1]); - assert_eq!(header(&s.work, work::DRAW, 4), vec![27, 1, 0, 0]); - assert_eq!(s.report, StatusReport::default()); - // The slots are the object function's: the scan leaves them. - assert_eq!(&s.work[work::HEADER as usize..][..3], &[2, 1, 1]); -} - -/// More object threadgroups than invocations: every run of them is placed after the runs -/// before. -#[test] -fn the_scan_places_runs_of_many_object_threadgroups() { - let grids: Vec<[u32; 3]> = (0..200u32).map(|i| [i % 3, 1, 1]).collect(); - let mut draw = Draw::of(&grids); - draw.pool_words = 100_000; - draw.row = 65535; - let s = scan(&draw, &[0], 0, 0); - let mut want = Vec::new(); - let mut running = 0; - for g in &grids { - want.push(running); - running += g[0]; - } - want.push(running); - assert_eq!(offsets(&draw, &s), want); - assert_eq!(s.work[work::MESH_GROUPS as usize], running); - assert_eq!(header(&s.work, work::DISPATCH, 3), vec![running, 1, 1]); -} - -/// An indirect draw's grid is Metal's arguments at their word, into slot 0; one past Metal's -/// limit launches nothing; arguments past the bound range read 0. -#[test] -fn an_indirect_scan_reads_metals_arguments() { - let mut draw = Draw::of(&[[0, 0, 0]]); - draw.arguments = 1 + 2; - let s = scan(&draw, &[9, 9, 3, 2, 2], 0, 0); - assert_eq!(&s.work[work::HEADER as usize..][..3], &[3, 2, 2]); - assert_eq!(offsets(&draw, &s), vec![0, 12]); - assert_eq!(s.work[work::MESH_GROUPS as usize], 12); - assert_eq!(header(&s.work, work::DRAW, 4), vec![36, 1, 0, 0]); - for past in [ - [1 << 20, 2, 1], - [65536, 1, 1], - [1, 1, 65536], - [1024, 1024, 1], - ] { - let s = scan(&draw, &[9, 9, past[0], past[1], past[2]], 0, 0); - assert_eq!( - &s.work[work::HEADER as usize..][..3], - &[0, 0, 0], - "{past:?}" - ); - assert_eq!(s.work[work::MESH_GROUPS as usize], 0, "{past:?}"); - assert_eq!( - header(&s.work, work::DISPATCH, 3), - vec![0, 0, 1], - "{past:?}" - ); - } - let s = scan(&draw, &[9, 9, 3, 2], 0, 0); - assert_eq!(s.work[work::MESH_GROUPS as usize], 0); -} - -/// A draw whose records the rest of the pool cannot hold draws nothing, keeps the cursor, sets -/// the bit and names itself; a later fault leaves the first one's words. -#[test] -fn a_draw_the_pool_cannot_hold_draws_nothing_and_says_so() { - let draw = Draw::of(&[[4, 1, 1], [3, 1, 1]]); - let s = scan(&draw, &[0], 940, 0); - assert_eq!(s.work[work::MESH_GROUPS as usize], 0); - assert_eq!(header(&s.work, work::DISPATCH, 3), vec![0, 0, 1]); - assert_eq!(header(&s.work, work::DRAW, 4), vec![0, 1, 0, 0]); - assert_eq!(s.cursor, 940); - assert_eq!( - s.report.mesh_records_overflow, - Some(MeshRecordsFault { - draw: 7, - object_threadgroups: 2, - mesh_threadgroups: 7, - }) - ); - // Exactly the room left: drawn. - let s = scan(&draw, &[0], 930, 0); - assert_eq!(s.work[work::MESH_GROUPS as usize], 7); - assert_eq!(s.cursor, 1000); - assert_eq!(s.report.mesh_records_overflow, None); - // A later fault leaves the first one's words (here all zero). - let s = scan(&draw, &[0], 940, StatusBits::MESH_RECORDS_OVERFLOW.0); - assert_eq!( - s.report.mesh_records_overflow, - Some(MeshRecordsFault::default()) - ); - // Vertices past a `u32` draw nothing either. - let mut wide = Draw::of(&[[1023, 1025, 1]]); - wide.pool_words = u32::MAX; - wide.group_words = 1; - wide.group_vertices = 1 << 13; - let s = scan(&wide, &[0], 0, 0); - assert_eq!(s.work[work::MESH_GROUPS as usize], 0); - assert_eq!( - s.report.mesh_records_overflow.map(|f| f.mesh_threadgroups), - Some(1023 * 1025) - ); -} - -/// Slots in the records pool scan as slots in the work buffer do, and the offsets land after -/// them there; the work buffer keeps its own words. -#[test] -fn the_scan_reads_slots_in_the_records_pool() { - let grids = [[2, 1, 1], [0, 5, 1], [3, 2, 1], [1, 1, 1], [1, 65536, 1]]; - let mut draw = Draw::of(&grids); - draw.pooled = Some(200); - let s = scan(&draw, &[0], 300, 0); - assert_eq!(offsets(&draw, &s), vec![0, 2, 2, 8, 9, 9]); - assert_eq!(s.work[work::MESH_GROUPS as usize], 9); - assert_eq!(s.work[work::RECORDS_BASE as usize], 300); - assert_eq!(s.cursor, 300 + 9 * 10); - assert_eq!(header(&s.work, work::DISPATCH, 3), vec![4, 3, 1]); - assert_eq!(s.report, StatusReport::default()); - assert_eq!(&s.work[work::HEADER as usize..], &[0xEEEE_EEEE]); - assert_eq!(&s.pool[200..][..3], &[2, 1, 1]); - // Below the slots, the pool is as it was. - assert!(s.pool[..200].iter().all(|&w| w == 0x5555_5555)); -} - -/// An object arguments pass: Metal's arguments `arguments` at word `at` (0: none), slots of 6 -/// words, a pool of `pool_words` with its cursor at `cursor`, the status bits `bits`, and the -/// device's `compute` limits. -struct Arguments { - arguments: Vec, - at: u32, - pool_words: u32, - cursor: u32, - bits: u32, - compute: [u32; 3], -} - -impl Arguments { - fn of(grid: [u32; 3]) -> Arguments { - let mut arguments = vec![9]; - arguments.extend(grid); - Arguments { - arguments, - at: 1, - pool_words: 1000, - cursor: 40, - bits: 0, - compute: [65535; 3], - } - } - - /// The work words before the pass. - fn work(&self) -> Vec { - let mut w = vec![0xAAAA_AAAA; work::HEADER as usize + 1]; - w[work::OBJECT_ARGUMENTS as usize] = self.at + 1; - w[work::SLOT_WORDS as usize] = 6; - w[work::POOL_WORDS as usize] = self.pool_words; - w[work::DRAW_ID as usize] = 7; - w - } - - /// Run the pass; the work words, the status report and the pool's cursor after it. - fn run(&self) -> Scanned { - let module = object_arguments_typed_module(self.compute).expect("arguments"); - let mut status = [0u32; 8]; - status[StatusWord::Status.index() as usize] = self.bits; - status[StatusWord::MeshRecordsCursor.index() as usize] = self.cursor; - let pool = vec![0x5555_5555; 16]; - let res = Resources { - buffers: vec![ - Buffer { - slot: Some(WORK), - address: None, - bytes: bytes(&self.work()), - }, - Buffer { - slot: Some(ARGUMENTS), - address: None, - bytes: bytes(&self.arguments), - }, - Buffer { - slot: Some(STATUS), - address: None, - bytes: bytes(&status), - }, - Buffer { - slot: Some(RECORDS), - address: None, - bytes: bytes(&pool), - }, - ], - push: Vec::new(), - spec: Default::default(), - }; - let after = run(&module, &Config::default(), res) - .expect("arguments run") - .buffers; - let status_bytes: [u8; 32] = after[2].as_slice().try_into().expect("status"); - let status = words(&after[2]); - Scanned { - work: words(&after[0]), - report: ExecutionStatus::decode(&status_bytes), - cursor: status[StatusWord::MeshRecordsCursor.index() as usize], - pool: words(&after[3]), - } - } -} - -/// The words a pass that runs nothing leaves: no object threadgroups, no slots, an empty -/// dispatch, and the cursor where it was. -fn runs_nothing(a: &Arguments, s: &Scanned) { - assert_eq!(s.work[work::OBJECT_GROUPS as usize], 0); - assert_eq!(s.work[work::SLOTS as usize], 0); - assert_eq!(header(&s.work, work::OBJECT_DISPATCH, 3), vec![0, 0, 0]); - assert_eq!(s.cursor, a.cursor); -} - -#[test] -fn the_object_arguments_pass_is_valid_on_every_committed_profile() { - for (_, p) in committed_profiles().expect("profiles") { - let compute = p.fields().limits.max_compute_work_group_count; - assert_valid( - object_arguments_typed_module(compute).expect("arguments"), - &p, - ); - } -} - -/// A grid that runs: its slots and offsets reserved after the cursor (`n · S + n + 1` words), the -/// slots' first word plus 1, and the grid as the object dispatch; the pool is the scan's to write. -#[test] -fn the_object_arguments_pass_reserves_a_grids_slots() { - let a = Arguments::of([3, 2, 2]); - let s = a.run(); - assert_eq!(s.work[work::OBJECT_GROUPS as usize], 12); - assert_eq!(s.work[work::SLOTS as usize], 41); - assert_eq!(header(&s.work, work::OBJECT_DISPATCH, 3), vec![3, 2, 2]); - assert_eq!(s.cursor, 40 + 12 * 6 + 13); - assert_eq!(s.report, StatusReport::default()); - assert!(s.pool.iter().all(|&w| w == 0x5555_5555)); - // The arguments at another word, and exactly the room left. - let mut a = Arguments::of([3, 2, 2]); - a.arguments.insert(0, 1); - a.at = 2; - a.cursor = 1000 - 85; - let s = a.run(); - assert_eq!(s.work[work::OBJECT_GROUPS as usize], 12); - assert_eq!(s.cursor, 1000); - assert_eq!(s.report, StatusReport::default()); -} - -/// A grid with an axis of 0 runs nothing and says nothing, however large its other axes; so do -/// arguments past the bound range. -#[test] -fn the_object_arguments_pass_runs_an_empty_grid_silently() { - for grid in [[3, 0, 2], [0, 1, 1], [1 << 20, 1 << 20, 0]] { - let a = Arguments::of(grid); - let s = a.run(); - runs_nothing(&a, &s); - assert_eq!(s.report, StatusReport::default(), "{grid:?}"); - } - let mut a = Arguments::of([3, 2, 2]); - a.arguments.pop(); - let s = a.run(); - runs_nothing(&a, &s); - assert_eq!(s.report, StatusReport::default()); -} - -/// More than 2^29 threadgroups in all (a wrapping product too): Metal discards the command -/// buffer, so the pass runs nothing and sets the discard bit alone; exactly 2^29 runs. -#[test] -fn the_object_arguments_pass_discards_what_metal_discards() { - for grid in [[1 << 15, 1 << 15, 1], [(1 << 29) + 1, 1, 1], [65535; 3]] { - let mut a = Arguments::of(grid); - a.compute = [u32::MAX; 3]; - let s = a.run(); - runs_nothing(&a, &s); - assert!(s.report.mesh_grid_discarded, "{grid:?}"); - assert!(!s.report.mesh_grid_past_limits, "{grid:?}"); - assert_eq!(s.report.mesh_records_overflow, None, "{grid:?}"); - } - let mut a = Arguments::of([1 << 29, 1, 1]); - a.compute = [u32::MAX; 3]; - a.pool_words = u32::MAX; - a.cursor = 0; - let s = a.run(); - assert_eq!(s.work[work::OBJECT_GROUPS as usize], 1 << 29); - assert_eq!(s.cursor, (1 << 29) * 7 + 1); - assert_eq!(s.report, StatusReport::default()); -} - -/// An axis past the device's compute limits runs nothing and sets the past-limits bit; a grid -/// whose threads per grid wrap runs whole (the object function reports the wrapped grid). -#[test] -fn the_object_arguments_pass_holds_the_device_limits() { - for (grid, compute) in [([65536, 1, 1], [65535; 3]), ([1, 1, 3], [65535, 65535, 2])] { - let mut a = Arguments::of(grid); - a.compute = compute; - let s = a.run(); - runs_nothing(&a, &s); - assert!(s.report.mesh_grid_past_limits, "{grid:?}"); - assert!(!s.report.mesh_grid_discarded, "{grid:?}"); - } - for grid in [[1 << 22, 1, 1], [1, 1 << 23, 1], [65535, 1, 1]] { - let mut a = Arguments::of(grid); - a.compute = [u32::MAX; 3]; - a.pool_words = u32::MAX; - let s = a.run(); - let n = grid.iter().product::(); - assert_eq!(s.work[work::OBJECT_GROUPS as usize], n, "{grid:?}"); - assert_eq!(header(&s.work, work::OBJECT_DISPATCH, 3), grid.to_vec()); - assert_eq!(s.report, StatusReport::default(), "{grid:?}"); - } -} - -/// Slots the rest of the pool cannot hold: nothing runs, the cursor stays, and the first such -/// draw names itself (no mesh threadgroups yet); a later fault leaves the first one's words. -#[test] -fn the_object_arguments_pass_says_when_the_pool_is_full() { - let mut a = Arguments::of([3, 2, 2]); - a.cursor = 1000 - 84; - let s = a.run(); - runs_nothing(&a, &s); - assert_eq!( - s.report.mesh_records_overflow, - Some(MeshRecordsFault { - draw: 7, - object_threadgroups: 12, - mesh_threadgroups: 0, - }) - ); - // A cursor already past the pool. - a.cursor = 5000; - let s = a.run(); - runs_nothing(&a, &s); - assert!(s.report.mesh_records_overflow.is_some()); - a.bits = StatusBits::MESH_RECORDS_OVERFLOW.0; - let s = a.run(); - assert_eq!( - s.report.mesh_records_overflow, - Some(MeshRecordsFault::default()) - ); -} - -/// The pass, the object function's slots and the scan in turn: the scan places the threadgroups -/// of the slots the pass reserved, after them in the pool. -#[test] -fn the_scan_places_the_grids_of_the_slots_the_pass_reserved() { - let a = Arguments::of([2, 2, 1]); - let s = a.run(); - let at = s.work[work::SLOTS as usize] - 1; - let grids = [[2, 1, 1], [0, 5, 1], [3, 2, 1], [1, 1, 1]]; - let mut draw = Draw::of(&grids); - draw.pooled = Some(at); - let scanned = scan(&draw, &[0], s.cursor, 0); - assert_eq!(offsets(&draw, &scanned), vec![0, 2, 2, 8, 9]); - assert_eq!(scanned.work[work::RECORDS_BASE as usize], s.cursor); - assert_eq!(scanned.cursor, s.cursor + 9 * 10); -} diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index 0b394fe93..01d6d7581 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -105,7 +105,6 @@ pub(crate) mod index_rewrite; pub mod indirect_commands; pub(crate) mod instantiate; pub(crate) mod mesh_arguments; -pub(crate) mod mesh_scan; pub(crate) mod neutral; pub(crate) mod plan; pub(crate) mod pvrtc_decode; @@ -142,10 +141,7 @@ pub use depth_stencil_copy::{ }; pub use dispatch::{Dispatch, DispatchCommands, DispatchRegion, IndirectArgs}; pub use etc_decode::{EtcDecode, EtcTexels}; -pub use graphics::{ - alpha_test_code, DrawCall, DrawCommands, IndexOverrun, MeshDispatch, MeshGroups, - MeshRecordsRegion, -}; +pub use graphics::{alpha_test_code, DrawCall, DrawCommands, IndexOverrun}; pub use heap::{ handle_entry, handle_entry_flags, heap_classes, heap_element, heap_raw_form, HeapElement, HeapElements, HeapSource, HANDLE_ENTRY_BYTES, HANDLE_TABLE_CAPACITY, NEUTRAL_HEAP_ELEMENT, @@ -169,7 +165,6 @@ pub use mesh_arguments::{ MeshArgumentsModule, MeshGridLimits, MeshGridRule, ObjectFold, METAL_MESH_GRID_AXIS, METAL_MESH_GRID_TOTAL, METAL_OBJECT_GRID_TOTAL, }; -pub use mesh_scan::{mesh_object_arguments_module, mesh_scan_module, MeshScanModule}; pub use neutral::NeutralResource; pub use plan::resources::sampler_desc; pub use plan::{ @@ -220,9 +215,7 @@ pub use sample_interleave::{ pub use sample_planes::{ planes_merge_modules, planes_split_module, PlanesCopy, PlanesMergeModules, PlanesSplitModule, }; -pub use status::{ - ExecutionStatus, MeshRecordsFault, ReplayFaults, StatusBits, StatusReport, StatusWord, -}; +pub use status::{ExecutionStatus, ReplayFaults, StatusBits, StatusReport, StatusWord}; pub use table::{FunctionTableSnapshot, FunctionTableWords}; pub use texel_parts::{part_texels, texel_buffer_parts}; pub use texel_rows::TexelRows; diff --git a/crates/metal2vulkan/src/bind/plan.rs b/crates/metal2vulkan/src/bind/plan.rs index 798018ba3..67c663acf 100644 --- a/crates/metal2vulkan/src/bind/plan.rs +++ b/crates/metal2vulkan/src/bind/plan.rs @@ -259,8 +259,7 @@ pub(crate) struct MeshTemplate { /// Every `LocalSizeConstraint{multiple}` of the pipeline: a threadgroup of either stage must /// be whole subgroups of the flattened tier's size. pub multiples: Vec, - /// The mesh stage's limits (`maxMeshWorkGroup*`; an emulated mesh function's are the - /// compute stage's, `maxComputeWorkGroup*`). + /// The mesh stage's limits (`maxMeshWorkGroup*`). pub mesh: GroupLimits, /// The task stage's limits (`maxTaskWorkGroup*`), of a pipeline with an object function. pub object: Option, @@ -274,10 +273,6 @@ pub(crate) struct MeshTemplate { /// draws it, its region flagged `lower::dispatch::NONUNIFORM`. #[cfg_attr(feature = "serde", serde(default))] pub partial_groups: bool, - /// An emulated mesh function's records: each draw dispatches its mesh threadgroups and - /// draws their primitives (`DrawCommands::mesh_dispatch`). - #[cfg_attr(feature = "serde", serde(default))] - pub records: Option, } /// A stage's threadgroup and grid limits. @@ -290,8 +285,8 @@ pub(crate) struct GroupLimits { pub invocations: u32, /// `max*WorkGroupCount`. pub count: [u32; 3], - /// `max*WorkGroupTotalCount`; `None` for the compute stage, which has none. - pub total: Option, + /// `max*WorkGroupTotalCount`. + pub total: u32, /// The stage the limits are of, which names them. pub stage: GroupStage, } @@ -304,30 +299,6 @@ pub(crate) enum GroupStage { Task, /// A mesh function's (`MESH_EXT`). Mesh, - /// An emulated mesh function's (`COMPUTE`). - Compute, -} - -/// What a draw of an emulated mesh function's pipeline sizes from its grid -/// (`DrawCommands::mesh_dispatch`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub(crate) struct RecordsTemplate { - /// The words of one threadgroup's records (`MeshRecords::group_words`). - pub group_words: u64, - /// The vertices of one threadgroup's primitives in the draw: `NP · k`. - pub group_vertices: u32, - /// The device's `maxStorageBufferRange`, past which a draw's records or work buffer cannot - /// be bound. - pub max_range: u32, - /// The words of an object threadgroup's slot in the work buffer (`MeshRecords::slot_words`). - pub slot_words: u32, - /// `maxComputeWorkGroupCount[0]`, the mesh dispatch's rows. - pub row: u32, - /// `maxComputeWorkGroupCount[1]`, its most rows. - pub rows: u32, - /// `minStorageBufferOffsetAlignment`, to which the scan's arguments range is aligned. - pub alignment: u64, } /// What a draw of a pipeline whose fragment function runs the draw's depth test itself @@ -822,15 +793,6 @@ pub enum WriteSource { /// stand when the command runs, which differs only for a CPU write racing the GPU. The /// stage's directory gives each listed id its record's offset, by the same sizes. FunctionTableSnapshot, - /// An emulated mesh function's records (`SyntheticBinding::MeshRecords`): the draw's - /// `MeshDispatch::records`, a region of its own or the command buffer's records pool, which - /// the consumer binds whole for the mesh dispatch and the draw alike - /// ([`MeshDispatch`](crate::bind::MeshDispatch)). - MeshRecords, - /// An emulated mesh draw's work buffer (`SyntheticBinding::MeshWork`, the object and mesh - /// stages' alike): the draw's region of `MeshDispatch::work_bytes`, holding - /// `MeshDispatch::work`, bound whole ([`MeshDispatch`](crate::bind::MeshDispatch)). - MeshWork, /// The command buffer's execution status (`SyntheticBinding::ExecutionStatus`) of a stage on /// a device that does not address buffers: a storage buffer of the /// [`ExecutionStatus`](crate::bind::ExecutionStatus) words, the same buffer every command of diff --git a/crates/metal2vulkan/src/bind/replay/rules.rs b/crates/metal2vulkan/src/bind/replay/rules.rs index 8442200bd..d22f357f8 100644 --- a/crates/metal2vulkan/src/bind/replay/rules.rs +++ b/crates/metal2vulkan/src/bind/replay/rules.rs @@ -56,8 +56,6 @@ pub enum DrawReplayRule { ArgumentsOnCpu, /// The state's draw bounds its indices. IndexBounds, - /// The state's draw dispatches before it draws (an emulated mesh draw's dispatch). - DispatchesFirst, /// The state's draw is amplified or draws views. Amplified, /// The state's vertex function fetches attributes of a layout whose stride is set per bind @@ -118,9 +116,6 @@ impl fmt::Display for DrawReplayRule { "the inherited state's indirect draw needs its arguments on the CPU" } DrawReplayRule::IndexBounds => "the inherited state's draw bounds its indices", - DrawReplayRule::DispatchesFirst => { - "the inherited state's draw dispatches before it draws" - } DrawReplayRule::Amplified => "the inherited state's draw is amplified or draws views", DrawReplayRule::VertexAttributes => { "the inherited state's vertex function fetches attributes at a stride set per bind" @@ -286,10 +281,6 @@ pub fn draw_replay_draw( DrawReplayRule::ArgumentsOnCpu, ), (commands.index_bounds_pass, DrawReplayRule::IndexBounds), - ( - commands.mesh_dispatch.is_some(), - DrawReplayRule::DispatchesFirst, - ), ( !commands.amplifications.is_empty() || plan.views != ViewSetup::default(), DrawReplayRule::Amplified, diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index 047d2a779..148958786 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -253,14 +253,6 @@ pub struct BindState { /// `VariantKey::rotated_weights`). Part of the shape; `false` for every other draw. #[cfg_attr(feature = "serde", serde(default))] pub rotated_weights: bool, - /// Whether a mesh draw of an emulated mesh function's pipeline draws each line or triangle - /// from its last index first: a draw under Apple's last provoking vertex - /// (`setProvokingVertexMode:` 1) on a device that takes flat inputs from the first vertex. - /// Its pipeline runs the variant whose synthesized vertex stage reads its corners so - /// (`BindShape::mesh_last_first`, `VariantKey::mesh_last_first`). Part of the shape; `false` - /// for every other draw. - #[cfg_attr(feature = "serde", serde(default))] - pub mesh_last_first: bool, /// What the draw draws as bands of triangles, where it draws its lines or its triangles' /// edges so, and its band (`PushField::LineBand`): `[sx, sy, h, f]`, the half extent of its /// Vulkan viewport 0 (its height negative, as the viewport is), half the band's width in @@ -646,7 +638,6 @@ impl BindState { kept_imageblock_bytes: self.kept_imageblock_bytes, depth_clamp_range: self.depth_clamp_range.is_some(), rotated_weights: self.rotated_weights, - mesh_last_first: self.mesh_last_first, line_band: self.line_band.map(|(primitive, _)| primitive), interlocked_colors: self.interlocked_colors.clone(), fragment_tests: self.fragment_tests, @@ -734,7 +725,6 @@ impl BindState { kept_imageblock_bytes, depth_clamp_range, rotated_weights, - mesh_last_first, line_band, interlocked_colors, fragment_tests, @@ -765,7 +755,6 @@ impl BindState { && self.kept_imageblock_bytes == *kept_imageblock_bytes && self.depth_clamp_range.is_some() == *depth_clamp_range && self.rotated_weights == *rotated_weights - && self.mesh_last_first == *mesh_last_first && self.line_band.map(|(primitive, _)| primitive) == *line_band && self.interlocked_colors == *interlocked_colors && self.fragment_tests == *fragment_tests @@ -1731,11 +1720,6 @@ pub struct BindShape { /// (`VariantKey::rotated_weights`). #[cfg_attr(feature = "serde", serde(default))] pub rotated_weights: bool, - /// `BindState.mesh_last_first`: the variant whose emulated mesh pipeline's synthesized - /// vertex stage draws each line or triangle from its last index first - /// (`VariantKey::mesh_last_first`). - #[cfg_attr(feature = "serde", serde(default))] - pub mesh_last_first: bool, /// What `BindState.line_band` draws as bands: the variant that draws its lines, or its /// triangles' edges, so (`VariantKey::line_band`). #[cfg_attr(feature = "serde", serde(default))] diff --git a/crates/metal2vulkan/src/bind/status.rs b/crates/metal2vulkan/src/bind/status.rs index e0a91b8e4..72ce5b898 100644 --- a/crates/metal2vulkan/src/bind/status.rs +++ b/crates/metal2vulkan/src/bind/status.rs @@ -4,9 +4,9 @@ //! with [`ExecutionStatus::initial`] before the command buffer's first use and reads it back with //! [`ExecutionStatus::decode`] after the last one (a `SHADER_WRITE -> HOST_READ` barrier first); //! the resident-set miss counter, the device replay's preprocess, the index -//! bounds pass, an absent argument's read, the mesh scans, a sample through a -//! cubic argument sampler, and a sequentially consistent fence write the words -//! named here. +//! bounds pass, an absent argument's read, a mesh draw's arguments pass, a sample +//! through a cubic argument sampler, and a sequentially consistent fence write the +//! words named here. Words 3 to 6 are not written. /// The `ExecutionStatus` buffer. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -15,7 +15,7 @@ pub struct ExecutionStatus; impl ExecutionStatus { /// Size of the buffer in bytes. pub const BYTES: usize = 32; - /// Size of the buffer in 32-bit words: [`StatusWord::ALL`]. + /// Size of the buffer in 32-bit words: up to the last of [`StatusWord::ALL`]. pub const WORDS: usize = 8; /// The buffer's initial bytes: every word 0. @@ -24,8 +24,8 @@ impl ExecutionStatus { } /// What the buffer's bytes report after the command buffer ran. The consumer maps a replay - /// fault, an index pool overflow, an absent argument read, a mesh records fault, a mesh - /// grid Metal's GPU discards or the device cannot launch, and a cubic argument sampler's sample + /// fault, an index pool overflow, an absent argument read, a mesh grid Metal's GPU + /// discards or the device cannot launch, and a cubic argument sampler's sample /// to a command-buffer execution error, and treats resident-set misses by its own policy. pub fn decode(bytes: &[u8; ExecutionStatus::BYTES]) -> StatusReport { let word = |w: StatusWord| { @@ -43,13 +43,6 @@ impl ExecutionStatus { cubic_argument_sampler: bits.contains(StatusBits::CUBIC_ARGUMENT_SAMPLER), mesh_grid_discarded: bits.contains(StatusBits::MESH_GRID_DISCARDED), mesh_grid_past_limits: bits.contains(StatusBits::MESH_GRID_PAST_LIMITS), - mesh_records_overflow: (bits.contains(StatusBits::MESH_RECORDS_OVERFLOW)).then(|| { - MeshRecordsFault { - draw: word(StatusWord::MeshFaultDraw), - object_threadgroups: word(StatusWord::MeshFaultObjects), - mesh_threadgroups: word(StatusWord::MeshFaultGroups), - } - }), } } } @@ -75,40 +68,18 @@ pub struct StatusReport { /// no value (`RuntimeFact::AbsentArgumentRead`): the read yielded zero, so no result of the /// command buffer is Metal's. pub absent_argument_read: bool, - /// A mesh scan found no room in the command buffer's records pool for an emulated mesh - /// draw's records, or the draw's vertices passed a `u32` (`bind::MeshScanModule`), or an - /// object arguments pass none for an emulated indirect draw's object slots - /// (`bind::mesh_object_arguments_module`, no mesh threadgroups yet): such draws drew nothing. - /// The command buffer's first one, as the pass saw it. - pub mesh_records_overflow: Option, /// A function sampled through an argument buffer's sampler whose min or mag filter is /// `Cubic`, whose bicubic filter it does not emulate there /// (`RuntimeFact::CubicArgumentSampler`): no result of the command buffer is then Metal's. pub cubic_argument_sampler: bool, - /// An indirect mesh draw's arguments pass (or an emulated one's object arguments pass) met an - /// object grid that Metal's GPU discards (`StatusBits::MESH_GRID_DISCARDED`): that draw drew + /// An indirect mesh draw's arguments pass met an object grid that Metal's GPU discards (`StatusBits::MESH_GRID_DISCARDED`): that draw drew /// nothing, and the command buffer fails as Metal's does (`MTLCommandBufferErrorInternal`). pub mesh_grid_discarded: bool, - /// An indirect mesh draw's arguments pass (or an emulated one's object arguments pass) met a - /// grid that Metal draws and the device cannot launch (`StatusBits::MESH_GRID_PAST_LIMITS`): + /// An indirect mesh draw's arguments pass met a grid that Metal draws and the device cannot launch (`StatusBits::MESH_GRID_PAST_LIMITS`): /// that draw drew nothing, and the command buffer fails (not Metal's failure). pub mesh_grid_past_limits: bool, } -/// The first emulated mesh draw of a command buffer that drew nothing because its records did -/// not fit (`StatusReport::mesh_records_overflow`). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub struct MeshRecordsFault { - /// The consumer's number for the draw (the work buffer's `DRAW_ID` word). - pub draw: u32, - /// The draw's object threadgroups (1 without an object function). - pub object_threadgroups: u32, - /// The mesh threadgroups the draw's object threadgroups launched, saturated at `u32::MAX`; 0 - /// where its object slots did not fit, before any launched. - pub mesh_threadgroups: u32, -} - /// A word of the `ExecutionStatus` buffer. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -119,16 +90,6 @@ pub enum StatusWord { ResidentMisses, /// The device replay's fault reasons ([`ReplayFaults`]). Initial 0. ReplayFaults, - /// The words of the command buffer's mesh records pool its scans reserved - /// (`bind::MeshScanModule`). Initial 0. - MeshRecordsCursor, - /// The consumer's number for the command buffer's first emulated mesh draw whose records did - /// not fit ([`StatusBits::MESH_RECORDS_OVERFLOW`]). Initial 0. - MeshFaultDraw, - /// That draw's object threadgroups. Initial 0. - MeshFaultObjects, - /// The mesh threadgroups that draw needed, saturated. Initial 0. - MeshFaultGroups, /// The word every sequentially consistent fence of the command buffer increments with an /// acquire-release atomic at the fence's scope (`lower::sync::barrier::seq_cst_order`), so /// that the fences of one command buffer are totally ordered, as Metal's are. Its value means @@ -138,14 +99,10 @@ pub enum StatusWord { impl StatusWord { /// Every word, in index order. - pub const ALL: [StatusWord; 8] = [ + pub const ALL: [StatusWord; 4] = [ StatusWord::Status, StatusWord::ResidentMisses, StatusWord::ReplayFaults, - StatusWord::MeshRecordsCursor, - StatusWord::MeshFaultDraw, - StatusWord::MeshFaultObjects, - StatusWord::MeshFaultGroups, StatusWord::SeqCstFences, ]; @@ -155,10 +112,7 @@ impl StatusWord { StatusWord::Status => 0, StatusWord::ResidentMisses => 1, StatusWord::ReplayFaults => 2, - StatusWord::MeshRecordsCursor => 3, - StatusWord::MeshFaultDraw => 4, - StatusWord::MeshFaultObjects => 5, - StatusWord::MeshFaultGroups => 6, + // Words 3 to 6 are not written. StatusWord::SeqCstFences => 7, } } @@ -184,12 +138,8 @@ impl StatusBits { /// A function read an argument its pipeline's function constants removed, a read Metal /// gives no value, and took zero for it (`RuntimeFact::AbsentArgumentRead`). pub const ABSENT_ARGUMENT_READ: StatusBits = StatusBits(1 << 4); - /// A mesh scan found no room in the command buffer's records pool for an emulated mesh - /// draw's records, or the draw's vertices passed a `u32`, or an object arguments pass none for - /// an emulated indirect draw's object slots, and the draw drew nothing - /// (`bind::MeshScanModule`, `bind::mesh_object_arguments_module`); the fault words name the - /// command buffer's first such draw. - pub const MESH_RECORDS_OVERFLOW: StatusBits = StatusBits(1 << 5); + // Bit 5 (an emulated mesh draw's records fault) is not reported: a device without + // `meshShader` refuses the pipeline. /// A function sampled, gathered, or queried through a sampler an argument buffer holds whose /// min or mag filter is `Cubic`, whose bicubic filter it does not emulate there /// (`RuntimeFact::CubicArgumentSampler`): its result is the device's through a nearest @@ -200,15 +150,11 @@ impl StatusBits { /// An indirect mesh draw's arguments pass met a grid that Metal draws and the device cannot /// launch: a mesh grid past the mesh stage's limits, an unfolded object grid past the task /// stage's, or a folded one of more pieces than `MeshArguments::OBJECT_PIECES` (only under task - /// limits below Vulkan's required least); or an emulated indirect draw's object arguments pass - /// met an object grid past the device's compute limits (`bind::mesh_object_arguments_module`); - /// the draw drew nothing - /// (`bind::MeshArguments`). + /// limits below Vulkan's required least); the draw drew nothing (`bind::MeshArguments`). pub const MESH_GRID_PAST_LIMITS: StatusBits = StatusBits(1 << 9); /// An indirect mesh draw's arguments pass met an object grid of more threadgroups than - /// `bind::METAL_OBJECT_GRID_TOTAL`, which Metal's GPU discards (or an emulated draw's object - /// arguments pass did); the draw drew nothing (`bind::MeshArguments`, - /// `bind::mesh_object_arguments_module`). + /// `bind::METAL_OBJECT_GRID_TOTAL`, which Metal's GPU discards; the draw drew nothing + /// (`bind::MeshArguments`). pub const MESH_GRID_DISCARDED: StatusBits = StatusBits(1 << 10); /// Every bit in `other` is set in `self`. pub const fn contains(self, other: StatusBits) -> bool { @@ -286,9 +232,13 @@ mod tests { #[test] fn words_are_distinct_and_inside_the_buffer() { for (i, w) in StatusWord::ALL.iter().enumerate() { - assert_eq!(w.index() as usize, i, "{w:?}"); + if let Some(next) = StatusWord::ALL.get(i + 1) { + assert!(w.index() < next.index(), "{w:?}"); + } assert!((w.byte_offset() as usize) + 4 <= ExecutionStatus::BYTES); } + let last = StatusWord::ALL[StatusWord::ALL.len() - 1]; + assert_eq!(last.index() as usize + 1, ExecutionStatus::WORDS); assert_eq!(ExecutionStatus::WORDS * 4, ExecutionStatus::BYTES); } @@ -299,8 +249,9 @@ mod tests { StatusBits::REPLAY_FAULT, StatusBits::INDEX_POOL_OVERFLOW, StatusBits::ABSENT_ARGUMENT_READ, - StatusBits::MESH_RECORDS_OVERFLOW, StatusBits::CUBIC_ARGUMENT_SAMPLER, + StatusBits::MESH_GRID_PAST_LIMITS, + StatusBits::MESH_GRID_DISCARDED, ]; let mut all = 0u32; for b in bits { @@ -358,23 +309,6 @@ mod tests { let c = ExecutionStatus::decode(&cubic); assert!(c.cubic_argument_sampler && !c.absent_argument_read); assert!(r.absent_argument_read && !r.index_pool_overflow); - assert_eq!(r.mesh_records_overflow, None); - bytes = [0u8; 32]; - bytes[0..4].copy_from_slice(&StatusBits::MESH_RECORDS_OVERFLOW.0.to_le_bytes()); - bytes[12..16].copy_from_slice(&40u32.to_le_bytes()); - bytes[16..20].copy_from_slice(&3u32.to_le_bytes()); - bytes[20..24].copy_from_slice(&2u32.to_le_bytes()); - bytes[24..28].copy_from_slice(&u32::MAX.to_le_bytes()); - let r = ExecutionStatus::decode(&bytes); - assert_eq!( - r.mesh_records_overflow, - Some(MeshRecordsFault { - draw: 3, - object_threadgroups: 2, - mesh_threadgroups: u32::MAX, - }) - ); - assert!(!r.index_pool_overflow); } #[test] diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index da0ec7171..d4c8692b6 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -47,10 +47,10 @@ use crate::pipeline::graphics::{ }; use crate::pipeline::interface::{ AccessSet, BufferForm, BufferKind, BufferSlot, CommandWrites, DescriptorView, LevelReads, - MeshRecords, NumberedSampler, PatchDomain, PipelineInterface, PlacedField, PushLoc, - PushPlacement, RecordField, RecordValue, SampledLevels, SamplerArray, SamplerSlot, - SlotInterface, SnapshotRefusal, StageDescriptor, StageInterface, StageSpec, TessellationStage, - TextureAccess, TextureSlot, ThreadgroupArgument, Window, + NumberedSampler, PatchDomain, PipelineInterface, PlacedField, PushLoc, PushPlacement, + SampledLevels, SamplerArray, SamplerSlot, SlotInterface, SnapshotRefusal, StageDescriptor, + StageInterface, StageSpec, TessellationStage, TextureAccess, TextureSlot, ThreadgroupArgument, + Window, }; use crate::pipeline::layout::{ BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange, @@ -858,8 +858,6 @@ codec_enum! { ControlPointIndices, TileMemory, FunctionTableSnapshot, - MeshRecords, - MeshWork, DepthStandIn, StencilStandIn, } @@ -1139,9 +1137,7 @@ codec_struct! { CommandWrites { operations, primitive_types, kinds } StageInterface { stage, slots, threadgroup, push, descriptors, spec, needs_pointer_translation, - needs_handle_translation, io, tessellation, writes_memory, mesh_records, mesh_corners, - emulated_payload, - payload, reaches_command_buffers, command_writes, writes_textures, + needs_handle_translation, io, tessellation, writes_memory, payload, reaches_command_buffers, command_writes, writes_textures, reads_unbound_resources, writes_unbound_resources, unbound_storage_textures, numbered_samplers, own_pixel_textures, snapshot_textures, snapshot_refusals, level_reads, private_bytes, sampler_arrays, @@ -1154,8 +1150,6 @@ codec_struct! { max_tessellation_factor, partition_mode, factor_format, factor_step_function, output_winding_order, control_point_index_type, factor_scale_enabled, } - MeshRecords { vertices, primitives, corners, vertex_words, primitive_words, fields, slot_words } - RecordField { value, per_primitive, offset, words, numeric } BufferSlot { access, window, form, kind } TextureSlot { texture_type, sampled_type, depth_compare, access, storage } TextureAccess { sample, read, write } @@ -1197,9 +1191,6 @@ codec_enum! { WritesMemory, Interlock, Coherent, Other, } PatchDomain { Triangle, Quad } - RecordValue { - Position, PointSize, ClipDistance, Culled, Layer, ViewportIndex, Varying(f0), - } Window { Bounded { start, len }, Whole } BufferForm { Descriptor(f0), Psb } BufferKind { Buffer, VisibleFunctionTable, IntersectionFunctionTable } @@ -1292,7 +1283,6 @@ codec_enum! { DroppedColor { color }, DepthClampRange, RotatedWeights, - MeshLastFirst, ConstantLanes { slot }, FunctionTableRange { addressed }, TestedStorageWrites { early_tests, early_variant }, @@ -1425,7 +1415,7 @@ codec_struct! { rasterization_order_attachment_access, max_vertex_amplification_count, declares_layer, tessellation, fragment_imageblock, sample_shading, vertex_writes_memory, writes_viewport_index, - storage_attachments, shadow_stencil, early_fragment_tests, mesh_records, mesh_corners, + storage_attachments, shadow_stencil, early_fragment_tests, writes_point_size, flat_fragment_inputs, clip_distances, writes_depth, reads_barycentric_coord, reads_primitive_id, reads_position_depth, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 894ff990f..da4d931e1 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2220; +pub const SEMANTICS_VERSION: u32 = 2221; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2220; /// 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 = 564; +pub const ARTIFACT_FORMAT_VERSION: u32 = 565; /// 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 @@ -357,13 +357,6 @@ pub struct VariantKey { /// it states it. #[cfg_attr(feature = "serde", serde(default))] pub rotated_weights: bool, - /// The synthesized vertex stage of an emulated mesh function's pipeline draws each line or - /// triangle from its last index first (`BindShape::mesh_last_first`): the variant a mesh draw - /// under Apple's last provoking vertex runs on a device that takes flat inputs from the - /// first (`pipeline::link::mesh`). The plan of a pipeline compiled under it states it - /// (`RuntimeFact::MeshLastFirst`). - #[cfg_attr(feature = "serde", serde(default))] - pub mesh_last_first: bool, /// The pipeline draws its lines, or its triangles' edges, as bands of triangles through /// synthesized tessellation stages, each patch one primitive of this kind /// (`BindShape::line_band`, `pipeline::link::band`): the variant a draw of lines, or of @@ -613,7 +606,6 @@ impl VariantKey { && self.kept_imageblock_bytes.is_none() && !self.depth_clamp_range && !self.rotated_weights - && !self.mesh_last_first && self.line_band.is_none() && self.swizzled_storage.is_empty() && !self.addressed_function_tables diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index 8ceb6eaec..f4ed8697b 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -205,7 +205,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { RuntimeFact::DepthClampRange => Mechanism::Variant, RuntimeFact::RotatedWeights => Mechanism::Variant, // A separate link of the mesh pipeline's synthesized vertex stage. - RuntimeFact::MeshLastFirst => Mechanism::Variant, // The binder's region flags a draw whose last object threadgroup along an axis is partial. RuntimeFact::PartialObjectThreadgroups => Mechanism::RegionSelected, // The binder specializes the lanes from the bound texture's pixel format and swizzle. diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 7dec34269..5e8c64c67 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -169,7 +169,6 @@ fn every_fact() -> Vec { device: true, }, RuntimeFact::TexelRows { slot }, - RuntimeFact::MeshLastFirst, RuntimeFact::AbsentArgumentRead { stage: Stage::Fragment, }, @@ -387,7 +386,6 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::QuadPrimitiveIds => 58, RuntimeFact::RotatedWeights => 82, RuntimeFact::PrivateList => 86, - RuntimeFact::MeshLastFirst => 71, RuntimeFact::YCbCrInPlace { .. } => 65, RuntimeFact::PartialObjectThreadgroups => 89, RuntimeFact::RotatedInputBlend { .. } => 90, @@ -404,7 +402,7 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::UnitAxes { .. } => 101, RuntimeFact::TexelBufferParts { .. } => 102, RuntimeFact::OpenClLineTexture { .. } => 103, - RuntimeFact::AddressAlignment { .. } => 104, + RuntimeFact::AddressAlignment { .. } => 71, RuntimeFact::GridTiles => 55, } } @@ -413,7 +411,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..105).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..104).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -498,7 +496,6 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::DroppedColor { .. } | RuntimeFact::DepthClampRange | RuntimeFact::RotatedWeights - | RuntimeFact::MeshLastFirst | RuntimeFact::TestedStorageWrites { .. } | RuntimeFact::MovableStorageWrites { .. } | RuntimeFact::ConstexprSampled { .. } diff --git a/crates/metal2vulkan/src/lower/access/local.rs b/crates/metal2vulkan/src/lower/access/local.rs index a407a0dd6..8fa38adbd 100644 --- a/crates/metal2vulkan/src/lower/access/local.rs +++ b/crates/metal2vulkan/src/lower/access/local.rs @@ -1117,11 +1117,7 @@ pub fn declare(mb: &mut ModuleBuilder, plan: &Plan) -> BResult { None => None, }, payload: match p.payload { - Some(size) => Some(arena::declare_payload( - mb, - size, - plan.families.mesh.emulated, - )?), + Some(size) => Some(arena::declare_payload(mb, size)?), None => None, }, typed, diff --git a/crates/metal2vulkan/src/lower/dispatch.rs b/crates/metal2vulkan/src/lower/dispatch.rs index e382a3f07..caaef6277 100644 --- a/crates/metal2vulkan/src/lower/dispatch.rs +++ b/crates/metal2vulkan/src/lower/dispatch.rs @@ -508,10 +508,6 @@ pub struct DispatchPlan { /// threadgroups, so its threadgroup's number adds `DrawIndex · nx · ny · nz` /// ([`KernelDecl::folded`]). pub draw_pieces: bool, - /// The kernel's threadgroup position and grid are what its entry wrapper computes, not its - /// dispatch's: an emulated mesh function under an object function, whose flat dispatch runs - /// every object threadgroup's mesh grid ([`WrapperGroups`]). - pub wrapper_groups: bool, /// An unfolded object function: its single-region `threadgroups_per_grid` is Metal's object /// grid's, the threadgroups its threads per grid fill once each axis wraps at 2^32 /// (`bind::metal_object_grid`, measured): `⌈(NumWorkgroups · L mod 2^32) / L⌉`, which is @@ -659,10 +655,9 @@ pub fn plan_kernel(cx: &mut SelectCx<'_>, tier: Tier) -> Result, tier: Tier) -> Result, /// The subgroup size the pipeline pins ([`DispatchPlan::pinned_subgroup_size`]). pinned_subgroup_size: Option, - /// The words the entry wrapper stores the threadgroup's position and grid into - /// ([`DispatchPlan::wrapper_groups`]), with the dispatch's own builtins it reads. - wrapper: Option, /// An unfolded object function's grid ([`DispatchPlan::object_grid`]). object_grid: bool, /// A function whose threadgroup may be partial ([`DispatchPlan::partial_groups`]). @@ -1012,18 +1003,6 @@ pub struct KernelDecl { grid_edge: bool, } -/// The threadgroup position and grid of a kernel whose entry wrapper computes them -/// ([`DispatchPlan::wrapper_groups`]): two `Private` `uvec3`s that every grid builtin reads in -/// place of `WorkgroupId` and `NumWorkgroups`, which the wrapper stores before the body; and the -/// dispatch's `WorkgroupId` and `NumWorkgroups`, which only the wrapper reads. -#[derive(Clone, Copy, Debug)] -pub struct WrapperGroups { - pub position: GlobalId, - pub grid: GlobalId, - pub workgroup_id: GlobalId, - pub num_workgroups: GlobalId, -} - /// Declare the kernel's workgroup size (module scope, before the entry is declared), its /// specialization constants, and its builtin variables. A non-kernel plan declares nothing. pub fn declare( @@ -1316,18 +1295,6 @@ impl KernelDecl { || (needs.local_pos && deep.is_some()); let subgroups = needs.lin && flat && !by_index && !dp.grid_edge; use crate::spv::BuiltIn as B; - // A wrapper that computes the threadgroup's position and grid stores them into private - // words, which the builtins read; it reads the dispatch's own. - let wrapper = if dp.wrapper_groups { - Some(WrapperGroups { - position: mb.plain_global(StorageClass::Private, uvec3, None)?, - grid: mb.plain_global(StorageClass::Private, uvec3, None)?, - workgroup_id: mb.builtin(B::WorkgroupId, IoDir::Input, uvec3)?, - num_workgroups: mb.builtin(B::NumWorkgroups, IoDir::Input, uvec3)?, - }) - } else { - None - }; let mut var = |on: bool, b: crate::spv::BuiltIn, ty: TypeId| -> BResult> { if on { mb.builtin(b, IoDir::Input, ty).map(Some) @@ -1335,13 +1302,10 @@ impl KernelDecl { Ok(None) } }; - let (workgroup_id, num_workgroups) = match wrapper { - Some(w) => (Some(w.position), Some(w.grid)), - None => ( - var(needs.workgroup_id, B::WorkgroupId, uvec3)?, - var(needs.num_workgroups, B::NumWorkgroups, uvec3)?, - ), - }; + let (workgroup_id, num_workgroups) = ( + var(needs.workgroup_id, B::WorkgroupId, uvec3)?, + var(needs.num_workgroups, B::NumWorkgroups, uvec3)?, + ); Ok(KernelDecl { form: dp.local_size, tile: dp.tile, @@ -1370,29 +1334,12 @@ impl KernelDecl { )?, subgroup_local: var(subgroups, B::SubgroupLocalInvocationId, u32_)?, pinned_subgroup_size: dp.pinned_subgroup_size, - wrapper, object_grid: dp.object_grid, partial_groups: dp.partial_groups, grid_edge: dp.grid_edge, }) } - /// The dispatch's own `WorkgroupId` and `NumWorkgroups`, of a kernel that reads its - /// threadgroup's position and the grid's threadgroups (an emulated object function's wrapper: - /// its slot's number counts the threadgroups the dispatch runs, not the grid Metal reports). - pub fn dispatch_groups(&self, fb: &mut FunctionBuilder<'_>) -> BResult<(SValue, SValue)> { - Ok(( - self.load(fb, self.workgroup_id)?, - self.load(fb, self.num_workgroups)?, - )) - } - - /// The words the entry wrapper computes the threadgroup's position and grid into, where it - /// does ([`DispatchPlan::wrapper_groups`]). - pub fn wrapper_groups(&self) -> Option { - self.wrapper - } - fn load(&self, fb: &mut FunctionBuilder<'_>, g: Option) -> BResult { let Some(g) = g else { return Err(dangling_value()); diff --git a/crates/metal2vulkan/src/lower/dispatch/tests.rs b/crates/metal2vulkan/src/lower/dispatch/tests.rs index 21fca2076..aa4a6330b 100644 --- a/crates/metal2vulkan/src/lower/dispatch/tests.rs +++ b/crates/metal2vulkan/src/lower/dispatch/tests.rs @@ -35,7 +35,6 @@ fn plan(form: LocalSizeForm, multi_region: bool) -> DispatchPlan { keys: SpecKey::dispatch_keys(Stage::Kernel), folded_groups: false, draw_pieces: false, - wrapper_groups: false, object_grid: false, partial_groups: false, grid_edge: false, diff --git a/crates/metal2vulkan/src/lower/emit.rs b/crates/metal2vulkan/src/lower/emit.rs index 238d68539..31b7bd8df 100644 --- a/crates/metal2vulkan/src/lower/emit.rs +++ b/crates/metal2vulkan/src/lower/emit.rs @@ -1568,8 +1568,6 @@ pub fn emit_module(e: &Entry, plan: &Plan, m: &mut Meter) -> Result ExecModel::Vertex, Stage::Fragment => ExecModel::Fragment, - // An emulated object or mesh function is a compute entry. - Stage::Object | Stage::Mesh if plan.families.mesh.emulated => ExecModel::GLCompute, Stage::Object => ExecModel::TaskEXT, Stage::Mesh => ExecModel::MeshEXT, }; diff --git a/crates/metal2vulkan/src/lower/mesh/mod.rs b/crates/metal2vulkan/src/lower/mesh/mod.rs index 648a61d81..51668c646 100644 --- a/crates/metal2vulkan/src/lower/mesh/mod.rs +++ b/crates/metal2vulkan/src/lower/mesh/mod.rs @@ -75,35 +75,6 @@ //! function reads from push fields, and the index as written to a raw per-primitive varying, which //! Metal's fragment function reads ([`target_index`]). //! -//! **Emulated meshes**. On a device without `VK_EXT_mesh_shader` (or its `meshShader` feature) a -//! mesh function is a `GLCompute` entry ([`MeshPlan::emulated`]): every output is a field of the -//! draw's records ([`records`], `StageInterface::mesh_records`), a storage buffer of words -//! (`SyntheticBinding::MeshRecords`) that the pipeline's synthesized vertex stage draws from -//! (`pipeline::link::mesh`). Each `set_*` stores its value's words at its field in its vertex's or -//! primitive's record, as it would store the output, and `set_index` its index at its word of the -//! primitive's record. The primitive id is not recorded: a fragment function that reads -//! `[[primitive_id]]` behind an emulated mesh is refused (`pipeline::link`). -//! -//! Every emulated draw has a work buffer ([`work`], `SyntheticBinding::MeshWork`): its header -//! (the object threadgroups `O`, the mesh threadgroups `T`, the records' first word, the mesh -//! dispatch's and the draw's indirect arguments), a slot per object threadgroup (the grid it -//! launched, then its payload's words), and each object threadgroup's first mesh threadgroup. An -//! indirect draw with an object function keeps its slots and offsets in its records instead, -//! where its object arguments pass reserved them (`work::SLOTS`); the wrappers and the scan read -//! the header's word to find them. An object function is a `GLCompute` entry too: its payload is -//! workgroup memory, its wrapper zeroes its grid, runs the body between two barriers, and writes -//! the grid it set (held to Metal's limit) and its payload into its slot, numbered by its -//! workgroup in the dispatch (whose grid is the threadgroups the draw runs, which an indirect -//! draw's wrapped threads make more than the grid Metal reports). The binder or a scan -//! (`bind::mesh_scan_module`) fills the rest of the header. The mesh wrapper's threadgroup is -//! number `w` of the draw's `T` (past `T` it returns); it finds its object threadgroup by -//! bisecting the offsets, and its place in that threadgroup's grid, which every grid builtin -//! reads; it copies in the payload (zero past the slot's words), zeroes its own records from -//! `RECORDS_BASE + w · group_words` and its count, runs the body between two barriers, and its -//! first thread stores the count (0 for points without point sizes) at its first word; the -//! vertex stage draws only the slots below it. The function's threadgroup memory is held to the -//! compute stage's `maxComputeSharedMemorySize`, with the count word. -//! //! Its hooks into `select` and `lower::emit`: the entry ([`plan_entry`]), the handle parameters //! ([`select_param`]), the operations ([`select`], [`emit`]), the module-scope objects and //! execution modes ([`declare`]), and the entry wrapper ([`wrap_entry`]). @@ -127,18 +98,15 @@ use crate::lower::sync::memory_model::coherence; use crate::memory::arena::{self, WorkgroupLimit}; use crate::memory::leaf::Coherence; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::interface::{MeshRecords, RecordField, RecordValue}; use crate::pipeline::stage_io::{IoNumeric, IoRole, IoType, IoVariable, StageBuiltin}; -use crate::pipeline::sym::{ - AirUserKey, PushField, ResourceKind, ResourceSlot, Stage, SyntheticBinding, VaryingKey, -}; +use crate::pipeline::sym::{AirUserKey, PushField, Stage, VaryingKey}; use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::{BResult, BuildError}; +use crate::spirv::error::BResult; use crate::spirv::ids::{FuncId, GlobalId, TypeId, Value as SValue}; use crate::spirv::ir::{ - natural_layout, BinOp, ConstBits, Constant, ConvOp, ExecMode, GlslOp, IoDecor, IoDir, - LayoutRule, MemAccess, MemoryOrder, Scope, Semantics, StorageClass, Type, + BinOp, ConstBits, Constant, ExecMode, GlslOp, IoDecor, IoDir, MemAccess, MemoryOrder, Scope, + StorageClass, Type, }; use crate::spv::BuiltIn as B; use std::borrow::Cow; @@ -245,14 +213,6 @@ pub struct MeshPlan { pub outputs: Vec, /// A point mesh whose vertex type has no `point_size`: it draws nothing (the module docs). pub unsized_points: bool, - /// An object or mesh function on a device without `VK_EXT_mesh_shader`: a `GLCompute` - /// entry, an object function writing its grid and payload to its slot of the draw's work - /// buffer and a mesh function its outputs as records ([`records`], the module docs). - pub emulated: bool, - /// An emulated object or mesh function's payload words ([`arena::payload_bytes`] of its - /// payload parameter's size), 0 without one: the words its wrapper copies out of or into - /// its object threadgroup's slot. - pub payload_words: u32, /// An object or mesh function's payload arena's bytes (`arena::payload_bytes` of /// [`payload_extent`]), `None` without a payload (`StageInterface::payload`). pub payload: Option, @@ -365,32 +325,30 @@ fn mesh_outputs<'e>(cx: &SelectCx<'e>) -> Option<&'e MeshOutputs> { }) } -/// What an object (`TaskEXT`) entry needs enabled: `VK_EXT_mesh_shader` and `taskShader`. The -/// missing ones, as the refusal names them. +/// What an object (`TaskEXT`) entry needs enabled, `VK_EXT_mesh_shader` and `taskShader`, and a +/// mesh (`MeshEXT`) entry, `VK_EXT_mesh_shader` and `meshShader`: the missing ones, as the +/// refusal names them. fn missing_caps(cx: &SelectCx<'_>) -> Vec { let enabled = cx.profile.enabled(); let mut missing = Vec::new(); if !enabled.extensions.contains(&VkExtension::ExtMeshShader) { missing.push(Capability::Extension(VkExtension::ExtMeshShader)); } - if !enabled.features.contains(&VkFeature::TaskShader) { - missing.push(Capability::Feature(VkFeature::TaskShader)); + let feature = match cx.stage { + Stage::Object => VkFeature::TaskShader, + _ => VkFeature::MeshShader, + }; + if !enabled.features.contains(&feature) { + missing.push(Capability::Feature(feature)); } missing } -/// Whether the entry is an object or mesh function the device runs as a compute entry (the -/// module docs). -fn emulated(cx: &SelectCx<'_>) -> bool { - matches!(cx.stage, Stage::Object | Stage::Mesh) && emulates(cx.profile) -} - -/// Whether profile `p` runs mesh functions as compute entries writing records (the module docs): -/// it does not enable `VK_EXT_mesh_shader` and `meshShader`. -pub fn emulates(p: &DeviceProfile) -> bool { +/// Whether profile `p` runs mesh functions: it enables `VK_EXT_mesh_shader` and `meshShader`. +pub fn mesh_stages(p: &DeviceProfile) -> bool { let enabled = p.enabled(); - !enabled.extensions.contains(&VkExtension::ExtMeshShader) - || !enabled.features.contains(&VkFeature::MeshShader) + enabled.extensions.contains(&VkExtension::ExtMeshShader) + && enabled.features.contains(&VkFeature::MeshShader) } /// Whether profile `p` compiles an object function folded (`LoweringInputs::folded_groups`), so @@ -401,7 +359,7 @@ pub fn emulates(p: &DeviceProfile) -> bool { /// draw's). pub fn folds_object_grids(p: &DeviceProfile) -> bool { let features = &p.enabled().features; - !emulates(p) + mesh_stages(p) && p.fields().buffer_access == crate::device::profile::BufferAccess::Addressed && features.contains(&VkFeature::ShaderInt64) && features.contains(&VkFeature::MultiDrawIndirect) @@ -438,8 +396,7 @@ pub fn workgroup_limit(cx: &SelectCx<'_>) -> WorkgroupLimit { /// The workgroup memory limit of a `stage` entry on `profile` ([`arena::workgroup_limit`]), with /// its payload arena's bytes where it has a payload of `payload` bytes (`arena::payload_bytes`): -/// an object or mesh entry's workgroup memory and payload share a limit. An emulated object or mesh -/// function's is the compute stage's, with its grid or count words and its payload. The binder +/// an object or mesh entry's workgroup memory and payload share a limit. The binder /// checks an object function's arena with the encoder's lengths against it /// (`RuntimeFact::ObjectThreadgroupArena`). pub fn stage_workgroup_limit( @@ -447,19 +404,7 @@ pub fn stage_workgroup_limit( profile: &DeviceProfile, payload: Option, ) -> WorkgroupLimit { - let limits = &profile.fields().limits; - // An emulated entry's: the compute stage's, with its wrapper's words (an object function's - // grid, a mesh function's count) and its payload, which is workgroup memory there. - if matches!(stage, Stage::Object | Stage::Mesh) && emulates(profile) { - let w = arena::workgroup_limit(Stage::Kernel, limits); - let words = if stage == Stage::Object { 12 } else { 4 }; - let payload = payload.map_or(0, arena::payload_bytes); - return WorkgroupLimit { - wrapper: w.wrapper.saturating_add(words).saturating_add(payload), - ..w - }; - } - let w = arena::workgroup_limit(stage, limits); + let w = arena::workgroup_limit(stage, &profile.fields().limits); match payload { Some(size) => w.with_payload(arena::payload_bytes(size)), None => w, @@ -470,10 +415,6 @@ pub fn stage_workgroup_limit( /// wrapper's workgroup words, within the stage's limit on its workgroup memory and payload together /// (the function's own workgroup memory joins that check where it is planned). pub fn check_payload(cx: &SelectCx<'_>, size: u64) -> Result<(), Error> { - // An emulated entry's payload is workgroup memory, held to the compute stage's limit. - if emulated(cx) { - return workgroup_limit(cx).check(0); - } let bytes = arena::payload_bytes(size); let available = cx.profile.fields().limits.mesh.max_task_payload_size; if bytes > u64::from(available) { @@ -524,34 +465,24 @@ pub fn plan_partial_groups(cx: &mut SelectCx<'_>) -> Result<(), Error> { Ok(()) } -/// Plan the entry: an object function needs `VK_EXT_mesh_shader` and `taskShader` enabled -/// (`Unsupported{MeshShading}` naming the missing ones), and a mesh function without them is -/// emulated (the module docs); a mesh function's shape, its always-declared outputs ([`CULLED`], +/// Plan the entry: an object function needs `VK_EXT_mesh_shader` and `taskShader` enabled, and a +/// mesh function `VK_EXT_mesh_shader` and `meshShader` (`Unsupported{MeshShading}` naming the +/// missing ones); a mesh function's shape, its always-declared outputs ([`CULLED`], /// [`PRIMITIVE_ID`]). Nothing for any other stage. pub fn plan_entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { if !matches!(cx.stage, Stage::Object | Stage::Mesh) { return Ok(()); } - let emulated = emulated(cx); + let missing = missing_caps(cx); + if !missing.is_empty() { + return Err(Unsupported::needs_any_of(Feature::MeshShading, vec![missing]).into()); + } let payload = payload_extent(cx) .map(|size| u32::try_from(arena::payload_bytes(size))) .transpose() .map_err(|_| cx.invariant("a payload past a u32's bytes"))?; - let payload_words = payload.map_or(0, |bytes| bytes / 4); cx.families.mesh.payload = payload; if cx.stage != Stage::Mesh { - // An emulated object function writes its grid and payload to its slot, which its - // threadgroup's position in the grid places (the module docs). - if emulated { - cx.push.insert(PushField::DispatchRegion); - cx.families.mesh.emulated = true; - cx.families.mesh.payload_words = payload_words; - return Ok(()); - } - let missing = missing_caps(cx); - if !missing.is_empty() { - return Err(Unsupported::needs_any_of(Feature::MeshShading, vec![missing]).into()); - } return Ok(()); } let Some(out) = mesh_outputs(cx) else { @@ -566,7 +497,7 @@ pub fn plan_entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { return Err(cx.invariant("a mesh type without vertices or primitives")); } // `OutputVertices` and `OutputPrimitivesEXT` are the type's `NV` and `NP`, each within the - // device's limit; an emulated function's records hold any. + // device's limit. let limits = &cx.profile.fields().limits.mesh; for (limit, required, available) in [ ( @@ -579,10 +510,7 @@ pub fn plan_entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { shape.primitives, limits.max_mesh_output_primitives, ), - ] - .into_iter() - .filter(|_| !emulated) - { + ] { if required > available { return Err(Unsupported::needs( Feature::MeshShading, @@ -606,8 +534,6 @@ pub fn plan_entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { } let plan = &mut cx.families.mesh; plan.mesh = Some(shape); - plan.emulated = emulated; - plan.payload_words = if emulated { payload_words } else { 0 }; plan.unsized_points = shape.topology == MeshTopology::Point && !point_size; let culled = plan.output(Output { kind: OutputKind::Builtin(B::CullPrimitiveEXT), @@ -864,20 +790,15 @@ pub fn select(cx: &mut SelectCx<'_>, _at: InstId, inst: &Inst) -> Result, /// The object function's mesh grid, a workgroup `uvec3`. pub grid: Option, - /// An emulated mesh function's records buffer (`SyntheticBinding::MeshRecords`). - pub records: Option, - /// An emulated mesh function's first word of its threadgroup's records: a private `uint` - /// the wrapper writes before the body. - pub first_word: Option, - /// An emulated mesh function's records ([`layout`]). - pub layout: Option, - /// An emulated object or mesh function's work buffer (`SyntheticBinding::MeshWork`, - /// [`WORK_SLOT`]). - pub work: Option, -} - -/// The binding symbol of an emulated mesh function's records (`SyntheticBinding::MeshRecords`), -/// declared with the mesh stage's symbols. -pub const RECORDS_SLOT: ResourceSlot = ResourceSlot { - stage: Stage::Mesh, - kind: ResourceKind::Synthetic(SyntheticBinding::MeshRecords), - index: 0, -}; - -/// The binding symbol of an emulated mesh pipeline's work buffer (`SyntheticBinding::MeshWork`) -/// for its mesh function and synthesized vertex stage; its object function binds the same -/// buffer under its own stage's symbol ([`OBJECT_WORK_SLOT`]). -pub const WORK_SLOT: ResourceSlot = ResourceSlot { - stage: Stage::Mesh, - kind: ResourceKind::Synthetic(SyntheticBinding::MeshWork), - index: 0, -}; - -/// The binding symbol of the work buffer for an emulated object function ([`WORK_SLOT`]). -pub const OBJECT_WORK_SLOT: ResourceSlot = ResourceSlot { - stage: Stage::Object, - kind: ResourceKind::Synthetic(SyntheticBinding::MeshWork), - index: 0, -}; - -/// The binding symbol of the records for an emulated object function ([`RECORDS_SLOT`]), where -/// an indirect draw keeps its slots (`work::SLOTS`). -pub const OBJECT_RECORDS_SLOT: ResourceSlot = ResourceSlot { - stage: Stage::Object, - kind: ResourceKind::Synthetic(SyntheticBinding::MeshRecords), - index: 0, -}; - -pub mod work; - -/// An emulated mesh function's records ([`MeshRecords`]) with each output's word offset in its -/// record, by [`MeshPlan::outputs`] index (`None` for an output not recorded). -#[derive(Clone, Debug)] -pub struct Layout { - pub offsets: Vec>, - pub records: MeshRecords, - /// [`MeshRecords::group_words`], which lies within a `u32`. - pub group_words: u32, -} - -/// The record value of output `kind`; `None` for the primitive id, which is not recorded (the -/// module docs). -fn record_value(kind: &OutputKind) -> Option { - match kind { - OutputKind::Builtin(B::Position) => Some(RecordValue::Position), - OutputKind::Builtin(B::PointSize) => Some(RecordValue::PointSize), - OutputKind::Builtin(B::ClipDistance) => Some(RecordValue::ClipDistance), - OutputKind::Builtin(B::CullPrimitiveEXT) => Some(RecordValue::Culled), - OutputKind::Builtin(B::Layer) => Some(RecordValue::Layer), - OutputKind::Builtin(B::ViewportIndex) => Some(RecordValue::ViewportIndex), - OutputKind::Builtin(_) => None, - OutputKind::User(key) => Some(RecordValue::Varying(key.clone())), - } -} - -/// The records of an emulated mesh plan (the module docs): every vertex record holds the -/// per-vertex outputs in output order, and every primitive record its indices and then the -/// per-primitive outputs in output order, one word per lane. `None` for any other plan, and for -/// records whose words a `u32` does not hold. -pub fn layout(plan: &MeshPlan) -> Option { - let shape = plan.mesh.filter(|_| plan.emulated)?; - // The end of the vertex record, and of the primitive record. - let (mut vertex_end, mut primitive_end) = (0u32, shape.per_primitive()); - let mut offsets = Vec::with_capacity(plan.outputs.len()); - let mut fields = Vec::new(); - for o in &plan.outputs { - let Some(value) = record_value(&o.kind) else { - offsets.push(None); - continue; - }; - let (words, numeric) = match o.element { - Element::Num { numeric, lanes } => (u32::from(lanes), numeric), - Element::Bool => (1, IoNumeric::Uint), - Element::Floats(n) => (n, IoNumeric::Float), - }; - let end = if o.per_primitive { - &mut primitive_end - } else { - &mut vertex_end - }; - offsets.push(Some(*end)); - fields.push(RecordField { - value, - per_primitive: o.per_primitive, - offset: *end, - words, - numeric, - }); - *end = end.checked_add(words)?; - } - fields.sort_by_key(|f| (f.per_primitive, f.offset)); - let records = MeshRecords { - vertices: shape.vertices, - primitives: shape.primitives, - corners: shape.per_primitive(), - vertex_words: vertex_end, - primitive_words: primitive_end, - fields, - slot_words: work::GRID.checked_add(plan.payload_words)?, - }; - let group_words = u32::try_from(records.group_words()).ok()?; - Some(Layout { - offsets, - records, - group_words, - }) -} - -/// The records of an emulated mesh plan (`StageInterface::mesh_records`, [`layout`]); `None` for -/// any other plan. -pub fn records(plan: &MeshPlan) -> Option { - layout(plan).map(|l| l.records) -} - -/// An emulated object or mesh plan's payload words (`StageInterface::emulated_payload`); `None` -/// for any other plan. -pub fn emulated_payload(plan: &MeshPlan) -> Option { - plan.emulated.then_some(plan.payload_words) } fn u32_ty(mb: &mut ModuleBuilder) -> BResult { @@ -1177,28 +964,9 @@ pub fn declare( let uvec3 = mb.ty(Type::Vector { elem: u32_, len: 3 })?; d.grid = Some(mb.plain_global(StorageClass::Workgroup, uvec3, None)?); } - // An emulated object function that sets its grid writes its slot: in the work buffer, or in - // the records where an indirect draw's object arguments pass reserved it (`work::SLOTS`). - if mp.emulated && mp.object { - d.work = Some(words_buffer(mb, OBJECT_WORK_SLOT)?); - d.records = Some(words_buffer(mb, OBJECT_RECORDS_SLOT)?); - } let Some(shape) = mp.mesh else { return Ok(d); }; - // An emulated mesh function's outputs are its records (the module docs). - if mp.emulated { - let Some(l) = layout(mp) else { - return Err(BuildError::IdSpaceExhausted); - }; - let u32_ = u32_ty(mb)?; - d.records = Some(words_buffer(mb, RECORDS_SLOT)?); - d.work = Some(words_buffer(mb, WORK_SLOT)?); - d.first_word = Some(mb.plain_global(StorageClass::Private, u32_, None)?); - d.count = Some(mb.plain_global(StorageClass::Workgroup, u32_, None)?); - d.layout = Some(l); - return Ok(d); - } modes.push(ExecMode::OutputVertices { n: shape.vertices }); modes.push(ExecMode::OutputPrimitives { n: shape.primitives, @@ -1261,21 +1029,6 @@ pub fn declare( Ok(d) } -/// A storage buffer of `u32` words (a block of one runtime array) at binding symbol `slot`. -fn words_buffer(mb: &mut ModuleBuilder, slot: ResourceSlot) -> BResult { - let u32_ = u32_ty(mb)?; - let words = mb.ty(Type::RuntimeArray { - elem: u32_, - stride: Some(4), - })?; - let block_layout = natural_layout(mb.types(), LayoutRule::Std430, true, &[words])?; - let block = mb.ty(Type::Struct { - members: [words].into(), - layout: Some(block_layout), - })?; - mb.resource(slot, StorageClass::StorageBuffer, block) -} - /// The operands of call `id`. fn call_args<'a>(cx: &EmitCx<'a>, id: InstId) -> Option<&'a [Value]> { let body: &'a crate::air::ir::Body = cx.body; @@ -1356,8 +1109,7 @@ fn store_element( } /// Store `value` at element `at` (and `inner`, a vector component or array element within it) -/// of output `output`: its output array's element, or, for an emulated mesh function, its words -/// in the element's record ([`store_record`]). +/// of output `output`: its output array's element. fn store_output( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, @@ -1366,219 +1118,10 @@ fn store_output( inner: Option, value: SValue, ) -> BResult<()> { - if cx.plan.families.mesh.emulated { - return store_record(cx, fb, output, at, inner, value); - } let (g, len) = output_of(cx, output)?; store_element(cx, fb, g, len, at, inner, value) } -/// The word of the records where record `at` of an emulated mesh function's threadgroup begins -/// (`per_primitive`: a primitive record, else a vertex record), plus `offset`. -fn record_word( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - per_primitive: bool, - at: SValue, - offset: u32, -) -> BResult { - let (Some(l), Some(first)) = ( - cx.decl.families.mesh.layout.as_ref(), - cx.decl.families.mesh.first_word, - ) else { - return Err(cx.fail("an emulated mesh store without its records")); - }; - let r = &l.records; - // Within the threadgroup's words, which lie within a `u32` ([`layout`]). - let (region, stride) = if per_primitive { - (r.primitive_base() as u32, r.primitive_words) - } else { - (1, r.vertex_words) - }; - let p = fb.module().global_value(first)?; - let first = fb.load(p, MemAccess::default())?; - let kstride = k32(fb, stride)?; - let into = fb.binary(BinOp::IMul, at, kstride)?; - let start = k32(fb, region + offset)?; - let word = fb.binary(BinOp::IAdd, first, start)?; - fb.binary(BinOp::IAdd, word, into) -} - -/// Store `words` (`u32`s) at word `word` of the records and the words after it. -fn store_words( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - word: SValue, - words: &[SValue], -) -> BResult<()> { - let Some(buffer) = cx.decl.families.mesh.records else { - return Err(cx.fail("an emulated mesh store without its records")); - }; - // Ordered with the wrapper's zeroing of the records by its barrier: the function's - // coherence of shared memory, as the wrapper's words take it. - let coherence = coherence(cx.plan); - for (j, &w) in words.iter().enumerate() { - let off = k32(fb, j as u32)?; - let at = fb.binary(BinOp::IAdd, word, off)?; - let access = word_access(coherence, fb, true)?; - store_word(fb, buffer, at, w, access)?; - } - Ok(()) -} - -/// Store `value` at word `at` of words buffer `buffer` ([`words_buffer`]). -fn store_word( - fb: &mut FunctionBuilder<'_>, - buffer: GlobalId, - at: SValue, - value: SValue, - access: MemAccess, -) -> BResult<()> { - let zero = k32(fb, 0)?; - let base = fb.module().global_value(buffer)?; - let ptr = fb.access_chain(base, &[zero, at])?; - fb.store(ptr, value, access) -} - -/// Word `at` of words buffer `buffer` ([`words_buffer`]). -fn load_word(fb: &mut FunctionBuilder<'_>, buffer: GlobalId, at: SValue) -> BResult { - let zero = k32(fb, 0)?; - let base = fb.module().global_value(buffer)?; - let ptr = fb.access_chain(base, &[zero, at])?; - fb.load(ptr, MemAccess::default()) -} - -/// Where an emulated draw's slots and offsets begin (`work::SLOTS`): in the records, at the word -/// the header names, for an indirect draw with an object function (whose object arguments pass -/// reserved them), else after the work buffer's header. -#[derive(Clone, Copy)] -struct Slots { - work: GlobalId, - records: GlobalId, - pooled: SValue, - start: SValue, -} - -impl Slots { - fn of(fb: &mut FunctionBuilder<'_>, work: GlobalId, records: GlobalId) -> BResult { - let at = k32(fb, work::SLOTS)?; - let word = load_word(fb, work, at)?; - let zero = k32(fb, 0)?; - let one = k32(fb, 1)?; - let pooled = fb.binary(BinOp::INotEqual, word, zero)?; - let in_pool = fb.binary(BinOp::ISub, word, one)?; - let header = k32(fb, work::HEADER)?; - let start = fb.select(pooled, in_pool, header)?; - Ok(Slots { - work, - records, - pooled, - start, - }) - } - - /// Word `at` of the slots and offsets (from their first). - fn load(self, fb: &mut FunctionBuilder<'_>, at: SValue) -> BResult { - let zero = k32(fb, 0)?; - let at = fb.binary(BinOp::IAdd, self.start, at)?; - let in_work = fb.select(self.pooled, zero, at)?; - let in_pool = fb.select(self.pooled, at, zero)?; - let from_work = load_word(fb, self.work, in_work)?; - let from_pool = load_word(fb, self.records, in_pool)?; - fb.select(self.pooled, from_pool, from_work) - } - - /// Store `value` at word `at` of the slots and offsets (from their first). - fn store( - self, - fb: &mut FunctionBuilder<'_>, - cx: &mut C, - at: SValue, - value: SValue, - access: MemAccess, - ) -> BResult<()> { - let at = fb.binary(BinOp::IAdd, self.start, at)?; - let (records, work) = (self.records, self.work); - let pool: ArmFn<'_, C> = Box::new(move |fb, _| { - store_word(fb, records, at, value, access)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - let local: ArmFn<'_, C> = Box::new(move |fb, _| { - store_word(fb, work, at, value, access)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - fb.if_(cx, self.pooled, pool, Some(local))?; - Ok(()) - } -} - -/// Store `value`, an element of output `output` of an emulated mesh function, as words in record -/// `at` (its element `inner` of a clip distance array, `value` a `float`), where `at` lies inside -/// the output's array: a lane per word, a `float` or `int` as its bits and a `bool` as 1 or 0 -/// (the module docs). An output the records do not hold (the primitive id) stores nothing. -fn store_record( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - output: usize, - at: SValue, - inner: Option, - value: SValue, -) -> BResult<()> { - let mp = &cx.plan.families.mesh; - let (Some(o), Some(l)) = ( - mp.outputs.get(output), - cx.decl.families.mesh.layout.as_ref(), - ) else { - return Err(cx.fail("an emulated mesh output that was not declared")); - }; - let Some(&offset) = l.offsets.get(output) else { - return Err(cx.fail("an emulated mesh output without its offset")); - }; - let Some(offset) = offset else { - return Ok(()); - }; - let (per_primitive, element) = (o.per_primitive, o.element); - let len = if per_primitive { - l.records.primitives - } else { - l.records.vertices - }; - let n = k32(fb, len)?; - let inside = fb.binary(BinOp::ULessThan, at, n)?; - when(fb, cx, inside, move |fb, cx| { - let mut word = record_word(cx, fb, per_primitive, at, offset)?; - if let Some(i) = inner { - word = fb.binary(BinOp::IAdd, word, i)?; - } - let u32_ = u32_ty(fb.module())?; - let lanes = match element { - Element::Bool => { - let (one, zero) = (k32(fb, 1)?, k32(fb, 0)?); - vec![fb.select(value, one, zero)?] - } - Element::Num { numeric, lanes } if lanes > 1 && inner.is_none() => { - let mut out = Vec::with_capacity(usize::from(lanes)); - for j in 0..u32::from(lanes) { - let lane = fb.composite_extract(value, &[j])?; - out.push(match numeric { - IoNumeric::Uint => lane, - _ => fb.convert(ConvOp::Bitcast, lane, u32_)?, - }); - } - out - } - Element::Num { - numeric: IoNumeric::Uint, - .. - } => vec![value], - Element::Num { .. } | Element::Floats(_) => { - vec![fb.convert(ConvOp::Bitcast, value, u32_)?] - } - }; - store_words(cx, fb, word, &lanes) - }) -} - /// The output array of `MeshPlan::outputs[output]` and its length. fn output_of(cx: &mut EmitCx<'_>, output: usize) -> BResult<(GlobalId, u32)> { let mp = &cx.plan.families.mesh; @@ -1604,31 +1147,11 @@ fn store_index( at: SValue, value: SValue, ) -> BResult<()> { - let (Some(g), Some(shape)) = ( - cx.decl - .families - .mesh - .indices - .or(cx.decl.families.mesh.records), - cx.plan.families.mesh.mesh, - ) else { + let (Some(g), Some(shape)) = (cx.decl.families.mesh.indices, cx.plan.families.mesh.mesh) else { return Err(cx.fail("mesh indices that were not declared")); }; let k = shape.per_primitive(); let len = shape.primitives.saturating_mul(k); - if cx.plan.families.mesh.emulated { - // The index's word in its primitive's record, which begins with its indices. - let n = k32(fb, len)?; - let inside = fb.binary(BinOp::ULessThan, at, n)?; - let kk = k32(fb, k)?; - let prim = fb.binary(BinOp::UDiv, at, kk)?; - let comp = fb.binary(BinOp::UMod, at, kk)?; - return when(fb, cx, inside, move |fb, cx| { - let word = record_word(cx, fb, true, prim, 0)?; - let word = fb.binary(BinOp::IAdd, word, comp)?; - store_words(cx, fb, word, &[value]) - }); - } if k == 1 { return store_element(cx, fb, g, len, at, None, value); } @@ -1796,31 +1319,11 @@ fn builtin(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, b: KernelBuiltin) } /// The builtins an entry wrapper reads (`dispatch::plan_kernel` derives them): its thread and -/// its threadgroup's threads, and an emulated object function's its threadgroup's position and -/// the grid's threadgroups, which declare the dispatch's `WorkgroupId` and `NumWorkgroups` that -/// number its slot (`KernelDecl::dispatch_groups`). -pub fn builtins(plan: &MeshPlan) -> &'static [KernelBuiltin] { - if plan.emulated && plan.mesh.is_none() { - &[ - KernelBuiltin::ThreadIndexInThreadgroup, - KernelBuiltin::ThreadsPerThreadgroup, - KernelBuiltin::ThreadgroupPositionInGrid, - KernelBuiltin::ThreadgroupsPerGrid, - ] - } else { - &[ - KernelBuiltin::ThreadIndexInThreadgroup, - KernelBuiltin::ThreadsPerThreadgroup, - ] - } -} - -/// Whether the entry's threadgroup position and grid are what its wrapper computes -/// (`dispatch::DispatchPlan::wrapper_groups`): an emulated mesh function's, found in its draw's -/// work buffer (the module docs). -pub fn wrapper_groups(plan: &MeshPlan) -> bool { - plan.emulated && plan.mesh.is_some() -} +/// its threadgroup's threads. +pub const BUILTINS: [KernelBuiltin; 2] = [ + KernelBuiltin::ThreadIndexInThreadgroup, + KernelBuiltin::ThreadsPerThreadgroup, +]; /// Whether the entry has a wrapper that reads [`builtins`]. pub fn wraps(plan: &MeshPlan) -> bool { @@ -1879,9 +1382,6 @@ pub fn wrap_entry(cx: &mut EmitCx<'_>, mb: &mut ModuleBuilder, body: FuncId) -> let zero = k32(&mut fb, 0)?; let first = fb.binary(BinOp::IEqual, lin, zero)?; let coherence = coherence(cx.plan); - if object && cx.plan.families.mesh.emulated { - return emulated_object_wrapper(cx, fb, (lin, first), body); - } if object { let Some(g) = cx.decl.families.mesh.grid else { return Err(cx.fail("an object wrapper without its grid")); @@ -1906,9 +1406,6 @@ pub fn wrap_entry(cx: &mut EmitCx<'_>, mb: &mut ModuleBuilder, body: FuncId) -> fb.emit_mesh_tasks(x, y, z, payload)?; return fb.finish(); } - if cx.plan.families.mesh.emulated { - return emulated_wrapper(cx, fb, (lin, first), body); - } let Some(shape) = mesh else { return Err(cx.fail("a mesh wrapper without its shape")); }; @@ -1993,305 +1490,3 @@ pub fn wrap_entry(cx: &mut EmitCx<'_>, mb: &mut ModuleBuilder, body: FuncId) -> fb.ret(None)?; fb.finish() } - -/// A barrier of the threadgroup's invocations that orders its workgroup memory and, for an -/// emulated mesh function's records and an emulated object function's slot, its device memory. -fn device_barrier(cx: &EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<()> { - let flags = MemFlags { - device: true, - threadgroup: true, - ..Default::default() - }; - let sem = semantics(flags, MemoryOrder::AcquireRelease, memory_model(cx.plan)); - fb.control_barrier(Scope::Workgroup, Scope::Workgroup, sem) -} - -/// The number of the threadgroup's threads, `x · y · z` of `ThreadsPerThreadgroup`. -fn thread_count(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult { - let threads = builtin(cx, fb, KernelBuiltin::ThreadsPerThreadgroup)?; - let [tx, ty, tz] = [0, 1, 2].map(|i| fb.composite_extract(threads, &[i])); - let txy = fb.binary(BinOp::IMul, tx?, ty?)?; - fb.binary(BinOp::IMul, txy, tz?) -} - -/// Word `at` of the payload arena, read (`store` is `None`) or written: a relaxed workgroup -/// atomic where the arena's words are atomics (`memory::arena::ArenaMem`), else plain. -fn payload_word( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - at: SValue, - store: Option, -) -> BResult> { - let Some(arena) = cx.decl.families.access.local.payload else { - return Err(cx.fail("an emulated payload copy without its arena")); - }; - let base = fb.module().global_value(arena.global)?; - let ptr = fb.access_chain(base, &[at])?; - let atomic = coherence(cx.plan) != Coherence::Plain; - match (store, atomic) { - (Some(v), true) => { - fb.atomic_store(ptr, Scope::Workgroup, Semantics::RELAXED, v)?; - Ok(None) - } - (Some(v), false) => { - fb.store(ptr, v, MemAccess::default())?; - Ok(None) - } - (None, true) => fb - .atomic_load(ptr, Scope::Workgroup, Semantics::RELAXED) - .map(Some), - (None, false) => fb.load(ptr, MemAccess::default()).map(Some), - } -} - -/// An emulated object function's wrapper (the module docs): its grid zeroed, the body between -/// two barriers, then its slot ([`Slots`]: in the work buffer, or in the records for an indirect -/// draw), placed by its workgroup's linear index in the dispatch: the grid it stored, held to -/// Metal's limit, and its payload's words that the slot holds. -fn emulated_object_wrapper( - cx: &mut EmitCx<'_>, - mut fb: FunctionBuilder<'_>, - (lin, first): (SValue, SValue), - body: FuncId, -) -> BResult { - let d = &cx.decl.families.mesh; - let (Some(g), Some(work), Some(records)) = (d.grid, d.work, d.records) else { - return Err(cx.fail("an emulated object wrapper without its grid, work buffer or records")); - }; - let coherence = coherence(cx.plan); - let zero = k32(&mut fb, 0)?; - let u32_ = u32_ty(fb.module())?; - let uvec3 = fb.module().ty(Type::Vector { elem: u32_, len: 3 })?; - let none = fb.composite_construct(uvec3, &[zero, zero, zero])?; - when(&mut fb, cx, first, move |fb, _| { - let p = fb.module().global_value(g)?; - let access = word_access(coherence, fb, true)?; - fb.store(p, none, access) - })?; - device_barrier(cx, &mut fb)?; - fb.call(body, &[])?; - device_barrier(cx, &mut fb)?; - // Its slot: word `o · S` of the slots, `o = x + X · (y + Y · z)` its workgroup's linear index - // in the dispatch, which runs Metal's threadgroups at their positions (no region of an - // emulated draw has a base). The dispatch's grid, not the one Metal reports, which an indirect - // draw's wrapped threads make smaller than the threadgroups it runs. - let Some(k) = cx.decl.families.dispatch.kernel.as_ref() else { - return Err(cx.fail("an emulated object wrapper without its dispatch")); - }; - let (at, grid) = k.dispatch_groups(&mut fb)?; - let [x, y, z] = [0, 1, 2].map(|i| fb.composite_extract(at, &[i])); - let [gx, gy] = [0, 1].map(|i| fb.composite_extract(grid, &[i])); - let yz = fb.binary(BinOp::IMul, gy?, z?)?; - let yz = fb.binary(BinOp::IAdd, y?, yz)?; - let xyz = fb.binary(BinOp::IMul, gx?, yz)?; - let o = fb.binary(BinOp::IAdd, x?, xyz)?; - let at_s = k32(&mut fb, work::SLOT_WORDS)?; - let s = load_word(&mut fb, work, at_s)?; - let slots = Slots::of(&mut fb, work, records)?; - let slot = fb.binary(BinOp::IMul, o, s)?; - when(&mut fb, cx, first, move |fb, cx| { - let p = fb.module().global_value(g)?; - let access = word_access(coherence, fb, false)?; - let stored = fb.load(p, access)?; - let [x, y, z] = [0, 1, 2].map(|i| fb.composite_extract(stored, &[i])); - let bounded = bounded_grid(cx, fb, [x?, y?, z?])?; - for (i, v) in bounded.into_iter().enumerate() { - let off = k32(fb, i as u32)?; - let w = fb.binary(BinOp::IAdd, slot, off)?; - slots.store(fb, cx, w, v, MemAccess::default())?; - } - Ok(()) - })?; - // Its payload's words, as many as the slot holds (`S − 4`). - // Every invocation copies, a partial threadgroup's past its threads too. - let words = cx.plan.families.mesh.payload_words; - if words > 0 && cx.decl.families.access.local.payload.is_some() { - let running = k.running_threads(&mut fb)?; - let [rx, ry, rz] = [0, 1, 2].map(|i| fb.composite_extract(running, &[i])); - let rxy = fb.binary(BinOp::IMul, rx?, ry?)?; - let n = fb.binary(BinOp::IMul, rxy, rz?)?; - let grid_words = k32(&mut fb, work::GRID)?; - let room = fb.binary(BinOp::ISub, s, grid_words)?; - let start = fb.binary(BinOp::IAdd, slot, grid_words)?; - strided(cx, &mut fb, (lin, n), words, move |fb, cx, i| { - let held = fb.binary(BinOp::ULessThan, i, room)?; - when(fb, cx, held, move |fb, cx| { - let Some(v) = payload_word(cx, fb, i, None)? else { - return Err(cx.fail("a payload read without its value")); - }; - let w = fb.binary(BinOp::IAdd, start, i)?; - slots.store(fb, cx, w, v, MemAccess::default()) - }) - })?; - } - fb.ret(None)?; - fb.finish() -} - -/// An emulated mesh function's wrapper (the module docs). Its threadgroup is number `w = -/// WorkgroupId.x + WorkgroupId.y · NumWorkgroups.x` of the draw's `T` mesh threadgroups (past -/// them, it returns as a whole); it finds its object threadgroup `o` (the last whose offset is -/// at most `w`) and its place in that object threadgroup's grid, which every grid builtin reads -/// (`dispatch::WrapperGroups`); it copies in that object threadgroup's payload, zeroes its own -/// records from word `RECORDS_BASE + w · group_words`, zeroes the count, runs the body between -/// two barriers, and its first thread stores the count at its first word. -fn emulated_wrapper( - cx: &mut EmitCx<'_>, - mut fb: FunctionBuilder<'_>, - (lin, first): (SValue, SValue), - body: FuncId, -) -> BResult { - let d = &cx.decl.families.mesh; - let (Some(l), Some(word), Some(count), Some(records), Some(work)) = - (d.layout.as_ref(), d.first_word, d.count, d.records, d.work) - else { - return Err(cx.fail("an emulated mesh wrapper without its records or work buffer")); - }; - let group_words = l.group_words; - let Some(groups) = cx - .decl - .families - .dispatch - .kernel - .as_ref() - .and_then(|k| k.wrapper_groups()) - else { - return Err(cx.fail("an emulated mesh wrapper without its threadgroup words")); - }; - let coherence = coherence(cx.plan); - let u32_ = u32_ty(fb.module())?; - let uvec3 = fb.module().ty(Type::Vector { elem: u32_, len: 3 })?; - let k = |fb: &mut FunctionBuilder<'_>, n: u32| k32(fb, n); - // `w`, from the flat dispatch's workgroup. - let p = fb.module().global_value(groups.workgroup_id)?; - let wid = fb.load(p, MemAccess::default())?; - let p = fb.module().global_value(groups.num_workgroups)?; - let dispatched = fb.load(p, MemAccess::default())?; - let wx = fb.composite_extract(wid, &[0])?; - let wy = fb.composite_extract(wid, &[1])?; - let nx = fb.composite_extract(dispatched, &[0])?; - let row = fb.binary(BinOp::IMul, wy, nx)?; - let w = fb.binary(BinOp::IAdd, wx, row)?; - let at = k(&mut fb, work::MESH_GROUPS)?; - let total = load_word(&mut fb, work, at)?; - let past = fb.binary(BinOp::UGreaterThanEqual, w, total)?; - let leave: ArmFn<'_, EmitCx<'_>> = Box::new(|fb, _| { - fb.ret(None)?; - Ok(ArmEnd::Exits) - }); - fb.if_(cx, past, leave, None)?; - // Its object threadgroup: the last `o` below `O` whose offset is at most `w` (`offsets[0]` - // is 0 and `offsets[O]` is `T`, past `w`), by bisection. - let at = k(&mut fb, work::OBJECT_GROUPS)?; - let objects = load_word(&mut fb, work, at)?; - let at = k(&mut fb, work::SLOT_WORDS)?; - let s = load_word(&mut fb, work, at)?; - let slots = Slots::of(&mut fb, work, records)?; - let offsets = fb.binary(BinOp::IMul, objects, s)?; - let lo = fb.local_var(u32_, None)?; - let hi = fb.local_var(u32_, None)?; - let (lo, hi) = (fb.var_ptr(lo)?, fb.var_ptr(hi)?); - let zero = k(&mut fb, 0)?; - let one = k(&mut fb, 1)?; - fb.store(lo, zero, MemAccess::default())?; - fb.store(hi, objects, MemAccess::default())?; - let search: LoopFn<'_, EmitCx<'_>> = Box::new(move |fb, cx, lc| { - let a = fb.load(lo, MemAccess::default())?; - let b = fb.load(hi, MemAccess::default())?; - let gap = fb.binary(BinOp::ISub, b, a)?; - let done = fb.binary(BinOp::ULessThanEqual, gap, one)?; - let exit: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, _| { - lc.break_(fb)?; - Ok(ArmEnd::Exits) - }); - fb.if_(cx, done, exit, None)?; - let half = fb.binary(BinOp::ShiftRightLogical, gap, one)?; - let mid = fb.binary(BinOp::IAdd, a, half)?; - let at = fb.binary(BinOp::IAdd, offsets, mid)?; - let offset = slots.load(fb, at)?; - let below = fb.binary(BinOp::ULessThanEqual, offset, w)?; - let a = fb.select(below, mid, a)?; - let b = fb.select(below, b, mid)?; - fb.store(lo, a, MemAccess::default())?; - fb.store(hi, b, MemAccess::default()) - }); - fb.loop_(cx, LoopSpec::default(), search)?; - let o = fb.load(lo, MemAccess::default())?; - // Its place in the object threadgroup's grid: `w − offsets[o]`, x fastest. - let slot = fb.binary(BinOp::IMul, o, s)?; - let mut axis = |i: u32| -> BResult { - let off = k(&mut fb, i)?; - let at = fb.binary(BinOp::IAdd, slot, off)?; - slots.load(&mut fb, at) - }; - let [gx, gy, gz] = [axis(0)?, axis(1)?, axis(2)?]; - let at = fb.binary(BinOp::IAdd, offsets, o)?; - let start = slots.load(&mut fb, at)?; - let local = fb.binary(BinOp::ISub, w, start)?; - // The object threadgroup launched `w`, so none of its counts is 0. - let x = fb.binary(BinOp::UMod, local, gx)?; - let rest = fb.binary(BinOp::UDiv, local, gx)?; - let y = fb.binary(BinOp::UMod, rest, gy)?; - let z = fb.binary(BinOp::UDiv, rest, gy)?; - let position = fb.composite_construct(uvec3, &[x, y, z])?; - let launched = fb.composite_construct(uvec3, &[gx, gy, gz])?; - let p = fb.module().global_value(groups.position)?; - fb.store(p, position, MemAccess::default())?; - let p = fb.module().global_value(groups.grid)?; - fb.store(p, launched, MemAccess::default())?; - // Its first word: within a `u32`, since the binder binds the records whole. - let at = k(&mut fb, work::RECORDS_BASE)?; - let base = load_word(&mut fb, work, at)?; - let gw = k(&mut fb, group_words)?; - let mine = fb.binary(BinOp::IMul, w, gw)?; - let first_word = fb.binary(BinOp::IAdd, base, mine)?; - let p = fb.module().global_value(word)?; - fb.store(p, first_word, MemAccess::default())?; - let n = thread_count(cx, &mut fb)?; - // The object threadgroup's payload, as many words as the slot holds (`S − 4`), zero past. - let words = cx.plan.families.mesh.payload_words; - if words > 0 && cx.decl.families.access.local.payload.is_some() { - let grid_words = k(&mut fb, work::GRID)?; - let room = fb.binary(BinOp::ISub, s, grid_words)?; - let from = fb.binary(BinOp::IAdd, slot, grid_words)?; - strided(cx, &mut fb, (lin, n), words, move |fb, cx, i| { - let held = fb.binary(BinOp::ULessThan, i, room)?; - let at = fb.binary(BinOp::IAdd, from, i)?; - let at = fb.select(held, at, from)?; - let read = slots.load(fb, at)?; - let zero = k32(fb, 0)?; - let v = fb.select(held, read, zero)?; - payload_word(cx, fb, i, Some(v)).map(|_| ()) - })?; - } - // Its records, zero: the body's stores and the wrapper's are ordered by the barrier. - strided(cx, &mut fb, (lin, n), group_words, move |fb, _, i| { - let at = fb.binary(BinOp::IAdd, first_word, i)?; - let zero = k32(fb, 0)?; - let access = word_access(coherence, fb, true)?; - store_word(fb, records, at, zero, access) - })?; - when(&mut fb, cx, first, move |fb, _| { - let p = fb.module().global_value(count)?; - let access = word_access(coherence, fb, true)?; - fb.store(p, zero, access) - })?; - device_barrier(cx, &mut fb)?; - fb.call(body, &[])?; - device_barrier(cx, &mut fb)?; - // A point mesh without point sizes draws nothing. - let unsized_points = cx.plan.families.mesh.unsized_points; - when(&mut fb, cx, first, move |fb, _| { - let drawn = if unsized_points { - zero - } else { - let p = fb.module().global_value(count)?; - let access = word_access(coherence, fb, false)?; - fb.load(p, access)? - }; - let access = word_access(coherence, fb, true)?; - store_word(fb, records, first_word, drawn, access) - })?; - fb.ret(None)?; - fb.finish() -} diff --git a/crates/metal2vulkan/src/lower/mesh/work.rs b/crates/metal2vulkan/src/lower/mesh/work.rs deleted file mode 100644 index 276e04b9a..000000000 --- a/crates/metal2vulkan/src/lower/mesh/work.rs +++ /dev/null @@ -1,61 +0,0 @@ -//! The words of an emulated mesh draw's work buffer (`SyntheticBinding::MeshWork`, `lower::mesh`'s -//! module docs), each a `u32`: a header of [`HEADER`] words, then a slot of `S` words per object -//! threadgroup (its grid's three counts and a zero, then its payload), then `O + 1` offsets: the -//! first mesh threadgroup of each object threadgroup, and `T`. An indirect draw with an object -//! function keeps its slots and offsets in its records binding instead, where its object arguments -//! pass reserves them (`bind::mesh_scan`, [`SLOTS`]). -//! -//! The binder, the mesh scan (`bind::mesh_scan`) and the runtime read these words at run time, -//! so this file is a runtime input (`validation/build.rs`); the lowering writes them. - -/// `O`: the object threadgroups (1 for a pipeline without an object function). -pub const OBJECT_GROUPS: u32 = 0; -/// `T`: the mesh threadgroups the draw runs, which its records hold. -pub const MESH_GROUPS: u32 = 1; -/// The word of the records binding where the draw's records begin. -pub const RECORDS_BASE: u32 = 2; -/// The mesh dispatch's `VkDispatchIndirectCommand`, three words. -pub const DISPATCH: u32 = 3; -/// The draw's `VkDrawIndirectCommand`, four words. -pub const DRAW: u32 = 6; -/// `S`: the words of one slot. -pub const SLOT_WORDS: u32 = 10; -/// The words of one mesh threadgroup's records (`MeshRecords::group_words`), which the scan -/// reserves for each. -pub const GROUP_WORDS: u32 = 11; -/// The vertices the draw draws for one mesh threadgroup, `NP · k`. -pub const GROUP_VERTICES: u32 = 12; -/// The words of the records pool the scan reserves the draw's records from. -pub const POOL_WORDS: u32 = 13; -/// The consumer's number for the draw, which a records fault reports. -pub const DRAW_ID: u32 = 14; -/// The most workgroups of the mesh dispatch along x (`maxComputeWorkGroupCount[0]`): the -/// scan folds `T` into rows of it. -pub const ROW: u32 = 15; -/// 0 for a draw of host-known object threadgroups; else 1 plus the word of the bound -/// arguments range where Metal's indirect arguments (the mesh grid of a pipeline without an -/// object function) begin, which the scan reads into slot 0. -pub const ARGUMENTS: u32 = 16; -/// 0 where the slots and offsets follow the header; else 1 plus the word of the records binding -/// (the command buffer's records pool) where they begin: an indirect draw with an object function, -/// whose object arguments pass reserves them. -pub const SLOTS: u32 = 17; -/// The object dispatch's `VkDispatchIndirectCommand`, three words, which the object arguments pass -/// writes (an indirect draw with an object function). -pub const OBJECT_DISPATCH: u32 = 18; -/// 0 for any other draw; else 1 plus the word of the bound arguments range where Metal's indirect -/// arguments (the object grid of an indirect draw with an object function) begin, which the -/// object arguments pass reads. -pub const OBJECT_ARGUMENTS: u32 = 21; -/// The header's words. -pub const HEADER: u32 = 22; -/// The words of a slot before its payload: the grid's three counts and a zero. -pub const GRID: u32 = 4; - -/// The words of a work buffer of `objects` slots of `slot_words` words, with its offsets. -pub fn words(objects: u64, slot_words: u32) -> u64 { - u64::from(HEADER) - .saturating_add(objects.saturating_mul(u64::from(slot_words))) - .saturating_add(objects) - .saturating_add(1) -} diff --git a/crates/metal2vulkan/src/lower/stage_io/mod.rs b/crates/metal2vulkan/src/lower/stage_io/mod.rs index f01769699..072cbc462 100644 --- a/crates/metal2vulkan/src/lower/stage_io/mod.rs +++ b/crates/metal2vulkan/src/lower/stage_io/mod.rs @@ -470,11 +470,6 @@ pub struct StageIoPlan { /// The render pipeline's private alpha test the fragment function runs at each return /// (`LoweringInputs::alpha_test`). pub alpha_test: Option, - /// A fragment function's per-primitive inputs (`StageIo::primitive_inputs`) are flat alone, - /// not decorated `PerPrimitiveEXT`: its device does not enable `VK_EXT_mesh_shader`, so the - /// pipeline's mesh function is emulated, and its synthesized vertex stage writes a - /// primitive's values at every corner of it. - pub flat_primitive_inputs: bool, /// The second outputs a fragment function writes for attachments held with their channels /// rotated (`LoweringInputs::rotated_factors`), each beside its first output there. pub rotated_seconds: Vec, @@ -2837,11 +2832,8 @@ pub fn declare( .insert(i, mb.plain_global(StorageClass::Private, array, None)?); } let g = mb.io(key.clone(), *dir, ty, *deco)?; - // An input of a key the mesh function writes per primitive, flat alone behind an - // emulated mesh function. - if *dir == IoDir::Input - && !sp.flat_primitive_inputs - && sp.interface.primitive_inputs.binary_search(key).is_ok() + // An input of a key the mesh function writes per primitive. + if *dir == IoDir::Input && sp.interface.primitive_inputs.binary_search(key).is_ok() { mb.per_primitive(g)?; } diff --git a/crates/metal2vulkan/src/lower/stage_io/plan.rs b/crates/metal2vulkan/src/lower/stage_io/plan.rs index 81ce00894..0835a39a0 100644 --- a/crates/metal2vulkan/src/lower/stage_io/plan.rs +++ b/crates/metal2vulkan/src/lower/stage_io/plan.rs @@ -1453,13 +1453,11 @@ fn push_var(list: &mut Vec, v: IoVariable) { /// Whether the fragment function reads the varying `key` per primitive: its mesh render /// pipeline's mesh function writes it per primitive (`LoweringInputs::primitive_varyings`). The /// stage interface lists it (`StageIo::primitive_inputs`), and the declaration decorates it -/// `PerPrimitiveEXT`, or, on a device that emulates mesh functions, reads it flat alone -/// (`StageIoPlan::flat_primitive_inputs`). +/// `PerPrimitiveEXT`. fn read_per_primitive(cx: &mut SelectCx<'_>, key: &VaryingKey) -> bool { if !cx.inputs.primitive_varyings.contains(key) { return false; } - cx.families.stage_io.flat_primitive_inputs = crate::lower::mesh::emulates(cx.profile); let keys = &mut cx.families.stage_io.interface.primitive_inputs; if let Err(at) = keys.binary_search(key) { keys.insert(at, key.clone()); diff --git a/crates/metal2vulkan/src/memory/arena.rs b/crates/metal2vulkan/src/memory/arena.rs index d36885892..adb60c710 100644 --- a/crates/metal2vulkan/src/memory/arena.rs +++ b/crates/metal2vulkan/src/memory/arena.rs @@ -555,20 +555,13 @@ pub fn payload_bytes(size: u64) -> u64 { } /// Declare the payload arena of a payload of `size` bytes: a `TaskPayloadWorkgroupEXT` array of -/// [`payload_bytes`], or, for an emulated object or mesh function (`emulated`), a `Workgroup` one -/// that its wrapper copies out of or into its slot of the draw's work buffer. Neither has an -/// initializer: an object function's payload "is assumed uninitialized at the entry of the object -/// function" (the Metal Shading Language Specification's `payload` attribute), and an emulated -/// mesh function's wrapper copies its payload in before the function runs. -pub fn declare_payload(mb: &mut ModuleBuilder, size: u64, emulated: bool) -> BResult { +/// [`payload_bytes`], with no initializer: an object function's payload "is assumed uninitialized +/// at the entry of the object function" (the Metal Shading Language Specification's `payload` +/// attribute). +pub fn declare_payload(mb: &mut ModuleBuilder, size: u64) -> BResult { let bytes = konst(mb, size)?; let words = konst(mb, static_words(size))?; - let class = if emulated { - StorageClass::Workgroup - } else { - StorageClass::TaskPayloadWorkgroupEXT - }; - let global = array(mb, class, words, false)?; + let global = array(mb, StorageClass::TaskPayloadWorkgroupEXT, words, false)?; Ok(ArenaDecl { arena: Arena::Payload, global, diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index 668ece983..b47b3184f 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -245,7 +245,6 @@ mod serde_round_trips { kept_imageblock_bytes: Some(8), depth_clamp_range: true, rotated_weights: true, - mesh_last_first: true, line_band: Some(crate::pipeline::BandPrimitive::Triangles), swizzled_storage: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 6)]), addressed_function_tables: true, @@ -638,41 +637,6 @@ mod serde_round_trips { }), early_fragment_tests: true, writes_sample_mask: true, - // An emulated mesh function's records. - mesh_records: Some(crate::pipeline::MeshRecords { - vertices: 3, - primitives: 1, - corners: 3, - vertex_words: 4, - primitive_words: 5, - fields: vec![ - crate::pipeline::RecordField { - value: crate::pipeline::RecordValue::Position, - per_primitive: false, - offset: 0, - words: 4, - numeric: crate::pipeline::stage_io::IoNumeric::Float, - }, - crate::pipeline::RecordField { - value: crate::pipeline::RecordValue::Culled, - per_primitive: true, - offset: 3, - words: 1, - numeric: crate::pipeline::stage_io::IoNumeric::Uint, - }, - crate::pipeline::RecordField { - value: crate::pipeline::RecordValue::Varying( - crate::pipeline::sym::VaryingKey::user(b"c"), - ), - per_primitive: true, - offset: 4, - words: 1, - numeric: crate::pipeline::stage_io::IoNumeric::Sint, - }, - ], - slot_words: 12, - }), - mesh_corners: Some(3), writes_point_size: true, flat_fragment_inputs: true, clip_distances: 2, @@ -1052,7 +1016,6 @@ mod bind_serde_round_trips { kept_imageblock_bytes: Some(4), depth_clamp_range: Some([0.25, 0.5]), rotated_weights: true, - mesh_last_first: true, line_band: Some(( crate::pipeline::BandPrimitive::Triangles, [8.0, -8.0, 1.75, -1.0], @@ -1126,7 +1089,6 @@ mod bind_serde_round_trips { kept_imageblock_bytes: Some(4), depth_clamp_range: true, rotated_weights: true, - mesh_last_first: true, line_band: Some(crate::pipeline::BandPrimitive::Lines), interlocked_colors: BTreeSet::from([0, 3]), fragment_tests: crate::bind::FragmentTests::Pass, @@ -1350,23 +1312,6 @@ mod bind_serde_round_trips { }], ], specialization: None, - // An emulated mesh draw's dispatch. - mesh_dispatch: Some(crate::bind::MeshDispatch { - work: vec![1, 0, 0, 2], - work_bytes: 112, - object_groups: Some([2, 1, 1]), - object_arguments: Some(crate::bind::BufferRange { - offset: 0, - range: 12, - }), - mesh: crate::bind::MeshGroups::Scanned { - arguments: Some(crate::bind::BufferRange { - offset: 64, - range: 16, - }), - }, - records: crate::bind::MeshRecordsRegion::Pool, - }), }); // A mesh draw's commands. round_trip(&vk::DrawCommand::DrawMeshTasks { diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index f5b9c24be..3d262386b 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -488,8 +488,7 @@ impl RuntimeDependency { /// maximum other than the function's or the required size's threads, and any of them above /// 1024, [`MeshPipelineProblem`](crate::error::MeshPipelineProblem)), held to this device's /// limit for the stage where that is lower: `maxTaskWorkGroupInvocations` and -/// `maxMeshWorkGroupInvocations` with `VK_EXT_mesh_shader`, and `maxComputeWorkGroupInvocations` -/// where the device runs both stages as compute work (`lower::mesh::emulates`). +/// `maxMeshWorkGroupInvocations`. #[non_exhaustive] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -508,8 +507,7 @@ pub struct MeshPipelineMetalInfo { pub mesh_thread_execution_width: u32, /// `maxTotalThreadgroupsPerMeshGrid`: the descriptor's maximum, else Metal's 2^20 (an object /// function's `[[max_total_threadgroups_per_mesh_grid(n)]]` changes neither), held to the - /// device's `maxMeshWorkGroupTotalCount` where it runs mesh functions natively and that is - /// lower. + /// device's `maxMeshWorkGroupTotalCount` where that is lower. pub max_total_threadgroups_per_mesh_grid: u32, } diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index be7a75f05..20d1122ee 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -3777,9 +3777,6 @@ fn stage_interface( io: plan.families.stage_io.interface.clone(), tessellation: crate::lower::tessellation::interface(plan), writes_memory, - mesh_records: crate::lower::mesh::records(&plan.families.mesh), - mesh_corners: (plan.families.mesh.mesh).map(crate::lower::mesh::MeshShape::per_primitive), - emulated_payload: crate::lower::mesh::emulated_payload(&plan.families.mesh), payload: plan.families.mesh.payload, reaches_command_buffers, command_writes, diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index ee3fb0626..9133a1a3c 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -54,7 +54,6 @@ use crate::pipeline::descriptor::{ use crate::pipeline::facts::RuntimeFact; use crate::pipeline::graphics::{GraphicsState, StorageAttachmentView}; use crate::pipeline::link::geometry; -use crate::pipeline::link::mesh::synthesized_stage as mesh_vertex_stage; use crate::pipeline::link::tessellation::{note_evaluation_stage, synthesized_stages}; use crate::pipeline::link::{link, LinkInputs, Linked, RenderLinkInputs}; use crate::pipeline::lower_inputs::LoweringInputs; @@ -551,10 +550,9 @@ impl Device { /// result is a [`RenderPipeline`] whose stages are the object stage (`TASK_EXT`), the mesh /// stage (`MESH_EXT`) and the fragment stage: it has no vertex input and no input assembly (its /// `GraphicsState::topology` is unused), and Metal's draws of it are `drawMeshThreadgroups` and - /// `drawMeshThreads`. On a device without `VK_EXT_mesh_shader` the mesh stage is a `COMPUTE` - /// module that writes records, followed by a synthesized `VERTEX` stage that draws them as a - /// list of the mesh's topology (`GraphicsState::mesh_records`). A `Compiled` stage must have - /// been compiled under the same inputs and Metal's call stack depth of 1. + /// `drawMeshThreads`. A device without `VK_EXT_mesh_shader` and `meshShader` (and `taskShader` + /// for an object function) refuses it (`Unsupported{MeshShading}`). A `Compiled` stage must + /// have been compiled under the same inputs and Metal's call stack depth of 1. pub fn compile_mesh_pipeline( &self, d: &MeshPipelineDescriptor, @@ -672,32 +670,7 @@ impl Device { { requirements = p.union_requirements(&requirements, &a.requirements); } - // An emulated mesh function's records are drawn by a synthesized vertex stage, which - // follows the mesh stage's compute module, the last compute module (an object - // function's comes first). - let records = linked - .graphics - .as_ref() - .and_then(|g| g.mesh_records.as_ref()); - let mut mesh_facts = Vec::new(); - if let Some(records) = records { - // Drawn from each primitive's last index first: Apple's last provoking vertex on a - // device that takes flat inputs from the first (`VariantKey::mesh_last_first`). - let last_first = v.mesh_last_first && records.corners > 1; - let (module, r) = mesh_vertex_stage(records, last_first, &linked, p, m)?; - if last_first { - let fact = RuntimeFact::MeshLastFirst; - mesh_facts.push(RuntimeDependency::new(fact, mechanism(&fact, p))); - } - requirements = p.union_requirements(&requirements, &r); - let at = stages - .iter() - .rposition(|s| s.stage == vk::ShaderStage::COMPUTE) - .ok_or_else(|| invariant("an emulated mesh pipeline without its compute stage"))?; - stages.insert(at + 1, module); - } - let mut dependencies = dependencies(&artifacts, self); - dependencies.extend(mesh_facts); + let dependencies = dependencies(&artifacts, self); let (graphics, requirements) = graphics_requirements(requirements, &linked, &artifacts, p)?; let profile = self.profile_fingerprint(); let mesh_info = self.mesh_info(d, object.as_ref(), &mesh); @@ -731,16 +704,11 @@ impl Device { ) -> MeshPipelineMetalInfo { let p = self.profile(); let limits = &p.fields().limits; - // Each stage's threadgroups run in the task and mesh stages, or as compute work. - let (object_limit, mesh_limit) = if crate::lower::mesh::emulates(p) { - let compute = limits.max_compute_work_group_invocations; - (compute, compute) - } else { - ( - limits.mesh.max_task_work_group_invocations, - limits.mesh.max_mesh_work_group_invocations, - ) - }; + // Each stage's threadgroups run in the task and mesh stages. + let (object_limit, mesh_limit) = ( + limits.mesh.max_task_work_group_invocations, + limits.mesh.max_mesh_work_group_invocations, + ); // Metal's on a first compile: the least of 1024, the function's own maximum, the // descriptor's (Metal's 0 is none) and the threads of the stage's required size (Metal's // all-zero size is none), within the device's. @@ -763,10 +731,7 @@ impl Device { .max_total_threadgroups_per_mesh_grid .filter(|&n| n > 0) .unwrap_or(METAL_MESH_GRID_THREADGROUPS); - let grid = match crate::lower::mesh::emulates(p) { - true => grid, - false => grid.min(limits.mesh.max_mesh_work_group_total_count), - }; + let grid = grid.min(limits.mesh.max_mesh_work_group_total_count); MeshPipelineMetalInfo { max_total_threads_per_object_threadgroup: object.map_or(0, |o| { threads( @@ -1773,18 +1738,13 @@ fn compute_fields(d: &ComputePipelineDescriptor) -> String { /// The pipeline key's fields of variant `v` past its stages' keys: its color group past the first /// (`VariantKey::color_group`), whose variant of a pipeline without a fragment function has no -/// stage of its own, its emulated mesh function's synthesized vertex stage, and a band variant's -/// synthesized tessellation stages. Empty for every other variant, so a pipeline keeps its key. +/// stage of its own, and a band variant's synthesized tessellation stages. Empty for every other variant, so a pipeline keeps its key. fn variant_fields(v: &VariantKey) -> String { let mut fields = String::new(); // The group a pipeline without a fragment function keeps in no stage's key. if v.color_group != 0 { fields.push_str(&format!(" color_group {}", v.color_group)); } - // The synthesized vertex stage of an emulated mesh function's pipeline, in no stage's key. - if v.mesh_last_first { - fields.push_str(" mesh_last_first"); - } // The band's synthesized stages, in no stage's key. match v.line_band { None => {} diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 402bc94d8..75ecf8fa8 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -482,10 +482,6 @@ pub enum RuntimeFact { /// weights back from a triangle drawn with Metal's last vertex first. Its plans state the /// variant the shape asks for (`BindShape::rotated_weights`). RotatedWeights, - /// The emulated mesh function's pipeline was compiled under `VariantKey::mesh_last_first`: - /// its synthesized vertex stage draws each line or triangle from its last index first. Its - /// plans state the variant the shape asks for (`BindShape::mesh_last_first`). - MeshLastFirst, /// The function reads, samples, gathers, or fetches through a sampler the color texture /// bound to the slot, on a profile whose sparse textures are sparse images (it enables /// `shaderResourceResidency`): where that texture is sparse, a block of it that holds no @@ -956,7 +952,6 @@ impl RuntimeFact { RuntimeFact::DroppedColor { .. } => "DroppedColor", RuntimeFact::DepthClampRange => "DepthClampRange", RuntimeFact::RotatedWeights => "RotatedWeights", - RuntimeFact::MeshLastFirst => "MeshLastFirst", RuntimeFact::ConstantLanes { .. } => "ConstantLanes", RuntimeFact::FunctionTableRange { .. } => "FunctionTableRange", RuntimeFact::TestedStorageWrites { .. } => "TestedStorageWrites", diff --git a/crates/metal2vulkan/src/pipeline/graphics.rs b/crates/metal2vulkan/src/pipeline/graphics.rs index cfb58892f..f859b01df 100644 --- a/crates/metal2vulkan/src/pipeline/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/graphics.rs @@ -14,7 +14,7 @@ use crate::error::{ Attachment, Capability, Error, Feature, InternalError, InternalKind, Unsupported, }; use crate::metal; -use crate::pipeline::interface::{MeshRecords, PatchDomain}; +use crate::pipeline::interface::PatchDomain; use crate::pipeline::sym::SampledType; use crate::vk; @@ -153,18 +153,6 @@ pub struct GraphicsState { /// [`Limits::early_fragment_multisample_coverage_after_sample_counting`](crate::device::Limits::early_fragment_multisample_coverage_after_sample_counting)). #[cfg_attr(feature = "serde", serde(default))] pub writes_sample_mask: bool, - /// A mesh render pipeline on a device without `VK_EXT_mesh_shader`: its mesh function is - /// the pipeline's `COMPUTE` module, which writes these records, and a synthesized `VERTEX` - /// module draws them as a list of [`MeshRecords::topology`](MeshRecords::topology) - /// (the binder's `DrawCommands::mesh_dispatch` states the consumer contract). `None` for - /// every other pipeline. - #[cfg_attr(feature = "serde", serde(default))] - pub mesh_records: Option, - /// A mesh render pipeline's primitive, its mesh function's: its indices, 1 (points), 2 - /// (lines) or 3 (triangles), whether the device draws the mesh or - /// [`mesh_records`](Self::mesh_records) does. `None` for every other pipeline. - #[cfg_attr(feature = "serde", serde(default))] - pub mesh_corners: Option, /// A render pipeline variant that draws its lines as bands of triangles /// (`VariantKey::line_band`, `pipeline::link::band`): its `topology` is `PATCH_LIST` (never /// dynamic), its stages the vertex stage, the band's synthesized tessellation control and @@ -544,8 +532,6 @@ impl GraphicsState { shadow_stencil: None, early_fragment_tests: false, writes_sample_mask: false, - mesh_records: None, - mesh_corners: None, line_band: None, region_fan_out: None, writes_point_size: false, diff --git a/crates/metal2vulkan/src/pipeline/interface.rs b/crates/metal2vulkan/src/pipeline/interface.rs index 22e959570..77b490c80 100644 --- a/crates/metal2vulkan/src/pipeline/interface.rs +++ b/crates/metal2vulkan/src/pipeline/interface.rs @@ -355,22 +355,6 @@ pub struct StageInterface { /// Metal's color attachment write. #[cfg_attr(feature = "serde", serde(default))] pub writes_memory: bool, - /// A mesh function compiled for a device without `VK_EXT_mesh_shader`: the module is a - /// `GLCompute` entry that writes its threadgroups' vertices and primitives as these records, - /// which the pipeline's synthesized vertex stage draws. - #[cfg_attr(feature = "serde", serde(default))] - pub mesh_records: Option, - /// A mesh function's primitive: its indices, 1 (points), 2 (lines) or 3 (triangles), on - /// every device, whether the device draws the mesh or the function writes records. `None` - /// for any other function. - #[cfg_attr(feature = "serde", serde(default))] - pub mesh_corners: Option, - /// An object or mesh function compiled for a device without `VK_EXT_mesh_shader` (a - /// `GLCompute` entry): its payload's words (0 without a payload), which its object - /// threadgroup's slot of the draw's work buffer holds (`MeshRecords::slot_words`). `None` - /// for any other function. - #[cfg_attr(feature = "serde", serde(default))] - pub emulated_payload: Option, /// An object or mesh function's payload arena's bytes (`memory::arena::payload_bytes` of its /// `[[payload]]` parameter's `air.arg_type_size`, a mesh function's at least /// `LoweringInputs::object_payload`), which its accesses of the payload read and write; `None` @@ -740,101 +724,6 @@ impl SampledLevels { impl LevelReads {} -/// An emulated mesh function's records: what each of its threadgroups writes to the draw's records -/// buffer (`SyntheticBinding::MeshRecords`), all of it words. -/// -/// Mesh threadgroup `w`, its number among the draw's mesh threadgroups (object threadgroup by -/// object threadgroup, each one's grid x fastest), owns [`MeshRecords::group_words`] words from -/// the draw's first word plus `w · group_words()`: its primitive count, then `vertices` vertex -/// records of `vertex_words` words each, then `primitives` primitive records of -/// `primitive_words` words each, every primitive record beginning with the primitive's -/// `corners` indices. Each field sits at its offset in its record, one word per lane. A -/// threadgroup zeroes its words before its body runs, so an index, a culled flag, or a render -/// target slice or viewport index the function does not write reads 0, as Metal's does. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct MeshRecords { - /// The mesh type's `NV`. - pub vertices: u32, - /// The mesh type's `NP`. - pub primitives: u32, - /// The indices of one primitive: 1 (points), 2 (lines) or 3 (triangles). - pub corners: u32, - pub vertex_words: u32, - pub primitive_words: u32, - /// Every field, in record order: the vertex record's, then the primitive record's. - pub fields: Vec, - /// The words of an object threadgroup's slot in the draw's work buffer: its grid's three - /// counts and a zero, then the larger payload of the pipeline's object and mesh functions - /// (in a function's own interface, its own payload). - pub slot_words: u32, -} - -impl MeshRecords { - /// The words of one threadgroup's records: its count, its vertex records and its primitive - /// records. - pub fn group_words(&self) -> u64 { - 1 + u64::from(self.vertices) * u64::from(self.vertex_words) - + u64::from(self.primitives) * u64::from(self.primitive_words) - } - - /// The word of a threadgroup's records where its primitive records begin. - pub fn primitive_base(&self) -> u64 { - 1 + u64::from(self.vertices) * u64::from(self.vertex_words) - } - - /// The Vulkan list topology of the records' primitives. - pub fn topology(&self) -> vk::PrimitiveTopology { - match self.corners { - 1 => vk::PrimitiveTopology::POINT_LIST, - 2 => vk::PrimitiveTopology::LINE_LIST, - _ => vk::PrimitiveTopology::TRIANGLE_LIST, - } - } -} - -/// One field of a vertex or primitive record ([`MeshRecords`]). -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct RecordField { - pub value: RecordValue, - /// In the primitive record, else in the vertex record. - pub per_primitive: bool, - /// Its first word in its record. - pub offset: u32, - /// Its words: its lanes, or the length of the clip distances. - pub words: u32, - /// What each word holds: a `float`'s bits, a `uint`, or an `int`'s bits (a `bool` is a - /// `uint`, 0 or 1). - pub numeric: crate::pipeline::stage_io::IoNumeric, -} - -/// What a [`RecordField`] holds. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum RecordValue { - /// `[[position]]`. - Position, - /// `[[point_size]]`. - PointSize, - /// `[[clip_distance]]`. - ClipDistance, - /// `[[primitive_culled]]`, 1 where set. - Culled, - /// The primitive's render target slice (`Layer`): its `[[render_target_array_index]]` where - /// that lies below the pass's length, else 0. - Layer, - /// The primitive's viewport (`ViewportIndex`): its `[[viewport_array_index]]` where that lies - /// below the draw's viewport count, else 0. - ViewportIndex, - /// A user varying: vertex data, primitive data, or a raw index (the link numbers its - /// location by key). - Varying(crate::pipeline::sym::VaryingKey), -} - /// What a tessellation evaluation module (a post-tessellation vertex function) needs of the /// pipeline's control stage: its patch domain and Metal's control points per patch. It reads the /// patch index and the instance as `uint` patch inputs at @@ -882,13 +771,11 @@ pub enum PatchDomain { impl StageInterface { /// The Vulkan stage of the module: the evaluation stage for a post-tessellation vertex - /// function, the compute stage for an emulated object or mesh function, else the Metal - /// stage's. + /// function, else the Metal stage's. pub fn vk_stage(&self) -> vk::ShaderStage { - match (self.tessellation, self.emulated_payload) { - (Some(_), _) => vk::ShaderStage::TESSELLATION_EVALUATION, - (None, Some(_)) => vk::ShaderStage::COMPUTE, - (None, None) => crate::device::derive::vk_stage(self.stage), + match self.tessellation { + Some(_) => vk::ShaderStage::TESSELLATION_EVALUATION, + None => crate::device::derive::vk_stage(self.stage), } } diff --git a/crates/metal2vulkan/src/pipeline/link.rs b/crates/metal2vulkan/src/pipeline/link.rs index d2caa9c34..e74469a2c 100644 --- a/crates/metal2vulkan/src/pipeline/link.rs +++ b/crates/metal2vulkan/src/pipeline/link.rs @@ -46,9 +46,7 @@ //! record, with the measured properties a conversion relies on in place of a note. A mesh //! render pipeline has an object stage when it has an object function, its mesh stage, and a //! fragment stage exactly when it rasterizes; its `GraphicsState` is a render pipeline's with the -//! mesh stage in the vertex stage's place, and it has no vertex input. An emulated mesh -//! function's pipeline ([`mesh`]) adds a synthesized vertex stage, which reads the mesh -//! function's records binding too (its stage flags are both stages'). +//! mesh stage in the vertex stage's place, and it has no vertex input. pub mod band; pub mod contract; @@ -425,28 +423,18 @@ pub fn link( }, _ => None, }; - // A mesh function reads its payload within its object function's. An emulated mesh - // function's pipeline draws through a synthesized vertex stage, which reads the records the - // mesh stage writes. - let records = match inputs { - LinkInputs::Mesh(_) => { - mesh::payload(&ifaces)?; - mesh::records(&ifaces)? - } - _ => None, - }; + // A mesh function reads its payload within its object function's. + if let LinkInputs::Mesh(_) = inputs { + mesh::payload(&ifaces)?; + } let mut table = LinkTable::default(); - let mut synthesized: Vec<(ResourceSlot, vk::ShaderStageFlags)> = plan + let synthesized: Vec<(ResourceSlot, vk::ShaderStageFlags)> = plan .as_ref() .map(tessellation::ControlPlan::slots) .unwrap_or_default() .into_iter() .map(|slot| (slot, vk::ShaderStageFlags::TESSELLATION_CONTROL)) .collect(); - if records.is_some() { - synthesized.push((mesh::RECORDS_SLOT, vk::ShaderStageFlags::VERTEX)); - synthesized.push((mesh::WORK_SLOT, vk::ShaderStageFlags::VERTEX)); - } // A fan-out variant's triangle stage reads the region table, and a probe's writes its flags. if let Some(fan) = geometry.as_ref().and_then(|g| g.fan_out) { let stage = vk::ShaderStageFlags::GEOMETRY; @@ -583,13 +571,7 @@ pub fn link( .ok_or_else(|| missing_stage(Stage::Mesh))?; let vi = VertexInputState::default(); let fragment = stages.get(at + 1).copied(); - let mut gs = render_state(r, ifaces[at], fragment, &vi, None, p)?; - gs.mesh_corners = ifaces[at].mesh_corners; - // An emulated mesh function's primitives are drawn as a list of their kind. - if let Some(records) = records { - gs.topology = records.topology(); - gs.mesh_records = Some(records); - } + let gs = render_state(r, ifaces[at], fragment, &vi, None, p)?; (vi, Some(gs)) } LinkInputs::Standalone | LinkInputs::Compute => (VertexInputState::default(), None), @@ -1009,8 +991,7 @@ struct HeapDecl { /// Number every binding symbol densely in set 0 and every heap array in set 1, build the layout, /// and check the pipeline-wide limits. `synthesized` are the storage buffers the pipeline's -/// synthesized stages read, with those stages: a tessellation pipeline's control-stage buffers, and -/// an emulated mesh function's records, which its vertex stage reads too. +/// synthesized stages read, with those stages: a tessellation pipeline's control-stage buffers. fn layout( ifaces: &[&StageInterface], synthesized: &[(ResourceSlot, vk::ShaderStageFlags)], @@ -1020,7 +1001,7 @@ fn layout( let mut decls: BTreeMap = BTreeMap::new(); // A tessellation pipeline's factor, patch index, and control-point index buffers are the - // control stage's; an emulated mesh function's records are its synthesized vertex stage's too. + // control stage's. for &(slot, stages) in synthesized { let d = StageDescriptor::new(slot, vk::DescriptorType::STORAGE_BUFFER, 1); decls.insert(d.slot, (d, stages)); @@ -1133,25 +1114,11 @@ fn layout( ), ))); } - let stages = i.vk_stage().flags(); - // An emulated mesh pipeline's object and mesh functions are both compute entries: - // Vulkan admits one range per stage, so theirs is the hull of their disjoint windows. - match push_constants - .iter_mut() - .find(|r: &&mut PushConstantRange| r.stages == stages) - { - Some(r) => { - let start = r.offset.min(offset); - let end = (r.offset + r.size).max(offset + size); - r.offset = start; - r.size = end - start; - } - None => push_constants.push(PushConstantRange { - stages, - offset, - size, - }), - } + push_constants.push(PushConstantRange { + stages: i.vk_stage().flags(), + offset, + size, + }); } } let mut sets = vec![DescriptorSetLayout { diff --git a/crates/metal2vulkan/src/pipeline/link/contract.rs b/crates/metal2vulkan/src/pipeline/link/contract.rs index bb8fc459b..7dc36e2d0 100644 --- a/crates/metal2vulkan/src/pipeline/link/contract.rs +++ b/crates/metal2vulkan/src/pipeline/link/contract.rs @@ -5,8 +5,8 @@ //! and data type declare, and every specialization constant its size and default. The module's //! user interface variables must be exactly the ones its stage-IO interface ([`StageIo`]) lists, in //! the listed direction and with the listed type (`StageIo::declared_type`: an extended-range color -//! output's is the raw texel's), so link numbers every `Location` key from that one contract; an -//! emulated mesh function's outputs are records instead. Nothing here reads a name. +//! output's is the raw texel's), so link numbers every `Location` key from that one contract. +//! Nothing here reads a name. use std::collections::BTreeMap; @@ -73,23 +73,11 @@ pub fn stage_symbols(m: &TypedModule, io: &StageIo) -> Result {} } } - // A compute entry's listed outputs are an emulated mesh function's: it writes them to its - // records binding and declares no interface variable for them. - let records = m.entry().model == ExecModel::GLCompute && !outputs.is_empty(); - let listed = inputs.len() + if records { 0 } else { outputs.len() }; - if declared != listed { + if declared != inputs.len() + outputs.len() { return Err(invariant( "an interface variable the module does not declare", )); } - if records - && !out - .descriptors - .iter() - .any(|d| d.slot == crate::lower::mesh::RECORDS_SLOT) - { - return Err(invariant("a compute entry's outputs without its records")); - } for d in m.decls() { if let Decl::Const(c) = d { let def = m.consts().get(*c)?; diff --git a/crates/metal2vulkan/src/pipeline/link/graphics.rs b/crates/metal2vulkan/src/pipeline/link/graphics.rs index fa64b8cad..265602379 100644 --- a/crates/metal2vulkan/src/pipeline/link/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/link/graphics.rs @@ -799,9 +799,6 @@ pub fn graphics_state( early_fragment_tests: fs.is_some_and(|fs| fs.io.early_fragment_tests), writes_sample_mask: fs .is_some_and(|fs| fs.io.builtins.contains(&StageBuiltin::SampleMaskOut)), - // An emulated mesh function's pipeline states its records (`link`). - mesh_records: None, - mesh_corners: None, // A band variant's pipeline states its band (`link`). line_band: None, // A fan-out variant's pipeline states its fan-out (`link`). diff --git a/crates/metal2vulkan/src/pipeline/link/mesh.rs b/crates/metal2vulkan/src/pipeline/link/mesh.rs index 02a2942aa..2e1502ae6 100644 --- a/crates/metal2vulkan/src/pipeline/link/mesh.rs +++ b/crates/metal2vulkan/src/pipeline/link/mesh.rs @@ -1,68 +1,8 @@ -//! The synthesized vertex stage of an emulated mesh function's pipeline. -//! -//! On a device without `VK_EXT_mesh_shader` a mesh function is a compute entry that writes each -//! of its threadgroups' vertices and primitives to the draw's records -//! ([`MeshRecords`], `SyntheticBinding::MeshRecords`; `lower::mesh` writes them). The pipeline -//! draws them through a vertex stage link adds after the mesh stage ([`vertex_module`]): the -//! draw is a non-indexed draw of `T · NP · k` vertices (`T` the draw's mesh threadgroups, `NP` -//! the mesh type's primitives, `k` a primitive's indices) as a list of the mesh's topology -//! ([`MeshRecords::topology`]), and vertex `v` is corner `c` of slot `s` of threadgroup `g` -//! (`v = (g · NP + s) · k + c`), whose records begin at the draw's first word (word -//! `RECORDS_BASE` of its work buffer, `SyntheticBinding::MeshWork`) plus `g` threadgroups' -//! words. It reads the slot's primitive record and the record of the vertex the corner's index -//! names, and writes: -//! -//! - `Position` from the vertex's position, and `PointSize` (a point mesh's, or a mesh's that -//! writes it) from its point size, 1.0 where it writes none; -//! - `ClipDistance` from its clip distances, and `Layer` and `ViewportIndex` from the -//! primitive's; -//! - each user varying from its record, the vertex's or, for primitive data and the raw indices, -//! the primitive's at every corner: the fragment function reads those flat -//! (`StageIoPlan::flat_primitive_inputs`), so whichever corner provokes, the primitive's value -//! is read. -//! -//! A slot at or past the threadgroup's count, a slot whose primitive is culled, and a slot with -//! an index at or past `NV` draw nothing: every corner lies at [`FAR`], wholly outside the clip -//! volume, and reads vertex 0's record instead (Vulkan defines no index past the mesh's vertices -//! either). Vulkan's primitive order for the draw is the vertices' order: threadgroup by -//! threadgroup in their linear order, slot by slot, which is the order Metal draws a mesh draw's -//! primitives in. -//! -//! Under `VariantKey::mesh_last_first` (a draw under Apple's last provoking vertex on a device -//! that takes flat inputs from the first) vertex `v` reads corner `(c + k - 1) mod k` instead: -//! each primitive is drawn from Metal's last index first, a triangle `(i0, i1, i2)` as -//! `(i2, i0, i1)`, which keeps its winding, and a line `(i0, i1)` as `(i1, i0)`, so its flat -//! inputs are its last vertex's, as Metal's are at mode 1 (Metal probe: a mesh triangle's flat -//! input from its last index). -//! -//! The records do not hold the primitive id: a fragment function that reads `[[primitive_id]]` -//! behind an emulated mesh function is not implemented ([`records`]), since the vertex stage's -//! primitives are counted across the draw. +//! A mesh render pipeline's link check: its mesh function's payload holds its object function's. -use crate::budget::Meter; -use crate::device::requirements::Requirements; -use crate::device::DeviceProfile; -use crate::error::{Error, Feature, InternalError, InternalKind, RuntimeInput, Unsupported}; -pub use crate::lower::mesh::{RECORDS_SLOT, WORK_SLOT}; -use crate::pipeline::artifact::{Reconvergence, SpecializationLayout, StageModule, StrategyCensus}; -use crate::pipeline::interface::{MeshRecords, RecordField, RecordValue, StageInterface}; -use crate::pipeline::stage_io::{IoNumeric, StageBuiltin}; +use crate::error::{Error, RuntimeInput}; +use crate::pipeline::interface::StageInterface; use crate::pipeline::sym::Stage; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, TypeId, Value}; -use crate::spirv::ir::{ - natural_layout, BinOp, ConstBits, Constant, ConvOp, ExecModel, IoDecor, IoDir, LayoutRule, - MemAccess, StorageClass, Type, TypedModule, -}; -use crate::spirv::serialize::{SymbolTable, ENTRY_NAME}; -use crate::spv::BuiltIn as B; -use crate::vk; - -/// Where a corner that draws nothing lies, in clip coordinates of `w` 1: `x` and `y` this far -/// past the clip volume, so every primitive of such corners lies wholly outside it, a point or a -/// wide line included. -pub const FAR: f32 = 65536.0; /// The payload check of the mesh render pipeline of stages `ifaces`: its mesh function's payload /// arena holds at least its object function's (`StageInterface::payload`, @@ -81,318 +21,3 @@ pub fn payload(ifaces: &[&StageInterface]) -> Result<(), Error> { _ => Ok(()), } } - -/// The records of the mesh render pipeline of stages `ifaces` whose mesh function is emulated -/// (`StageInterface::mesh_records`); `None` where its mesh function is not. A fragment function -/// that reads `[[primitive_id]]` behind an emulated mesh function is -/// `NotImplemented(MeshShading)` (the module docs). -pub fn records(ifaces: &[&StageInterface]) -> Result, Error> { - let Some(r) = ifaces.iter().find_map(|i| i.mesh_records.as_ref()) else { - return Ok(None); - }; - let reads_id = ifaces.iter().any(|i| { - i.stage == Stage::Fragment - && (i.io.builtins.contains(&StageBuiltin::PrimitiveId) - || i.io - .inputs - .iter() - .any(|v| v.role == crate::pipeline::stage_io::IoRole::PrimitiveId)) - }); - if reads_id { - return Err(Unsupported::not_implemented(Feature::MeshShading).into()); - } - // An object threadgroup's slot holds the larger of the object and mesh functions' payloads - // (Metal links payloads of different sizes). - let payload = ifaces - .iter() - .filter_map(|i| i.emulated_payload) - .max() - .unwrap_or(0); - let slot_words = crate::lower::mesh::work::GRID - .checked_add(payload) - .ok_or_else(|| { - Error::Internal(InternalError::new( - InternalKind::Invariant, - "mesh records: a payload past the slot's word range".to_owned(), - )) - })?; - Ok(Some(MeshRecords { - slot_words, - ..r.clone() - })) -} - -/// The synthesized vertex stage of records `r`, each primitive drawn from its last index first -/// where `last_first`, as a final module under link table `table`, with its module's -/// requirements: verified by the owned verifier, serialized, and relocated, as a compiled -/// function's module is. -pub fn synthesized_stage( - r: &MeshRecords, - last_first: bool, - table: &impl SymbolTable, - p: &DeviceProfile, - m: &mut Meter, -) -> Result<(StageModule, Requirements), Error> { - let module = vertex_module(r, last_first)?; - let stats = crate::spirv::verify::verify(&module, p, m)?; - let module = crate::spirv::serialize::serialize(module)?; - let words = crate::spirv::serialize::relocate(&module, table)?; - Ok(( - StageModule { - stage: vk::ShaderStage::VERTEX, - entry_point: ENTRY_NAME.to_owned(), - spirv: words.into(), - specialization: SpecializationLayout::default(), - required_subgroup_size: None, - stage_flags: vk::PipelineShaderStageCreateFlags::empty(), - reconvergence: Reconvergence::Guaranteed, - precision_notes: Vec::new(), - strategies: StrategyCensus::default(), - constant_blob: None, - rounded_colors: Vec::new(), - specialized_notes: Vec::new(), - own_pixel_textures: Vec::new(), - snapshot_textures: Vec::new(), - snapshot_refusals: Vec::new(), - level_reads: Vec::new(), - private_bytes: 0, - stats, - }, - module.requirements, - )) -} - -fn ku(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult { - let c = fb.u32_const(v)?; - fb.module().const_value(c) -} - -fn kf(fb: &mut FunctionBuilder<'_>, v: f32) -> BResult { - let ty = fb.module().ty(Type::Float { width: 32 })?; - let c = fb.module().constant(Constant::Scalar { - ty, - bits: ConstBits(u64::from(v.to_bits())), - })?; - fb.module().const_value(c) -} - -/// Word `at` of the records. -fn word(fb: &mut FunctionBuilder<'_>, records: GlobalId, at: Value) -> BResult { - let zero = ku(fb, 0)?; - let base = fb.module().global_value(records)?; - let ptr = fb.access_chain(base, &[zero, at])?; - fb.load(ptr, MemAccess::default()) -} - -/// The scalar type of `numeric`. -fn scalar(mb: &mut ModuleBuilder, numeric: IoNumeric) -> BResult { - match numeric { - IoNumeric::Float => mb.ty(Type::Float { width: 32 }), - IoNumeric::Sint => mb.ty(Type::Int { - width: 32, - signed: true, - }), - IoNumeric::Uint => mb.ty(Type::Int { - width: 32, - signed: false, - }), - } -} - -/// The lanes of field `f` of the record at word `record`, each of its numeric type. -fn lanes( - fb: &mut FunctionBuilder<'_>, - records: GlobalId, - record: Value, - f: &RecordField, -) -> BResult> { - let ty = scalar(fb.module(), f.numeric)?; - let mut out = Vec::with_capacity(f.words as usize); - for j in 0..f.words { - let off = ku(fb, f.offset + j)?; - let at = fb.binary(BinOp::IAdd, record, off)?; - let w = word(fb, records, at)?; - out.push(match f.numeric { - IoNumeric::Uint => w, - IoNumeric::Float | IoNumeric::Sint => fb.convert(ConvOp::Bitcast, w, ty)?, - }); - } - Ok(out) -} - -/// What one field becomes: the output it is stored to and that output's type. -struct Out<'r> { - field: &'r RecordField, - global: GlobalId, - ty: TypeId, -} - -/// The synthesized vertex stage of records `r`, each primitive drawn from its last index first -/// where `last_first` (the module docs). -pub fn vertex_module(r: &MeshRecords, last_first: bool) -> BResult { - let mut mb = ModuleBuilder::new(); - let u32_ = scalar(&mut mb, IoNumeric::Uint)?; - let f32_ = scalar(&mut mb, IoNumeric::Float)?; - let vec4 = mb.ty(Type::Vector { elem: f32_, len: 4 })?; - let void = mb.ty(Type::Void)?; - let words = mb.ty(Type::RuntimeArray { - elem: u32_, - stride: Some(4), - })?; - let layout = natural_layout(mb.types(), LayoutRule::Std430, true, &[words])?; - let block = mb.ty(Type::Struct { - members: [words].into(), - layout: Some(layout), - })?; - let records = mb.resource(RECORDS_SLOT, StorageClass::StorageBuffer, block)?; - let work = mb.resource(WORK_SLOT, StorageClass::StorageBuffer, block)?; - let vertex_index = mb.builtin(B::VertexIndex, IoDir::Input, u32_)?; - let position = mb.builtin(B::Position, IoDir::Output, vec4)?; - let find = |value: RecordValue| r.fields.iter().find(|f| f.value == value); - let position_field = find(RecordValue::Position); - let culled_field = find(RecordValue::Culled); - let size_field = find(RecordValue::PointSize); - // A point list needs its point sizes; a mesh that writes them has them in any topology. - let point_size = if r.corners == 1 || size_field.is_some() { - Some(mb.builtin(B::PointSize, IoDir::Output, f32_)?) - } else { - None - }; - let mut outs = Vec::new(); - for f in &r.fields { - let (global, ty) = match &f.value { - RecordValue::Position | RecordValue::PointSize | RecordValue::Culled => continue, - RecordValue::ClipDistance => { - let len = mb.constant(Constant::Scalar { - ty: u32_, - bits: ConstBits(u64::from(f.words)), - })?; - let ty = mb.ty(Type::Array { - elem: f32_, - len, - stride: None, - })?; - (mb.builtin(B::ClipDistance, IoDir::Output, ty)?, ty) - } - RecordValue::Layer => (mb.builtin(B::Layer, IoDir::Output, u32_)?, u32_), - RecordValue::ViewportIndex => { - (mb.builtin(B::ViewportIndex, IoDir::Output, u32_)?, u32_) - } - RecordValue::Varying(key) => { - let elem = scalar(&mut mb, f.numeric)?; - let ty = match f.words { - 1 => elem, - n => mb.ty(Type::Vector { elem, len: n as u8 })?, - }; - ( - mb.io(key.clone(), IoDir::Output, ty, IoDecor::default())?, - ty, - ) - } - }; - outs.push(Out { - field: f, - global, - ty, - }); - } - let mut fb = mb.function(void)?; - let p = fb.module().global_value(vertex_index)?; - let v = fb.load(p, MemAccess::default())?; - // `v = (g · NP + s) · k + c`. - let per_group = ku(&mut fb, r.primitives.saturating_mul(r.corners))?; - let k = ku(&mut fb, r.corners)?; - let g = fb.binary(BinOp::UDiv, v, per_group)?; - let rem = fb.binary(BinOp::UMod, v, per_group)?; - let slot = fb.binary(BinOp::UDiv, rem, k)?; - let mut corner = fb.binary(BinOp::UMod, rem, k)?; - // Drawn from the last index first: corner `(c + k - 1) mod k`. - if last_first && r.corners > 1 { - let back = ku(&mut fb, r.corners - 1)?; - let moved = fb.binary(BinOp::IAdd, corner, back)?; - corner = fb.binary(BinOp::UMod, moved, k)?; - } - // The threadgroup's records, from the draw's first word: within a `u32`, since the binder - // binds them whole. - let at = ku(&mut fb, crate::lower::mesh::work::RECORDS_BASE)?; - let base = word(&mut fb, work, at)?; - let group_words = ku(&mut fb, r.group_words() as u32)?; - let mine = fb.binary(BinOp::IMul, g, group_words)?; - let first = fb.binary(BinOp::IAdd, base, mine)?; - let count = word(&mut fb, records, first)?; - let primitive_base = ku(&mut fb, r.primitive_base() as u32)?; - let stride = ku(&mut fb, r.primitive_words)?; - let into = fb.binary(BinOp::IMul, slot, stride)?; - let primitives = fb.binary(BinOp::IAdd, first, primitive_base)?; - let primitive = fb.binary(BinOp::IAdd, primitives, into)?; - let at = fb.binary(BinOp::IAdd, primitive, corner)?; - let index = word(&mut fb, records, at)?; - let below = fb.binary(BinOp::ULessThan, slot, count)?; - let nv = ku(&mut fb, r.vertices)?; - let named = fb.binary(BinOp::ULessThan, index, nv)?; - let mut drawn = fb.binary(BinOp::LogicalAnd, below, named)?; - if let Some(f) = culled_field { - let off = ku(&mut fb, f.offset)?; - let at = fb.binary(BinOp::IAdd, primitive, off)?; - let culled = word(&mut fb, records, at)?; - let zero = ku(&mut fb, 0)?; - let kept = fb.binary(BinOp::IEqual, culled, zero)?; - drawn = fb.binary(BinOp::LogicalAnd, drawn, kept)?; - } - let zero = ku(&mut fb, 0)?; - let index = fb.select(drawn, index, zero)?; - let one = ku(&mut fb, 1)?; - let vertex_stride = ku(&mut fb, r.vertex_words)?; - let into = fb.binary(BinOp::IMul, index, vertex_stride)?; - let vertices = fb.binary(BinOp::IAdd, first, one)?; - let vertex = fb.binary(BinOp::IAdd, vertices, into)?; - // The position, or `FAR` where the corner draws nothing. - let written = match position_field { - Some(f) => lanes(&mut fb, records, vertex, f)?, - None => vec![ - kf(&mut fb, 0.0)?, - kf(&mut fb, 0.0)?, - kf(&mut fb, 0.0)?, - kf(&mut fb, 1.0)?, - ], - }; - let far = [FAR, FAR, 0.0, 1.0]; - let mut xyzw = Vec::with_capacity(4); - for (lane, away) in written.into_iter().zip(far) { - let away = kf(&mut fb, away)?; - xyzw.push(fb.select(drawn, lane, away)?); - } - let value = fb.composite_construct(vec4, &xyzw)?; - let p = fb.module().global_value(position)?; - fb.store(p, value, MemAccess::default())?; - if let Some(g) = point_size { - let written = match size_field { - Some(f) => lanes(&mut fb, records, vertex, f)?, - None => Vec::new(), - }; - let size = match written.first() { - Some(&size) => size, - None => kf(&mut fb, 1.0)?, - }; - let p = fb.module().global_value(g)?; - fb.store(p, size, MemAccess::default())?; - } - for o in &outs { - let record = if o.field.per_primitive { - primitive - } else { - vertex - }; - let parts = lanes(&mut fb, records, record, o.field)?; - let value = match parts.as_slice() { - [one] if !matches!(o.field.value, RecordValue::ClipDistance) => *one, - _ => fb.composite_construct(o.ty, &parts)?, - }; - let p = fb.module().global_value(o.global)?; - fb.store(p, value, MemAccess::default())?; - } - fb.ret(None)?; - let f = fb.finish()?; - mb.entry(ExecModel::Vertex, f, Vec::new())?; - mb.finalize() -} diff --git a/crates/metal2vulkan/src/pipeline/link/tests.rs b/crates/metal2vulkan/src/pipeline/link/tests.rs index ebe3fcea3..34f556ad1 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests.rs @@ -129,9 +129,6 @@ pub(super) fn iface( io: positioned(stage, StageIo::default()), tessellation: None, writes_memory: false, - mesh_records: None, - mesh_corners: None, - emulated_payload: None, payload: None, reaches_command_buffers: false, command_writes: Default::default(), diff --git a/crates/metal2vulkan/src/pipeline/link/tests/geometry.rs b/crates/metal2vulkan/src/pipeline/link/tests/geometry.rs index 57db37de4..3be4e9799 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests/geometry.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests/geometry.rs @@ -359,7 +359,7 @@ fn a_selected_slice_and_viewport_take_the_stages() { /// `LayeredRendering`: a post-tessellation vertex function and a vertex function's own /// `ViewportIndex` beside a selected slice as not implemented, and a selected viewport drawn as /// multiview without `multiviewGeometryShader` as needing the output instead. A selected slice is -/// never drawn as multiview, and an emulated mesh pipeline's indices take no stage. +/// never drawn as multiview. #[test] fn what_the_stages_cannot_carry_for_an_index_is_refused() { let p = profile("lavapipe"); diff --git a/crates/metal2vulkan/src/pipeline/link/varyings.rs b/crates/metal2vulkan/src/pipeline/link/varyings.rs index 4cd2a96e5..4018b707d 100644 --- a/crates/metal2vulkan/src/pipeline/link/varyings.rs +++ b/crates/metal2vulkan/src/pipeline/link/varyings.rs @@ -23,8 +23,8 @@ //! (`LoweringInputs::window_depth_varying`), and one linked with another vertex function is //! `NeedsInput(FramebufferFetch)`. //! The primitive ID (`IoRole::PrimitiveId`) is such a varying, read flat: a fragment function -//! compiled for a device that cannot declare a fragment `PrimitiveId`, or for an emulated -//! post-tessellation vertex function, reads its `[[primitive_id]]` from it, and its pipeline's +//! compiled for a device that cannot declare a fragment `PrimitiveId` reads its +//! `[[primitive_id]]` from it, and its pipeline's //! vertex function writes it, compiled under `LoweringInputs::primitive_id_varying` //! (`NeedsInput(PrimitiveId)` otherwise, and for a fragment function that reads Vulkan's //! `PrimitiveId` behind a vertex function that writes the varying). A mesh function writes none, @@ -36,9 +36,7 @@ //! every vertex output's, below `maxFragmentInputComponents / 4`, and is never packed. A //! fragment function alone numbers them with its other inputs. //! - **Mesh outputs**, per vertex and per primitive alike, are numbered densely in output order, -//! one location each at component 0, within `maxMeshOutputComponents / 4` locations -//! (`maxVertexOutputComponents / 4` for an emulated mesh function's, which its pipeline's -//! synthesized vertex stage writes). In a mesh render pipeline each fragment input takes the +//! one location each at component 0, within `maxMeshOutputComponents / 4` locations. In a mesh render pipeline each fragment input takes the //! number of the mesh output of its key and type (`UnmatchedVarying` without one), below //! `maxFragmentInputComponents / 4`; the raw indices follow the vertex rule above. The fragment //! function reads per primitive exactly the inputs whose keys the mesh function writes per @@ -348,17 +346,13 @@ pub fn assign(stages: &[&FunctionArtifact], p: &DeviceProfile) -> Result = None; let mut fragment: Option<&StageIo> = None; let mut mesh: Option<&StageIo> = None; - let mut emulated_mesh = false; for a in stages { let io = &a.interface.io; check_roles(a.interface.stage, io)?; match a.interface.stage { Stage::Vertex => vertex = Some(io), Stage::Fragment => fragment = Some(io), - Stage::Mesh => { - mesh = Some(io); - emulated_mesh = a.interface.mesh_records.is_some(); - } + Stage::Mesh => mesh = Some(io), Stage::Kernel | Stage::Object => {} } } @@ -374,18 +368,13 @@ pub fn assign(stages: &[&FunctionArtifact], p: &DeviceProfile) -> Result ( - VkLimit::MaxVertexOutputComponents, - l.max_vertex_output_components, - ), - false => ( - VkLimit::MaxMeshOutputComponents, - l.mesh.max_mesh_output_components, - ), - }; + let available = l.mesh.max_mesh_output_components; if need.saturating_mul(4) > u64::from(available) { - return Err(limit_error(limit, need, available)); + return Err(limit_error( + VkLimit::MaxMeshOutputComponents, + need, + available, + )); } for (n, x) in m.outputs.iter().enumerate() { table.insert(x.key.clone(), (n as u32, 0)); diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index 8ff2a12c9..a248be621 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -124,10 +124,9 @@ pub use graphics::{ }; pub use interface::{ AccessSet, AttributeFetch, BufferForm, BufferKind, BufferSlot, CommandWrites, DescriptorView, - LevelReads, MeshRecords, NumberedSampler, PatchDomain, PipelineInterface, PlacedField, PushLoc, - PushPlacement, RecordField, RecordValue, SampledLevels, SamplerArray, SamplerLevels, - SamplerSlot, SlotInterface, SnapshotRefusal, TextureAccess, TextureSlot, ThreadgroupArgument, - Window, + LevelReads, NumberedSampler, PatchDomain, PipelineInterface, PlacedField, PushLoc, + PushPlacement, SampledLevels, SamplerArray, SamplerLevels, SamplerSlot, SlotInterface, + SnapshotRefusal, TextureAccess, TextureSlot, ThreadgroupArgument, Window, }; pub use layout::{ BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange, diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 636501ace..83dd730db 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -340,17 +340,6 @@ pub enum SyntheticBinding { /// its words ([`FunctionTableSnapshot`](crate::bind::FunctionTableSnapshot)). The stage's /// function-table directory gives each id the word offset of its table's record. FunctionTableSnapshot, - /// An emulated mesh function's records (`StageInterface::mesh_records`): a storage buffer of - /// words from the draw's first word (`lower::mesh::work::RECORDS_BASE`), each mesh - /// threadgroup's zeroed by its own threads before its body runs, which the mesh function's - /// compute entry writes and the pipeline's synthesized vertex stage reads. Declared with the - /// mesh stage's symbols. - MeshRecords, - /// An emulated mesh pipeline's work buffer for one draw: its object threadgroups' grids and - /// payloads, their offsets in the draw's mesh threadgroups, and where its records begin, - /// which its object function writes and its mesh function and synthesized vertex stage read - /// (`lower::mesh::work`). Declared with the mesh stage's symbols. - MeshWork, /// The stand-in of the render pass's depth attachment a fragment function that runs the /// draw's depth test itself tests and writes (`GraphicsState::shader_tests`): a coherent /// `R32f` storage image holding pixel `(x, y)`'s depth at texel `(x, y)` (its samples as the diff --git a/crates/metal2vulkan/src/spirv/requirements/writes.rs b/crates/metal2vulkan/src/spirv/requirements/writes.rs index fe053bd33..0a71ef954 100644 --- a/crates/metal2vulkan/src/spirv/requirements/writes.rs +++ b/crates/metal2vulkan/src/spirv/requirements/writes.rs @@ -24,12 +24,6 @@ //! The trace also ends at an `OpIAdd` whose one operand is a load of the address member, whatever //! the other: the guest does not hold the address, so no sum of the guest's has such an operand. //! -//! An emulated mesh function's records (`Synthetic(MeshRecords)`) are the product's too, traced as -//! the status buffer's binding is: they hand the function's outputs to the pipeline's synthesized -//! vertex stage, as a mesh function's output variables would. So is an emulated object function's -//! slot of its draw's work buffer (`Synthetic(MeshWork)`), which hands its grid and payload to the -//! mesh function, as `OpEmitMeshTasksEXT` would. -//! //! The shader-side stencil's shadow (`Synthetic(ShadowStencil)`) is the product's too: its writes //! carry Metal's stencil test, which Metal applies per sample whether the function runs per pixel //! or per sample, so they do not make the function run per sample. An image write counts unless its @@ -99,8 +93,7 @@ fn class(m: &TypedModule, ptr: Value) -> BResult { /// is traced through. #[derive(Default)] struct Status<'m> { - /// The variables of the `Synthetic(ExecutionStatus)`, `Synthetic(MeshRecords)` and - /// `Synthetic(MeshWork)` bindings. + /// The variables of the `Synthetic(ExecutionStatus)` binding. bindings: Vec, /// The variables of the `Synthetic(ShadowStencil)`, `Synthetic(DepthStandIn)`, /// `Synthetic(StencilStandIn)`, `TileAttachment`, `ExtendedShadow` and `SnapshotTexels` @@ -123,11 +116,7 @@ impl<'m> Status<'m> { GlobalKind::Resource(slot) if matches!( slot.kind, - ResourceKind::Synthetic( - SyntheticBinding::ExecutionStatus - | SyntheticBinding::MeshRecords - | SyntheticBinding::MeshWork - ) + ResourceKind::Synthetic(SyntheticBinding::ExecutionStatus) ) => { s.bindings.push(g.value); diff --git a/crates/metal2vulkan/src/tests/engine_mesh.rs b/crates/metal2vulkan/src/tests/engine_mesh.rs index 4b109a12a..968dc1dce 100644 --- a/crates/metal2vulkan/src/tests/engine_mesh.rs +++ b/crates/metal2vulkan/src/tests/engine_mesh.rs @@ -176,10 +176,10 @@ fn a_mesh_function_is_a_mesh_entry() { } } -/// The committed profiles whose device does not list `VK_EXT_mesh_shader`: those that emulate a -/// mesh function. Only those that take threadgroup memory, which the object and mesh functions +/// The committed profiles whose device does not list `VK_EXT_mesh_shader`, which refuse object and +/// mesh functions. Only those that take threadgroup memory, which the object and mesh functions /// here use (`spirv::testing::threadgroup_profiles`). -pub(super) fn emulating_profiles() -> Vec<(String, DeviceProfile)> { +fn refusing_profiles() -> Vec<(String, DeviceProfile)> { let out: Vec<(String, DeviceProfile)> = threadgroup_profiles() .expect("committed profiles") .into_iter() @@ -189,180 +189,38 @@ pub(super) fn emulating_profiles() -> Vec<(String, DeviceProfile)> { !out.is_empty(), "every committed profile lists the extension" ); - for (stem, p) in &out { - assert!(crate::lower::mesh::emulates(p), "{stem}"); - } out } -/// Whether profile `p` lets a vertex stage write every output `mesh_outputs_points` writes: its -/// render target slice, its viewport and its clip distances. -fn writes_points_outputs(p: &DeviceProfile) -> bool { - let f = p.fields().fragment; - f.output_layer - && f.output_viewport_index - && p.enabled() - .features - .contains(&VkFeature::ShaderClipDistance) -} - -/// The execution models of a module's entry points. -fn execution_models(words: &[u32]) -> Vec { - let mut out = Vec::new(); - let mut i = 5; - while let Some(&w) = words.get(i) { - let len = (w >> 16).max(1) as usize; - if w & 0xFFFF == crate::spv::Op::EntryPoint as u32 { - out.extend(words.get(i + 1).copied()); - } - i += len; - } - out -} - -/// Without the extension a mesh function is emulated, a `GLCompute` entry that writes its -/// threadgroup's records to the records buffer, valid, needing no mesh shading, and whose stage -/// interface states the records' layout; an object function and a mesh function reading its payload -/// are `GLCompute` entries too, their payload workgroup memory and their work buffer bound. +/// Without the extension a mesh or object function is refused (`Unsupported{MeshShading}`), needing +/// `VK_EXT_mesh_shader` and the stage's feature (`meshShader`, an object function's `taskShader`) +/// where the profile lacks them. #[test] -fn without_the_extension_mesh_and_object_functions_are_compute_entries() { - use crate::pipeline::interface::RecordValue; +fn without_the_extension_mesh_and_object_functions_are_refused() { let (Some(order), Some(outputs)) = (fixture("mesh_order"), fixture("mesh_outputs")) else { return; }; - for (stem, p) in emulating_profiles() { - // (bytecode, entry, the indices of a primitive) - for (bc, entry, corners) in [ - (&order, "mesh_order_solo", 3), - (&outputs, "mesh_outputs_lines", 2), - (&outputs, "mesh_outputs_points", 1), + for (stem, p) in refusing_profiles() { + for (bc, entry, feature) in [ + (&order, "mesh_order_solo", VkFeature::MeshShader), + (&outputs, "mesh_outputs_lines", VkFeature::MeshShader), + (&outputs, "mesh_outputs_points", VkFeature::MeshShader), + (&order, "mesh_order_object", VkFeature::TaskShader), + (&order, "mesh_order_mesh", VkFeature::MeshShader), ] { let what = format!("{stem} {entry}"); - // The points choose their slice and viewport and write clip distances, which the - // synthesized vertex stage writes as a vertex function's: a device that lacks one - // refuses them as needing it. - if entry == "mesh_outputs_points" && !writes_points_outputs(&p) { - match compile(bc, entry, &p) { - Err(Error::Unsupported(u)) - if matches!( - u.feature, - Feature::LayeredRendering | Feature::ClipDistance - ) => {} - other => panic!("{what}: {other:?}"), - } - continue; + let mut missing = vec![Capability::Extension(VkExtension::ExtMeshShader)]; + if !p.enabled().features.contains(&feature) { + missing.push(Capability::Feature(feature)); } - let a = compile(bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(a.interface.stage, Stage::Mesh, "{what}"); - let r = &a.module.requirements; - assert!( - !r.extensions.contains(&VkExtension::ExtMeshShader) - && !r.features.contains(&VkFeature::MeshShader), - "{what}: {r:?}" - ); - check_words_valid(&a.module.words, r, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - assert_eq!( - execution_models(&a.module.words), - [crate::spv::ExecutionModel::GLCompute as u32], - "{what}" - ); - let ops = opcodes(&a.module.words); - assert!( - !ops.contains(&(crate::spv::Op::SetMeshOutputsEXT as u32)), - "{what}" - ); - assert_eq!( - a.interface.vk_stage(), - crate::vk::ShaderStage::COMPUTE, - "{what}" - ); - assert!( - a.interface - .descriptors - .iter() - .any(|d| d.slot == crate::lower::mesh::RECORDS_SLOT - && d.ty == crate::vk::DescriptorType::STORAGE_BUFFER), - "{what}: the records binding" - ); - let records = a.interface.mesh_records.as_ref().expect("the records"); - assert_eq!(records.corners, corners, "{what}"); - // Every field fits its record, the vertex record holds the position, and no two - // fields of a record overlap. - assert!( - records - .fields - .iter() - .any(|f| f.value == RecordValue::Position && !f.per_primitive), - "{what}: {records:?}" - ); - for per_primitive in [false, true] { - let (start, size) = if per_primitive { - (corners, records.primitive_words) - } else { - (0, records.vertex_words) - }; - let mut words: Vec<(u32, u32)> = records - .fields - .iter() - .filter(|f| f.per_primitive == per_primitive) - .map(|f| (f.offset, f.offset + f.words)) - .collect(); - words.sort_unstable(); - let mut at = start; - for (from, to) in words { - assert!(from >= at && to <= size, "{what}: {records:?}"); - at = to; - } - } - assert_eq!( - records.group_words(), - 1 + u64::from(records.vertices) * u64::from(records.vertex_words) - + u64::from(records.primitives) * u64::from(records.primitive_words), - "{what}" - ); - } - // An object function and a mesh function reading its payload are compute entries too: - // the payload is workgroup memory, which the draw's work buffer carries between them. - for entry in ["mesh_order_object", "mesh_order_mesh"] { - let what = format!("{stem} {entry}"); - let a = compile(&order, entry, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - let r = &a.module.requirements; - assert!( - !r.extensions.contains(&VkExtension::ExtMeshShader), - "{what}: {r:?}" - ); - check_words_valid(&a.module.words, r, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - assert_eq!( - execution_models(&a.module.words), - [crate::spv::ExecutionModel::GLCompute as u32], - "{what}" - ); - assert_eq!( - variables_of( - &a.module.words, - crate::spv::StorageClass::TaskPayloadWorkgroupEXT + match compile(bc, entry, &p) { + Err(Error::Unsupported(u)) => assert_eq!( + (u.feature, &u.needs), + (Feature::MeshShading, &Needs::AnyOf(vec![missing])), + "{what}" ), - 0, - "{what}" - ); - assert!( - a.interface.emulated_payload.is_some_and(|words| words > 0), - "{what}: {:?}", - a.interface.emulated_payload - ); - assert_eq!( - a.interface.vk_stage(), - crate::vk::ShaderStage::COMPUTE, - "{what}" - ); - let work = match a.interface.stage { - Stage::Object => crate::lower::mesh::OBJECT_WORK_SLOT, - _ => crate::lower::mesh::WORK_SLOT, - }; - assert!( - a.interface.descriptors.iter().any(|d| d.slot == work), - "{what}: the work buffer" - ); + other => panic!("{what}: {:?}", other.map(|_| ())), + } } } } @@ -855,8 +713,8 @@ fn wide_object_payload() -> Option> { /// payload by the type the object function declares: in the mesh render pipeline of /// `mesh_outputs_object`, its payload declared 64 bytes ([`wide_object_payload`]), and /// `mesh_outputs_triangles`, which declares 16 and reads 64, the mesh function's payload arena -/// holds the object function's 64 bytes (`LoweringInputs::object_payload`), emulated or not, and -/// each stage is valid. Compiled on its own, the mesh function's arena is its own 32 (the +/// holds the object function's 64 bytes (`LoweringInputs::object_payload`), and each stage is +/// valid. Compiled on its own, the mesh function's arena is its own 32 (the /// smallest), and the pipeline refuses it as `NeedsInput(ObjectPayload)`; compiled under the object /// function's bytes it links. An object payload its own arena holds leaves its key as compiled /// alone. @@ -865,7 +723,6 @@ fn a_mesh_function_reads_its_payload_within_its_object_functions() { use crate::budget::Budget; use crate::error::RuntimeInput; use crate::library::Library; - use crate::lower::mesh::work; use crate::pipeline::descriptor::{FunctionDescriptor, MeshPipelineDescriptor, StageSource}; let Some(wide) = wide_object_payload() else { return; @@ -873,9 +730,8 @@ fn a_mesh_function_reads_its_payload_within_its_object_functions() { let wide = Library::from_air(&wide).expect("library"); let function = |name: &str| FunctionDescriptor::new(wide.function(name).expect("function")); let budget = Budget::standard(); - for (stem, p) in mesh_profiles().into_iter().chain(emulating_profiles()) { + for (stem, p) in mesh_profiles() { let dev = device(&stem); - let emulated = crate::lower::mesh::emulates(&p); let compiled = |name: &str, inputs: &LoweringInputs| { dev.compile_function(&function(name), inputs, &budget) .unwrap_or_else(|e| panic!("{stem} {name}: {e}")) @@ -893,11 +749,6 @@ fn a_mesh_function_reads_its_payload_within_its_object_functions() { let within = compiled("mesh_outputs_triangles", &inputs); let a = within.artifact(); assert_eq!(a.interface.payload, Some(64), "{stem}"); - assert_eq!( - a.interface.emulated_payload, - emulated.then_some(16), - "{stem}" - ); check_words_valid(&a.module.words, &a.module.requirements, &p) .unwrap_or_else(|e| panic!("{stem}: L3: {e}")); // An object payload the mesh function's own arena holds keeps its key. @@ -919,8 +770,6 @@ fn a_mesh_function_reads_its_payload_within_its_object_functions() { check_words_valid(&m.spirv, &made.requirements, dev.profile()) .unwrap_or_else(|e| panic!("{stem} {:?}: L3: {e}", m.stage)); } - let slot = made.graphics.mesh_records.as_ref().map(|r| r.slot_words); - assert_eq!(slot, emulated.then_some(work::GRID + 16), "{stem}"); assert_eq!( pipeline(StageSource::Compiled(alone)).err(), Some(Error::NeedsInput(RuntimeInput::ObjectPayload)), @@ -931,450 +780,39 @@ fn a_mesh_function_reads_its_payload_within_its_object_functions() { } } -/// Without the extension a mesh render pipeline is emulated. Its mesh function is a compute stage -/// writing records, a synthesized vertex stage draws them and the fragment reads the primitive's -/// outputs flat (no `PerPrimitiveEXT`); every stage is valid under the pipeline's requirements, the -/// records and work bindings are the compute and vertex stages', and the pipeline's topology is the -/// records'. A draw of `G` threadgroups is the host's: a dispatch of `G` over records of `G` -/// threadgroups' words, its work buffer complete, then a draw of `NP · k` vertices each; a grid -/// whose records pass `maxStorageBufferRange` is refused naming it. An indirect draw is scanned -/// from Metal's arguments into the command buffer's records pool and drawn from the work buffer. -/// With an object function, the object stage is a compute stage first, the push range one hull, and -/// a draw dispatches its object threadgroups and is scanned. A fragment reading `[[primitive_id]]` -/// is not emulated yet. +/// Without the extension a mesh render pipeline is refused (`Unsupported{MeshShading}`), with or +/// without an object function. #[test] -fn without_the_extension_a_mesh_pipeline_draws_its_records() { - use crate::bind::{ - AccessClass, BindState, BufferRange, DrawCall, IndirectRef, MeshDispatch, MeshGroups, - MeshRecordsRegion, UseTarget, - }; +fn without_the_extension_a_mesh_pipeline_is_refused() { use crate::budget::Budget; - use crate::device::requirements::VkLimit; - use crate::error::{BindError, Unsupported}; use crate::library::Library; - use crate::lower::mesh::work; - use crate::metal::PixelFormat; - use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, MeshPipelineDescriptor, StageSource, - }; - use crate::pipeline::layout::BindingSource; - use crate::pipeline::sym::SyntheticBinding; - use crate::vk; - let (Some(draws), Some(outputs)) = (fixture("mesh_draws"), fixture("mesh_outputs")) else { + use crate::pipeline::descriptor::{FunctionDescriptor, MeshPipelineDescriptor, StageSource}; + let Some(draws) = fixture("mesh_draws") else { return; }; - let (draws, outputs) = ( - Library::from_air(&draws).expect("library"), - Library::from_air(&outputs).expect("library"), - ); - let stage = |lib: &Library, name: &str| { - StageSource::Function(FunctionDescriptor::new( - lib.function(name).expect("function"), - )) - }; - let budget = Budget::standard(); - for (stem, _) in emulating_profiles() { - let dev = device(&stem); - let mut d = MeshPipelineDescriptor::new(stage(&draws, "mesh_draws_grid")); - d.fragment = Some(stage(&draws, "mesh_draws_fragment")); - for slot in d.color_attachments.iter_mut().take(2) { - *slot = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Uint)); - } - let pipeline = dev - .compile_mesh_pipeline(&d, &budget) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let kinds: Vec = pipeline.stages.iter().map(|m| m.stage).collect(); - assert_eq!( - kinds, - [ - vk::ShaderStage::COMPUTE, - vk::ShaderStage::VERTEX, - vk::ShaderStage::FRAGMENT - ], - "{stem}" - ); - assert!( - !pipeline - .requirements - .extensions - .contains(&VkExtension::ExtMeshShader), - "{stem}" - ); - for m in &pipeline.stages { - check_words_valid(&m.spirv, &pipeline.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{stem} {:?}: L3: {e}", m.stage)); - } - assert_eq!( - per_primitive_decorations(&pipeline.stages[2].spirv), - 0, - "{stem}: the fragment reads the primitive's outputs flat" - ); - let records = pipeline - .graphics - .mesh_records - .clone() - .expect("the pipeline's records"); - assert_eq!( - pipeline.graphics.topology, - vk::PrimitiveTopology::TRIANGLE_LIST, - "{stem}" - ); - let binding_of = |p: &crate::pipeline::RenderPipeline, stage, binding| { - p.layout - .sets - .iter() - .flat_map(|s| &s.bindings) - .find(|b| b.source == BindingSource::Synthetic { stage, binding }) - .cloned() - }; - for kind in [SyntheticBinding::MeshRecords, SyntheticBinding::MeshWork] { - let binding = binding_of(&pipeline, Stage::Mesh, kind).expect("the binding"); - assert_eq!(binding.ty, vk::DescriptorType::STORAGE_BUFFER, "{stem}"); - assert_eq!( - binding.stages, - vk::ShaderStageFlags::COMPUTE | vk::ShaderStageFlags::VERTEX, - "{stem} {kind:?}" - ); - } - // A draw of two threadgroups. - let state = BindState::default(); - let plan = pipeline - .plan(&dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem}: plan: {e}")); - let groups = |groups| DrawCall::MeshThreadgroups { - groups, - threads_per_object_group: [1; 3], - threads_per_mesh_group: [8, 1, 1], - }; - let cmds = plan - .instantiate_draw(&state, &groups([2, 1, 1])) - .unwrap_or_else(|e| panic!("{stem}: a draw: {e}")); - assert_eq!( - cmds.draw, - vk::DrawCommand::Draw { - vertex_count: 2 * records.primitives * records.corners, - instance_count: 1, - first_vertex: 0, - first_instance: 0, - }, - "{stem}" - ); - let d = cmds.mesh_dispatch.clone().expect("the draw's dispatch"); - assert_eq!(d.mesh, MeshGroups::Direct([2, 1, 1]), "{stem}"); - assert_eq!(d.object_groups, None, "{stem}"); - assert_eq!( - d.records, - MeshRecordsRegion::Exact(2 * 4 * records.group_words()), - "{stem}" - ); - // The host's work buffer: one virtual object threadgroup of the draw's grid and no - // payload, the draw's two mesh threadgroups from word 0 of its records, and the offsets. - let header = work::HEADER as usize; - let slot = records.slot_words as usize; - assert_eq!(records.slot_words, work::GRID, "{stem}: no payload"); - assert_eq!(d.work.len(), header + slot + 2, "{stem}"); - assert_eq!(d.work_bytes, 4 * (header + slot + 2) as u64, "{stem}"); - assert_eq!(d.work[work::OBJECT_GROUPS as usize], 1, "{stem}"); - assert_eq!(d.work[work::MESH_GROUPS as usize], 2, "{stem}"); - assert_eq!(d.work[work::RECORDS_BASE as usize], 0, "{stem}"); - assert_eq!(&d.work[header..header + 4], &[2, 1, 1, 0], "{stem}"); - assert_eq!(&d.work[header + slot..], &[0, 2], "{stem}"); - // A grid Metal draws nothing for (65,535 by 65,535) draws nothing, with no records. - let none = plan - .instantiate_draw(&state, &groups([65535, 65535, 1])) - .unwrap_or_else(|e| panic!("{stem}: a grid past Metal's: {e}")); - assert!( - matches!( - none.draw, - vk::DrawCommand::Draw { - vertex_count: 0, - .. - } - ), - "{stem}: {:?}", - none.draw - ); - // Records past the device's storage buffer range, of the largest grid Metal draws. - let l = &dev.profile().fields().limits; - let x = l.max_compute_work_group_count[0].min(crate::bind::METAL_MESH_GRID_AXIS); - let y = l.max_compute_work_group_count[1].min(crate::bind::METAL_MESH_GRID_TOTAL / x); - let bytes = u64::from(x) * u64::from(y) * 4 * records.group_words(); - if bytes > u64::from(l.max_storage_buffer_range) { - assert_eq!( - plan.instantiate_draw(&state, &groups([x, y, 1])).err(), - Some(BindError::Unsupported(Unsupported::needs( - Feature::MeshShading, - Capability::Limit { - limit: VkLimit::MaxStorageBufferRange, - required: bytes, - available: u64::from(l.max_storage_buffer_range), - }, - ))), - "{stem}" - ); - } - // An indirect draw: scanned from Metal's arguments, bound from their offset aligned - // down, and drawn from the work buffer. - let indirect = DrawCall::MeshThreadgroupsIndirect { - indirect: IndirectRef::new(1, 260), - threads_per_object_group: [1; 3], - threads_per_mesh_group: [8, 1, 1], - }; - let cmds = plan - .instantiate_draw(&state, &indirect) - .unwrap_or_else(|e| panic!("{stem}: an indirect draw: {e}")); - assert!(!cmds.indirect_needs_arguments, "{stem}"); - assert_eq!( - cmds.draw, - vk::DrawCommand::DrawIndirect { - offset: MeshDispatch::DRAW_OFFSET, - draw_count: 1, - stride: 16, - }, - "{stem}" - ); - let d = cmds.mesh_dispatch.clone().expect("the draw's dispatch"); - let a = l.min_storage_buffer_offset_alignment.max(4); - let start = 260 - 260 % a; - assert_eq!( - d.mesh, - MeshGroups::Scanned { - arguments: Some(BufferRange { - offset: start, - range: 260 - start + 12, - }), - }, - "{stem}" - ); - assert_eq!(d.records, MeshRecordsRegion::Pool, "{stem}"); - assert_eq!(d.object_groups, None, "{stem}"); - assert_eq!( - d.work[work::ARGUMENTS as usize], - 1 + ((260 - start) / 4) as u32, - "{stem}" - ); - assert!( - cmds.uses.iter().any(|u| u.resource == UseTarget::Indirect - && u.class == AccessClass::Storage - && u.stages == vk::PipelineStageFlags2::COMPUTE_SHADER), - "{stem}: the scan's read of the arguments" - ); - object_records_draws(&dev, &draws, &stem); - // A fragment reading the primitive's id (behind the points, where the device lets a - // vertex stage write their outputs). - if !writes_points_outputs(dev.profile()) { - continue; - } - let mut d = MeshPipelineDescriptor::new(stage(&outputs, "mesh_outputs_points")); - d.fragment = Some(stage(&outputs, "mesh_outputs_fragment")); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Float)); - match dev.compile_mesh_pipeline(&d, &budget) { - Err(Error::Unsupported(u)) - if u.feature == Feature::MeshShading && u.needs == Needs::NotImplemented => {} - other => panic!("{stem}: a fragment reading the primitive's id: {other:?}"), - } - } -} - -/// An emulated pipeline with an object function (`mesh_draws_object`, a 32-byte payload, with -/// `mesh_draws_mesh` and `mesh_draws_fragment`): the object function's compute stage first, at most -/// one push range of both compute stages' windows, both work bindings; a draw of object threadgroups -/// dispatches them, is scanned into the records pool, and is drawn from the work buffer, whose -/// slots hold the payload; an indirect one runs its object arguments pass first, its slots in the -/// pool. -fn object_records_draws(dev: &crate::device::Device, draws: &crate::library::Library, stem: &str) { - use crate::bind::{ - BindState, DrawCall, MeshDispatch, MeshGroups, MeshRecordsRegion, UseTarget, - }; - use crate::budget::Budget; - use crate::lower::mesh::work; - use crate::metal::PixelFormat; - use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, MeshPipelineDescriptor, StageSource, - }; - use crate::pipeline::layout::BindingSource; - use crate::pipeline::sym::SyntheticBinding; - use crate::pipeline::AccessSet; - use crate::vk; + let draws = Library::from_air(&draws).expect("library"); let stage = |name: &str| { StageSource::Function(FunctionDescriptor::new( draws.function(name).expect("function"), )) }; - let mut d = MeshPipelineDescriptor::new(stage("mesh_draws_mesh")); - d.object = Some(stage("mesh_draws_object")); - d.fragment = Some(stage("mesh_draws_fragment")); - for slot in d.color_attachments.iter_mut().take(2) { - *slot = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Uint)); + for (stem, _) in refusing_profiles() { + let dev = device(&stem); + for object in [None, Some("mesh_draws_object")] { + let mut d = MeshPipelineDescriptor::new(stage(match object { + Some(_) => "mesh_draws_mesh", + None => "mesh_draws_grid", + })); + d.object = object.map(&stage); + d.rasterization_enabled = false; + match dev.compile_mesh_pipeline(&d, &Budget::standard()) { + Err(Error::Unsupported(u)) => { + assert_eq!(u.feature, Feature::MeshShading, "{stem} {object:?}") + } + other => panic!("{stem} {object:?}: {:?}", other.map(|_| ())), + } + } } - let pipeline = dev - .compile_mesh_pipeline(&d, &Budget::standard()) - .unwrap_or_else(|e| panic!("{stem}: an object function: {e}")); - let kinds: Vec = pipeline.stages.iter().map(|m| m.stage).collect(); - assert_eq!( - kinds, - [ - vk::ShaderStage::COMPUTE, - vk::ShaderStage::COMPUTE, - vk::ShaderStage::VERTEX, - vk::ShaderStage::FRAGMENT - ], - "{stem}" - ); - for m in &pipeline.stages { - check_words_valid(&m.spirv, &pipeline.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{stem} {:?}: L3: {e}", m.stage)); - } - let compute: Vec<_> = pipeline - .layout - .push_constants - .iter() - .filter(|r| r.stages.contains(vk::ShaderStageFlags::COMPUTE)) - .collect(); - // One range at most: none where neither compute stage pushes a field (Intel's Iris Xe). - assert!( - compute.len() <= 1, - "{stem}: {:?}", - pipeline.layout.push_constants - ); - let stages_of = |stage, binding| { - pipeline - .layout - .sets - .iter() - .flat_map(|s| &s.bindings) - .find(|b| b.source == BindingSource::Synthetic { stage, binding }) - .map(|b| b.stages) - }; - assert_eq!( - stages_of(Stage::Object, SyntheticBinding::MeshWork), - Some(vk::ShaderStageFlags::COMPUTE), - "{stem}" - ); - assert_eq!( - stages_of(Stage::Mesh, SyntheticBinding::MeshWork), - Some(vk::ShaderStageFlags::COMPUTE | vk::ShaderStageFlags::VERTEX), - "{stem}" - ); - // The object function's slots of an indirect draw lie in the records (`work::SLOTS`). - assert_eq!( - stages_of(Stage::Object, SyntheticBinding::MeshRecords), - Some(vk::ShaderStageFlags::COMPUTE), - "{stem}" - ); - let records = pipeline - .graphics - .mesh_records - .clone() - .expect("the pipeline's records"); - assert_eq!( - records.slot_words, - work::GRID + 8, - "{stem}: the 32-byte payload" - ); - let state = BindState::default(); - let plan = pipeline - .plan(dev, &state.shape()) - .unwrap_or_else(|e| panic!("{stem}: plan: {e}")); - let draw = DrawCall::MeshThreadgroups { - groups: [2, 3, 1], - threads_per_object_group: [4, 1, 1], - threads_per_mesh_group: [8, 1, 1], - }; - let cmds = plan - .instantiate_draw(&state, &draw) - .unwrap_or_else(|e| panic!("{stem}: a draw: {e}")); - assert_eq!( - cmds.draw, - vk::DrawCommand::DrawIndirect { - offset: MeshDispatch::DRAW_OFFSET, - draw_count: 1, - stride: 16, - }, - "{stem}" - ); - let d = cmds.mesh_dispatch.expect("the draw's dispatch"); - assert_eq!(d.object_groups, Some([2, 3, 1]), "{stem}"); - assert_eq!(d.mesh, MeshGroups::Scanned { arguments: None }, "{stem}"); - assert_eq!(d.records, MeshRecordsRegion::Pool, "{stem}"); - assert_eq!(d.work.len(), work::HEADER as usize, "{stem}"); - assert_eq!(d.work[work::OBJECT_GROUPS as usize], 6, "{stem}"); - assert_eq!( - d.work[work::SLOT_WORDS as usize], - records.slot_words, - "{stem}" - ); - assert_eq!( - d.work_bytes, - 4 * work::words(6, records.slot_words), - "{stem}" - ); - // An indirect draw runs its object arguments pass first: Metal's arguments at word 1 plus - // the offset's residual, the object threadgroup packed, no object count yet, and the slots in - // the pool, which the pass reserves. - let indirect = DrawCall::MeshThreadgroupsIndirect { - indirect: crate::bind::IndirectRef::new(1, 4), - threads_per_object_group: [4, 1, 1], - threads_per_mesh_group: [8, 1, 1], - }; - let cmds = plan - .instantiate_draw(&state, &indirect) - .unwrap_or_else(|e| panic!("{stem}: an indirect draw: {e}")); - let d = cmds.mesh_dispatch.expect("the draw's dispatch"); - assert_eq!(d.object_groups, None, "{stem}"); - let range = d.object_arguments.expect("the object arguments pass"); - assert_eq!(range.offset + range.range, 16, "{stem}"); - assert_eq!(d.mesh, MeshGroups::Scanned { arguments: None }, "{stem}"); - assert_eq!(d.records, MeshRecordsRegion::Pool, "{stem}"); - assert_eq!( - d.work[work::OBJECT_ARGUMENTS as usize], - u32::try_from((4 - range.offset) / 4 + 1).expect("a word"), - "{stem}" - ); - assert_eq!(d.work[work::OBJECT_GROUPS as usize], 0, "{stem}"); - assert_eq!( - d.work_bytes, - 4 * work::words(0, records.slot_words), - "{stem}" - ); - assert!( - cmds.uses - .iter() - .any(|u| u.resource == UseTarget::Indirect && u.access == AccessSet::READ), - "{stem}: the pass reads Metal's arguments" - ); - // A `drawMeshThreads` that leaves a partial object threadgroup: its object function, whose - // body holds no barrier, runs one, so the draw dispatches the threadgroups its threads fill, - // rounded up, its region flagged. - assert!( - pipeline - .dependencies - .iter() - .any(|d| d.fact == RuntimeFact::PartialObjectThreadgroups), - "{stem}" - ); - let threads = DrawCall::MeshThreads { - threads: [6, 1, 1], - threads_per_object_group: [4, 1, 1], - threads_per_mesh_group: [8, 1, 1], - }; - let cmds = plan - .instantiate_draw(&state, &threads) - .unwrap_or_else(|e| panic!("{stem}: a partial object threadgroup: {e}")); - let d = cmds.mesh_dispatch.as_ref().expect("the draw's dispatch"); - assert_eq!(d.object_groups, Some([2, 1, 1]), "{stem}"); - assert_eq!(d.work[work::OBJECT_GROUPS as usize], 2, "{stem}"); - let regions: Vec<_> = (pipeline.interface.push.iter()) - .flat_map(|s| &s.fields) - .filter(|f| f.field == PushField::DispatchRegion) - .map(|f| f.loc) - .collect(); - assert!( - flags_region(&cmds, [6, 1, 1], [4, 1, 1]), - "{stem}: regions at {regions:?}, pushed {:?}, tables {:?}", - cmds.push_constants, - cmds.descriptor_bytes - ); } /// Whether a draw's push constants hold the flagged region of a partial object threadgroup's draw @@ -1864,17 +1302,17 @@ fn a_mesh_function_stores_each_index_into_its_component() { } /// A mesh function's buffer writes need no stage store feature: Vulkan's -/// `vertexPipelineStoresAndAtomics` and `fragmentStoresAndAtomics` name no task or mesh stage, and -/// the emulation runs the function as a compute entry. `mesh_barrier_writer`, whose one store is -/// to its device buffer, compiles on every committed profile with both features removed, as a -/// `MeshEXT` entry or the emulation's compute entry, and passes L3 within that profile. +/// `vertexPipelineStoresAndAtomics` and `fragmentStoresAndAtomics` name no task or mesh stage. +/// `mesh_barrier_writer`, whose one store is to its device buffer, compiles on every committed +/// profile with `VK_EXT_mesh_shader` with both features removed, as a `MeshEXT` entry, and passes +/// L3 within that profile. #[test] fn a_mesh_functions_buffer_writes_need_no_stage_store_feature() { use crate::device::{Device, DeviceDescription, DevicePolicy}; let Some(barrier) = fixture("mesh_barrier") else { return; }; - for (stem, _) in committed_profiles().expect("committed profiles") { + for (stem, _) in mesh_profiles() { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join(format!("../metal2vulkan-validation/profiles/{stem}.json")); let text = std::fs::read_to_string(path).expect("profile"); @@ -1902,13 +1340,13 @@ fn a_mesh_functions_buffer_writes_need_no_stage_store_feature() { } /// A mesh render pipeline's answers to Metal's mesh queries (`RenderPipeline::mesh_info`), on -/// every committed profile, emulated or not: each stage's thread limit is the least of the +/// every committed profile with `VK_EXT_mesh_shader`: each stage's thread limit is the least of the /// descriptor's maximum, the function's `[[max_total_threads_per_threadgroup(n)]]`, the threads of /// the stage's required size and 1024, within the device's limit for the stage (the task and mesh -/// stages' invocations, or the compute stage's where it runs them as compute work); the widths are +/// stages' invocations); the widths are /// 32; the mesh grid is the descriptor's maximum, else 2^20 whatever the object function's -/// `[[max_total_threadgroups_per_mesh_grid(n)]]`, within the device's `maxMeshWorkGroupTotalCount` -/// where it runs mesh functions natively. Without an object function the object stage answers 0 +/// `[[max_total_threadgroups_per_mesh_grid(n)]]`, within the device's `maxMeshWorkGroupTotalCount`. +/// Without an object function the object stage answers 0 /// and 0. Each as an M3 Max answers on a first compile (`mesh_pipeline_limits.m`). #[test] fn a_mesh_pipeline_answers_metals_mesh_queries_within_the_device() { @@ -1929,22 +1367,14 @@ fn a_mesh_pipeline_answers_metals_mesh_queries_within_the_device() { )) }; let budget = Budget::standard(); - for (stem, p) in mesh_profiles().into_iter().chain(emulating_profiles()) { + for (stem, p) in mesh_profiles() { let dev = device(&stem); let l = &p.fields().limits; - let emulated = crate::lower::mesh::emulates(&p); - let (object, mesh, total) = match emulated { - true => ( - l.max_compute_work_group_invocations, - l.max_compute_work_group_invocations, - u32::MAX, - ), - false => ( - l.mesh.max_task_work_group_invocations, - l.mesh.max_mesh_work_group_invocations, - l.mesh.max_mesh_work_group_total_count, - ), - }; + let (object, mesh, total) = ( + l.mesh.max_task_work_group_invocations, + l.mesh.max_mesh_work_group_invocations, + l.mesh.max_mesh_work_group_total_count, + ); let info = |d: &MeshPipelineDescriptor| { dev.compile_mesh_pipeline(d, &budget) .unwrap_or_else(|e| panic!("{stem}: {e}")) @@ -2047,7 +1477,7 @@ fn a_mesh_pipeline_answers_metals_mesh_queries_within_the_device() { /// A mesh render pipeline descriptor Metal refuses is refused as Metal's rule /// (`InvalidDescriptor(MeshPipeline)`, measured on an M3 Max, `mesh_pipeline_limits.m`), on every -/// committed profile, and the descriptors beside each are made: a required size with an axis of +/// committed profile with `VK_EXT_mesh_shader`, and the descriptors beside each are made: a required size with an axis of /// 0, of more than 1024 threads or more than its stage's maximum, or of an object stage without an /// object function; a maximum past 1024; a required size of other threads than its stage's /// maximum, in either stage (Metal's first compile); a function's maximum other than the @@ -2077,7 +1507,7 @@ fn a_mesh_descriptor_metal_refuses_is_refused_as_its_rule() { crate::error::DescriptorError::MeshPipeline { problem }, )) }; - for (stem, _) in mesh_profiles().into_iter().chain(emulating_profiles()) { + for (stem, _) in mesh_profiles() { let dev = device(&stem); let answer = |d: &MeshPipelineDescriptor| dev.compile_mesh_pipeline(d, &budget).err(); let mut d = MeshPipelineDescriptor::new(stage(&draws, "mesh_draws_mesh")); @@ -2281,7 +1711,7 @@ fn a_mesh_descriptor_metal_refuses_is_refused_as_its_rule() { /// A mesh render pipeline of `maxVertexAmplificationCount` 2, which Metal makes (the /// `mesh-limits-amplification-2` conformance recording, an M3 Max under macOS 27.0.1), is made on -/// every committed profile without multiview, and draws one amplification, Metal's default, as a +/// every committed profile with `VK_EXT_mesh_shader`, without multiview, and draws one amplification, Metal's default, as a /// pipeline without amplification does. Its draw of two is refused /// `NotImplemented(VertexAmplification)`: Vulkan's multiview may run the task stage once a view, /// where Metal runs the object function once a draw, and a mesh function does not add a view @@ -2301,7 +1731,7 @@ fn an_amplified_mesh_pipeline_draws_one_amplification() { draws.function(name).expect("function"), )) }; - for (stem, _) in mesh_profiles().into_iter().chain(emulating_profiles()) { + for (stem, _) in mesh_profiles() { let dev = device(&stem); let mut d = MeshPipelineDescriptor::new(stage("mesh_draws_mesh")); d.object = Some(stage("mesh_draws_object")); @@ -2345,7 +1775,7 @@ fn an_amplified_mesh_pipeline_draws_one_amplification() { /// `payloadMemoryLength` sizes the payload of both stages: in the mesh render pipeline of /// `mesh_outputs_object`, which declares 16 bytes, and `mesh_outputs_triangles`, which declares 16 /// and reads 64, a length of 64 gives the object function's arena and the mesh function's its 64 -/// bytes, as the object function's declaring 64 does ([`wide_object_payload`]), emulated or not; +/// bytes, as the object function's declaring 64 does ([`wide_object_payload`]); /// a length the declared type holds leaves the object function's key as without it; and a stage /// compiled on its own without the length is refused as `NeedsInput(ObjectPayload)`. #[test] @@ -2353,7 +1783,6 @@ fn the_descriptors_payload_length_sizes_both_stages_payloads() { use crate::budget::Budget; use crate::error::RuntimeInput; use crate::library::Library; - use crate::lower::mesh::work; use crate::pipeline::descriptor::{FunctionDescriptor, MeshPipelineDescriptor, StageSource}; let Some(outputs) = fixture("mesh_outputs") else { return; @@ -2361,9 +1790,8 @@ fn the_descriptors_payload_length_sizes_both_stages_payloads() { let outputs = Library::from_air(&outputs).expect("library"); let function = |name: &str| FunctionDescriptor::new(outputs.function(name).expect("function")); let budget = Budget::standard(); - for (stem, p) in mesh_profiles().into_iter().chain(emulating_profiles()) { + for (stem, _) in mesh_profiles() { let dev = device(&stem); - let emulated = crate::lower::mesh::emulates(&p); let mut d = MeshPipelineDescriptor::new(StageSource::Function(function("mesh_outputs_triangles"))); d.object = Some(StageSource::Function(function("mesh_outputs_object"))); @@ -2381,8 +1809,6 @@ fn the_descriptors_payload_length_sizes_both_stages_payloads() { }) .collect(); assert_eq!(arena, [Some(64)], "{stem}"); - let slot = made.graphics.mesh_records.as_ref().map(|r| r.slot_words); - assert_eq!(slot, emulated.then_some(work::GRID + 16), "{stem}"); for m in &made.stages { check_words_valid(&m.spirv, &made.requirements, dev.profile()) .unwrap_or_else(|e| panic!("{stem} {:?}: L3: {e}", m.stage)); @@ -2414,11 +1840,11 @@ fn the_descriptors_payload_length_sizes_both_stages_payloads() { /// (`setObjectThreadgroupMemoryLength:atIndex:`, the object stage's `threadgroup_lengths`): in the /// pipeline of `mesh_outputs_object` (its payload 64 bytes, [`wide_object_payload`]) and /// `mesh_outputs_triangles`, a draw specializes `TgLength(0)` to the length rounded up to 16, as -/// a kernel's, and to 0 where it is unset, emulated or not. The artifact states the arena's static +/// a kernel's, and to 0 where it is unset. The artifact states the arena's static /// part and its payload (`RuntimeFact::ObjectThreadgroupArena`). The plan checks the arena with the /// lengths against the object stage's workgroup memory limit: the task stage's /// (`maxTaskSharedMemorySize`, beside the wrapper's 12-byte grid), whose 76 bytes fit a 64-byte -/// length and not a 65-byte one, or, emulated, the compute stage's. +/// length and not a 65-byte one. #[test] fn an_object_functions_threadgroup_memory_is_the_encoders_lengths() { use crate::bind::{BindState, DrawCall}; @@ -2479,9 +1905,8 @@ fn an_object_functions_threadgroup_memory_is_the_encoders_lengths() { }, _ => None, }; - for (stem, p) in mesh_profiles().into_iter().chain(emulating_profiles()) { + for (stem, p) in mesh_profiles() { let dev = device(&stem); - let emulated = crate::lower::mesh::emulates(&p); let made = pipeline(&dev).unwrap_or_else(|e| panic!("{stem}: {e}")); let arena: Vec<_> = made .dependencies @@ -2522,26 +1947,17 @@ fn an_object_functions_threadgroup_memory_is_the_encoders_lengths() { ); } // Past the object stage's limit, refused at plan naming it. - let l = &p.fields().limits; - let past = if emulated { - l.max_compute_shared_memory_size - } else { - l.mesh.max_task_shared_memory_size - }; + let past = p.fields().limits.mesh.max_task_shared_memory_size; let refused = refused_limit(made.plan(&dev, &with_length(Some(past)).shape())); let named = refused.map(|(limit, _, _)| limit); - if emulated { - assert_eq!(named, Some(VkLimit::MaxComputeSharedMemorySize), "{stem}"); - } else { - assert!( - matches!( - named, - Some(VkLimit::MaxTaskSharedMemorySize) - | Some(VkLimit::MaxTaskPayloadAndSharedMemorySize) - ), - "{stem}: {refused:?}" - ); - } + assert!( + matches!( + named, + Some(VkLimit::MaxTaskSharedMemorySize) + | Some(VkLimit::MaxTaskPayloadAndSharedMemorySize) + ), + "{stem}: {refused:?}" + ); } // The task stage's limit: 76 bytes hold the wrapper's 12 and a 64-byte length, and a 65-byte // length, 80 rounded, is refused naming it. @@ -2561,118 +1977,3 @@ fn an_object_functions_threadgroup_memory_is_the_encoders_lengths() { "{stem} at 76: 65 bytes" ); } - -/// Under `VariantKey::mesh_last_first` an emulated mesh pipeline's synthesized vertex stage reads -/// each triangle's corner `(c + k - 1) mod k`, so the draw takes each primitive from its last -/// index first: one `OpIAdd` and one `OpUMod` more than the base's, valid, its plan stating the -/// variant (`RuntimeFact::MeshLastFirst`). A draw whose shape asks for it runs it -/// (`BindError::NeedsVariant` from the base), and the variant's plan of the default shape asks -/// for the base again. -#[test] -fn a_last_first_mesh_draw_reads_its_corners_from_the_last() { - use crate::bind::{BindState, DrawCall}; - use crate::budget::Budget; - use crate::error::BindError; - use crate::library::Library; - use crate::metal::PixelFormat; - use crate::pipeline::descriptor::{ - ColorAttachmentDescriptor, FunctionDescriptor, MeshPipelineDescriptor, StageSource, - }; - use crate::vk; - /// `OpIAdd` and `OpUMod`. - const ADD_MOD: [u32; 2] = [128, 137]; - let Some(draws) = fixture("mesh_draws") else { - return; - }; - let draws = Library::from_air(&draws).expect("library"); - let stage = |name: &str| { - StageSource::Function(FunctionDescriptor::new( - draws.function(name).expect("function"), - )) - }; - let budget = Budget::standard(); - let draw = DrawCall::MeshThreadgroups { - groups: [2, 1, 1], - threads_per_object_group: [1; 3], - threads_per_mesh_group: [8, 1, 1], - }; - let last_first = BindState { - mesh_last_first: true, - ..Default::default() - }; - for (stem, _) in emulating_profiles() { - let dev = device(&stem); - let mut d = MeshPipelineDescriptor::new(stage("mesh_draws_grid")); - d.fragment = Some(stage("mesh_draws_fragment")); - for slot in d.color_attachments.iter_mut().take(2) { - *slot = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Uint)); - } - let base = dev - .compile_mesh_pipeline(&d, &budget) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - let plan = base - .plan(&dev, &last_first.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert!(plan.variant.mesh_last_first, "{stem}"); - assert_eq!( - plan.instantiate_draw(&last_first, &draw), - Err(BindError::NeedsVariant { - variant: Box::new(plan.variant.clone()) - }), - "{stem}" - ); - let key = plan.variant.clone(); - let v = dev - .compile_mesh_variant(&d, &key, &budget) - .unwrap_or_else(|e| panic!("{stem}: {e}")); - for m in &v.stages { - check_words_valid(&m.spirv, &v.requirements, dev.profile()) - .unwrap_or_else(|e| panic!("{stem} {:?}: L3: {e}", m.stage)); - } - assert!( - v.dependencies - .iter() - .any(|x| x.fact == RuntimeFact::MeshLastFirst), - "{stem}" - ); - assert!( - !base - .dependencies - .iter() - .any(|x| x.fact == RuntimeFact::MeshLastFirst), - "{stem}" - ); - assert_ne!(v.key, base.key, "{stem}"); - let vertex = |p: &crate::pipeline::RenderPipeline| { - let m = p - .stages - .iter() - .find(|m| m.stage == vk::ShaderStage::VERTEX) - .expect("the synthesized vertex stage"); - opcodes(&m.spirv) - }; - let (a, b) = (vertex(&v), vertex(&base)); - for op in ADD_MOD { - let n = |ops: &[u32]| ops.iter().filter(|&&o| o == op).count(); - assert_eq!(n(&a), n(&b) + 1, "{stem}: opcode {op}"); - } - let plan = v - .plan(&dev, &last_first.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert_eq!(plan.variant, key, "{stem}"); - plan.instantiate_draw(&last_first, &draw) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - let plain = BindState::default(); - let plan = v - .plan(&dev, &plain.shape()) - .unwrap_or_else(|e| panic!("{stem}: {e:?}")); - assert!(!plan.variant.mesh_last_first, "{stem}"); - assert!( - matches!( - plan.instantiate_draw(&plain, &draw), - Err(BindError::NeedsVariant { .. }) - ), - "{stem}" - ); - } -} diff --git a/crates/metal2vulkan/src/tests/engine_mesh_barriers.rs b/crates/metal2vulkan/src/tests/engine_mesh_barriers.rs index 329c91999..e41b10411 100644 --- a/crates/metal2vulkan/src/tests/engine_mesh_barriers.rs +++ b/crates/metal2vulkan/src/tests/engine_mesh_barriers.rs @@ -3,36 +3,23 @@ //! The owned fixture `engine/mesh_partial_barrier` holds three object functions, whose barriers //! stand in uniform control flow and in a loop, after a divergent early return, and under a //! thread-dependent condition, and a mesh function that returns before its barrier. On every -//! committed profile, natively or emulated, each object function runs a `drawMeshThreads` partial -//! object threadgroup (`RuntimeFact::PartialObjectThreadgroups`) and is walked predicated from its -//! threadgroup's threads (`lower::simd::divergent`'s partial object threadgroups), the mesh function -//! is walked predicated for its divergent barrier, and no workgroup barrier of a body stands in a -//! block the body's own uniformity does not prove uniform (`spirv::testing::barriers`). On the -//! emulating profiles, whose object functions are compute entries, each object function runs on -//! the CPU interpreter under Vulkan's barrier rule (`BarrierRule::Vulkan`: an invocation that -//! returned while others wait at a barrier traps), in both scheduling orders, for draws that leave -//! partial threadgroups and for whole ones, giving the reading where the threads that reach a -//! barrier synchronize among themselves: Metal's threads alone count themselves and write, the -//! invocations past a partial threadgroup's threads writing nothing. No GPU is used. +//! committed profile with `VK_EXT_mesh_shader`, each object function runs a `drawMeshThreads` +//! partial object threadgroup (`RuntimeFact::PartialObjectThreadgroups`) and is walked predicated +//! from its threadgroup's threads (`lower::simd::divergent`'s partial object threadgroups), the mesh +//! function is walked predicated for its divergent barrier, and no workgroup barrier of a body +//! stands in a block the body's own uniformity does not prove uniform +//! (`spirv::testing::barriers`). No GPU is used. //! //! `llvm-as` assembles the fixtures; a missing tool skips visibly. -use std::collections::BTreeMap; - -use super::engine_mesh::{device, emulating_profiles, fixture, mesh_profiles}; +use super::engine_mesh::{device, fixture, mesh_profiles}; use crate::bind::{BindState, DrawCall}; use crate::budget::Budget; use crate::library::Library; -use crate::lower::mesh::{work, OBJECT_RECORDS_SLOT, OBJECT_WORK_SLOT}; -use crate::lower::select::Plan; use crate::pipeline::descriptor::{FunctionDescriptor, MeshPipelineDescriptor, StageSource}; use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::interface::PushLoc; -use crate::pipeline::sym::{ - Axis, PushField, ResourceKind, ResourceSlot, SpecKey, Stage, SyntheticBinding, -}; +use crate::pipeline::sym::Stage; use crate::pipeline::testing::typed_module; -use crate::spirv::interp::{run, BarrierRule, Buffer, Config, Order, Resources, SubgroupSize}; use crate::spirv::ir::{Inst, TypedModule}; use crate::spirv::testing::barriers::workgroup_barriers_of; @@ -46,12 +33,6 @@ const OBJECTS: [&str; 3] = [ /// The fixture's mesh function with a divergent barrier. const MESH: &str = "mesh_partial_barrier_mesh_early_return"; -/// The words of out a case's buffer starts as, but its count. -const POISON: u32 = 0xABAB_ABAB; - -/// The control words: the loop's trip count and the threads that stay past the early return. -const CTL: [u32; 4] = [3, 3, 0, 0]; - /// The function the entry of `m` calls: an object or mesh function's body, which its entry wrapper /// calls between its own barriers. fn body(m: &TypedModule) -> crate::spirv::ids::FuncId { @@ -78,11 +59,7 @@ fn object_and_mesh_functions_wait_at_their_barriers_predicated() { let Some(bc) = fixture("mesh_partial_barrier") else { return; }; - let profiles: Vec<_> = mesh_profiles() - .into_iter() - .chain(emulating_profiles()) - .collect(); - for (stem, p) in &profiles { + for (stem, p) in &mesh_profiles() { for entry in OBJECTS.into_iter().chain([MESH]) { let what = format!("{stem} {entry}"); let object = entry != MESH; @@ -121,7 +98,7 @@ fn object_and_mesh_functions_wait_at_their_barriers_predicated() { } /// An object function whose body waits at a threadgroup barrier draws a `drawMeshThreads` that -/// leaves a partial object threadgroup, emulated or not: its pipeline records +/// leaves a partial object threadgroup: its pipeline records /// `PartialObjectThreadgroups`, and both whole and partial draws instantiate, a partial one at the /// threadgroups its threads fill, rounded up. `icb_object_threadgroup_object`'s barriers stand /// under its thread 0's condition, the fixture's in uniform control flow. @@ -157,7 +134,7 @@ fn a_partial_object_threadgroup_of_a_body_with_a_barrier_draws() { threads_per_object_group: [4, 1, 1], threads_per_mesh_group: [8, 1, 1], }; - for (stem, _) in mesh_profiles().into_iter().chain(emulating_profiles()) { + for (stem, _) in mesh_profiles() { let dev = device(&stem); for (lib, object, mesh) in pipelines { let what = format!("{stem} {object}"); @@ -182,235 +159,15 @@ fn a_partial_object_threadgroup_of_a_body_with_a_barrier_draws() { let cmds = plan .instantiate_draw(&state, &draw([6, 1, 1])) .unwrap_or_else(|e| panic!("{what}: a partial object threadgroup: {e}")); - let groups = match (&cmds.mesh_dispatch, &cmds.draw) { - (Some(d), _) => d.object_groups, - ( - None, - crate::vk::DrawCommand::DrawMeshTasks { - group_count_x, - group_count_y, - group_count_z, - }, - ) => Some([*group_count_x, *group_count_y, *group_count_z]), - (None, other) => panic!("{what}: {other:?}"), + let groups = match &cmds.draw { + crate::vk::DrawCommand::DrawMeshTasks { + group_count_x, + group_count_y, + group_count_z, + } => [*group_count_x, *group_count_y, *group_count_z], + other => panic!("{what}: {other:?}"), }; - assert_eq!(groups, Some([2, 1, 1]), "{what}"); - } - } -} - -/// One draw: Metal's threads and its threads per object threadgroup. -#[derive(Clone, Copy, Debug)] -struct Draw { - threads: [u32; 2], - l: [u32; 2], -} - -/// The draws each object function runs: partial threadgroups along x, along both axes, past a -/// simdgroup, and whole ones. -const DRAWS: [Draw; 5] = [ - Draw { - threads: [6, 1], - l: [4, 1], - }, - Draw { - threads: [5, 3], - l: [4, 2], - }, - Draw { - threads: [37, 1], - l: [32, 1], - }, - Draw { - threads: [2, 1], - l: [4, 1], - }, - Draw { - threads: [8, 2], - l: [4, 2], - }, -]; - -/// The words of out after `draw` of object function `entry`, by the reading where the threads -/// that reach a barrier synchronize among themselves: every Metal thread counted in word 0, each -/// writing its two words at its grid position, the rest of the buffer untouched. -fn expected(entry: &str, draw: Draw) -> Vec { - let [tx, ty] = draw.threads; - let [lx, ly] = draw.l; - let mut out = vec![POISON; 4 + 2 * (tx * ty) as usize]; - out[0] = tx * ty; - for gy in 0..ty.div_ceil(ly) { - for gx in 0..tx.div_ceil(lx) { - // The threads this threadgroup runs, per axis. - let rx = (tx - gx * lx).min(lx); - let ry = (ty - gy * ly).min(ly); - let n = rx * ry; - let stay = CTL[1].min(n); - let mut words: Vec = (0..n).map(|t| t * 3 + 1).collect(); - let mut acc = vec![0u32; n as usize]; - for _ in 0..CTL[0] { - let next: Vec = (0..n).map(|t| words[((t + 1) % n) as usize]).collect(); - for t in 0..n as usize { - acc[t] += next[t]; - words[t] = next[t] + 100; - } - } - for y in 0..ry { - for x in 0..rx { - let tid = x + rx * y; - let (px, py) = (gx * lx + x, gy * ly + y); - let at = (4 + 2 * (px + tx * py)) as usize; - out[at] = match entry { - "mesh_partial_barrier_uniform" => { - acc[tid as usize] + words[((tid + 2) % n) as usize] - } - "mesh_partial_barrier_early_return" if tid >= stay => 0xE000_0000 | tid, - "mesh_partial_barrier_early_return" => ((tid + 1) % stay) * 3 + 1, - "mesh_partial_barrier_if" if tid < stay => ((tid + 1) % stay) * 5 + 2, - "mesh_partial_barrier_if" => 0xE100_0000 | tid, - other => panic!("no expectation for {other}"), - }; - out[at + 1] = rx | (ry << 8) | (tid << 16); - } - } - } - } - out -} - -fn bytes(w: &[u32]) -> Vec { - w.iter().flat_map(|x| x.to_le_bytes()).collect() -} - -fn words(b: &[u8]) -> Vec { - b.as_chunks::<4>() - .0 - .iter() - .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect() -} - -/// The out buffer after `draw` of the emulated object module `m` (planned as `plan`), every object -/// threadgroup its threads fill a workgroup of the whole size, the draw's region flagged -/// `lower::dispatch::NONUNIFORM` as the binder flags a `drawMeshThreads`, with `lanes`-wide -/// subgroups under Vulkan's barrier rule, identical in both scheduling orders. -fn run_draw(plan: &Plan, m: &TypedModule, draw: Draw, lanes: SubgroupSize) -> Vec { - let [tx, ty] = draw.threads; - let [lx, ly] = draw.l; - let groups = [tx.div_ceil(lx), ty.div_ceil(ly), 1]; - let mut spec = BTreeMap::new(); - for (a, v) in [Axis::X, Axis::Y, Axis::Z].into_iter().zip([lx, ly, 1]) { - spec.insert(SpecKey::ObjectLocalSize(a), u64::from(v)); - } - spec.insert(SpecKey::ObjectFlatLocalSize, u64::from(lx * ly)); - spec.insert(SpecKey::ObjectMultiRegion, 1); - let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; - // The fields a profile's push window has no room for: every offset word 0. - let mut table = vec![0u8; plan.push.argument_table_size.max(4) as usize]; - for f in &plan.push.fields { - match (f.field, f.loc) { - (PushField::DispatchRegion, loc) => { - let region = crate::lower::dispatch::partial_region_bytes([tx, ty, 1], [lx, ly, 1]) - .expect("a region"); - let (words, at) = match loc { - PushLoc::Push { offset } => (&mut push, offset as usize), - PushLoc::ArgumentTable { offset } => (&mut table, offset as usize), - }; - words[at..at + region.len()].copy_from_slice(®ion); - } - // Every buffer is bound at offset 0, wherever its offset word is placed. - (PushField::SlotBindOffset(_), _) => {} - other => panic!("unexpected push field {other:?}"), - } - } - let slot = |index| { - Some(ResourceSlot { - stage: Stage::Object, - kind: ResourceKind::Buffer, - index, - }) - }; - let objects = u64::from(groups[0] * groups[1]); - let slot_words = work::GRID + plan.families.mesh.payload_words; - let mut header = vec![0u32; work::words(objects, slot_words) as usize]; - header[work::SLOT_WORDS as usize] = slot_words; - header[work::OBJECT_GROUPS as usize] = u32::try_from(objects).expect("a word"); - let mut out = vec![POISON; 4 + 2 * (tx * ty) as usize]; - out[0] = 0; - let res = Resources { - buffers: vec![ - Buffer { - slot: slot(0), - address: None, - bytes: bytes(&out), - }, - Buffer { - slot: slot(1), - address: None, - bytes: bytes(&CTL), - }, - Buffer { - slot: Some(OBJECT_WORK_SLOT), - address: None, - bytes: bytes(&header), - }, - Buffer { - slot: Some(OBJECT_RECORDS_SLOT), - address: None, - bytes: bytes(&[0; 4]), - }, - Buffer { - slot: Some(ResourceSlot { - stage: Stage::Object, - kind: ResourceKind::Synthetic(SyntheticBinding::ArgumentTable), - index: 0, - }), - address: None, - bytes: table, - }, - ], - push, - spec, - }; - let mut outs = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let cfg = Config { - workgroups: groups, - subgroup: lanes, - order, - barriers: BarrierRule::Vulkan, - ..Config::default() - }; - let o = run(m, &cfg, res.clone()).unwrap_or_else(|e| panic!("{draw:?} {lanes:?}: {e}")); - outs.push(o.buffers); - } - assert_eq!( - outs[0][0], outs[1][0], - "{draw:?} {lanes:?}: order independent" - ); - words(&outs[0][0]) -} - -/// Each object function of the fixture, compiled as a compute entry on every emulating profile, -/// runs each of [`DRAWS`] on the interpreter under Vulkan's barrier rule and answers the reading -/// where the threads that reach a barrier synchronize among themselves: the invocations past a -/// partial threadgroup's threads reach every barrier, count nothing and write nothing. -#[test] -fn partial_object_threadgroups_wait_at_barriers_as_metal_runs_them() { - let Some(bc) = fixture("mesh_partial_barrier") else { - return; - }; - for (stem, p) in emulating_profiles() { - for entry in OBJECTS { - let what = format!("{stem} {entry}"); - let (plan, m) = typed_module(&bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - assert!(plan.families.mesh.emulated, "{what}: a compute entry"); - for draw in DRAWS { - for lanes in [SubgroupSize::W8, SubgroupSize::W32] { - let got = run_draw(&plan, &m, draw, lanes); - assert_eq!(got, expected(entry, draw), "{what} {draw:?} {lanes:?}"); - } - } + assert_eq!(groups, [2, 1, 1], "{what}"); } } } diff --git a/crates/metal2vulkan/src/tests/owned_divisions.rs b/crates/metal2vulkan/src/tests/owned_divisions.rs index 9694801ce..d2e46215b 100644 --- a/crates/metal2vulkan/src/tests/owned_divisions.rs +++ b/crates/metal2vulkan/src/tests/owned_divisions.rs @@ -29,8 +29,6 @@ fn modules() -> Vec { plain!( index_bounds_fill_module, index_bounds_plan_module, - mesh_object_arguments_module, - mesh_scan_module, replay_preprocess_module, ycbcr_write_module, ); diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 13def4cdf..c9f628e5c 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -124,16 +124,6 @@ assoc-const metal2vulkan::bind::MeshArgumentsModule::SCRATCH_BINDING pub const S assoc-const metal2vulkan::bind::MeshArgumentsModule::SET pub const SET: u32 assoc-const metal2vulkan::bind::MeshArgumentsModule::SOURCE_BINDING pub const SOURCE_BINDING: u32 assoc-const metal2vulkan::bind::MeshArgumentsModule::STATUS_BINDING pub const STATUS_BINDING: u32 -assoc-const metal2vulkan::bind::MeshDispatch::DISPATCH_OFFSET pub const DISPATCH_OFFSET: u64 -assoc-const metal2vulkan::bind::MeshDispatch::DRAW_ID pub const DRAW_ID: usize -assoc-const metal2vulkan::bind::MeshDispatch::DRAW_OFFSET pub const DRAW_OFFSET: u64 -assoc-const metal2vulkan::bind::MeshDispatch::POOL_WORDS pub const POOL_WORDS: usize -assoc-const metal2vulkan::bind::MeshScanModule::ARGUMENTS_BINDING pub const ARGUMENTS_BINDING: u32 -assoc-const metal2vulkan::bind::MeshScanModule::LOCAL_SIZE pub const LOCAL_SIZE: u32 -assoc-const metal2vulkan::bind::MeshScanModule::RECORDS_BINDING pub const RECORDS_BINDING: u32 -assoc-const metal2vulkan::bind::MeshScanModule::SET pub const SET: u32 -assoc-const metal2vulkan::bind::MeshScanModule::STATUS_BINDING pub const STATUS_BINDING: u32 -assoc-const metal2vulkan::bind::MeshScanModule::WORK_BINDING pub const WORK_BINDING: u32 assoc-const metal2vulkan::bind::NeutralResource::SINK_BYTES pub const SINK_BYTES: u32 assoc-const metal2vulkan::bind::PlanesCopy::ALL pub const ALL: [PlanesCopy; 6] assoc-const metal2vulkan::bind::PlanesMergeModules::PLANES_BINDING pub const PLANES_BINDING: u32 @@ -168,10 +158,9 @@ assoc-const metal2vulkan::bind::StatusBits::CUBIC_ARGUMENT_SAMPLER pub const CUB assoc-const metal2vulkan::bind::StatusBits::INDEX_POOL_OVERFLOW pub const INDEX_POOL_OVERFLOW: StatusBits assoc-const metal2vulkan::bind::StatusBits::MESH_GRID_DISCARDED pub const MESH_GRID_DISCARDED: StatusBits assoc-const metal2vulkan::bind::StatusBits::MESH_GRID_PAST_LIMITS pub const MESH_GRID_PAST_LIMITS: StatusBits -assoc-const metal2vulkan::bind::StatusBits::MESH_RECORDS_OVERFLOW pub const MESH_RECORDS_OVERFLOW: StatusBits assoc-const metal2vulkan::bind::StatusBits::REPLAY_FAULT pub const REPLAY_FAULT: StatusBits assoc-const metal2vulkan::bind::StatusBits::RESIDENT_MISS pub const RESIDENT_MISS: StatusBits -assoc-const metal2vulkan::bind::StatusWord::ALL pub const ALL: [StatusWord; 8] +assoc-const metal2vulkan::bind::StatusWord::ALL pub const ALL: [StatusWord; 4] assoc-const metal2vulkan::bind::StencilBit::ALL pub const ALL: [StencilBit; 8] assoc-const metal2vulkan::bind::StencilSplitModule::DESTINATION_BINDING pub const DESTINATION_BINDING: u32 assoc-const metal2vulkan::bind::StencilSplitModule::LOCAL_SIZE pub const LOCAL_SIZE: u32 @@ -401,16 +390,6 @@ assoc-const-value metal2vulkan::bind::MeshArgumentsModule::SCRATCH_BINDING 1 assoc-const-value metal2vulkan::bind::MeshArgumentsModule::SET 0 assoc-const-value metal2vulkan::bind::MeshArgumentsModule::SOURCE_BINDING 0 assoc-const-value metal2vulkan::bind::MeshArgumentsModule::STATUS_BINDING 2 -assoc-const-value metal2vulkan::bind::MeshDispatch::DISPATCH_OFFSET 4 * crate::lower::mesh::work::DISPATCH as u64 -assoc-const-value metal2vulkan::bind::MeshDispatch::DRAW_ID crate::lower::mesh::work::DRAW_ID as usize -assoc-const-value metal2vulkan::bind::MeshDispatch::DRAW_OFFSET 4 * crate::lower::mesh::work::DRAW as u64 -assoc-const-value metal2vulkan::bind::MeshDispatch::POOL_WORDS crate::lower::mesh::work::POOL_WORDS as usize -assoc-const-value metal2vulkan::bind::MeshScanModule::ARGUMENTS_BINDING 2 -assoc-const-value metal2vulkan::bind::MeshScanModule::LOCAL_SIZE 64 -assoc-const-value metal2vulkan::bind::MeshScanModule::RECORDS_BINDING 3 -assoc-const-value metal2vulkan::bind::MeshScanModule::SET 0 -assoc-const-value metal2vulkan::bind::MeshScanModule::STATUS_BINDING 1 -assoc-const-value metal2vulkan::bind::MeshScanModule::WORK_BINDING 0 assoc-const-value metal2vulkan::bind::NeutralResource::SINK_BYTES 64 assoc-const-value metal2vulkan::bind::PlanesCopy::ALL [PlanesCopy::R8, PlanesCopy::R16, PlanesCopy::R32, PlanesCopy::Rg32, PlanesCopy::Rgba32, PlanesCopy::Alpha8] assoc-const-value metal2vulkan::bind::PlanesMergeModules::PLANES_BINDING 0 @@ -445,10 +424,9 @@ assoc-const-value metal2vulkan::bind::StatusBits::CUBIC_ARGUMENT_SAMPLER StatusB assoc-const-value metal2vulkan::bind::StatusBits::INDEX_POOL_OVERFLOW StatusBits(1 <<3) assoc-const-value metal2vulkan::bind::StatusBits::MESH_GRID_DISCARDED StatusBits(1 <<10) assoc-const-value metal2vulkan::bind::StatusBits::MESH_GRID_PAST_LIMITS StatusBits(1 <<9) -assoc-const-value metal2vulkan::bind::StatusBits::MESH_RECORDS_OVERFLOW StatusBits(1 <<5) assoc-const-value metal2vulkan::bind::StatusBits::REPLAY_FAULT StatusBits(1 <<2) assoc-const-value metal2vulkan::bind::StatusBits::RESIDENT_MISS StatusBits(1 <<1) -assoc-const-value metal2vulkan::bind::StatusWord::ALL [StatusWord::Status, StatusWord::ResidentMisses, StatusWord::ReplayFaults, StatusWord::MeshRecordsCursor, StatusWord::MeshFaultDraw, StatusWord::MeshFaultObjects, StatusWord::MeshFaultGroups, StatusWord::SeqCstFences] +assoc-const-value metal2vulkan::bind::StatusWord::ALL [StatusWord::Status, StatusWord::ResidentMisses, StatusWord::ReplayFaults, StatusWord::SeqCstFences] assoc-const-value metal2vulkan::bind::StencilBit::ALL [StencilBit(0), StencilBit(1), StencilBit(2), StencilBit(3), StencilBit(4), StencilBit(5), StencilBit(6), StencilBit(7)] assoc-const-value metal2vulkan::bind::StencilSplitModule::DESTINATION_BINDING 1 assoc-const-value metal2vulkan::bind::StencilSplitModule::LOCAL_SIZE 8 @@ -946,8 +924,6 @@ enum metal2vulkan::bind::IndexOverrun #[cfg_attr(feature = "serde", derive(serde enum metal2vulkan::bind::IndirectArgs #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum IndirectArgs enum metal2vulkan::bind::MergePhase #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum MergePhase enum metal2vulkan::bind::MeshArgumentsForm #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum MeshArgumentsForm -enum metal2vulkan::bind::MeshGroups #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum MeshGroups -enum metal2vulkan::bind::MeshRecordsRegion #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum MeshRecordsRegion enum metal2vulkan::bind::NeutralResource #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum NeutralResource enum metal2vulkan::bind::PlanDiagnostic #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum PlanDiagnostic enum metal2vulkan::bind::PlanesCopy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum PlanesCopy @@ -1073,7 +1049,6 @@ enum metal2vulkan::pipeline::PrecisionNote #[cfg_attr(feature = "serde", derive( enum metal2vulkan::pipeline::PushField #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum PushField enum metal2vulkan::pipeline::PushLoc #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum PushLoc enum metal2vulkan::pipeline::Reconvergence #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Reconvergence -enum metal2vulkan::pipeline::RecordValue #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum RecordValue enum metal2vulkan::pipeline::RegionFanOut #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum RegionFanOut enum metal2vulkan::pipeline::ResourceKind #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ResourceKind enum metal2vulkan::pipeline::RotatedBlendForm #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum RotatedBlendForm @@ -2103,7 +2078,6 @@ field metal2vulkan::bind::BindShape.imageblock_size pub imageblock_size: Imagebl field metal2vulkan::bind::BindShape.interlocked_colors pub interlocked_colors: BTreeSet field metal2vulkan::bind::BindShape.kept_imageblock_bytes pub kept_imageblock_bytes: Option field metal2vulkan::bind::BindShape.line_band pub line_band: Option -field metal2vulkan::bind::BindShape.mesh_last_first pub mesh_last_first: bool field metal2vulkan::bind::BindShape.primitive_id_indices pub primitive_id_indices: Option field metal2vulkan::bind::BindShape.private_list pub private_list: bool field metal2vulkan::bind::BindShape.quad_primitive_ids pub quad_primitive_ids: bool @@ -2136,7 +2110,6 @@ field metal2vulkan::bind::BindState.imageblock_size pub imageblock_size: Imagebl field metal2vulkan::bind::BindState.interlocked_colors pub interlocked_colors: BTreeSet field metal2vulkan::bind::BindState.kept_imageblock_bytes pub kept_imageblock_bytes: Option field metal2vulkan::bind::BindState.line_band pub line_band: Option<(crate::pipeline::BandPrimitive, [f32; 4])> -field metal2vulkan::bind::BindState.mesh_last_first pub mesh_last_first: bool field metal2vulkan::bind::BindState.primitive_id_indices pub primitive_id_indices: Option field metal2vulkan::bind::BindState.primitive_type pub primitive_type: Option field metal2vulkan::bind::BindState.private_list pub private_list: bool @@ -2232,7 +2205,6 @@ field metal2vulkan::bind::DrawCommands.index_bounds_pass pub index_bounds_pass: field metal2vulkan::bind::DrawCommands.index_overrun pub index_overrun: Option field metal2vulkan::bind::DrawCommands.indirect_needs_arguments pub indirect_needs_arguments: bool field metal2vulkan::bind::DrawCommands.mesh_arguments pub mesh_arguments: Option -field metal2vulkan::bind::DrawCommands.mesh_dispatch pub mesh_dispatch: Option field metal2vulkan::bind::DrawCommands.object_fold pub object_fold: Option field metal2vulkan::bind::DrawCommands.push_constants pub push_constants: Vec field metal2vulkan::bind::DrawCommands.push_holes pub push_holes: Vec @@ -2341,21 +2313,10 @@ field metal2vulkan::bind::MeshArguments.source_range pub source_range: BufferRan field metal2vulkan::bind::MeshArgumentsModule.requirements pub requirements: Requirements field metal2vulkan::bind::MeshArgumentsModule.rule pub rule: MeshGridRule field metal2vulkan::bind::MeshArgumentsModule.spirv pub spirv: Arc<[u32]> -field metal2vulkan::bind::MeshDispatch.mesh pub mesh: MeshGroups -field metal2vulkan::bind::MeshDispatch.object_arguments pub object_arguments: Option -field metal2vulkan::bind::MeshDispatch.object_groups pub object_groups: Option<[u32; 3]> -field metal2vulkan::bind::MeshDispatch.records pub records: MeshRecordsRegion -field metal2vulkan::bind::MeshDispatch.work pub work: Vec -field metal2vulkan::bind::MeshDispatch.work_bytes pub work_bytes: u64 field metal2vulkan::bind::MeshGridLimits.axes pub axes: [u32; 3] field metal2vulkan::bind::MeshGridLimits.total pub total: u32 field metal2vulkan::bind::MeshGridRule.device pub device: MeshGridLimits field metal2vulkan::bind::MeshGridRule.metal pub metal: Option -field metal2vulkan::bind::MeshRecordsFault.draw pub draw: u32 -field metal2vulkan::bind::MeshRecordsFault.mesh_threadgroups pub mesh_threadgroups: u32 -field metal2vulkan::bind::MeshRecordsFault.object_threadgroups pub object_threadgroups: u32 -field metal2vulkan::bind::MeshScanModule.requirements pub requirements: Requirements -field metal2vulkan::bind::MeshScanModule.spirv pub spirv: Arc<[u32]> field metal2vulkan::bind::MetalInstance.intersection_function_table_offset pub intersection_function_table_offset: u32 field metal2vulkan::bind::MetalInstance.mask pub mask: u32 field metal2vulkan::bind::MetalInstance.options pub options: u32 @@ -2486,7 +2447,6 @@ field metal2vulkan::bind::StatusReport.cubic_argument_sampler pub cubic_argument field metal2vulkan::bind::StatusReport.index_pool_overflow pub index_pool_overflow: bool field metal2vulkan::bind::StatusReport.mesh_grid_discarded pub mesh_grid_discarded: bool field metal2vulkan::bind::StatusReport.mesh_grid_past_limits pub mesh_grid_past_limits: bool -field metal2vulkan::bind::StatusReport.mesh_records_overflow pub mesh_records_overflow: Option field metal2vulkan::bind::StatusReport.replay_fault pub replay_fault: bool field metal2vulkan::bind::StatusReport.replay_faults pub replay_faults: ReplayFaults field metal2vulkan::bind::StatusReport.resident_miss pub resident_miss: bool @@ -2600,7 +2560,6 @@ field metal2vulkan::cache::VariantKey.interlocked_colors pub interlocked_colors: field metal2vulkan::cache::VariantKey.kept_imageblock_bytes pub kept_imageblock_bytes: Option field metal2vulkan::cache::VariantKey.line_band pub line_band: Option field metal2vulkan::cache::VariantKey.merged_draws pub merged_draws: bool -field metal2vulkan::cache::VariantKey.mesh_last_first pub mesh_last_first: bool field metal2vulkan::cache::VariantKey.one_row pub one_row: bool field metal2vulkan::cache::VariantKey.open_cl_lines pub open_cl_lines: BTreeSet field metal2vulkan::cache::VariantKey.partial_threadgroups pub partial_threadgroups: bool @@ -3106,8 +3065,6 @@ field metal2vulkan::pipeline::GraphicsState.interpolates_at_sample pub interpola field metal2vulkan::pipeline::GraphicsState.line_band pub line_band: Option field metal2vulkan::pipeline::GraphicsState.logic_op pub logic_op: Option field metal2vulkan::pipeline::GraphicsState.max_vertex_amplification_count pub max_vertex_amplification_count: u32 -field metal2vulkan::pipeline::GraphicsState.mesh_corners pub mesh_corners: Option -field metal2vulkan::pipeline::GraphicsState.mesh_records pub mesh_records: Option field metal2vulkan::pipeline::GraphicsState.rasterization_order_attachment_access pub rasterization_order_attachment_access: bool field metal2vulkan::pipeline::GraphicsState.rasterization_samples pub rasterization_samples: vk::SampleCountFlags field metal2vulkan::pipeline::GraphicsState.rasterizer_discard pub rasterizer_discard: bool @@ -3256,13 +3213,6 @@ field metal2vulkan::pipeline::MeshPipelineMetalInfo.max_total_threads_per_mesh_t field metal2vulkan::pipeline::MeshPipelineMetalInfo.max_total_threads_per_object_threadgroup pub max_total_threads_per_object_threadgroup: u32 field metal2vulkan::pipeline::MeshPipelineMetalInfo.mesh_thread_execution_width pub mesh_thread_execution_width: u32 field metal2vulkan::pipeline::MeshPipelineMetalInfo.object_thread_execution_width pub object_thread_execution_width: u32 -field metal2vulkan::pipeline::MeshRecords.corners pub corners: u32 -field metal2vulkan::pipeline::MeshRecords.fields pub fields: Vec -field metal2vulkan::pipeline::MeshRecords.primitive_words pub primitive_words: u32 -field metal2vulkan::pipeline::MeshRecords.primitives pub primitives: u32 -field metal2vulkan::pipeline::MeshRecords.slot_words pub slot_words: u32 -field metal2vulkan::pipeline::MeshRecords.vertex_words pub vertex_words: u32 -field metal2vulkan::pipeline::MeshRecords.vertices pub vertices: u32 field metal2vulkan::pipeline::ModuleStats.blocks pub blocks: u32 field metal2vulkan::pipeline::ModuleStats.constructs pub constructs: u32 field metal2vulkan::pipeline::ModuleStats.functions pub functions: u32 @@ -3620,8 +3570,6 @@ fn metal2vulkan::bind::instance_record pub fn instance_record(instance: &MetalIn fn metal2vulkan::bind::interleave_merge_modules pub fn interleave_merge_modules(device: &Device, samples: u32) -> Result fn metal2vulkan::bind::interleave_split_module pub fn interleave_split_module(device: &Device, copy: PlanesCopy, samples: u32) -> Result fn metal2vulkan::bind::mesh_arguments_module pub fn mesh_arguments_module(device: &Device, form: MeshArgumentsForm) -> Result -fn metal2vulkan::bind::mesh_object_arguments_module pub fn mesh_object_arguments_module(device: &Device) -> Result -fn metal2vulkan::bind::mesh_scan_module pub fn mesh_scan_module(device: &Device) -> Result fn metal2vulkan::bind::metal_object_grid pub fn metal_object_grid(groups: [u32; 3], threads: [u32; 3], direct: bool) -> Option<([u32; 3], [u32; 3])> fn metal2vulkan::bind::part_texels pub fn part_texels(limits: &Limits) -> u64 fn metal2vulkan::bind::planes_merge_modules pub fn planes_merge_modules(device: &Device, copy: PlanesCopy) -> Result @@ -7545,9 +7493,6 @@ method metal2vulkan::pipeline::MeshPipelineDescriptor::reflection pub fn reflect method metal2vulkan::pipeline::MeshPipelineDescriptor::slot_writes pub fn slot_writes(&self, budget: &crate::Budget) -> Result method metal2vulkan::pipeline::MeshPipelineDescriptor::stages_using_direct_arguments pub fn stages_using_direct_arguments(&self, budget: &crate::Budget, entries: &StageEntries) -> Result, Error> method metal2vulkan::pipeline::MeshPipelineDescriptor::unwritten_fragment_inputs pub fn unwritten_fragment_inputs(&self, budget: &crate::Budget, entries: &StageEntries) -> Result, Error> -method metal2vulkan::pipeline::MeshRecords::group_words pub fn group_words(&self) -> u64 -method metal2vulkan::pipeline::MeshRecords::primitive_base pub fn primitive_base(&self) -> u64 -method metal2vulkan::pipeline::MeshRecords::topology pub fn topology(&self) -> vk::PrimitiveTopology method metal2vulkan::pipeline::PrecisionNote::of_float_operator pub fn of_float_operator(op: AirBin, width: FloatWidth, fmf: FastMath, p: &DeviceProfile, math: EntryMath) -> Option> method metal2vulkan::pipeline::PrecisionNote::of_math_call pub fn of_math_call(call: Math, fmf: FastMath, p: &DeviceProfile, math: EntryMath) -> Option> method metal2vulkan::pipeline::PrivateRenderState::new pub const fn new() -> PrivateRenderState @@ -7977,11 +7922,8 @@ struct metal2vulkan::bind::InterleaveSplitModule #[derive(Clone, Debug, PartialE struct metal2vulkan::bind::MergedLayout #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct MergedLayout struct metal2vulkan::bind::MeshArguments #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct MeshArguments struct metal2vulkan::bind::MeshArgumentsModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct MeshArgumentsModule -struct metal2vulkan::bind::MeshDispatch #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct MeshDispatch struct metal2vulkan::bind::MeshGridLimits #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct MeshGridLimits struct metal2vulkan::bind::MeshGridRule #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct MeshGridRule -struct metal2vulkan::bind::MeshRecordsFault #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct MeshRecordsFault -struct metal2vulkan::bind::MeshScanModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct MeshScanModule struct metal2vulkan::bind::MetalInstance #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct MetalInstance struct metal2vulkan::bind::ObjectFold #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ObjectFold struct metal2vulkan::bind::PlanesMergeModules #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct PlanesMergeModules @@ -8145,7 +8087,6 @@ struct metal2vulkan::pipeline::LinkedSource #[derive(Clone, Copy, Debug)] pub st struct metal2vulkan::pipeline::LoweringInputs #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct LoweringInputs struct metal2vulkan::pipeline::MeshPipelineDescriptor #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct MeshPipelineDescriptor struct metal2vulkan::pipeline::MeshPipelineMetalInfo #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct MeshPipelineMetalInfo -struct metal2vulkan::pipeline::MeshRecords #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct MeshRecords struct metal2vulkan::pipeline::ModuleStats #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ModuleStats struct metal2vulkan::pipeline::PipelineInterface #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct PipelineInterface struct metal2vulkan::pipeline::PipelineLayout #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct PipelineLayout @@ -9875,7 +9816,6 @@ variant metal2vulkan::bind::DrawCall::Primitives Primitives { vertex_start: u32, variant metal2vulkan::bind::DrawReplayRule::Amplified Amplified variant metal2vulkan::bind::DrawReplayRule::ArgumentsOnCpu ArgumentsOnCpu variant metal2vulkan::bind::DrawReplayRule::CommandTypes CommandTypes -variant metal2vulkan::bind::DrawReplayRule::DispatchesFirst DispatchesFirst variant metal2vulkan::bind::DrawReplayRule::FragmentImageblock FragmentImageblock variant metal2vulkan::bind::DrawReplayRule::FragmentWritesMemory FragmentWritesMemory variant metal2vulkan::bind::DrawReplayRule::IndexBounds IndexBounds @@ -9935,10 +9875,6 @@ variant metal2vulkan::bind::MergePhase::Starts Starts variant metal2vulkan::bind::MeshArgumentsForm::FoldedObject FoldedObject variant metal2vulkan::bind::MeshArgumentsForm::Mesh Mesh variant metal2vulkan::bind::MeshArgumentsForm::Object Object -variant metal2vulkan::bind::MeshGroups::Direct Direct([u32; 3]) -variant metal2vulkan::bind::MeshGroups::Scanned Scanned { arguments: Option } -variant metal2vulkan::bind::MeshRecordsRegion::Exact Exact(u64) -variant metal2vulkan::bind::MeshRecordsRegion::Pool Pool variant metal2vulkan::bind::NeutralResource::Image Image { view_type: vk::ImageViewType, sampled_type: SampledType, depth_compare: bool, samples: u32, storage_format: Option } variant metal2vulkan::bind::NeutralResource::Sampler Sampler { compare: bool } variant metal2vulkan::bind::NeutralResource::Sink Sink { min_bytes: u32 } @@ -10022,10 +9958,6 @@ variant metal2vulkan::bind::RewriteSource::IndirectVertices IndirectVertices { a variant metal2vulkan::bind::SamplerSource::Immutable Immutable variant metal2vulkan::bind::SamplerSource::Neutral Neutral(NeutralResource) variant metal2vulkan::bind::SamplerSource::Slot Slot { slot: SlotRef, compare: bool, integer: bool, opaque_black: OpaqueBlackBorder } -variant metal2vulkan::bind::StatusWord::MeshFaultDraw MeshFaultDraw -variant metal2vulkan::bind::StatusWord::MeshFaultGroups MeshFaultGroups -variant metal2vulkan::bind::StatusWord::MeshFaultObjects MeshFaultObjects -variant metal2vulkan::bind::StatusWord::MeshRecordsCursor MeshRecordsCursor variant metal2vulkan::bind::StatusWord::ReplayFaults ReplayFaults variant metal2vulkan::bind::StatusWord::ResidentMisses ResidentMisses variant metal2vulkan::bind::StatusWord::SeqCstFences SeqCstFences @@ -10071,8 +10003,6 @@ variant metal2vulkan::bind::WriteSource::HandleTable HandleTable { stage: Stage, variant metal2vulkan::bind::WriteSource::HeapEntry HeapEntry { class: HandleClass, element: u32, source: HeapSource, view: ImageViewDesc } variant metal2vulkan::bind::WriteSource::Imageblock Imageblock variant metal2vulkan::bind::WriteSource::InlineBytes InlineBytes { slot: SlotRef } -variant metal2vulkan::bind::WriteSource::MeshRecords MeshRecords -variant metal2vulkan::bind::WriteSource::MeshWork MeshWork variant metal2vulkan::bind::WriteSource::Neutral Neutral(NeutralResource) variant metal2vulkan::bind::WriteSource::PatchIndices PatchIndices { min_bytes: u32 } variant metal2vulkan::bind::WriteSource::RateMapFlags RateMapFlags @@ -11373,13 +11303,6 @@ variant metal2vulkan::pipeline::PushLoc::ArgumentTable ArgumentTable { offset: u variant metal2vulkan::pipeline::PushLoc::Push Push { offset: u32 } variant metal2vulkan::pipeline::Reconvergence::Guaranteed Guaranteed variant metal2vulkan::pipeline::Reconvergence::ImplementationDefined ImplementationDefined -variant metal2vulkan::pipeline::RecordValue::ClipDistance ClipDistance -variant metal2vulkan::pipeline::RecordValue::Culled Culled -variant metal2vulkan::pipeline::RecordValue::Layer Layer -variant metal2vulkan::pipeline::RecordValue::PointSize PointSize -variant metal2vulkan::pipeline::RecordValue::Position Position -variant metal2vulkan::pipeline::RecordValue::Varying Varying(crate::pipeline::sym::VaryingKey) -variant metal2vulkan::pipeline::RecordValue::ViewportIndex ViewportIndex variant metal2vulkan::pipeline::RegionFanOut::Draw Draw variant metal2vulkan::pipeline::RegionFanOut::DrawFew DrawFew variant metal2vulkan::pipeline::RegionFanOut::Probe Probe @@ -11447,7 +11370,6 @@ variant metal2vulkan::pipeline::RuntimeFact::InterlockedFramebufferFetch Interlo variant metal2vulkan::pipeline::RuntimeFact::LocalSizeConstraint LocalSizeConstraint { multiple: u32 } variant metal2vulkan::pipeline::RuntimeFact::LocalSizeLimits LocalSizeLimits variant metal2vulkan::pipeline::RuntimeFact::MergedDraws MergedDraws -variant metal2vulkan::pipeline::RuntimeFact::MeshLastFirst MeshLastFirst variant metal2vulkan::pipeline::RuntimeFact::MovableStorageWrites MovableStorageWrites { early_variant: bool } variant metal2vulkan::pipeline::RuntimeFact::ObjectThreadgroupArena ObjectThreadgroupArena { static_bytes: u32, payload: Option } variant metal2vulkan::pipeline::RuntimeFact::OneRow OneRow @@ -11619,8 +11541,6 @@ variant metal2vulkan::pipeline::SyntheticBinding::FunctionTableDirectory Functio variant metal2vulkan::pipeline::SyntheticBinding::FunctionTableSnapshot FunctionTableSnapshot variant metal2vulkan::pipeline::SyntheticBinding::HandleTable HandleTable variant metal2vulkan::pipeline::SyntheticBinding::Imageblock Imageblock -variant metal2vulkan::pipeline::SyntheticBinding::MeshRecords MeshRecords -variant metal2vulkan::pipeline::SyntheticBinding::MeshWork MeshWork variant metal2vulkan::pipeline::SyntheticBinding::PatchIndices PatchIndices variant metal2vulkan::pipeline::SyntheticBinding::RateMapFlags RateMapFlags variant metal2vulkan::pipeline::SyntheticBinding::RateMapRegions RateMapRegions diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index a5105b988..c649ce8bf 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -380,15 +380,12 @@ surface! { struct CommandWrites E; enum DescriptorView N; struct LevelReads N; - struct MeshRecords N; enum NumberedSampler N; enum PatchDomain N; struct PipelineInterface N; struct PlacedField N; enum PushLoc N; struct PushPlacement N; - struct RecordField N; - enum RecordValue N; struct SampledLevels N; struct SamplerArray N; struct SamplerLevels N; @@ -468,9 +465,6 @@ surface! { struct DrawCommands N; fn alpha_test_code; enum IndexOverrun N; - struct MeshDispatch N; - enum MeshGroups N; - enum MeshRecordsRegion N; fn heap_classes; struct HeapElements O; enum HeapSource E; @@ -547,7 +541,6 @@ surface! { struct TileThreadgroupArgument N; enum FragmentTests N; struct ExecutionStatus E; - struct MeshRecordsFault N; struct StatusBits E; struct StatusReport N; enum StatusWord N; @@ -626,9 +619,6 @@ surface! { enum EtcDecode N; enum EtcTexels N; enum ChromaDecode N; - fn mesh_scan_module; - fn mesh_object_arguments_module; - struct MeshScanModule N; fn mesh_arguments_module; fn fold_object_grid; fn metal_object_grid; diff --git a/docs/API.md b/docs/API.md index 1d3220897..7bcab5b6c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -594,8 +594,8 @@ through buffer arguments it reads at any index. threadgroup memory on a profile without it is `Unsupported` with `Feature::ZeroedThreadgroupMemory`. The translator's own `Workgroup` words have none: an emulated SIMD group's exchange scratch and vote word, an object function's mesh grid, a mesh - function's primitive count and staged indices, an emulated object or mesh function's payload, - and those of the binder's own scan, shadow-merge and index-rewrite kernels. Each is written + function's primitive count and staged indices, and those of the binder's own shadow-merge and + index-rewrite kernels. Each is written before any read of it, and an object function's payload "is assumed uninitialized at the entry of the object function" (the Metal Shading Language Specification, the `payload` attribute). Metal's documents give threadgroup memory no first contents: `MTLComputeCommandEncoder.h`'s @@ -874,7 +874,7 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: function that selects its slice is refused needing either feature (its pass of one layer still runs), and so is one that selects its viewport on a device with `multiViewport`; one whose index differs among a primitive's vertices is refused needing `geometryShader`. The stages cannot serve - a post-tessellation vertex function or an emulated mesh function, nor sit beside a vertex function + a post-tessellation vertex function, nor sit beside a vertex function that writes the builtins itself (a device with the outputs but without `fragmentShaderBarycentric`): those are refused as not implemented. A fragment function that reads an index no stage writes, on a device that can declare neither builtin, reads 0, Metal's value @@ -972,16 +972,16 @@ the feature), and a fragment `[[primitive_id]]` behind it is `NotImplemented(Tes `Device::compile_mesh_pipeline` compiles a `MeshPipelineDescriptor` (an optional object function, a mesh function and a fragment function), and `compile_mesh_variant` its variants. Its plan draws -mesh draws only (`DrawCall::MeshThreadgroups`, `MeshThreads` and their indirect forms). With -`VK_EXT_mesh_shader` the stages are task and mesh shaders. Without it (MoltenVK, older ANV) the -pipeline is an exact emulation: the object and mesh functions run as compute stages that write the -mesh's vertices and primitives as records into buffers, and a synthesized vertex stage draws those -records; the plan says which dispatches and draw to record. +mesh draws only (`DrawCall::MeshThreadgroups`, `MeshThreads` and their indirect forms). The +stages are task and mesh shaders, which need `VK_EXT_mesh_shader` with `meshShader` (and +`taskShader` for an object function). A device without them (MoltenVK, older ANV) refuses the +pipeline and each of its object and mesh functions (`Unsupported{MeshShading}`, naming what it +lacks). A grid Metal draws nothing for (an axis past `bind::METAL_MESH_GRID_AXIS`, or more than `bind::METAL_MESH_GRID_TOTAL` threadgroups, measured on the M3 Max) draws nothing in every form: a direct draw's command is zeroed, an object function's wrapper launches nothing for such a grid, -and an indirect draw reads its counts on the GPU. With the extension, an indirect draw's +and an indirect draw reads its counts on the GPU. An indirect draw's `DrawCommands::mesh_arguments` is a pass to record before the render pass (`bind::mesh_arguments_module`, one invocation): it writes the draw's counts into the consumer's scratch (`MeshArguments::scratch_bytes`), which the draw reads in place of Metal's arguments. @@ -1011,17 +1011,6 @@ through `StatusBits::MESH_GRID_PAST_LIMITS`, or a fold of more pieces than A direct object grid past the task limits of a device that does not fold is refused naming the limit. -Without the extension, an indirect draw with an object function first dispatches an object -arguments pass (`MeshDispatch::object_arguments`, `bind::mesh_object_arguments_module`, one -invocation over the scan's bindings): it reads Metal's arguments, reserves the object threadgroups' -slots in the command buffer's records pool, and writes the object function's -`VkDispatchIndirectCommand` into the work buffer. A grid -Metal's GPU discards sets `StatusBits::MESH_GRID_DISCARDED`; one past the device's compute limits -sets `MESH_GRID_PAST_LIMITS`; slots the rest of the pool cannot hold set `MESH_RECORDS_OVERFLOW`. -Each draws nothing. A grid whose threads per grid wrap along an axis runs every threadgroup, and -the object function reports the wrapped grid as Metal's: an unfolded object function's -`threadgroups_per_grid` is the threadgroups its wrapped threads fill. - ### Tile pipelines `Device::compile_tile_pipeline` compiles a `TileRenderPipelineDescriptor` (the tile function and the diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 0791550b6..2c7d209a4 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -131,7 +131,7 @@ Columns: | `VertexStepRate` | A vertex buffer layout stepped per instance at a rate above 1, on a profile that fetches every attribute in fixed function (the identity domains,... | devices without a capability the site computes (`needs`) | `device` | 1: `crates/metal2vulkan/src/metal/vertex.rs (divided)` | `app`: instanced vertex layouts stepped at a rate above 1 | | `VertexInputLayout` | A vertex attribute whose layout fixed-function input cannot fetch, on a profile that fetches every attribute in fixed function (the identity... | devices without a capability the site computes (`limit`); every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/pipeline/link/vertex.rs (resolve, 4 sites)` | `rare`: vertex offsets or strides off their format's alignment, or past a device's limits | | `Tessellation` | Tessellation | devices without VkFeature::TessellationShader; devices without VkLimit::MaxTessellationGenerationLevel; every device (not implemented) | `ours` | 13: `crates/metal2vulkan-air/src/canon/mod.rs (post_check, 2 sites)`, `crates/metal2vulkan/src/lower/stage_io/fetch.rs (select)` (+8) | `rare`: tessellation | -| `MeshShading` | | devices short of a device limit the site names; devices without VkLimit::MaxMeshOutputLayers; devices without VkLimit::MaxTaskPayloadSize; devices without a capability the site computes (`missing`); every device (not implemented) | `ours` | 7: `crates/metal2vulkan/src/bind/graphics.rs (mesh_limit)`, `crates/metal2vulkan/src/bind/graphics.rs (plan)` (+4) | `rare`: mesh pipelines | +| `MeshShading` | | devices short of a device limit the site names; devices without VkLimit::MaxMeshOutputLayers; devices without VkLimit::MaxTaskPayloadSize; devices without a capability the site computes (`missing`); every device (not implemented) | `ours` | 6: `crates/metal2vulkan/src/bind/graphics.rs (mesh_limit)`, `crates/metal2vulkan/src/bind/graphics.rs (plan)` (+3) | `rare`: mesh pipelines | | `TileShading` | | devices without VkLimit::MaxStorageBufferRange; every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/bind/plan/compute.rs (tile_memory)`, `crates/metal2vulkan/src/lower/access/tile.rs (not_implemented)` (+2) | `rare`: tile shaders (Apple GPU families) | | `Imageblocks` | An imageblock outside the forms implemented | devices without VkFeature::SampleRateShading; devices without a capability the site computes (`missing`); every device (not implemented) | `ours` | 8: `crates/metal2vulkan/src/lower/access/imageblock.rs (imageblocks)`, `crates/metal2vulkan/src/lower/access/mod.rs (select_param)` (+6) | `rare`: imageblocks (Apple GPU families) | | `RayTracing` | | devices without a capability the site computes (`missing`); every device (no Vulkan mechanism); every device (not implemented) | `ours` | 12: `crates/metal2vulkan/src/bind/acceleration.rs (instance_record, 2 sites)`, `crates/metal2vulkan/src/lower/raytracing/mod.rs (instance_count)` (+5) | `rare`: ray tracing (out of scope by ruling) | @@ -153,7 +153,7 @@ Columns: | `StageStoresAndAtomics` | Buffer or image stores or atomics in a vertex or fragment function without the stage's store feature (`vertexPipelineStoresAndAtomics`,... | devices without VkFeature::FragmentStoresAndAtomics | `device` | 1: `crates/metal2vulkan/src/lower/access/tile_memory.rs (written)` | `app`: stores or atomics in vertex or fragment functions on a device without the feature | | `FunctionConstantArgument` | An observed read of a pointer entry argument that a function-constant predicate removes, other than an absent buffer (which reads as null) or an... | every device (not implemented) | `ours` | 1: `crates/metal2vulkan-air/src/canon/interface.rs (absent_values)` | `rare`: a function-constant-removed argument read | | `SamplerBicubicFilter` | A use of Metal's bicubic filter that no Metal reading establishes | every device (not implemented) | `ours` | 5: `crates/metal2vulkan/src/bind/heap.rs (new)`, `crates/metal2vulkan/src/bind/plan/resources.rs (bicubic_texels)` (+3) | `system`: bicubic filtering forms Metal does not establish; macOS 26.6.2 makes a runtime sampler with MTLSamplerMinMagFilterCubic (the consumer's boots), whose mip-filtered form is refused | -| `GroupCount` | A dispatch whose threadgroup count on `axis` exceeds `maxComputeWorkGroupCount` by more than the binder splits into regions (`None` | every device (no Vulkan mechanism) | `device` | 6: `crates/metal2vulkan/src/bind/dispatch.rs (2 sites)`, `crates/metal2vulkan/src/bind/dispatch.rs (product)` (+3) | `rare`: more threadgroups than a device dispatches, past the binder's split | +| `GroupCount` | A dispatch whose threadgroup count on `axis` exceeds `maxComputeWorkGroupCount` by more than the binder splits into regions (`None` | every device (no Vulkan mechanism) | `device` | 5: `crates/metal2vulkan/src/bind/dispatch.rs (2 sites)`, `crates/metal2vulkan/src/bind/dispatch.rs (product)` (+2) | `rare`: more threadgroups than a device dispatches, past the binder's split | | `IntersectionFunctionTable` | A ray intersection through intersection functions | every device (no Vulkan mechanism); every device (not implemented) | `ours` | 9: `crates/metal2vulkan/src/bind/acceleration.rs (geometry_table_offset, 3 sites)`, `crates/metal2vulkan/src/lower/raytracing/mod.rs (intersect, 2 sites)` (+4) | `rare`: ray tracing (out of scope by ruling) | | `IndependentBlending` | Color attachments whose write masks or blend states differ, as Metal sets them per attachment, on a device without `independentBlend`, where no... | devices without VkFeature::IndependentBlend | `device` | 1: `crates/metal2vulkan/src/pipeline/link/graphics.rs (uniform_blend)` | `rare`: per-attachment blending on a device without independentBlend | | `RasterSampleCount` | A `rasterSampleCount` outside the device's framebuffer sample counts for the pipeline's attachments (`framebuffer*SampleCounts`), and, for a color... | devices without a capability the site computes | `device` | 1: `crates/metal2vulkan/src/pipeline/graphics.rs (sample_count_properties)` | `app`: a sample count a device lacks for the attachments | @@ -470,7 +470,7 @@ Each refusal's sites, with the function that builds it. - `feature::VertexStepRate`: `crates/metal2vulkan/src/metal/vertex.rs (divided)` - `feature::VertexInputLayout`: `crates/metal2vulkan/src/pipeline/link/vertex.rs (resolve, 4 sites)` - `feature::Tessellation`: `crates/metal2vulkan-air/src/canon/mod.rs (post_check, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs (select)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (input_builtin)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (primitive_id_output)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (not_implemented)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (plan_entry, 2 sites)`; `crates/metal2vulkan/src/metal/vertex.rs (fetch_as)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (check_fragment)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (control_plan, 2 sites)` -- `feature::MeshShading`: `crates/metal2vulkan/src/bind/graphics.rs (mesh_limit)`; `crates/metal2vulkan/src/bind/graphics.rs (plan)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (check_payload)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (plan_entry, 2 sites)`; `crates/metal2vulkan/src/memory/plan.rs (reprs)`; `crates/metal2vulkan/src/pipeline/link/mesh.rs (records)` +- `feature::MeshShading`: `crates/metal2vulkan/src/bind/graphics.rs (mesh_limit)`; `crates/metal2vulkan/src/bind/graphics.rs (plan)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (check_payload)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (plan_entry, 2 sites)`; `crates/metal2vulkan/src/memory/plan.rs (reprs)` - `feature::TileShading`: `crates/metal2vulkan/src/bind/plan/compute.rs (tile_memory)`; `crates/metal2vulkan/src/lower/access/tile.rs (not_implemented)`; `crates/metal2vulkan/src/lower/sync/barrier.rs (tile_shading)`; `crates/metal2vulkan/src/pipeline/compile/api.rs (tile_pipeline)` - `feature::Imageblocks`: `crates/metal2vulkan/src/lower/access/imageblock.rs (imageblocks)`; `crates/metal2vulkan/src/lower/access/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs (not_implemented)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs (reach)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs (require)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select)`; `crates/metal2vulkan/src/lower/texture/slice.rs (imageblocks)`; `crates/metal2vulkan/src/pipeline/link/imageblock.rs (fragment_imageblock)` - `feature::RayTracing`: `crates/metal2vulkan/src/bind/acceleration.rs (instance_record, 2 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (instance_count)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (intersect, 5 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (primitive_data_read)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (select_param)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (slot_of)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` @@ -492,7 +492,7 @@ Each refusal's sites, with the function that builds it. - `feature::StageStoresAndAtomics`: `crates/metal2vulkan/src/lower/access/tile_memory.rs (written)` - `feature::FunctionConstantArgument`: `crates/metal2vulkan-air/src/canon/interface.rs (absent_values)` - `feature::SamplerBicubicFilter`: `crates/metal2vulkan/src/bind/heap.rs (new)`; `crates/metal2vulkan/src/bind/plan/resources.rs (bicubic_texels)`; `crates/metal2vulkan/src/bind/plan/slots.rs (cubic_variant)`; `crates/metal2vulkan/src/lower/sampler/bicubic.rs (refuse)`; `crates/metal2vulkan/src/lower/sampler/select.rs (bicubic_refused)` -- `feature::GroupCount`: `crates/metal2vulkan/src/bind/dispatch.rs (2 sites)`; `crates/metal2vulkan/src/bind/dispatch.rs (product)`; `crates/metal2vulkan/src/bind/dispatch.rs (regions)`; `crates/metal2vulkan/src/bind/graphics.rs (emulated_draw)`; `crates/metal2vulkan/src/bind/graphics.rs (mesh_draw)` +- `feature::GroupCount`: `crates/metal2vulkan/src/bind/dispatch.rs (2 sites)`; `crates/metal2vulkan/src/bind/dispatch.rs (product)`; `crates/metal2vulkan/src/bind/dispatch.rs (regions)`; `crates/metal2vulkan/src/bind/graphics.rs (mesh_draw)` - `feature::IntersectionFunctionTable`: `crates/metal2vulkan/src/bind/acceleration.rs (geometry_table_offset, 3 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (intersect, 2 sites)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (null_table)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (select_table)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs (table_of)`; `crates/metal2vulkan/src/lower/select.rs (route_air)` - `feature::IndependentBlending`: `crates/metal2vulkan/src/pipeline/link/graphics.rs (uniform_blend)` - `feature::RasterSampleCount`: `crates/metal2vulkan/src/pipeline/graphics.rs (sample_count_properties)`