diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 9a8b70854..b40237be8 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2381; +pub const SEMANTICS_VERSION: u32 = 2382; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index 6808b045a..e233b6544 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -474,7 +474,10 @@ impl Device { /// its raw render target slice and viewport indices and the pipeline's attachments, as a /// render pipeline's. The /// 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 + /// stage (`MESH_EXT`) and the fragment stage, a pipeline without an object function's first + /// stage the launcher link adds in its place (a task stage of one invocation that emits the + /// grid whose counts its draw's `PushField::GroupCountsAddress` points at, within Metal's and + /// the device's mesh limits; `link::mesh::Launcher`): it has no vertex input and no input assembly (its /// `GraphicsState::topology` is unused), and Metal's draws of it are `drawMeshThreadgroups` and /// `drawMeshThreads`. A device without `VK_EXT_mesh_shader`, `taskShader`, `meshShader`, /// `multiDrawIndirect` and `drawIndirectCount`, all enabled together, refuses it, with or @@ -564,7 +567,7 @@ impl Device { } let artifacts: Vec<&FunctionArtifact> = compiled.iter().map(|c| c.artifact()).collect(); let linked = link(&artifacts, &LinkInputs::mesh(d), p)?; - let mut stages = Vec::with_capacity(compiled.len()); + let mut stages = Vec::with_capacity(compiled.len() + 1); for (i, c) in compiled.iter().enumerate() { stages.push(stage_module(c, &linked, i)?); } @@ -578,6 +581,12 @@ impl Device { { requirements = p.union_requirements(&requirements, &a.requirements); } + // A pipeline without an object function draws through its launcher, the first stage. + if let Some(launcher) = &linked.launcher { + let (module, r) = launcher.stage(&linked, p, m)?; + requirements = p.union_requirements(&requirements, &r); + stages.insert(0, module); + } let dependencies = dependencies(&artifacts, self); let (graphics, requirements) = graphics_requirements(requirements, &linked, &artifacts, p)?; let profile = self.profile_fingerprint(); diff --git a/crates/metal2vulkan/src/pipeline/link.rs b/crates/metal2vulkan/src/pipeline/link.rs index 3c99df606..a3d61f76e 100644 --- a/crates/metal2vulkan/src/pipeline/link.rs +++ b/crates/metal2vulkan/src/pipeline/link.rs @@ -276,6 +276,9 @@ pub struct Linked { /// The synthesized control and evaluation stages of a render pipeline variant that draws its /// lines as bands ([`band`]), with their push range placed: the compile API builds them. pub band: Option, + /// The launcher task stage of a mesh render pipeline without an object function + /// ([`mesh::Launcher`]), with its push field placed: the compile API builds it. + pub launcher: Option, } impl SymbolTable for Linked { @@ -388,6 +391,11 @@ pub fn link( } None => None, }; + // A mesh render pipeline without an object function draws through the launcher. + let launcher = match inputs { + LinkInputs::Mesh(_) => mesh::Launcher::plan(&ifaces, &mut layout.push_constants, p)?, + _ => None, + }; let specialization = specialize(&ifaces, &mut table)?; table.locations = varyings::assign(stages, p)?; let mut interface = pipeline_interface(&ifaces); @@ -395,6 +403,10 @@ pub fn link( if let Some(placement) = control.and_then(|(plan, offset)| plan.placement(offset)) { interface.push.push(placement); } + // The launcher states its field as the object stage's, first. + if let Some(l) = &launcher { + interface.push.insert(0, l.placement()); + } let mut vertex_notes = Vec::new(); let (vertex_input, graphics) = match inputs { LinkInputs::Render(r) => { @@ -475,6 +487,7 @@ pub fn link( specialization, control: control.map(|(plan, offset)| plan.control(offset)), band, + launcher, }) } diff --git a/crates/metal2vulkan/src/pipeline/link/mesh.rs b/crates/metal2vulkan/src/pipeline/link/mesh.rs index 2e1502ae6..d6cc8592e 100644 --- a/crates/metal2vulkan/src/pipeline/link/mesh.rs +++ b/crates/metal2vulkan/src/pipeline/link/mesh.rs @@ -1,8 +1,36 @@ -//! A mesh render pipeline's link check: its mesh function's payload holds its object function's. +//! A mesh render pipeline's link: its mesh function's payload holds its object function's, and a +//! pipeline without an object function draws through a launcher ([`Launcher`]). +//! +//! **The launcher.** Metal draws a mesh function without an object function over a grid the draw +//! names, directly or in an indirect buffer, and draws nothing for one past its limits on a mesh +//! grid (`bind::mesh_arguments`, as the M3 measured). Vulkan's `vkCmdDrawMeshTasksEXT` and its +//! indirect form take a grid only within the device's mesh limits, and an indirect grid's counts +//! are the GPU's. So such a pipeline's first stage is a task stage link adds: one invocation that +//! reads the draw's three group counts at the address its draw pushes +//! (`PushField::GroupCountsAddress`, Metal's `MTLDispatchThreadgroupsIndirectArguments` layout: +//! an indirect buffer's place, or counts a direct draw writes) and emits that mesh grid where it +//! lies within Metal's limits and the device's mesh limits, and no mesh threadgroup past them, as +//! an object function's wrapper does (`lower::mesh`). Every draw of the pipeline, direct or +//! indirect, is one task workgroup, `vkCmdDrawMeshTasksEXT(1, 1, 1)`, in its pass and in order, +//! with no write before it; the mesh function's grid is the one emitted. Where the mesh function +//! reads a payload, the launcher emits an arena of its size, never written: Metal gives a mesh +//! function without an object function no payload contents. -use crate::error::{Error, RuntimeInput}; -use crate::pipeline::interface::StageInterface; -use crate::pipeline::sym::Stage; +use crate::bind::mesh_arguments::{METAL_MESH_GRID_AXIS, METAL_MESH_GRID_TOTAL}; +use crate::budget::Meter; +use crate::device::requirements::Requirements; +use crate::device::DeviceProfile; +use crate::error::{Error, Feature, RuntimeInput}; +use crate::pipeline::artifact::{Reconvergence, SpecializationLayout, StageModule, StrategyCensus}; +use crate::pipeline::interface::{PlacedField, PushLoc, PushPlacement, StageInterface}; +use crate::pipeline::layout::PushConstantRange; +use crate::pipeline::sym::{PushField, Stage}; +use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; +use crate::spirv::error::BResult; +use crate::spirv::ids::Value; +use crate::spirv::ir::{BinOp, ExecMode, ExecModel, GlslOp, MemAccess, Type, TypedModule}; +use crate::spirv::serialize::{SymbolTable, ENTRY_NAME}; +use crate::vk; /// 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`, @@ -21,3 +49,198 @@ pub fn payload(ifaces: &[&StageInterface]) -> Result<(), Error> { _ => Ok(()), } } + +/// The launcher of a mesh render pipeline without an object function (the module docs). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Launcher { + /// The push offset of its one field, `PushField::GroupCountsAddress`. + pub push_offset: u32, + /// The mesh function's payload arena's bytes (`StageInterface::payload`), which the launcher + /// emits unwritten; `None` where the mesh function has no payload. + pub payload: Option, + /// The most mesh threadgroups along each axis and in all of a grid it launches: Metal's + /// limits on a mesh grid, within the device's mesh limits. + pub limits: ([u32; 3], u32), +} + +impl Launcher { + /// The bytes of its push range: the counts' address. + pub const PUSH_BYTES: u32 = 8; + + /// The launcher of the mesh render pipeline of stages `ifaces`, its push range placed beside + /// `ranges` (which it joins) at the first offset none covers (`tessellation::push_offset`); + /// `None` for a pipeline with an object function. + /// + /// Err: `Unsupported{MeshShading}` needing a larger `maxPushConstantsSize` where no offset + /// within it is free. + pub fn plan( + ifaces: &[&StageInterface], + ranges: &mut Vec, + p: &DeviceProfile, + ) -> Result, Error> { + if ifaces.iter().any(|i| i.stage == Stage::Object) { + return Ok(None); + } + let payload = (ifaces.iter()) + .find(|i| i.stage == Stage::Mesh) + .and_then(|i| i.payload); + let push_offset = super::tessellation::push_offset( + ranges, + (Self::PUSH_BYTES, Self::PUSH_BYTES), + Feature::MeshShading, + p, + )?; + ranges.push(PushConstantRange { + stages: vk::ShaderStageFlags::TASK_EXT, + offset: push_offset, + size: Self::PUSH_BYTES, + }); + let limits = &p.fields().limits.mesh; + Ok(Some(Launcher { + push_offset, + payload, + limits: ( + (limits.max_mesh_work_group_count).map(|axis| axis.min(METAL_MESH_GRID_AXIS)), + (limits.max_mesh_work_group_total_count).min(METAL_MESH_GRID_TOTAL), + ), + })) + } + + /// Its push field, as the pipeline interface's placement of an object-stage range: the task + /// stage stands in the object function's place. + pub fn placement(&self) -> PushPlacement { + PushPlacement { + stage: Stage::Object, + fields: vec![PlacedField { + field: PushField::GroupCountsAddress, + loc: PushLoc::Push { + offset: self.push_offset, + }, + size: Self::PUSH_BYTES, + }], + push_range: Some((self.push_offset, Self::PUSH_BYTES)), + argument_table_size: 0, + tail_word: None, + } + } + + /// Its task stage as a final module under link table `table`, with the requirements of its + /// module: verified by the owned verifier, serialized and relocated, as a compiled function's + /// module is. + pub fn stage( + &self, + table: &impl SymbolTable, + p: &DeviceProfile, + m: &mut Meter, + ) -> Result<(StageModule, Requirements), Error> { + let module = self.module()?; + 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::TASK_EXT, + 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(), + rounded_colors: Vec::new(), + own_pixel_textures: Vec::new(), + private_bytes: 0, + stats, + }, + module.requirements, + )) + } + + /// Its `TaskEXT` entry: one invocation that loads the counts at the pushed address, holds them + /// within [`limits`](Self::limits) (none past them) and emits them with the payload. + fn module(&self) -> BResult { + let mut mb = ModuleBuilder::new(); + let u32_ = mb.ty(Type::Int { + width: 32, + signed: false, + })?; + let u64_ = mb.ty(Type::Int { + width: 64, + signed: false, + })?; + let field = mb.push_member(PushField::GroupCountsAddress, u64_, self.push_offset)?; + let push = mb.push_global()?; + let payload = match self.payload { + Some(bytes) => crate::memory::arena::declare_payload(&mut mb, u64::from(bytes))?.global, + None => None, + }; + let void = mb.ty(Type::Void)?; + let mut fb = mb.function(void)?; + let base = fb.module().global_value(push)?; + let member = k32(&mut fb, field.index)?; + let at = fb.access_chain(base, &[member])?; + let address = fb.load(at, MemAccess::default())?; + let mut counts = Vec::with_capacity(3); + for word in 0..3u64 { + let at = match word { + 0 => address, + word => { + let offset = crate::memory::roots::k64(&mut fb, 4 * word)?; + fb.binary(BinOp::IAdd, address, offset)? + } + }; + let place = fb.device_place(at, u32_)?; + let access = MemAccess { + aligned: Some(4), + ..MemAccess::default() + }; + counts.push(fb.load(place, access)?); + } + let [x, y, z] = self.bounded(&mut fb, [counts[0], counts[1], counts[2]])?; + fb.emit_mesh_tasks(x, y, z, payload)?; + let f = fb.finish()?; + mb.entry( + ExecModel::TaskEXT, + f, + vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }], + )?; + mb.finalize() + } + + /// The grid `g` where it lies within [`limits`](Self::limits), and none past them: each axis + /// at most its count, and the product at most the total, tested as `x ≤ total / max(y, 1)` + /// then `x·y ≤ total / max(z, 1)`, so the product compared wraps only where the first test + /// fails. + fn bounded(&self, fb: &mut FunctionBuilder<'_>, g: [Value; 3]) -> BResult<[Value; 3]> { + let (count, total) = self.limits; + let one = k32(fb, 1)?; + let [x, y, z] = g; + let total = k32(fb, total)?; + let ny = fb.glsl(GlslOp::UMax, &[y, one])?; + let room = fb.binary(BinOp::UDiv, total, ny)?; + let mut all = fb.binary(BinOp::ULessThanEqual, x, room)?; + let xy = fb.binary(BinOp::IMul, x, y)?; + let nz = fb.glsl(GlslOp::UMax, &[z, one])?; + let room = fb.binary(BinOp::UDiv, total, nz)?; + let within = fb.binary(BinOp::ULessThanEqual, xy, room)?; + all = fb.binary(BinOp::LogicalAnd, all, within)?; + for (v, max) in g.into_iter().zip(count) { + let max = k32(fb, max)?; + let within = fb.binary(BinOp::ULessThanEqual, v, max)?; + all = fb.binary(BinOp::LogicalAnd, all, within)?; + } + let zero = k32(fb, 0)?; + Ok([ + fb.select(all, x, zero)?, + fb.select(all, y, zero)?, + fb.select(all, z, zero)?, + ]) + } +} + +/// A `u32` constant. +fn k32(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult { + let c = fb.u32_const(v)?; + fb.module().const_value(c) +} diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index ee6da3638..3d03eeb68 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -61,7 +61,8 @@ //! //! **Mesh pipelines.** `Device::compile_mesh_pipeline` compiles a [`MeshPipelineDescriptor`] //! into a [`RenderPipeline`] whose stages are its object (`TASK_EXT`), mesh (`MESH_EXT`) and -//! fragment stages, with no vertex input; its fragment function reads the mesh function's primitive +//! fragment stages, with no vertex input, a pipeline without an object function drawing through a +//! task stage link adds (`link::mesh::Launcher`); its fragment function reads the mesh function's primitive //! outputs per primitive (`LoweringInputs::primitive_varyings`). It draws mesh draws //! (`DrawCall::MeshThreadgroups` and its siblings), each with the specialization of its mesh //! threadgroup's size. diff --git a/docs/API.md b/docs/API.md index 2e207204e..b80b70d52 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1179,6 +1179,15 @@ an object function (a mesh draw's pieces take the two draw features). A device w them (MoltenVK, older ANV) refuses the pipeline and each of its object and mesh functions (`Unsupported{MeshShading}`, naming what it lacks). +A pipeline without an object function draws through a launcher, a task stage the compile adds as +its first stage: one invocation that reads the draw's three group counts at the address its +draw pushes (`PushField::GroupCountsAddress`, Metal's `MTLDispatchThreadgroupsIndirectArguments` +layout, placed as the object stage's field) and launches that mesh grid, and nothing for a grid +past Metal's limits (below) or the device's mesh limits. Every draw of such a pipeline, direct or +indirect, is `vkCmdDrawMeshTasksEXT(1, 1, 1)`: the counts are the guest's indirect buffer where +the draw names one, so the draw reads it in its pass, in order, with nothing written before it. +Where the mesh function reads a payload, the launcher emits an arena of its size, never written. + An object or mesh function's SIMD groups run on its stage's own subgroups, as a kernel's run on the compute stage's, read from Vulkan's task and mesh stage facts: the stage in `subgroupSupportedStages` with the operations' classes, full subgroups (`computeFullSubgroups`,