From 5a722b5c3f5362a31ec284c511bedba1447ccff5 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 24 Nov 2026 02:55:06 -0800 Subject: [PATCH] Stencil output: a device without VK_EXT_shader_stencil_export draws it by bits, the owner's tenth form A fragment function's [[stencil]] output is the reference of both faces' stencil test for its fragment (MSL Table 5.7, 5.2.3.5). On a device without VK_EXT_shader_stencil_export it was refused at creation (StencilExport). Under the owner's grant (rule 2's tenth form, chosen by that extension's query alone), such a device now draws it by bits; a device with the extension is unchanged (FragStencilRefEXT, no fact, no note, the draw issued once). Translator: the function stores no reference; each return kills the fragment where the draw's new push field PushField::StencilBit k is below 8 and bit k of the output's low 8 is 0, and keeps every fragment at 8 or more (one module, no specialization). The function states RuntimeFact::StencilBitDraws (Mechanism::PushConstant) and its fragment stage the static note PrecisionNote::StencilOutputOverlap. Refused there, naming the extension (Unsupported StencilExport): a function that also writes a colour (the colour would be written by every repeat) or memory, one whose returns cannot kill (an interlocked body, a loop over its covered samples), a mesh pipeline, and a render pipeline made for indirect command buffers. Where the device also lacks the pixel interlock, a function writing memory in a raster order group meets that refusal first (RasterOrderGroups). SEMANTICS_VERSION 2301 -> 2302, ARTIFACT_FORMAT_VERSION 595 -> 596 (new codec members). Runtime (depth_stencil::BitDraws, render_encoder::draw): with w the low 8 bits of the write masks of the faces having a Replace operation, a draw whose stencil test is on and w is not 0 is drawn once with every fragment kept under the reference 0 (Replace zeroes w's bits, every other operation runs once), then once per bit k of w keeping the fragments whose output holds bit k, under the reference 255, write mask (1 << k) & mask, Replace kept and every other operation Keep, and no depth write; where the state writes depth under a compare other than Always and Never, the first draw writes none and a last draw writes it with stencil write masks of 0. Each draw records only the dynamic state that differs from the last; the encoder's tests and reference are recorded again at the next draw. Counted in Metrics::stencil_bit_draws (the draws beyond the first). Refused at a draw, Gap::Draw of DrawKind::StencilOutput: a face compare other than Always or Never (the output decides that test), and, where w is not 0, a draw inside a Counting visibility segment (every draw would add its samples). A Boolean segment is drawn. Vulkan Appendix I: the repeats change stencil reference, operations and write masks between draws of one pipeline, which Rule 2 lists as required (write masks) and strongly suggested (stencil parameters) to be invariant; the note records the one difference the repeats make. The note (rule 1): fragments of one draw that overlap leave the OR of their values. Where two fragments of one draw reach one sample under Replace, the sample stores the OR of their outputs' low 8 bits within the write mask, where Metal stores the later fragment's value; under a depth test that writes, each fragment's stencil operation is chosen against the depth from before the draw. Measured on an RTX 3090 (NVIDIA 620.70.06) under the validation layer 1.4.363.0, job m3-max-73635: two triangles of one draw outputting 0x35 then 0x4a store 0x7f on the 32 texels both reach, where Metal stores 0x4a, and 0x35 on the 32 one reaches, in 8 bit draws; the 780M (RADV) and the Iris Xe (ANV), which list the extension, store 0x4a with 0 bit draws. AGENTS.md rule 2: "for nine only" becomes "for ten only", the list ending with fragment stencil output (the planner's text, relayed by main, word for word). Tests: the translator's engine_stencil (every committed profile: the extension or the draws by bits, L3 both ways; refusals for colour, memory, mesh and indirect command buffers); rt's host test of BitDraws::of; rt's device cells (stencil_export.rs): the stencil alone and the stencil with the depth under Always and Less over a quad, exact, texels of stencil 0 among them; the overlap row; the refusals; the route of a 4-sample Depth32Float_Stencil8 source read at sample 0 into a single-sample target under Always/Replace 0xff and depth Always with write, beside colour 0 RGBA8 of write mask none; the codec round trip; the mechanism table. Docs: docs/API.md (the stencil output passage and the catalogue entry metal2vulkan-degrade-stencil-output-overlap), rt README known gap and floor row, docs/REFUSALS.md regenerated, api_signatures blessed. The conformance degradation and the validation allowance (unbounded) of the note. known-gaps-rt.tsv: stencil-output and stencil-output-loaded on NVIDIA, refused at renderCommandEncoder (draw 3's back face Equal against the output) and divergent at case/stencil as a result. runtime-sources.sha256: the guard's inputs changed only by mechanism.rs gaining the new fact's arm, which no existing artifact states, so no run of an existing artifact changes. Golden rows and the engine inventory (22 cells) are re-blessed on development: 20 move from the StencilExport refusal to a module (stx_stencil_by_pixel, stx_stencil_discard, stx_stencil_with_depth, stx_stencil_ms_by_sample, fragment_depth_stencil on nvidia-pascal-linux, nvidia-rtx50-linux, nvidia-rtx5080-laptop and runtime-floor), and the 2 cells stx_stencil_in_order and stx_stencil_ms_in_order on runtime-floor move from StencilExport to RasterOrderGroups, still refused. Why: the memory-write refusal now runs on the emitted module (pipeline/compile.rs), after the body's own refusals, so on a profile without the pixel interlock the raster order group these functions write memory in is refused first; at the base the plan's entry refused every [[stencil]] output on such a device before any body was lowered. Verified (this tree, or the rt archive of d6bd77d203 where named; the rt and translator sources there differ from this tree in the translator's test and a doc comment alone): - msi check, job m3-max-73648 (this tree): fmt, signatures, refusals, clippy -D warnings with all features plain, --cfg m2v_gpu and --cfg m2v_cpu_icd, Rustdoc, the rt nextest archive and the conformance binary built; rt's whole suite on lavapipe under the validation layer 1.4.363.0, 738 tests run: 738 passed, 3 skipped; the lavapipe leg, 7 tests run: 7 passed: export enabled, the overlap row storing {4a}, bit draws 0 on every cell. - RTX 3090 (NVIDIA 620.70.06, layer 1.4.363.0), job m3-max-73635 (d6bd77d203): 7 passed; the overlap row above, bit draws 8; the stencil alone and with depth under Always and Less, 64 texels exact, bit draws [8, 8, 9]; the route exact, bit draws 8; refused a colour beside the stencil (StencilExport), Equal and a Counting segment (DrawKind::StencilOutput), a Boolean segment drawn. Conformance stencil-output and stencil-output-loaded: refused at renderCommandEncoder and divergent at case/stencil (4 elements, largest difference 80), the four known-gaps rows. - RTX 5080 Laptop GPU (NVIDIA 615.71.09, layer 1.4.363.0), job m3-max-73652 (this tree): 7 passed; overlap {7f} where both reach, {35} where one, bit draws 8; cells exact, bit draws [8, 8, 9]; the route exact, bit draws 8; the same refusals; conformance replay with this tree's binary matched the four NVIDIA rows (exit 0). - Radeon 780M (RADV, Mesa 26.2.6), job m3-max-73636 (d6bd77d203), and Iris Xe (ANV, Mesa 26.2.6), job m3-max-73650 (this tree): 7 passed each, export enabled, overlap {4a}, bit draws 0. - States-only plays of recorded streams, base 0c9db49765 against d6bd77d203, every play in states-only mode, made and refused equal, refused 0: lavapipe, jobs m3-max-73632 and m3-max-73631 (two streams: render 10643 and 9014, compute 15299 and 221); the RTX 3090 with --device-type gpu, job m3-max-73638 (two streams: render 9834 and 10643, compute 214 and 15299); the RTX 5080, job m3-max-73652 (two streams: render 9014 and 9645, compute 221 and 250). Those two carry a library holding a [[stencil]] function that no recorded pipeline state uses; no stream on either NVIDIA node makes a [[stencil]] pipeline (job m3-max-73646 and m3-max-73652's scan). - Owed: the translator and validation suites of this tree (the suites of d6bd77d203, job m3-max-73627, failed in the memory refusal's test on runtime-floor, the runtime guard's hash and the golden and inventory cells above; this tree fixes the first two). --- AGENTS.md | 13 +- .../known-gaps-rt.tsv | 4 + .../src/degradation.rs | 5 + crates/metal2vulkan-runtime/README.md | 26 +- crates/metal2vulkan-runtime/src/counters.rs | 15 +- .../metal2vulkan-runtime/src/depth_stencil.rs | 126 ++ crates/metal2vulkan-runtime/src/error.rs | 9 + crates/metal2vulkan-runtime/src/render.rs | 21 + .../src/render_encoder.rs | 396 ++++--- .../src/tests/indirect.rs | 1 + .../src/tests/stencil_export.rs | 1013 +++++++++++++++-- crates/metal2vulkan-runtime/src/visibility.rs | 14 +- .../runtime-sources.sha256 | 2 +- .../src/observation_contract/comparison.rs | 5 +- .../observation_contract/comparison/tests.rs | 1 + crates/metal2vulkan/src/cache/codec.rs | 3 + crates/metal2vulkan/src/cache/mod.rs | 4 +- crates/metal2vulkan/src/cache/tests.rs | 16 + crates/metal2vulkan/src/device/mechanism.rs | 3 + .../src/device/tests/mechanism.rs | 7 +- crates/metal2vulkan/src/lower/fragment/mod.rs | 12 +- crates/metal2vulkan/src/lower/push.rs | 4 +- crates/metal2vulkan/src/lower/select.rs | 5 +- crates/metal2vulkan/src/lower/stage_io/mod.rs | 49 +- .../metal2vulkan/src/lower/stage_io/plan.rs | 38 +- crates/metal2vulkan/src/pipeline/artifact.rs | 21 + crates/metal2vulkan/src/pipeline/compile.rs | 6 + .../metal2vulkan/src/pipeline/compile/api.rs | 14 + crates/metal2vulkan/src/pipeline/facts.rs | 17 + crates/metal2vulkan/src/pipeline/sym.rs | 5 + .../metal2vulkan/src/tests/engine_stencil.rs | 234 +++- crates/metal2vulkan/tests/api_signatures.tsv | 6 + docs/API.md | 28 +- docs/REFUSALS.md | 4 +- 34 files changed, 1810 insertions(+), 317 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4d6a02a5c..a9c39c629 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,7 +58,7 @@ order, and a lower one never overrides a higher one. limit and memory-type queries. Product code holds no vendor, device or driver ID, and no runtime policy switch. A test enforces this for `metal2vulkan-runtime`. One form means one form per Vulkan capability: where the floor cannot require a feature, that feature's query may choose a - second form, for nine only: 16-bit floats, storage-image reads without a format, 64-bit + second form, for ten only: 16-bit floats, storage-image reads without a format, 64-bit atomics, 64-bit floats, SIMD groups (the subgroup size range with its stages and operations, and maximal reconvergence), unified memory (decided by Vulkan's physical device type alone: one copy of a Managed buffer on an integrated or CPU @@ -66,10 +66,17 @@ order, and a lower one never overrides a higher one. target through a counted copy of that target, recorded as a known gap), run-time texel offsets (a device with the maintenance8 feature takes a run-time texel offset as the sampling or read instruction's own operand; a device without it branches over the offset's values, and - that branch's compile time is recorded as a known gap), and the push window (the device's + that branch's compile time is recorded as a known gap), the push window (the device's push-constant limit sizes it, up to 256 bytes; on a device below 256 the fields past the window come from the stage's parameter block, and an indirect command carries fewer vertex slots, - recorded as a known gap). A second form chosen by anything else is not allowed. + recorded as a known gap), and fragment stencil output (a device with + VK_EXT_shader_stencil_export writes a fragment function's [[stencil]] as the fragment's stencil + reference; a device without it draws each draw of such a pipeline once with a stencil reference + of 0, which clears the stencil bits its depth-stencil state can replace and runs its other + stencil operations, then once for each of those bits, and, where the draw writes depth under a + depth compare other than always or never, once more for the depth; those draws, and the note + that fragments of one draw that overlap leave the OR of their values, are recorded as a known + gap). A second form chosen by anything else is not allowed. 3. **Native-like speed.** Structure decides speed: driver-owned memory, optimal images in real layouts, direct addresses, nothing copied that Metal would not copy. Optimal images have two exceptions. A texture over a Shared buffer: a linear image on that buffer's memory, in the diff --git a/crates/metal2vulkan-conformance/known-gaps-rt.tsv b/crates/metal2vulkan-conformance/known-gaps-rt.tsv index d61b76db4..963b8f154 100644 --- a/crates/metal2vulkan-conformance/known-gaps-rt.tsv +++ b/crates/metal2vulkan-conformance/known-gaps-rt.tsv @@ -2376,6 +2376,10 @@ shared-exponent-update-float RX 550 refused case/fpv_srgb_update/dispatch Err(Er shared-exponent-update-half RX 550 refused case/fpv_srgb_update_half/dispatch Err(Error::Unsupported("texture slot 0, which a function writes or reads as storage, bound to a RGB9E5Float texture with no storage element on this device, or one it cannot read without a format, is not built")) The device's own answer (rule 2): this device's format queries offer no storage image of MTLPixelFormatRGB9E5Float, so rt binds no such texture to a read_write or write slot. shared-exponent-write-float RX 550 refused case/fpv_srgb_write/dispatch Err(Error::Unsupported("texture slot 0, which a function writes or reads as storage, bound to a RGB9E5Float texture with no storage element on this device, or one it cannot read without a format, is not built")) The device's own answer (rule 2): this device's format queries offer no storage image of MTLPixelFormatRGB9E5Float, so rt binds no such texture to a read_write or write slot. shared-exponent-write-half RX 550 refused case/fpv_srgb_write_half/dispatch Err(Error::Unsupported("texture slot 0, which a function writes or reads as storage, bound to a RGB9E5Float texture with no storage element on this device, or one it cannot read without a format, is not built")) The device's own answer (rule 2): this device's format queries offer no storage image of MTLPixelFormatRGB9E5Float, so rt binds no such texture to a read_write or write slot. +stencil-output NVIDIA refused case/program/renderCommandEncoder Err(Error::Unsupported("a draw with StencilOutput is not built")) A known gap of the runtime (its README, Known gaps of render pipeline states): NVIDIA's 615 and 620 drivers do not list `VK_EXT_shader_stencil_export`, so the runtime draws the fragment function's `[[stencil]]` output by bits, which gives Metal's answer only under a stencil compare of `Always` or `Never`. Metal tests draw 3's back face, `Equal` under the read mask `0x0f`, against that draw's output; the runtime refuses that draw, `Gap::Draw` of `DrawKind::StencilOutput`. Draws 1 and 2 are drawn, draw 1 by bits. +stencil-output NVIDIA divergent case/stencil 4 elements differ (U8), the largest difference 80 Follows from the refused draw 3 (the row above): the stencil holds draw 1's output, drawn by bits, and draw 2's increment, where Metal's draw 3 has applied its back face's `Invert` or `Zero`. The first differing element is at [image 0, row 0, 0] (U8, byte 0): Metal 1 (0x1), ours 17 (0x11). +stencil-output-loaded NVIDIA refused case/program/renderCommandEncoder Err(Error::Unsupported("a draw with StencilOutput is not built")) A known gap of the runtime (its README, Known gaps of render pipeline states): NVIDIA's 615 and 620 drivers do not list `VK_EXT_shader_stencil_export`, so the runtime draws the fragment function's `[[stencil]]` output by bits, which gives Metal's answer only under a stencil compare of `Always` or `Never`. Metal tests draw 3's back face, `Equal` under the read mask `0x0f`, against that draw's output; the runtime refuses that draw, `Gap::Draw` of `DrawKind::StencilOutput`. Draws 1 and 2 are drawn, draw 1 by bits. +stencil-output-loaded NVIDIA divergent case/stencil 4 elements differ (U8), the largest difference 80 Follows from the refused draw 3 (the row above): the stencil holds draw 1's output, drawn by bits, and draw 2's increment, where Metal's draw 3 has applied its back face's `Invert` or `Zero`. The first differing element is at [image 0, row 0, 0] (U8, byte 0): Metal 1 (0x1), ours 17 (0x11). surface-fills-over-planes-and-buffers * refused case/500/b4/texture Err(Unavailable({call: "newTextureWithDescriptor:iosurface:plane: of a two-plane YCbCr format"})) refused: no stream uses it yet (full selector census 11-19, m3-max-53207-53208, 53213, 53217-53221: 26 streams, no texture descriptor of a pixel format above 260, so none of Metal's two-plane YCbCr formats, 500 on). A texture of a two-plane YCbCr format over a surface's planes, which converts both planes' codes as it reads; rt has no texture of one, and the replay streams' surface textures are of ordinary formats (surface_textures). surface-textures-420v-chroma-rg8 NVIDIA refused case/replace-region Err(Error::Refused("the CPU reaches no Private or Memoryless texture")) rt's own gap: this device lays the case's two-plane surface in place under neither the dma-buf nor the opaque fd (53626: 0 in place, 2 copied), so the surface takes the copy form, in which a plane's texture is a texture over a buffer in the exported block, whose memory is Private, and rt refuses the CPU's replaceRegion: of it; Metal's texture over an IOSurface plane takes the CPU's write. The one-plane cases are in place here and compare. Why each handle took the copy form (SurfaceCopy) this run does not record. surface-textures-420v-luma-r8 NVIDIA refused case/replace-region Err(Error::Refused("the CPU reaches no Private or Memoryless texture")) rt's own gap: this device lays the case's two-plane surface in place under neither the dma-buf nor the opaque fd (53626: 0 in place, 2 copied), so the surface takes the copy form, in which a plane's texture is a texture over a buffer in the exported block, whose memory is Private, and rt refuses the CPU's replaceRegion: of it; Metal's texture over an IOSurface plane takes the CPU's write. The one-plane cases are in place here and compare. Why each handle took the copy form (SurfaceCopy) this run does not record. diff --git a/crates/metal2vulkan-conformance/src/degradation.rs b/crates/metal2vulkan-conformance/src/degradation.rs index 48187ae65..dd93db3eb 100644 --- a/crates/metal2vulkan-conformance/src/degradation.rs +++ b/crates/metal2vulkan-conformance/src/degradation.rs @@ -173,6 +173,8 @@ pub enum Degradation { VertexSimdgroupGrouping, /// `metal2vulkan-degrade-restricted-depth-upload`. RestrictedDepthUpload, + /// `metal2vulkan-degrade-stencil-output-overlap`. + StencilOutputOverlap, } impl Degradation { @@ -259,6 +261,7 @@ impl Degradation { Degradation::DeviceOcclusionCount, Degradation::VertexSimdgroupGrouping, Degradation::RestrictedDepthUpload, + Degradation::StencilOutputOverlap, ]; /// The kind's code, `metal2vulkan-degrade-`. @@ -387,6 +390,7 @@ impl Degradation { "metal2vulkan-degrade-vertex-simdgroup-grouping" } Degradation::RestrictedDepthUpload => "metal2vulkan-degrade-restricted-depth-upload", + Degradation::StencilOutputOverlap => "metal2vulkan-degrade-stencil-output-overlap", } } @@ -476,6 +480,7 @@ impl Degradation { PrecisionNote::DeviceOcclusionCount => Degradation::DeviceOcclusionCount, PrecisionNote::VertexSimdgroupGrouping => Degradation::VertexSimdgroupGrouping, PrecisionNote::RestrictedDepthUpload => Degradation::RestrictedDepthUpload, + PrecisionNote::StencilOutputOverlap => Degradation::StencilOutputOverlap, } } } diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 69cc153d7..97e9eb900 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -3993,10 +3993,26 @@ cache is answered compile-required on both. states (jobs m3-max-63105 to 63108, and m3-max-63132 and m3-max-63156 for the two streams that ran past those jobs' 300-second limit). - On a device that does not list `VK_EXT_shader_stencil_export`, a fragment function's `[[stencil]]` - output is refused at creation, an `Error::Translation` naming `StencilExport`: the translator has - no other form. The runtime has refused it on such a device all along, worded otherwise before: - the translator's other form bound a storage image through a descriptor, which the identity - domains hold none of. Metal's feature set tables give stencil + output is drawn by bits (`RuntimeFact::StencilBitDraws`). Each draw through its state is drawn + once under the stencil reference 0, then once for each bit of the low 8 of the write masks of + the faces whose operations replace, each keeping only the fragments whose output holds that bit + (`PushField::StencilBit`), under the reference 255, that bit's write mask, `Replace` kept and + every other operation `Keep`, and no depth write; where the state writes the depth under a + compare other than `Always` and `Never`, the first draw writes none and a last draw writes it. + That is up to 10 draws where Metal draws once (`Metrics::stencil_bit_draws`), and a draw whose + state replaces no bit, or tests no stencil, is drawn once. Two fragments of one draw on one + sample store the OR of their outputs where Metal stores the later one, and under a depth test + that writes, each fragment's stencil operation is chosen against the depth from before the + draw: the static note `PrecisionNote::StencilOutputOverlap` on the fragment stage of every such + function. Refused at creation there, an `Error::Translation` naming `StencilExport`: a function + that also writes a colour or memory, one whose returns cannot discard, a mesh pipeline, and a + state made for indirect command buffers. Refused at a draw, `Gap::Draw` of + `DrawKind::StencilOutput`: a stencil compare other than `Always` and `Never` on a face, whose + answer the output decides, and, where the state replaces a bit, a draw inside a `Counting` + visibility result's segment, whose count every one of the draws would add to. A colour beside + the output can be built under this form when a guest needs it: every draw through the one + pipeline, the colour written the same each time, with blending off on every attachment, the + logic operation off and no colour input. Metal's feature set tables give stencil feedback to the Apple5 family and later and to Metal 3 and Metal 4. NVIDIA's 615 and 620 drivers on the RTX 2080, RTX 3090 and RTX 5080 Laptop list none (`vulkaninfo`, jobs m3-max-48727, 48729 and 48731); RADV on the RX 7900 XTX, the 780Ms and the RX 550, ANV on the Iris Xe, lavapipe, @@ -5113,7 +5129,7 @@ Presenting runs on the runtime's own device; nothing is exported or imported. | `VK_KHR_shader_subgroup_uniform_control_flow` | device, where listed | SIMD groups' reconvergence where maximal reconvergence is not offered | | `VK_KHR_shader_quad_control` | device, where listed | a fragment function's group operations over other lanes, through the quad-control feature below | | `VK_EXT_fragment_shader_interlock` | device, where listed | a fragment function's raster order groups on memory it reads and writes, through the pixel-interlock feature below | -| `VK_EXT_shader_stencil_export` | device, where listed | a fragment function's `[[stencil]]` output as the fragment's stencil reference (`FragStencilRefEXT`); RADV, ANV, lavapipe, KosmicKrisp and the UHD 630's Windows driver list it, NVIDIA's 615 and 620 drivers do not | +| `VK_EXT_shader_stencil_export` | device, where listed | a fragment function's `[[stencil]]` output as the fragment's stencil reference (`FragStencilRefEXT`); a device without it draws the output by bits (the known gaps); RADV, ANV, lavapipe, KosmicKrisp and the UHD 630's Windows driver list it, NVIDIA's 615 and 620 drivers do not | | `VK_KHR_portability_enumeration` | instance, where offered | listing portability devices, each checked against the floor as any other | | `VK_KHR_portability_subset` | device, where listed | Vulkan requires it enabled where a device lists it; the device is asked for the portability features below | | `VK_EXT_attachment_feedback_loop_layout` | device, with the feedback loop | a draw's read of an attachment of its own pass through a texture, in the feedback layout, with the colour flag every render pipeline takes (below) | diff --git a/crates/metal2vulkan-runtime/src/counters.rs b/crates/metal2vulkan-runtime/src/counters.rs index 9109e37d6..e1c079840 100644 --- a/crates/metal2vulkan-runtime/src/counters.rs +++ b/crates/metal2vulkan-runtime/src/counters.rs @@ -317,10 +317,12 @@ pub(crate) enum Metric { OverlappingCopiesRefused, /// [`Metrics::heap_moves`]. HeapMoves, + /// [`Metrics::stencil_bit_draws`]. + StencilBitDraws, } /// The number of [`Metric`]s. -const METRICS: usize = Metric::HeapMoves as usize + 1; +const METRICS: usize = Metric::StencilBitDraws as usize + 1; /// Every [`Metric`], in its order: each at its own index. const METRIC_ORDER: [Metric; METRICS] = [ @@ -377,6 +379,7 @@ const METRIC_ORDER: [Metric; METRICS] = [ Metric::AccumulatedVisibilityRefused, Metric::OverlappingCopiesRefused, Metric::HeapMoves, + Metric::StencilBitDraws, ]; // Each metric of the order is at its own index. @@ -804,6 +807,7 @@ struct Atomics { accumulated_visibility_refused: AtomicU64, overlapping_copies_refused: AtomicU64, heap_moves: AtomicU64, + stencil_bit_draws: AtomicU64, /// Each [`Part`]'s calls, at its index: their count, bytes, total and longest nanoseconds, /// and those over each of [`OVER_NANOS`]. parts: [[AtomicU64; 7]; PARTS], @@ -974,6 +978,7 @@ impl Counters { Metric::AccumulatedVisibilityRefused => &a.accumulated_visibility_refused, Metric::OverlappingCopiesRefused => &a.overlapping_copies_refused, Metric::HeapMoves => &a.heap_moves, + Metric::StencilBitDraws => &a.stencil_bit_draws, } } @@ -1915,6 +1920,7 @@ impl Counters { accumulated_visibility_refused: a.accumulated_visibility_refused.load(Relaxed), overlapping_copies_refused: a.overlapping_copies_refused.load(Relaxed), heap_moves: a.heap_moves.load(Relaxed), + stencil_bit_draws: a.stencil_bit_draws.load(Relaxed), takes: part(Part::Take), take_lock_waits: part(Part::TakeLock), take_makes: part(Part::TakeMake), @@ -2910,6 +2916,13 @@ pub struct Metrics { /// command buffer of its own that leads the command's part of its command buffer. No Metal /// counterpart. pub heap_moves: u64, + /// On a device without `VK_EXT_shader_stencil_export`, the draws recorded beyond a draw's + /// own for a pipeline state whose fragment function writes `[[stencil]]`: one for each + /// stencil bit the draw's depth-stencil state can replace, and one that writes the depth last + /// where the state writes it under a compare other than `Always` and `Never` + /// ([`DrawKind::StencilOutput`](crate::DrawKind::StencilOutput) says where they are refused). + /// 0 on a device with the extension. Metal draws once. + pub stencil_bit_draws: u64, /// Takes from the pool on the consumer's threads, each whole: a block of /// [`Device::take_block`](crate::Device::take_block) and a texture block, carved from a free /// range or from an allocation the take made ([`take_makes`](Self::take_makes)); their bytes diff --git a/crates/metal2vulkan-runtime/src/depth_stencil.rs b/crates/metal2vulkan-runtime/src/depth_stencil.rs index a68e6bc3a..4f6832503 100644 --- a/crates/metal2vulkan-runtime/src/depth_stencil.rs +++ b/crates/metal2vulkan-runtime/src/depth_stencil.rs @@ -81,6 +81,132 @@ impl Tests { } } +/// The bit a draw through a pipeline whose fragment function's stencil output is drawn by bits +/// pushes to keep every fragment (`PushField::StencilBit` at 8 or more). +pub(crate) const EVERY_FRAGMENT: u32 = 8; + +/// The most draws one draw takes: its first, one per stencil bit, and its depth's. +const MOST_DRAWS: usize = 10; + +/// One of the draws a draw takes through a pipeline whose fragment function's stencil output is +/// drawn by bits (`RuntimeFact::StencilBitDraws`, on a device without +/// `VK_EXT_shader_stencil_export`): its tests, its stencil reference of each face, and the bit its +/// function keeps (`PushField::StencilBit`). +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) struct BitDraw { + pub(crate) tests: Tests, + pub(crate) reference: [u32; 2], + pub(crate) bit: u32, +} + +/// The draws one draw takes through such a pipeline, in order ([`BitDraws::of`]). +pub(crate) struct BitDraws { + draws: [BitDraw; MOST_DRAWS], + len: usize, +} + +impl BitDraws { + /// The draws of a draw under the encoder's `tests` and `reference`. Where the stencil test + /// replaces no bit (it is off, no operation of a face is `Replace`, or those faces' write + /// masks are 0), the draw alone, every fragment kept: its output is no reference anything + /// reads. Otherwise, with `w` the low 8 bits of the write masks of the faces with a `Replace` + /// operation: + /// + /// 1. every fragment kept, under the tests but the reference 0 on both faces, so `Replace` + /// zeroes the bits of `w` and every other operation runs once; + /// 2. for each bit `k` of `w`, the fragments whose output holds bit `k`, under the reference + /// 255, each face's write mask cut to bit `k`, its `Replace` operations kept and its others + /// `Keep`, and no depth write, so `Replace` sets bit `k` where the output holds it; + /// 3. where the tests write depth under a compare other than `Always` and `Never`, the first + /// draw writes none, and a last one, every fragment kept, writes it under the tests with + /// stencil write masks of 0: each draw before it tests against the depth from before the + /// draw, as Metal's draw does. + /// + /// Each draw takes the same fragments through the same tests where the compare is `Always` + /// or `Never` on both faces, which the reference does not change, so a sample one fragment + /// reaches stores Metal's value. + /// + /// `None` for a stencil test that compares by another function on a face, whose answer the + /// reference decides. + pub(crate) fn of(tests: Tests, reference: [u32; 2]) -> Option { + let own = BitDraw { + tests, + reference, + bit: EVERY_FRAGMENT, + }; + let mut draws = BitDraws { + draws: [own; MOST_DRAWS], + len: 1, + }; + if !tests.stencil { + return Some(draws); + } + let fixed = |compare| matches!(compare, vk::CompareOp::ALWAYS | vk::CompareOp::NEVER); + if !tests.faces.iter().all(|face| fixed(face.compare)) { + return None; + } + let replaces = |f: &&Face| [f.fail, f.pass, f.depth_fail].contains(&vk::StencilOp::REPLACE); + let bits = (tests.faces.iter().filter(replaces)).fold(0, |bits, f| bits | f.write_mask); + let bits = bits & 0xff; + if bits == 0 { + return Some(draws); + } + let last = tests.depth_write && !fixed(tests.depth_compare); + draws.draws[0] = BitDraw { + tests: Tests { + depth_write: tests.depth_write && !last, + ..tests + }, + reference: [0; 2], + bit: EVERY_FRAGMENT, + }; + let kept = |op| match op { + vk::StencilOp::REPLACE => op, + _ => vk::StencilOp::KEEP, + }; + for k in (0..8).filter(|k| bits & (1 << k) != 0) { + let face = |f: Face| Face { + fail: kept(f.fail), + pass: kept(f.pass), + depth_fail: kept(f.depth_fail), + write_mask: f.write_mask & (1 << k), + ..f + }; + draws.push(BitDraw { + tests: Tests { + depth_write: false, + faces: tests.faces.map(face), + ..tests + }, + reference: [255; 2], + bit: k, + }); + } + if last { + let unwritten = |f: Face| Face { write_mask: 0, ..f }; + draws.push(BitDraw { + tests: Tests { + faces: tests.faces.map(unwritten), + ..tests + }, + reference, + bit: EVERY_FRAGMENT, + }); + } + Some(draws) + } + + fn push(&mut self, draw: BitDraw) { + self.draws[self.len] = draw; + self.len += 1; + } + + /// The draws, in order: at least one. + pub(crate) fn draws(&self) -> &[BitDraw] { + &self.draws[..self.len] + } +} + impl Device { /// `newDepthStencilStateWithDescriptor:`. pub fn new_depth_stencil_state( diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index e509e5843..c1d70702f 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1829,6 +1829,15 @@ pub enum DrawKind { /// word is not built. Counted in /// [`Metrics::accumulated_visibility_refused`](crate::Metrics::accumulated_visibility_refused). AccumulatedVisibilityResults, + /// On a device without `VK_EXT_shader_stencil_export`, a draw through a pipeline state whose + /// fragment function writes `[[stencil]]`, which the runtime draws once and then once per + /// stencil bit the depth-stencil state can replace (`Metrics::stencil_bit_draws`), where + /// those draws do not give Metal's answer: under a stencil test whose compare function is + /// other than `Always` and `Never` on a face, as the fragment's output is that test's + /// reference; and, where the state replaces a bit, inside a `Counting` visibility result's + /// segment, whose count each draw would add to. Metal tests and writes the stencil against the + /// output in one draw. + StencilOutput, } /// What a render pass asks that the runtime does not build ([`Gap::RenderPass`]). diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 188288057..dffee2ee2 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -72,6 +72,7 @@ use crate::cache::{self, Lowerings}; use crate::counters::{Counters, FirstUse, Gauge, Metric}; +use crate::depth_stencil::EVERY_FRAGMENT; use crate::device::{lock, Core}; use crate::error::{Error, Gap, Refusal, RenderPipelineKind, StageGap}; use crate::hazard::Access; @@ -191,6 +192,11 @@ pub(crate) struct Draws { /// (`GraphicsState::writes_viewport_index`): its primitives reach every viewport the encoder /// set, where any other function's reach viewport 0. pub(crate) selects_viewport: bool, + /// The push offset of the bit the fragment function keeps its fragments for + /// (`PushField::StencilBit`), where its stencil output is drawn by bits + /// (`RuntimeFact::StencilBitDraws`): each draw takes the draws of + /// [`BitDraws`](crate::depth_stencil::BitDraws), each pushing its bit there. + pub(crate) stencil_bit: Option, } /// The state Vulkan 1.3 lets a draw set, which every render `VkPipeline` takes as dynamic. @@ -669,6 +675,9 @@ fn draws( // past the encoder's viewport count, read from its push field // (`FieldValue::ViewportCount`). RuntimeFact::ViewportCount => {} + // A fragment function's stencil output on a device without stencil export, which each + // draw takes by bits through its push field (`Draws::stencil_bit`). + RuntimeFact::StencilBitDraws => {} // `RuntimeFact` is non-exhaustive: a fact this match does not name is one a draw does // not supply. _ => return Err(draw_input()), @@ -713,6 +722,7 @@ fn draws( let mut levels = Vec::new(); let mut push_len = 0; let mut blocks = [None; 2]; + let mut stencil_bit = None; for placement in &translated.push { let at = table(placement.stage)?; if let Some((offset, size)) = placement.push_range { @@ -852,6 +862,16 @@ fn draws( PushField::IndirectRange if at == VERTEX => FieldValue::IndirectRange, PushField::IndirectSequence if at == VERTEX => FieldValue::IndirectSequence, PushField::IndirectBase if at == VERTEX => FieldValue::IndirectBase, + // The bit a fragment function whose stencil output is drawn by bits keeps its + // fragments for: every fragment, but in a draw's bit draws, which write their own + // bit over it. One in the parameter block is not supplied. + PushField::StencilBit if at == FRAGMENT => match offset { + DrawPlace::Push(pushed) => { + stencil_bit = Some(pushed); + FieldValue::Word(EVERY_FRAGMENT) + } + DrawPlace::Block(..) => return Err(draw_input()), + }, _ => return Err(draw_input()), }; fields.push((offset, at, value)); @@ -902,6 +922,7 @@ fn draws( first_instance_zero: divided && !nonzero_first_instance, patches: pipeline.graphics.tessellation.is_some(), selects_viewport: pipeline.graphics.writes_viewport_index, + stencil_bit, }; Ok((draws, (numbered, constexprs))) } diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index 450cdda5a..f74dbb342 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -87,7 +87,7 @@ use crate::alias; use crate::buffer::{Buffer, BufferInner, BufferObject}; use crate::command::{Building, CommandBuffer}; use crate::counters::Metric; -use crate::depth_stencil::{DepthStencilState, Face, Tests}; +use crate::depth_stencil::{BitDraws, DepthStencilState, Face, Tests, EVERY_FRAGMENT}; use crate::device::Core; use crate::encoder::{ check_alignment, merge, Declared, Resource, ResourceUsage, BUFFER_SLOTS, SAMPLER_SLOTS, @@ -1540,7 +1540,8 @@ impl RenderCommandEncoder { let query = self.building().take_query()?; // SAFETY: as above. unsafe { self.results.end(&self.core.device, self.command) }; - self.results.start(offset, query); + self.results + .start(offset, query, mode == VisibilityResultMode::Counting); Ok(()) } @@ -2491,6 +2492,17 @@ impl RenderCommandEncoder { if lines && self.line_width != 1.0 { return gap(DrawKind::LineWidth); } + // A fragment function's stencil output drawn by bits: the draws this draw takes and the + // push offset of the bit each keeps, where it takes more than one. + let bits = match draws.stencil_bit { + None => None, + Some(at) => match BitDraws::of(self.tests, self.stencil_reference) { + None => return gap(DrawKind::StencilOutput), + Some(each) if each.draws().len() == 1 => None, + Some(_) if self.results.counts_samples() => return gap(DrawKind::StencilOutput), + Some(each) => Some((at as usize, each)), + }, + }; // Points Metal does not rasterize: the vertex function runs, behind an empty scissor. let hidden = topology == vk::PrimitiveTopology::POINT_LIST && !compiled.rasterizes_points(); let pipeline = compiled.pipeline(topology, self.raster)?; @@ -2627,6 +2639,10 @@ impl RenderCommandEncoder { self.push_filled = !commands; } let push = !self.push.is_empty() && building.push_needed(&self.push); + // A draw by bits records each of its draws' tests and reference before that draw. + if bits.is_some() { + self.dirty &= !(DEPTH | STENCIL | REFERENCE); + } let core = &*self.core; let command = self.command; // SAFETY: the command buffer is inside the pass's rendering, which the pipeline renders @@ -2678,127 +2694,153 @@ impl RenderCommandEncoder { if push { device.cmd_push_constants(command, core.layout, PUSH_STAGES, 0, &self.push); } - match (call, index) { - ( - Call::Indexed { - index_count, - base_vertex, - .. - }, - Some((_, buffer, offset, ty)), - ) => { - device.cmd_bind_index_buffer(command, buffer, offset, ty); - device.cmd_draw_indexed( - command, - index_count, - instance_count, - 0, - base_vertex, - base_instance, - ); - } - ( - Call::Direct { - vertex_start, - vertex_count, - }, - _, - ) => device.cmd_draw( - command, - vertex_count, - instance_count, - vertex_start, - base_instance, - ), - ( - Call::Patches { - patch_start, - patch_count, - }, - _, - ) => device.cmd_draw( - command, - patch_count, - instance_count, - patch_start, - base_instance, - ), - ( - Call::Indirect { - arguments, offset, .. - }, - index, - ) => { - let (reached, at) = arguments.device_range(); - let stride = indirect_bytes(index.is_some()) as u32; - match index { - Some((_, buffer, index_offset, ty)) => { - device.cmd_bind_index_buffer(command, buffer, index_offset, ty); - device.cmd_draw_indexed_indirect( - command, - reached, - at + offset, - 1, - stride, - ); + // A draw by bits: each of its draws after its tests, its reference and, past the + // first, whose bit is the one the push bytes hold, its bit. + let bit_draws = bits + .as_ref() + .map_or(&[][..], |(_, bit_draws)| bit_draws.draws()); + for at in 0..bit_draws.len().max(1) { + if let (Some(draw), Some((offset, _))) = (bit_draws.get(at), &bits) { + record_tests(device, command, draw.tests, self.recorded, (true, true)); + self.recorded = Some(draw.tests); + if at == 0 || bit_draws[at - 1].reference != draw.reference { + record_reference(device, command, draw.reference); + } + if at > 0 { + let offset = *offset; + let bit = draw.bit.to_le_bytes(); + self.push[offset..offset + 4].copy_from_slice(&bit); + if building.push_needed(&self.push) { + let pushed = &self.push; + device.cmd_push_constants(command, core.layout, PUSH_STAGES, 0, pushed); } - None => device.cmd_draw_indirect(command, reached, at + offset, 1, stride), } } - ( - Call::Commands { - buffer, - first, - sequences, - counts, - .. - }, - _, - ) => { - if let (Some(indirect), Some((shape, _, preprocess))) = - (&core.indirect, &execution) - { - // One execution of each part, in order, each part's first command pushed - // at the base field; the first part's push is the draw's own. Over a - // range a buffer holds, each part runs as many as its count says. - let layout = buffer.layout(); - let info = crate::dgc::PipelineInfo::new(pipeline); - let base = shape.base as usize; - for (part, from) in (0..sequences).step_by(shape.part as usize).enumerate() - { - let count = (sequences - from).min(shape.part); - let counted = match counts { - 0 => 0, - counts => counts + 4 * part as u64, - }; - if part > 0 { - let command_index = first + from; - self.push[base..base + 4] - .copy_from_slice(&command_index.to_le_bytes()); - device.cmd_push_constants( + match (call, index) { + ( + Call::Indexed { + index_count, + base_vertex, + .. + }, + Some((_, buffer, offset, ty)), + ) => { + device.cmd_bind_index_buffer(command, buffer, offset, ty); + device.cmd_draw_indexed( + command, + index_count, + instance_count, + 0, + base_vertex, + base_instance, + ); + } + ( + Call::Direct { + vertex_start, + vertex_count, + }, + _, + ) => device.cmd_draw( + command, + vertex_count, + instance_count, + vertex_start, + base_instance, + ), + ( + Call::Patches { + patch_start, + patch_count, + }, + _, + ) => device.cmd_draw( + command, + patch_count, + instance_count, + patch_start, + base_instance, + ), + ( + Call::Indirect { + arguments, offset, .. + }, + index, + ) => { + let (reached, at) = arguments.device_range(); + let stride = indirect_bytes(index.is_some()) as u32; + match index { + Some((_, buffer, index_offset, ty)) => { + device.cmd_bind_index_buffer(command, buffer, index_offset, ty); + device.cmd_draw_indexed_indirect( command, - core.layout, - PUSH_STAGES, - 0, - &self.push, + reached, + at + offset, + 1, + stride, ); } - let stream = - buffer.records().memory.address + layout.command(first + from); - let size = u64::from(count) * u64::from(layout.stride()); - let at = *preprocess + shape.part_stride() * part as u64; - let generated = crate::dgc::CommandsInfo::new( - &info, - shape.layout.handle(), - (stream, size), - (at, shape.preprocess_size()), - (count, counted), - ); - (indirect.dgc.execute)(command, vk::FALSE, &generated); + None => { + device.cmd_draw_indirect(command, reached, at + offset, 1, stride) + } } } + ( + Call::Commands { + buffer, + first, + sequences, + counts, + .. + }, + _, + ) => { + if let (Some(indirect), Some((shape, _, preprocess))) = + (&core.indirect, &execution) + { + // One execution of each part, in order, each part's first command pushed + // at the base field; the first part's push is the draw's own. Over a + // range a buffer holds, each part runs as many as its count says. + let layout = buffer.layout(); + let info = crate::dgc::PipelineInfo::new(pipeline); + let base = shape.base as usize; + for (part, from) in + (0..sequences).step_by(shape.part as usize).enumerate() + { + let count = (sequences - from).min(shape.part); + let counted = match counts { + 0 => 0, + counts => counts + 4 * part as u64, + }; + if part > 0 { + let command_index = first + from; + self.push[base..base + 4] + .copy_from_slice(&command_index.to_le_bytes()); + device.cmd_push_constants( + command, + core.layout, + PUSH_STAGES, + 0, + &self.push, + ); + } + let stream = + buffer.records().memory.address + layout.command(first + from); + let size = u64::from(count) * u64::from(layout.stride()); + let at = *preprocess + shape.part_stride() * part as u64; + let generated = crate::dgc::CommandsInfo::new( + &info, + shape.layout.handle(), + (stream, size), + (at, shape.preprocess_size()), + (count, counted), + ); + (indirect.dgc.execute)(command, vk::FALSE, &generated); + } + } + } + (Call::Indexed { .. }, None) => {} } - (Call::Indexed { .. }, None) => {} } } // An execution holds its records, layout and region until the command buffer retires, @@ -2809,6 +2851,16 @@ impl RenderCommandEncoder { building.keep_executed(executed); building.pushes_lost(); } + // After a draw by bits, the push bytes keep every fragment again, and the next draw + // records the encoder's tests and reference where they differ from the last draw's. + if let Some((offset, bit_draws)) = &bits { + let every = EVERY_FRAGMENT.to_le_bytes(); + self.push[*offset..*offset + 4].copy_from_slice(&every); + self.dirty |= DEPTH | STENCIL | REFERENCE; + for _ in 1..bit_draws.draws().len() { + building.count(Metric::StencilBitDraws); + } + } if self.facts.levels { building.count(Metric::LevelFieldCommands); } @@ -3358,7 +3410,6 @@ impl RenderCommandEncoder { let command = self.command; let dirty = self.dirty; self.dirty = 0; - let both = [vk::StencilFaceFlags::FRONT, vk::StencilFaceFlags::BACK]; // SAFETY: the command buffer records; each state is dynamic in every render pipeline. unsafe { // As many scissors as viewports, as Vulkan's with-count states require. @@ -3398,50 +3449,12 @@ impl RenderCommandEncoder { // Of the tests, the fields that differ from the ones last recorded; every field // before the first draw. A draw whose tests are not dirty copies none of them. if dirty & (DEPTH | STENCIL) != 0 { - let (t, was) = (self.tests, self.recorded); - if dirty & DEPTH != 0 { - if was.is_none_or(|w| w.depth_test != t.depth_test) { - device.cmd_set_depth_test_enable(command, t.depth_test); - } - if was.is_none_or(|w| w.depth_write != t.depth_write) { - device.cmd_set_depth_write_enable(command, t.depth_write); - } - if was.is_none_or(|w| w.depth_compare != t.depth_compare) { - device.cmd_set_depth_compare_op(command, t.depth_compare); - } - } - if dirty & STENCIL != 0 { - if was.is_none_or(|w| w.stencil != t.stencil) { - device.cmd_set_stencil_test_enable(command, t.stencil); - } - for (at, face) in both.iter().enumerate() { - let f = &t.faces[at]; - let old = was.map(|w| w.faces[at]); - let ops = |f: &Face| (f.fail, f.pass, f.depth_fail, f.compare); - if old.is_none_or(|o| ops(&o) != ops(f)) { - device.cmd_set_stencil_op( - command, - *face, - f.fail, - f.pass, - f.depth_fail, - f.compare, - ); - } - if old.is_none_or(|o| o.compare_mask != f.compare_mask) { - device.cmd_set_stencil_compare_mask(command, *face, f.compare_mask); - } - if old.is_none_or(|o| o.write_mask != f.write_mask) { - device.cmd_set_stencil_write_mask(command, *face, f.write_mask); - } - } - } - self.recorded = Some(t); + let parts = (dirty & DEPTH != 0, dirty & STENCIL != 0); + record_tests(device, command, self.tests, self.recorded, parts); + self.recorded = Some(self.tests); } if dirty & REFERENCE != 0 { - for (face, reference) in both.iter().zip(self.stencil_reference) { - device.cmd_set_stencil_reference(command, *face, reference); - } + record_reference(device, command, self.stencil_reference); } if dirty & BLEND != 0 { device.cmd_set_blend_constants(command, &self.blend_color); @@ -3648,6 +3661,75 @@ impl RenderCommandEncoder { } } +/// Records the fields of `tests` that differ from `was`, the tests last recorded (every field +/// where none were), of its depth part and of its stencil part where `parts` says so. +/// +/// # Safety +/// +/// `command` records; each state is dynamic in every render pipeline. +unsafe fn record_tests( + device: &ash::Device, + command: vk::CommandBuffer, + t: Tests, + was: Option, + (depth, stencil): (bool, bool), +) { + let both = [vk::StencilFaceFlags::FRONT, vk::StencilFaceFlags::BACK]; + // SAFETY: by the caller. + unsafe { + if depth { + if was.is_none_or(|w| w.depth_test != t.depth_test) { + device.cmd_set_depth_test_enable(command, t.depth_test); + } + if was.is_none_or(|w| w.depth_write != t.depth_write) { + device.cmd_set_depth_write_enable(command, t.depth_write); + } + if was.is_none_or(|w| w.depth_compare != t.depth_compare) { + device.cmd_set_depth_compare_op(command, t.depth_compare); + } + } + if stencil { + if was.is_none_or(|w| w.stencil != t.stencil) { + device.cmd_set_stencil_test_enable(command, t.stencil); + } + for (at, face) in both.iter().enumerate() { + let f = &t.faces[at]; + let old = was.map(|w| w.faces[at]); + let ops = |f: &Face| (f.fail, f.pass, f.depth_fail, f.compare); + if old.is_none_or(|o| ops(&o) != ops(f)) { + device.cmd_set_stencil_op( + command, + *face, + f.fail, + f.pass, + f.depth_fail, + f.compare, + ); + } + if old.is_none_or(|o| o.compare_mask != f.compare_mask) { + device.cmd_set_stencil_compare_mask(command, *face, f.compare_mask); + } + if old.is_none_or(|o| o.write_mask != f.write_mask) { + device.cmd_set_stencil_write_mask(command, *face, f.write_mask); + } + } + } + } +} + +/// Records `reference`, each face's stencil reference. +/// +/// # Safety +/// +/// As [`record_tests`]. +unsafe fn record_reference(device: &ash::Device, command: vk::CommandBuffer, reference: [u32; 2]) { + let both = [vk::StencilFaceFlags::FRONT, vk::StencilFaceFlags::BACK]; + for (face, reference) in both.iter().zip(reference) { + // SAFETY: by the caller. + unsafe { device.cmd_set_stencil_reference(command, *face, reference) }; + } +} + /// The topology of a draw of `primitive_type`, and whether it restarts strips. fn primitives(primitive_type: PrimitiveType) -> (vk::PrimitiveTopology, bool) { let (topology, restart) = input_assembly(primitive_type); diff --git a/crates/metal2vulkan-runtime/src/tests/indirect.rs b/crates/metal2vulkan-runtime/src/tests/indirect.rs index 7c08be372..d2aff5c0e 100644 --- a/crates/metal2vulkan-runtime/src/tests/indirect.rs +++ b/crates/metal2vulkan-runtime/src/tests/indirect.rs @@ -87,6 +87,7 @@ fn draws(fields: Vec<(DrawPlace, usize, FieldValue)>) -> Draws { first_instance_zero: false, patches: false, selects_viewport: false, + stencil_bit: None, } } diff --git a/crates/metal2vulkan-runtime/src/tests/stencil_export.rs b/crates/metal2vulkan-runtime/src/tests/stencil_export.rs index be41cc53a..442fe7155 100644 --- a/crates/metal2vulkan-runtime/src/tests/stencil_export.rs +++ b/crates/metal2vulkan-runtime/src/tests/stencil_export.rs @@ -1,120 +1,977 @@ -//! A fragment function's `[[stencil]]` output (`floor`'s `OPTIONAL_EXTENSIONS`), under a device cfg -//! on every device of the cfg's kind: where the device lists `VK_EXT_shader_stencil_export`, -//! device creation enables it, the translator's profile has it, the state is made, and a draw -//! whose depth-stencil state replaces the stencil stores each fragment's output, its low 8 bits as -//! Metal takes them, at every pixel; elsewhere the device names no such extension and creation -//! refuses the state naming `StencilExport`, the pixel interlock choosing no other form under the -//! identity domains. +//! A fragment function's `[[stencil]]` output, the reference of both faces' stencil test for its +//! fragment. Where the device lists `VK_EXT_shader_stencil_export` (`floor`'s +//! `OPTIONAL_EXTENSIONS`), device creation enables it and the function writes +//! `FragStencilRefEXT`; elsewhere each draw takes the draws of `depth_stencil::BitDraws` +//! (`RuntimeFact::StencilBitDraws`), counted in `Metrics::stencil_bit_draws`. //! -//! `colored_vertex` (the runtime's examples) draws the fullscreen triangle; `stx_stencil_by_pixel` -//! (engine `stx_stencil`) returns word `y * width + x` of its buffer 0 at pixel `(x, y)`. +//! Without a device: the draws `BitDraws` takes for each kind of depth-stencil state. //! -//! `llvm-as` assembles the functions; without it the test skips visibly. +//! Under a device cfg, on every device of the cfg's kind, each draw a quad of two triangles over +//! an 8 x 8 target, the encoder's reference `0x5a`, both faces `Always` and `Replace` under write +//! mask `0xff`: +//! +//! - the stencil alone (`stx_stencil_by_pixel`, a `Stencil8` attachment cleared to `0x3c`): every +//! texel the low 8 bits of its fragment's output, the texels whose output's low bits are 0 +//! among them; +//! - the stencil and the depth (`stx_stencil_with_depth`, a `Depth32Float_Stencil8` attachment +//! cleared to `0x3c` and 0.5): under a depth compare of `Always` that writes, every texel its +//! fragment's stencil and depth, a texel whose output's low bits are 0 holding what the first +//! draw alone wrote; under `Less` that writes, with a depth failure of `Invert`, a fragment that +//! passes stores its stencil and its depth, and one that fails keeps 0.5 and inverts the stencil; +//! - the counter: 8 draws more for each of those draws, 9 under `Less`, on a device without the +//! extension, and 0 on one with it; +//! - two triangles of one draw over one half of the target (`overlap_stencil`, outputs `0x35`, +//! then `0x4a`): the half one fragment reaches stores `0x35`; the half both reach stores the +//! later `0x4a` with the extension and their OR, `0x7f`, without it +//! (`PrecisionNote::StencilOutputOverlap`), the row printed; +//! - refused without the extension, made and drawn with it: a function that writes a colour +//! beside its stencil (`stx_stencil_ms_color`, at the state's creation, naming +//! `StencilExport`), a draw under a stencil compare of `Equal` and one in a `Counting` visibility +//! result's segment (`DrawKind::StencilOutput`); a draw in a `Boolean` segment is drawn. +//! +//! And the route a guest's GL layer takes to copy a depth and stencil texture by drawing: a +//! 4-sample `Depth32Float_Stencil8` source, each quadrant's stencil and each pixel's depth drawn +//! there, read at sample 0 by a function writing `[[depth(any)]]` and `[[stencil]]` +//! (`blit_stencil`) into a single-sample target through a triangle strip of 4 vertices, under +//! both faces `Always` and `Replace` under `0xff` and a depth compare of `Always` that writes, +//! beside a colour attachment 0 of `RGBA8Unorm` whose write mask is none and blending off: each +//! texel the source's stencil and depth, the colour as its clear left it, and 8 draws more +//! without the extension. +//! +//! `colored_vertex` (the runtime's examples) draws the geometry; `overlap_stencil` and +//! `blit_stencil` are owned AIR text ([`STENCIL_FRAGMENTS`]). `llvm-as` assembles the functions; +//! without it the tests skip visibly. + +use crate::depth_stencil::{BitDraw, BitDraws, Tests, EVERY_FRAGMENT}; +use ash::vk; +use metal2vulkan::metal::state::DepthStencilDescriptor; +use metal2vulkan::metal::{CompareFunction, StencilOperation}; + +/// Both faces of `d` replace on a pass. +fn replacing(mut d: DepthStencilDescriptor) -> DepthStencilDescriptor { + for face in [&mut d.front_face_stencil, &mut d.back_face_stencil] { + face.depth_stencil_pass_operation = StencilOperation::Replace; + } + d +} + +/// A draw takes itself alone where its state replaces no bit, a zeroing draw and a draw per bit +/// its replacing faces' write masks hold where it does, and a last draw that writes the depth +/// where the state writes it under a compare that tests; none under a compare the reference +/// decides. +#[test] +fn a_draw_by_bits_takes_a_draw_for_each_bit_its_state_can_replace() { + let reference = [0x5a, 0x5a]; + let draws = |d: &DepthStencilDescriptor| BitDraws::of(Tests::of(d), reference); + let own = |d: &DepthStencilDescriptor| BitDraw { + tests: Tests::of(d), + reference, + bit: EVERY_FRAGMENT, + }; + // No stencil test, and a `Replace` under a write mask of 0: the draw alone. + let plain = DepthStencilDescriptor::default(); + let alone = draws(&plain).expect("no stencil test"); + assert!(alone.draws() == [own(&plain)]); + let mut unwritten = replacing(DepthStencilDescriptor::default()); + unwritten.front_face_stencil.write_mask = 0x100; + unwritten.back_face_stencil.write_mask = 0; + let alone = draws(&unwritten).expect("Always"); + assert!(alone.draws() == [own(&unwritten)]); + + // Both faces `Always` and `Replace` under every bit, a depth compare of `Always` that writes: + // the zeroing draw, which writes the depth, then a draw for each bit. + let mut replace = replacing(DepthStencilDescriptor::default()); + replace.depth_write_enabled = true; + let all = draws(&replace).expect("Always"); + let zeroing = BitDraw { + reference: [0; 2], + ..own(&replace) + }; + assert_eq!(all.draws().len(), 9); + assert!(all.draws()[0] == zeroing); + for (k, draw) in all.draws()[1..].iter().enumerate() { + assert_eq!((draw.bit, draw.reference), (k as u32, [255; 2]), "bit {k}"); + assert!(!draw.tests.depth_write, "bit {k}"); + for face in draw.tests.faces { + let ops = (face.fail, face.pass, face.depth_fail); + let (keep, replace) = (vk::StencilOp::KEEP, vk::StencilOp::REPLACE); + assert!(ops == (keep, replace, keep), "bit {k}"); + assert_eq!(face.write_mask, 1 << k, "bit {k}"); + assert!(face.compare == vk::CompareOp::ALWAYS, "bit {k}"); + } + } + + // Under a depth compare that tests and writes: no draw before the last writes the depth, and + // the last writes it under the encoder's reference and stencil write masks of 0. + replace.depth_compare_function = CompareFunction::Less; + let last = draws(&replace).expect("Always"); + assert_eq!(last.draws().len(), 10); + assert!(last.draws()[..9].iter().all(|draw| !draw.tests.depth_write)); + let fin = last.draws()[9]; + assert_eq!((fin.bit, fin.reference), (EVERY_FRAGMENT, reference)); + let tests = Tests::of(&replace); + assert!(fin.tests.depth() == tests.depth()); + assert!(fin.tests.faces.iter().all(|face| face.write_mask == 0)); + + // Only a face that replaces counts, and only the low 8 bits of its write mask: a front face + // that increments under `0xff0` beside a back face of `Never` that replaces on a failure under + // `0x105`. The first draw keeps the increment; the bit draws keep none. + let mut mixed = DepthStencilDescriptor::default(); + mixed.front_face_stencil.depth_stencil_pass_operation = StencilOperation::IncrementClamp; + mixed.front_face_stencil.write_mask = 0xff0; + let back = &mut mixed.back_face_stencil; + back.stencil_compare_function = CompareFunction::Never; + back.stencil_failure_operation = StencilOperation::Replace; + back.write_mask = 0x105; + let mixed = draws(&mixed).expect("Always and Never"); + let bits: Vec = mixed.draws().iter().map(|draw| draw.bit).collect(); + assert_eq!(bits, [EVERY_FRAGMENT, 0, 2]); + let first = mixed.draws()[0].tests.faces; + assert!(first[0].pass == vk::StencilOp::INCREMENT_AND_CLAMP); + for draw in &mixed.draws()[1..] { + let [front, back] = draw.tests.faces; + assert!((front.pass, front.write_mask) == (vk::StencilOp::KEEP, 0)); + assert!(back.fail == vk::StencilOp::REPLACE); + assert_eq!(back.write_mask, 1 << draw.bit); + } + + // A compare the reference decides. + let mut equal = replace; + equal.back_face_stencil.stencil_compare_function = CompareFunction::Equal; + assert!(draws(&equal).is_none()); +} + +/// Two fragment functions of our own: `overlap_stencil` returns as its `[[stencil]]` its flat +/// colour input's red channel, converted to `uint`; `blit_stencil` returns as its +/// `[[depth(any)]]` sample 0 of its `depth2d_ms` (texture 0) and as its `[[stencil]]` the +/// first component of sample 0 of its `texture2d_ms` (texture 1), each at its pixel. +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +const STENCIL_FRAGMENTS: &str = r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +define <{ i32 }> @overlap_stencil(<4 x float> %position, <4 x float> %color) { + %red = extractelement <4 x float> %color, i64 0 + %stencil = tail call i32 @air.convert.u.i32.f.f32(float %red) + %out = insertvalue <{ i32 }> undef, i32 %stencil, 0 + ret <{ i32 }> %out +} + +define <{ float, i32 }> @blit_stencil(<4 x float> %position, ptr addrspace(1) %depths, ptr addrspace(1) %stencils) { + %x = extractelement <4 x float> %position, i64 0 + %y = extractelement <4 x float> %position, i64 1 + %xi = tail call i32 @air.convert.u.i32.f.f32(float %x) + %yi = tail call i32 @air.convert.u.i32.f.f32(float %y) + %p0 = insertelement <2 x i32> undef, i32 %xi, i64 0 + %p = insertelement <2 x i32> %p0, i32 %yi, i64 1 + %sampler = tail call ptr addrspace(2) @air.get_read_sampler() + %d = tail call { float, i8 } @air.read_depth_2d_ms.f32(ptr addrspace(1) %depths, ptr addrspace(2) %sampler, i32 1, <2 x i32> %p, i32 0, i32 1) + %depth = extractvalue { float, i8 } %d, 0 + %t = tail call { <4 x i32>, i8 } @air.read_texture_2d_ms.u.v4i32(ptr addrspace(1) %stencils, ptr addrspace(2) %sampler, <2 x i32> %p, i32 0, i32 1) + %texel = extractvalue { <4 x i32>, i8 } %t, 0 + %stencil = extractelement <4 x i32> %texel, i64 0 + %o0 = insertvalue <{ float, i32 }> undef, float %depth, 0 + %out = insertvalue <{ float, i32 }> %o0, i32 %stencil, 1 + ret <{ float, i32 }> %out +} + +declare i32 @air.convert.u.i32.f.f32(float) +declare ptr addrspace(2) @air.get_read_sampler() +declare { float, i8 } @air.read_depth_2d_ms.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x i32>, i32, i32) +declare { <4 x i32>, i8 } @air.read_texture_2d_ms.u.v4i32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, i32, i32) + +!air.fragment = !{!0, !6} +!air.version = !{!20} +!air.language_version = !{!21} + +!0 = !{ptr @overlap_stencil, !1, !3} +!1 = !{!2} +!2 = !{!"air.stencil", !"air.arg_type_name", !"uint", !"air.arg_name", !"stencil"} +!3 = !{!4, !5} +!4 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position", !"air.arg_unused"} +!5 = !{i32 1, !"air.fragment_input", !"generated(5colorDv4_f)", !"air.flat", !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} +!6 = !{ptr @blit_stencil, !7, !9} +!7 = !{!8, !2} +!8 = !{!"air.depth", !"air.depth_qualifier", !"air.any", !"air.arg_type_name", !"float", !"air.arg_name", !"depth"} +!9 = !{!10, !11, !12} +!10 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!11 = !{i32 1, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"depth2d_ms", !"air.arg_name", !"depths"} +!12 = !{i32 2, !"air.texture", !"air.location_index", i32 1, i32 1, !"air.read", !"air.arg_type_name", !"texture2d_ms", !"air.arg_name", !"stencils"} +!20 = !{i32 2, i32 8, i32 0} +!21 = !{!"Metal", i32 4, i32 0, i32 0} +"#; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod on_device { - use crate::tests::command::on_device::each_device; - use crate::tests::draw::on_device::{ - descriptor, examples, library, pass, read, run, target, vertices, Buffers, SIDE, - }; - use crate::texture::TextureObject; + use super::{replacing, STENCIL_FRAGMENTS}; + use crate::tests::command::on_device::{each_device, finished}; + use crate::tests::draw::on_device::{examples, floats, library, Buffers, SIDE}; use crate::{ - DepthStencilDescriptor, Error, FunctionDescriptor, PixelFormat, PrimitiveType, StageSource, - StencilOperation, TextureUsage, + Buffer, BufferLayout, ClearColor, ColorAttachmentDescriptor, CompareFunction, + DepthStencilDescriptor, DepthStencilState, Device, DrawKind, Error, FunctionDescriptor, + Gap, IndexClass, Library, LoadAction, PixelFormat, PrimitiveType, RenderPassDescriptor, + RenderPipelineDescriptor, RenderPipelineState, ScissorRect, StageSource, StencilOperation, + StorageMode, StoreAction, Texture, TextureDescriptor, TexturePlace, TextureType, + TextureUsage, VisibilityResultMode, }; use metal2vulkan::error::Feature; - use metal2vulkan_devtools::engine_dir; + use metal2vulkan::metal::ColorWriteMask; + use metal2vulkan_devtools::{engine_dir, llvm_assemble_text, AssembleError}; + + /// The stencil the attachments clear to, and the depth. + const CLEARED: u32 = 0x3c; + const CLEARED_DEPTH: f32 = 0.5; + /// The encoder's reference, which each fragment's output replaces. + const REFERENCE: u32 = 0x5a; + /// The overlap row's outputs: the first triangle's, then the second's. + const FIRST: u32 = 0x35; + const SECOND: u32 = 0x4a; + const TEXELS: usize = (SIDE * SIDE) as usize; /// The word pixel `i` (row-major) of the fragment function's buffer returns: bits above the - /// low 8 on two of every three pixels, which Metal's stencil reference drops. + /// low 8 on two of every three pixels, which Metal's stencil reference drops, and low bits of + /// 0 on every fifth pixel, which only the zeroing draw reaches. fn value(i: u32) -> u32 { - 0x100 * (i % 3) + (i * 29 + 7) % 256 + let low = match i % 5 { + 0 => 0, + _ => (i * 29 + 7) % 256, + }; + 0x100 * (i % 3) + low } + /// The depth pixel `i` returns: eighths along the diagonals, half of them below + /// [`CLEARED_DEPTH`]. + fn depth(i: u32) -> f32 { + ((i + i / SIDE) % 8) as f32 / 8.0 + } + + /// The library of [`STENCIL_FRAGMENTS`], or `None` where `llvm-as` is missing. + fn ours() -> Option { + match llvm_assemble_text(STENCIL_FRAGMENTS) { + Ok(bitcode) => Some(Library::from_air(&bitcode).expect("the library")), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(error) => panic!("the stencil fragments: {error:?}"), + } + } + + fn stage(library: &Library, name: &str) -> StageSource { + StageSource::Function(FunctionDescriptor::new( + library.function(name).expect("the function"), + )) + } + + /// A pipeline of `colored_vertex` and `fragment`, drawing into a `format` attachment as its + /// depth (where the format has it) and its stencil, and no colour attachment. + fn descriptor( + examples: &Library, + (library, fragment): (&Library, &str), + format: PixelFormat, + ) -> RenderPipelineDescriptor { + let mut d = RenderPipelineDescriptor::new(stage(examples, "colored_vertex")); + d.fragment = Some(stage(library, fragment)); + d.stencil_format = Some(format); + if format == PixelFormat::Depth32FloatStencil8 { + d.depth_format = Some(format); + } + d + } + + /// Whether `device` lists the extension, which its translator's profile then has. + fn exports(name: &str, device: &Device) -> bool { + let export = ash::ext::shader_stencil_export::NAME; + let listed = device.extensions().iter().any(|e| e.as_c_str() == export); + let profile = device.core().translator.profile().fragment().stencil_export; + assert_eq!(profile, listed, "{name}: the translator's stencil export"); + listed + } + + /// The bit draws the device counted. + fn bit_draws(device: &Device) -> u64 { + device.counters().metrics().stencil_bit_draws + } + + /// A Shared buffer's bytes, as the host reads them. + fn bytes(buffer: &Buffer) -> Vec { + let contents = buffer.contents().expect("a Shared buffer"); + // SAFETY: the buffer is alive, `length` bytes long, and no GPU work uses it. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), buffer.length() as usize) }.to_vec() + } + + fn floats_of(bytes: &[u8]) -> Vec { + let (words, _) = bytes.as_chunks::<4>(); + words.iter().map(|word| f32::from_le_bytes(*word)).collect() + } + + /// A Private `SIDE` x `SIDE` render target of `format` and `samples`, at texture index + /// `index` where given. + fn attachment( + device: &Device, + format: PixelFormat, + samples: u32, + index: Option, + ) -> Texture { + let kind = match samples { + 1 => TextureType::Type2D, + _ => TextureType::Type2DMultisample, + }; + let mut d = TextureDescriptor::new(kind, format, SIDE, SIDE); + d.sample_count = samples; + d.usage = TextureUsage::RENDER_TARGET; + if index.is_some() { + d.usage |= TextureUsage::SHADER_READ | TextureUsage::PIXEL_FORMAT_VIEW; + } + d.storage_mode = StorageMode::Private; + let made = match index { + Some(index) => device.new_texture(&d, Some(index)), + None => device.new_texture_for_views(&d), + }; + made.unwrap_or_else(|error| panic!("{format:?}: {error}")) + } + + /// A pass of `attachment` as its stencil, and its depth where its format has one, cleared to + /// [`CLEARED`] and [`CLEARED_DEPTH`] and stored. + fn pass(attachment: &Texture) -> RenderPassDescriptor { + let mut d = RenderPassDescriptor::default(); + let s = &mut d.stencil_attachment; + s.texture = Some(attachment.clone()); + s.load_action = LoadAction::Clear; + s.store_action = StoreAction::Store; + s.clear_stencil = CLEARED; + if attachment.descriptor().pixel_format == PixelFormat::Depth32FloatStencil8 { + let z = &mut d.depth_attachment; + z.texture = Some(attachment.clone()); + z.load_action = LoadAction::Clear; + z.store_action = StoreAction::Store; + z.clear_depth = f64::from(CLEARED_DEPTH); + } + d + } + + /// The planes a blit reads back. + #[derive(Clone, Copy, PartialEq)] + enum BlitPlanes { + Stencil, + Both, + } + + /// What a draw stored: each texel's stencil, its depth where the attachment has one, and the + /// bit draws the device counted for it. + struct Stored { + stencil: Vec, + depth: Vec, + bit_draws: u64, + } + + /// The vertices of `colored_vertex`: `positions`, two `float`s each, and `reds`, each + /// vertex's colour's red channel. + fn vertices( + device: &Device, + buffers: &mut Buffers, + positions: &[f32], + reds: &[f32], + ) -> [Buffer; 2] { + let colors: Vec = reds.iter().flat_map(|&red| [red, 0.0, 0.0, 0.0]).collect(); + [floats(positions), floats(&colors)].map(|bytes| buffers.of(device, &bytes)) + } + + /// The quad over the whole target, a triangle strip of 4 vertices. + const QUAD: [f32; 8] = [-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0]; + + /// A draw of `state` under `tests` into a new `format` attachment ([`pass`]), its fragment + /// buffers `fragment` from index 0 and the width at index 1, of `positions` as `primitive` + /// with `reds` as their colours' red channels; then the attachment's `planes` read back. + fn stored( + name: &str, + device: &Device, + (state, tests): (&RenderPipelineState, &DepthStencilState), + format: PixelFormat, + fragment: [Option<&Buffer>; 3], + (primitive, positions, reds): (PrimitiveType, &[f32], &[f32]), + ) -> Stored { + let mut buffers = Buffers::new(device); + let [positions, colors] = vertices(device, &mut buffers, positions, reds); + let count = positions.length() as u32 / 8; + let target = attachment(device, format, 1, None); + let planes = match format { + PixelFormat::Depth32FloatStencil8 => BlitPlanes::Both, + _ => BlitPlanes::Stencil, + }; + let stencil_out = buffers.of(device, &[0xee; TEXELS]); + let depth_out = buffers.of(device, &[0xee; 4 * TEXELS]); + let before = bit_draws(device); + let queue = device.new_command_queue(4).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let ok = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + let mut encoder = (command_buffer.render_command_encoder(&pass(&target))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + ok(encoder.set_render_pipeline_state(state)); + ok(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + ok(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + for (index, buffer) in fragment.into_iter().enumerate() { + if let Some(buffer) = buffer { + ok(encoder.set_fragment_buffer(Some(buffer), 0, index as u32)); + } + } + ok(encoder.set_fragment_bytes(&SIDE.to_le_bytes(), 1)); + encoder.set_stencil_reference_value(REFERENCE); + ok(encoder.set_depth_stencil_state(Some(tests))); + ok(encoder.draw_primitives(primitive, 0, count, 1, 0)); + encoder.end_encoding(); + read_back( + name, + &command_buffer, + &target, + planes, + [&depth_out, &stencil_out], + ); + Stored { + stencil: bytes(&stencil_out), + depth: floats_of(&bytes(&depth_out)), + bit_draws: bit_draws(device) - before, + } + } + + /// Copies `texture`'s `planes` into `outs` (depth, then stencil), commits `command_buffer`, + /// and waits for it. + fn read_back( + name: &str, + command_buffer: &crate::CommandBuffer, + texture: &Texture, + planes: BlitPlanes, + [depth_out, stencil_out]: [&Buffer; 2], + ) { + use crate::BlitOption::{DepthFromDepthStencil, StencilFromDepthStencil}; + let ok = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + let mut blit = (command_buffer.blit_command_encoder()) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let place = TexturePlace { + slice: 0, + level: 0, + origin: [0; 3], + }; + let whole = [SIDE, SIDE, 1]; + let tight = |bytes: u64| BufferLayout { + offset: 0, + bytes_per_row: bytes * u64::from(SIDE), + bytes_per_image: bytes * u64::from(SIDE * SIDE), + }; + match planes { + BlitPlanes::Stencil => { + ok(blit.copy_from_texture_to_buffer(texture, place, whole, stencil_out, tight(1))) + } + BlitPlanes::Both => { + ok(blit.copy_from_texture_to_buffer_with_options( + texture, + place, + whole, + depth_out, + tight(4), + DepthFromDepthStencil, + )); + ok(blit.copy_from_texture_to_buffer_with_options( + texture, + place, + whole, + stencil_out, + tight(1), + StencilFromDepthStencil, + )); + } + } + blit.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + } + + /// Panics, naming the first texel and how many differ, where `got` is not `want`. + fn exact(name: &str, what: &str, got: &[T], want: &[T]) { + assert_eq!(got.len(), want.len(), "{name}: {what}: the texels read"); + let differ: Vec = (0..got.len()).filter(|&i| got[i] != want[i]).collect(); + if let Some(&first) = differ.first() { + let side = SIDE as usize; + panic!( + "{name}: {what}: {} of {} texels differ, the first at ({}, {}): {:?}, not {:?}", + differ.len(), + got.len(), + first % side, + first / side, + got[first], + want[first] + ); + } + } + + /// The bits of `depths`. + fn bits(depths: &[f32]) -> Vec { + depths.iter().map(|depth| depth.to_bits()).collect() + } + + /// The stencil alone, and the stencil with the depth under `Always` and under `Less`: every + /// texel exact, and the draws by bits counted where the device has no stencil export. #[test] - fn every_device_stores_a_fragment_functions_stencil_output_where_it_lists_the_export() { - let Some(examples) = examples() else { + fn every_device_stores_a_fragment_functions_stencil_output() { + let (Some(examples), Some(stencils)) = + (examples(), library(&engine_dir().join("stx_stencil.ll"))) + else { return; }; - let Some(stencils) = library(&engine_dir().join("stx_stencil.ll")) else { - return; - }; - let mut d = descriptor(&examples, "colored_fragment", PixelFormat::RGBA8Unorm); - d.fragment = Some(StageSource::Function(FunctionDescriptor::new( - stencils - .function("stx_stencil_by_pixel") - .expect("the function"), - ))); - d.stencil_format = Some(PixelFormat::Stencil8); + let alone = descriptor( + &examples, + (&stencils, "stx_stencil_by_pixel"), + PixelFormat::Stencil8, + ); + let with_depth = descriptor( + &examples, + (&stencils, "stx_stencil_with_depth"), + PixelFormat::Depth32FloatStencil8, + ); each_device("stencil_export", |name, _, device| { - let export = ash::ext::shader_stencil_export::NAME; - let listed = device.extensions().iter().any(|e| e.as_c_str() == export); - let profile = device.core().translator.profile().fragment().stencil_export; - assert_eq!(profile, listed, "{name}: the translator's stencil export"); - let made = device.new_render_pipeline_state(&d, crate::tests::no_constexpr_samplers); - let state = match (listed, made) { - (true, Ok(state)) => state, - (true, Err(error)) => panic!("{name}: {error}"), - (false, Ok(_)) => panic!("{name}: a state made without the export"), + let export = exports(name, &device); + let make = |d: &RenderPipelineDescriptor| { + (device.new_render_pipeline_state(d, crate::tests::no_constexpr_samplers)) + .unwrap_or_else(|error| panic!("{name}: {error}")) + }; + let (alone, with_depth) = (make(&alone), make(&with_depth)); + let mut buffers = Buffers::new(&device); + let words: Vec = (0..SIDE * SIDE) + .flat_map(|i| value(i).to_le_bytes()) + .collect(); + let values = buffers.of(&device, &words); + let depths: Vec = (0..SIDE * SIDE).map(depth).collect(); + let depth_buffer = buffers.of(&device, &floats(&depths)); + let quad = (PrimitiveType::TriangleStrip, &QUAD[..], &[0.0; 4][..]); + let replace = replacing(DepthStencilDescriptor::default()); + let outputs: Vec = (0..SIDE * SIDE).map(|i| value(i) as u8).collect(); + let zeros = outputs.iter().filter(|&&s| s == 0).count(); + // What a device without the extension draws beyond each draw. + let more = |n: u64| if export { 0 } else { n }; + let mut counted = Vec::new(); + + // The stencil alone. + let tests = device.new_depth_stencil_state(&replace); + let fragment = [Some(&values), None, None]; + let got = stored( + name, + &device, + (&alone, &tests), + PixelFormat::Stencil8, + fragment, + quad, + ); + exact(name, "the stencil alone", &got.stencil, &outputs); + assert_eq!( + got.bit_draws, + more(8), + "{name}: the stencil alone's bit draws" + ); + counted.push(got.bit_draws); + + // With the depth, under `Always` that writes. + let mut always = replace; + always.depth_write_enabled = true; + let tests = device.new_depth_stencil_state(&always); + let fragment = [Some(&values), None, Some(&depth_buffer)]; + let format = PixelFormat::Depth32FloatStencil8; + let got = stored(name, &device, (&with_depth, &tests), format, fragment, quad); + exact(name, "the stencil beside the depth", &got.stencil, &outputs); + exact( + name, + "the depth beside the stencil", + &bits(&got.depth), + &bits(&depths), + ); + assert_eq!(got.bit_draws, more(8), "{name}: Always's bit draws"); + counted.push(got.bit_draws); + + // With the depth, under `Less` that writes, a depth failure inverting. + let mut less = always; + less.depth_compare_function = CompareFunction::Less; + for face in [&mut less.front_face_stencil, &mut less.back_face_stencil] { + face.depth_failure_operation = StencilOperation::Invert; + } + let tests = device.new_depth_stencil_state(&less); + let got = stored(name, &device, (&with_depth, &tests), format, fragment, quad); + let passes = |i: usize| depths[i] < CLEARED_DEPTH; + let want_stencil: Vec = (0..TEXELS) + .map(|i| match passes(i) { + true => outputs[i], + false => !(CLEARED as u8), + }) + .collect(); + let want_depth: Vec = (0..TEXELS) + .map(|i| match passes(i) { + true => depths[i], + false => CLEARED_DEPTH, + }) + .collect(); + exact(name, "the stencil under Less", &got.stencil, &want_stencil); + exact( + name, + "the depth under Less", + &bits(&got.depth), + &bits(&want_depth), + ); + assert_eq!(got.bit_draws, more(9), "{name}: Less's bit draws"); + counted.push(got.bit_draws); + let passing = (0..TEXELS).filter(|&i| passes(i)).count(); + let form = match export { + true => "VK_EXT_shader_stencil_export enabled", + false => "no VK_EXT_shader_stencil_export: drawn by bits", + }; + println!( + "{name}: {form}; {TEXELS} texels exact for the stencil alone, for the stencil and \ + depth under Always, {zeros} of them of stencil 0 (the zeroing draw's alone), and \ + under Less ({passing} passing, the rest inverted); bit draws {counted:?}" + ); + }); + } + + /// Two triangles of one draw over one half of the target: the half they both reach stores + /// the later output with the extension and the OR of both without it, the row printed. + #[test] + fn every_device_stores_its_answer_where_two_fragments_of_one_draw_overlap() { + let (Some(examples), Some(ours)) = (examples(), ours()) else { + return; + }; + let d = descriptor(&examples, (&ours, "overlap_stencil"), PixelFormat::Stencil8); + each_device("stencil_overlap", |name, _, device| { + let export = exports(name, &device); + let state = (device.new_render_pipeline_state(&d, crate::tests::no_constexpr_samplers)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let tests = + device.new_depth_stencil_state(&replacing(DepthStencilDescriptor::default())); + // The whole target, then its top half (clip space y up). + let positions = [ + -1.0, -1.0, 3.0, -1.0, -1.0, 3.0, -1.0, 0.0, 3.0, 0.0, -1.0, 4.0, + ]; + let reds = [FIRST, FIRST, FIRST, SECOND, SECOND, SECOND].map(|s| s as f32); + let geometry = (PrimitiveType::Triangle, &positions[..], &reds[..]); + let format = PixelFormat::Stencil8; + let got = stored(name, &device, (&state, &tests), format, [None; 3], geometry); + let both = match export { + true => SECOND, + false => FIRST | SECOND, + }; + let want: Vec = (0..SIDE * SIDE) + .map(|i| match i / SIDE < SIDE / 2 { + true => both as u8, + false => FIRST as u8, + }) + .collect(); + let top: std::collections::BTreeSet = + got.stencil[..TEXELS / 2].iter().copied().collect(); + println!( + "{name}: overlap row: {} texels two fragments of one draw reach ({FIRST:#04x}, then \ + {SECOND:#04x}) store {top:02x?}; the {} one reaches store {:02x?}; bit draws {}", + TEXELS / 2, + TEXELS / 2, + (got.stencil[TEXELS / 2..].iter().copied()).collect::>(), + got.bit_draws + ); + exact(name, "the overlap", &got.stencil, &want); + assert_eq!( + got.bit_draws, + if export { 0 } else { 8 }, + "{name}: bit draws" + ); + }); + } + + /// Without the extension: a function that writes a colour beside its stencil is refused at + /// the state's creation, a draw under a stencil compare of `Equal` and one in a `Counting` + /// visibility result's segment are refused; a draw in a `Boolean` segment is drawn. With it, + /// each is made and drawn. + #[test] + fn without_stencil_export_what_draws_by_bits_cannot_answer_is_refused() { + let (Some(examples), Some(stencils), Some(colors)) = ( + examples(), + library(&engine_dir().join("stx_stencil.ll")), + library(&engine_dir().join("stx_stencil_ms.ll")), + ) else { + return; + }; + let alone = descriptor( + &examples, + (&stencils, "stx_stencil_by_pixel"), + PixelFormat::Stencil8, + ); + let mut colored = descriptor( + &examples, + (&colors, "stx_stencil_ms_color"), + PixelFormat::Stencil8, + ); + colored.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::R32Uint)); + each_device("stencil_refusals", |name, _, device| { + let export = exports(name, &device); + let made = + device.new_render_pipeline_state(&colored, crate::tests::no_constexpr_samplers); + match (export, made) { + (true, Ok(_)) => {} ( false, Err(Error::Translation { error: metal2vulkan::error::Error::Unsupported(u), .. }), - ) => { - assert_eq!(u.feature, Feature::StencilExport, "{name}: {u:?}"); - println!("{name}: no stencil export listed; refused naming StencilExport"); - return; - } - (false, Err(error)) => panic!("{name}: {error}"), - }; + ) => assert_eq!(u.feature, Feature::StencilExport, "{name}: {u:?}"), + (_, made) => panic!("{name}: the colour beside the stencil: {:?}", made.err()), + } + let state = (device + .new_render_pipeline_state(&alone, crate::tests::no_constexpr_samplers)) + .unwrap_or_else(|error| panic!("{name}: {error}")); let mut buffers = Buffers::new(&device); - let (positions, colors) = vertices(&device, &mut buffers); let words: Vec = (0..SIDE * SIDE) .flat_map(|i| value(i).to_le_bytes()) .collect(); let values = buffers.of(&device, &words); - let color = target( + let [positions, colors] = vertices(&device, &mut buffers, &QUAD, &[0.0; 4]); + let visibility = buffers.of(&device, &[0xaa; 32]); + let mut equal = replacing(DepthStencilDescriptor::default()); + for face in [&mut equal.front_face_stencil, &mut equal.back_face_stencil] { + face.stencil_compare_function = CompareFunction::Equal; + } + let equal = device.new_depth_stencil_state(&equal); + let replace = + device.new_depth_stencil_state(&replacing(DepthStencilDescriptor::default())); + let target = attachment(&device, PixelFormat::Stencil8, 1, None); + let mut d = pass(&target); + d.visibility_result_buffer = Some(visibility.clone()); + let queue = device.new_command_queue(4).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let ok = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + let mut encoder = (command_buffer.render_command_encoder(&d)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + ok(encoder.set_render_pipeline_state(&state)); + ok(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + ok(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + ok(encoder.set_fragment_buffer(Some(&values), 0, 0)); + ok(encoder.set_fragment_bytes(&SIDE.to_le_bytes(), 1)); + let refused = |result: Result<(), Error>, what: &str| match (export, result) { + (true, Ok(())) => {} + ( + false, + Err(Error::Unsupported(Gap::Draw { + kind: DrawKind::StencilOutput, + })), + ) => {} + (_, result) => panic!("{name}: {what}: {result:?}"), + }; + let quad = |encoder: &mut crate::RenderCommandEncoder| { + encoder.draw_primitives(PrimitiveType::TriangleStrip, 0, 4, 1, 0) + }; + ok(encoder.set_depth_stencil_state(Some(&equal))); + refused(quad(&mut encoder), "under Equal"); + ok(encoder.set_depth_stencil_state(Some(&replace))); + ok(encoder.set_visibility_result_mode(VisibilityResultMode::Counting, 0)); + refused(quad(&mut encoder), "in a Counting segment"); + ok(encoder.set_visibility_result_mode(VisibilityResultMode::Boolean, 8)); + ok(quad(&mut encoder)); + ok(encoder.set_visibility_result_mode(VisibilityResultMode::Disabled, 0)); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + let boolean = + u64::from_le_bytes((&bytes(&visibility)[8..16]).try_into().expect("8 bytes")); + assert_ne!(boolean, 0, "{name}: the Boolean segment saw no sample"); + let refusals = match export { + true => "made and drawn: a colour beside the stencil, Equal, a Counting segment", + false => { + "refused: a colour beside the stencil (StencilExport), Equal and a \ + Counting segment (DrawKind::StencilOutput)" + } + }; + println!("{name}: {refusals}; a Boolean segment drawn, its result {boolean}"); + }); + } + + /// The route: a 4-sample source's stencil and depth, read at sample 0 by `blit_stencil`, into + /// a single-sample target beside a colour attachment whose write mask is none. + #[test] + fn every_device_draws_a_multisampled_depth_and_stencil_into_a_single_sample_target() { + let (Some(examples), Some(ours), Some(fill)) = ( + examples(), + ours(), + library(&engine_dir().join("depth_fill.ll")), + ) else { + return; + }; + let format = PixelFormat::Depth32FloatStencil8; + let mut filling = RenderPipelineDescriptor::new(stage(&fill, "depth_fill_vertex")); + filling.fragment = Some(stage(&fill, "depth_fill_fragment")); + filling.depth_format = Some(format); + filling.stencil_format = Some(format); + filling.raster_sample_count = 4; + let mut blit = descriptor(&examples, (&ours, "blit_stencil"), format); + let mut color = ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm); + color.write_mask = ColorWriteMask::NONE; + blit.color_attachments[0] = Some(color); + // Each quadrant's stencil: top left, top right, bottom left, bottom right. + let quadrants: [u32; 4] = [0x00, 0x5a, 0xa5, 0xff]; + let quadrant = |i: u32| { + let (x, y) = (i % SIDE, i / SIDE); + quadrants[usize::from(y >= SIDE / 2) * 2 + usize::from(x >= SIDE / 2)] + }; + each_device("stencil_route", |name, _, device| { + let export = exports(name, &device); + let make = |d: &RenderPipelineDescriptor| { + (device.new_render_pipeline_state(d, crate::tests::no_constexpr_samplers)) + .unwrap_or_else(|error| panic!("{name}: {error}")) + }; + let (filling, blit) = (make(&filling), make(&blit)); + let first = IndexClass::Texture.range().start; + let _textures = (device.grant_indices(IndexClass::Texture, first, 2)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let source = attachment(&device, format, 4, Some(first)); + let stencil_view = (source.new_texture_view( + PixelFormat::X32Stencil8, + TextureType::Type2DMultisample, + 0..1, + 0..1, + Some(first + 1), + )) + .unwrap_or_else(|error| panic!("{name}: the stencil view: {error}")); + let target = attachment(&device, format, 1, None); + let mut buffers = Buffers::new(&device); + let depths: Vec = (0..SIDE * SIDE).map(depth).collect(); + let depth_buffer = buffers.of(&device, &floats(&depths)); + let [positions, colors] = vertices(&device, &mut buffers, &QUAD, &[0.0; 4]); + let stencil_out = buffers.of(&device, &[0xee; TEXELS]); + let depth_out = buffers.of(&device, &[0xee; 4 * TEXELS]); + let colors_target = crate::tests::draw::on_device::target( &device, PixelFormat::RGBA8Unorm, TextureUsage::RENDER_TARGET, ); - let stencil = target(&device, PixelFormat::Stencil8, TextureUsage::RENDER_TARGET); - let mut replace = DepthStencilDescriptor::default(); + let mut always = replacing(DepthStencilDescriptor::default()); + always.depth_write_enabled = true; for face in [ - &mut replace.front_face_stencil, - &mut replace.back_face_stencil, + &mut always.front_face_stencil, + &mut always.back_face_stencil, ] { - face.depth_stencil_pass_operation = StencilOperation::Replace; + face.stencil_failure_operation = StencilOperation::Replace; + face.depth_failure_operation = StencilOperation::Replace; } - let replace = device.new_depth_stencil_state(&replace); + let always = device.new_depth_stencil_state(&always); + let ok = |result: Result<(), Error>, what: &str| { + result.unwrap_or_else(|error| panic!("{name}: {what}: {error}")) + }; let queue = device.new_command_queue(4).expect("a queue"); let command_buffer = queue.command_buffer().expect("a command buffer"); - let mut encoder = (command_buffer - .render_command_encoder(&pass(&color, Some(&stencil)))) - .unwrap_or_else(|error| panic!("{name}: {error}")); - let draw = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); - draw(encoder.set_render_pipeline_state(&state)); - draw(encoder.set_vertex_buffer(Some(&positions), 0, 0)); - draw(encoder.set_vertex_buffer(Some(&colors), 0, 1)); - draw(encoder.set_fragment_buffer(Some(&values), 0, 0)); - draw(encoder.set_fragment_bytes(&SIDE.to_le_bytes(), 1)); - // The encoder's reference, which the fragment's output replaces. - encoder.set_stencil_reference_value(0x5a); - draw(encoder.set_depth_stencil_state(Some(&replace))); - // The second triangle covers the whole target. - draw(encoder.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0)); - encoder.end_encoding(); - run(name, &command_buffer); - if stencil.unit().is_some() { - let want: Vec = (0..SIDE * SIDE).map(|i| value(i) as u8).collect(); - assert_eq!(read(&stencil, 1), want, "{name}: the stencil"); + + // The source: each pixel's depth, each quadrant's stencil through its reference. + let mut fills = RenderPassDescriptor::default(); + let z = &mut fills.depth_attachment; + z.texture = Some(source.clone()); + z.load_action = LoadAction::Clear; + z.store_action = StoreAction::Store; + z.clear_depth = 1.0; + let s = &mut fills.stencil_attachment; + s.texture = Some(source.clone()); + s.load_action = LoadAction::Clear; + s.store_action = StoreAction::Store; + let mut encoder = (command_buffer.render_command_encoder(&fills)) + .unwrap_or_else(|error| panic!("{name}: the source's pass: {error}")); + ok(encoder.set_render_pipeline_state(&filling), "the fill"); + ok( + encoder.set_fragment_buffer(Some(&depth_buffer), 0, 0), + "the depths", + ); + ok( + encoder.set_fragment_bytes(&SIDE.to_le_bytes(), 1), + "the width", + ); + ok( + encoder.set_depth_stencil_state(Some(&always)), + "the fill's state", + ); + let half = u64::from(SIDE / 2); + for (q, &stencil) in quadrants.iter().enumerate() { + encoder.set_scissor_rect(ScissorRect { + x: half * (q as u64 % 2), + y: half * (q as u64 / 2), + width: half, + height: half, + }); + encoder.set_stencil_reference_value(stencil); + ok( + encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0), + "a quadrant", + ); } + encoder.end_encoding(); + + // The route. + let mut route = RenderPassDescriptor::default(); + let c = &mut route.color_attachments[0]; + c.texture = Some(colors_target.clone()); + c.load_action = LoadAction::Clear; + c.clear_color = ClearColor::new(1.0, 0.0, 1.0, 1.0); + let z = &mut route.depth_attachment; + z.texture = Some(target.clone()); + z.load_action = LoadAction::Clear; + z.store_action = StoreAction::Store; + z.clear_depth = f64::from(CLEARED_DEPTH); + let s = &mut route.stencil_attachment; + s.texture = Some(target.clone()); + s.load_action = LoadAction::Clear; + s.store_action = StoreAction::Store; + s.clear_stencil = CLEARED; + let before = bit_draws(&device); + let mut encoder = (command_buffer.render_command_encoder(&route)) + .unwrap_or_else(|error| panic!("{name}: the route's pass: {error}")); + ok(encoder.set_render_pipeline_state(&blit), "the route"); + ok( + encoder.set_vertex_buffer(Some(&positions), 0, 0), + "the positions", + ); + ok( + encoder.set_vertex_buffer(Some(&colors), 0, 1), + "the colours", + ); + ok(encoder.set_fragment_texture(Some(&source), 0), "the source"); + ok( + encoder.set_fragment_texture(Some(&stencil_view), 1), + "the stencil view", + ); + encoder.set_stencil_reference_value(REFERENCE); + ok( + encoder.set_depth_stencil_state(Some(&always)), + "the route's state", + ); + ok( + encoder.draw_primitives(PrimitiveType::TriangleStrip, 0, 4, 1, 0), + "the quad", + ); + encoder.end_encoding(); + read_back( + name, + &command_buffer, + &target, + BlitPlanes::Both, + [&depth_out, &stencil_out], + ); + let counted = bit_draws(&device) - before; + + let want: Vec = (0..SIDE * SIDE).map(|i| quadrant(i) as u8).collect(); + exact(name, "the route's stencil", &bytes(&stencil_out), &want); + exact( + name, + "the route's depth", + &bits(&floats_of(&bytes(&depth_out))), + &bits(&depths), + ); + let colours = crate::tests::draw::on_device::read(&colors_target, 4); + let cleared: Vec = [255, 0, 255, 255].repeat(TEXELS); + exact(name, "the route's colour", &colours, &cleared); + assert_eq!(counted, if export { 0 } else { 8 }, "{name}: bit draws"); println!( - "{name}: VK_EXT_shader_stencil_export enabled; {} pixels stored their fragment's \ - stencil output", - SIDE * SIDE + "{name}: the route: a 4-sample Depth32Float_Stencil8 source read at sample 0 into a \ + single-sample target, {TEXELS} stencils {quadrants:02x?} by quadrant and depths \ + exact, the colour under write mask none as cleared; bit draws {counted}" ); }); } diff --git a/crates/metal2vulkan-runtime/src/visibility.rs b/crates/metal2vulkan-runtime/src/visibility.rs index c078cb91f..06d3be6bc 100644 --- a/crates/metal2vulkan-runtime/src/visibility.rs +++ b/crates/metal2vulkan-runtime/src/visibility.rs @@ -151,6 +151,8 @@ pub(crate) struct Results { /// The `Boolean` or `Counting` mode set last, where no mode set or end of the encoder ended /// it: its offset, its query, and whether a draw began the query. segment: Option<(u64, Query, bool)>, + /// Whether that segment's mode is `Counting`, whose result each draw's passing samples add to. + counted: bool, /// The segments ended, in order. ended: Vec<(u64, Query)>, /// The offsets the encoder's modes took. @@ -174,10 +176,18 @@ impl Results { matches!(self.segment, Some((_, _, true))) } - /// A segment of `query` at `offset` starts, the one before it ended ([`end`](Self::end)). - pub(crate) fn start(&mut self, offset: u64, query: Query) { + /// A segment of `query` at `offset` starts, of mode `Counting` where `counted`, the one before it + /// ended ([`end`](Self::end)). + pub(crate) fn start(&mut self, offset: u64, query: Query, counted: bool) { self.taken.insert(offset); self.segment = Some((offset, query, false)); + self.counted = counted; + } + + /// Whether a `Counting` mode's segment holds the draws: each draw adds its passing samples to + /// the result. + pub(crate) fn counts_samples(&self) -> bool { + self.segment.is_some() && self.counted } /// Before a draw: begins the segment's query where no draw of it began it. diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 32f1fb798..bf94b8b54 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -5f611d76cc7fe24cedb2197787d0796be5a8eb5a228d33aecb08e4a0e7d1a302 +b484a6b037e2ae562f5a3c89313babecbce60262b0adbe70508e73426167dff8 diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs index 75bafcc56..2df42e968 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs @@ -184,6 +184,8 @@ impl UlpTable { /// otherwise. /// - `RestrictedDepthUpload`: unbounded: a depth uploaded outside `[0, 1]` is the device's, which /// Vulkan does not define without `VK_EXT_depth_range_unrestricted`. +/// - `StencilOutputOverlap`: unbounded: a sample two fragments of one draw reach stores the OR of +/// their stencil outputs where Metal stores the later one, which moves any of its 8 bits. /// - `CubeGradientFootprint`: unbounded: Apple's approximate length and truncated level against the /// device's can select another level or filter near a boundary, which changes whole texels, not /// lanes. @@ -334,7 +336,8 @@ pub fn allowance(note: PrecisionNote) -> Allowance { | N::DeviceFragmentRuns | N::DeviceOcclusionCount | N::VertexSimdgroupGrouping - | N::RestrictedDepthUpload => Allowance::Unbounded, + | N::RestrictedDepthUpload + | N::StencilOutputOverlap => Allowance::Unbounded, } } diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs index bd5bc7fbc..c9f52c323 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs @@ -90,6 +90,7 @@ fn every_precision_note_has_its_table_row() { (N::DeviceOcclusionCount, Allowance::Unbounded), (N::VertexSimdgroupGrouping, Allowance::Unbounded), (N::RestrictedDepthUpload, Allowance::Unbounded), + (N::StencilOutputOverlap, Allowance::Unbounded), ]; for (note, expected) in rows { assert_eq!(allowance(note), expected, "{note:?}"); diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 703d6eb0c..57f8dee4e 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -899,6 +899,7 @@ codec_enum! { IndirectSequence, IndirectBase, TextureLevelBase(f0), + StencilBit, } Symbol { Binding(f0), DescriptorSet(f0), Location(f0), Component(f0), SpecId(f0) } } @@ -1266,6 +1267,7 @@ codec_enum! { AddressAlignment { slot, align }, GridTiles, PrivateArena { slot_bytes }, + StencilBitDraws, } Mechanism { Specialization, Variant, PushConstant, DynamicState, DynamicStateOrPushConstant, @@ -1446,6 +1448,7 @@ codec_enum! { DeviceOcclusionCount, VertexSimdgroupGrouping, RestrictedDepthUpload, + StencilOutputOverlap, } BindingSource { Buffer(f0), Texture(f0), Sampler(f0), CombinedTextureSampler { texture, sampler }, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 5cb317991..5a0ed5fb9 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 = 2301; +pub const SEMANTICS_VERSION: u32 = 2302; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 2301; /// 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 = 595; +pub const ARTIFACT_FORMAT_VERSION: u32 = 596; /// The version of what this crate gives a runtime for the runs of a compiled pipeline, beside the /// compile: the device a run opens and what it enables, the Vulkan and Metal vocabularies a runtime diff --git a/crates/metal2vulkan/src/cache/tests.rs b/crates/metal2vulkan/src/cache/tests.rs index d65c494b4..ce991820e 100644 --- a/crates/metal2vulkan/src/cache/tests.rs +++ b/crates/metal2vulkan/src/cache/tests.rs @@ -716,6 +716,22 @@ fn the_version_535_member_round_trips() { assert_ne!(encode(&facts), encode(&KernelFacts::default())); } +/// The members format version 596 appends encode and decode as themselves: a stencil output drawn +/// by bits, `PushField::StencilBit`, `RuntimeFact::StencilBitDraws` and +/// `PrecisionNote::StencilOutputOverlap`. +#[test] +fn the_version_596_members_round_trip() { + use crate::pipeline::artifact::PrecisionNote; + use crate::pipeline::facts::RuntimeFact; + use crate::pipeline::sym::PushField; + let field = PushField::StencilBit; + assert_eq!(decode::(&encode(&field)), Ok(field)); + let fact = RuntimeFact::StencilBitDraws; + assert_eq!(decode::(&encode(&fact)), Ok(fact)); + let note = PrecisionNote::StencilOutputOverlap; + assert_eq!(decode::(&encode(¬e)), Ok(note)); +} + /// The members format versions 153, 154, 155, 157 and 161 joined from every side encode and /// decode together in one render pipeline: `PrecisionNote::CubeGradientFootprint` and /// `CombinedSampler`, `RuntimeFact::SrgbTexture` and diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index 9609c8a67..d4bf14db9 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -166,6 +166,9 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { // The runtime pushes its arena's address, and sizes and orders the arena's slots by the // slot's bytes. RuntimeFact::PrivateArena { .. } => Mechanism::PushConstant, + // The consumer draws each draw once and then once per stencil bit its state can replace, + // pushing the bit for each. + RuntimeFact::StencilBitDraws => Mechanism::PushConstant, // Keyed by the slots bound to a texture buffer of more texels than one view holds. RuntimeFact::TexelBufferParts { .. } => Mechanism::Variant, // The runtime refuses a dispatch whose slot address is not a multiple of the alignment. diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index fea9b74d7..b2b596556 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -200,6 +200,7 @@ fn every_fact() -> Vec { payload: None, }, RuntimeFact::PrivateArena { slot_bytes: 28_704 }, + RuntimeFact::StencilBitDraws, ] } @@ -294,6 +295,7 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::AddressAlignment { .. } => 66, RuntimeFact::GridTiles => 51, RuntimeFact::PrivateArena { .. } => 70, + RuntimeFact::StencilBitDraws => 87, } } @@ -301,7 +303,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..87).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..88).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -424,7 +426,8 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::StorageTextureIntegerChannels { .. } | RuntimeFact::AccelerationStructureInstanceCount { .. } | RuntimeFact::ViewportCount - | RuntimeFact::PrivateArena { .. } => Mechanism::PushConstant, + | RuntimeFact::PrivateArena { .. } + | RuntimeFact::StencilBitDraws => Mechanism::PushConstant, RuntimeFact::AliasedImageblock { .. } => Mechanism::None, RuntimeFact::CallStackDepth { .. } | RuntimeFact::OpenClMode => Mechanism::None, }; diff --git a/crates/metal2vulkan/src/lower/fragment/mod.rs b/crates/metal2vulkan/src/lower/fragment/mod.rs index 1dce32def..cfc7edfc0 100644 --- a/crates/metal2vulkan/src/lower/fragment/mod.rs +++ b/crates/metal2vulkan/src/lower/fragment/mod.rs @@ -18,8 +18,12 @@ //! specialization constant (`RuntimeFact::SampleCount`, default 1), which the binder sets to the //! pipeline's `rasterizationSamples`. A call with another operand is refused: no other operand's //! meaning is established. -//! - **Stencil output**: a `[[stencil]]` output needs `VK_EXT_shader_stencil_export` -//! (`stage_io`), refused naming it on a device without the extension. +//! - **Stencil output**: a `[[stencil]]` output is `FragStencilRefEXT` where the device has +//! `VK_EXT_shader_stencil_export` (`stage_io`). Without it the function stores no reference and +//! keeps a fragment only where its output holds the bit the draw pushes, and the consumer draws +//! once per stencil bit (`RuntimeFact::StencilBitDraws`); a function whose returns cannot kill +//! (an interlocked body, a loop over the covered samples) refuses the output naming the +//! extension ([`finish`]). //! - **Coverage at sample rate** (`coverage`): a function that reads `[[sample_mask]]` and that //! Metal runs once per covered sample runs, compiled for a multisampled pipeline, once per pixel, //! and its body once per covered sample from a loop over the pixel's coverage ([`wrap_entry`]), @@ -269,6 +273,10 @@ pub fn finish(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> { fp.guarded = guarded; fp.terminate_invocation = terminate; fp.interlock = interlock; + // A stencil output drawn by bits kills at each return the fragments the draw does not keep. + if cx.families.stage_io.stencil_bits.is_some() && fp.return_kill().is_none() { + return Err(crate::lower::stage_io::stencil_export_refused()); + } Ok(()) } diff --git a/crates/metal2vulkan/src/lower/push.rs b/crates/metal2vulkan/src/lower/push.rs index 8ee6dc5e5..4a531d183 100644 --- a/crates/metal2vulkan/src/lower/push.rs +++ b/crates/metal2vulkan/src/lower/push.rs @@ -193,8 +193,8 @@ pub const fn shape(f: PushField) -> FieldShape { // A draw's depth bias: its constant, slope and clamp as `f32`s' bits, and a zero word. // Base vertex, base instance. PushField::BaseVertexInstance => FieldShape::UVec2, - // The draw's vertices per primitive. - PushField::VerticesPerPrimitive => FieldShape::U32, + // The draw's vertices per primitive, and the stencil bit a draw keeps. + PushField::VerticesPerPrimitive | PushField::StencilBit => FieldShape::U32, // A zero word, the index count, the first instance, and the base vertex. PushField::CaptureLayout => FieldShape::UVec4Array(1), // A constexpr sampler's index in its use's sampler array, and the sampled-texture array's diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index 5180d9a07..94e24f54f 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1868,7 +1868,9 @@ fn identity_unsourced(f: &RuntimeFact) -> bool { /// reference code a fragment function under the private alpha test compares with /// (`PushField::AlphaTestReference`); the index of the sampled-texture array's element a /// fragment function reads a colour attachment through (`PushField::FetchedColor`, framebuffer -/// fetch on a device with neither ordered form); the render pass's length, at or past which a +/// fetch on a device with neither ordered form); the stencil bit a fragment function whose +/// stencil output is drawn by bits keeps (`PushField::StencilBit`); the render pass's length, at +/// or past which a /// vertex function that writes `[[render_target_array_index]]` stores `Layer` 0 /// (`PushField::RenderTargetArrayLength`); the address of the runtime's memory that holds a /// kernel's private arena past the floor (`PushField::PrivateArenaAddress`); the draw's viewport @@ -1916,6 +1918,7 @@ fn identity_refusal(plan: &Plan) -> Option { | PushField::VertexBufferStride(_) | PushField::AlphaTestReference | PushField::FetchedColor { .. } + | PushField::StencilBit | PushField::RenderTargetArrayLength | PushField::PrivateArenaAddress | PushField::ViewportCount diff --git a/crates/metal2vulkan/src/lower/stage_io/mod.rs b/crates/metal2vulkan/src/lower/stage_io/mod.rs index cc5ee6c75..a553e74c9 100644 --- a/crates/metal2vulkan/src/lower/stage_io/mod.rs +++ b/crates/metal2vulkan/src/lower/stage_io/mod.rs @@ -178,7 +178,8 @@ use crate::spirv::ir::{ }; pub(crate) use plan::{ - amplification_count_form, finish_merged, note_device_point_size, view_index_enabled, + amplification_count_form, finish_merged, note_device_point_size, stencil_export_refused, + view_index_enabled, }; pub use plan::{DrawBase, Link, Place, Shape}; @@ -434,6 +435,10 @@ 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 `[[stencil]]` output on a device without stencil export + /// (`RuntimeFact::StencilBitDraws`): the field of a returned struct (0 for a returned value + /// itself) whose bit `PushField::StencilBit` each return tests ([`stencil_bit`]). + pub stencil_bits: Option, /// 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, @@ -1793,6 +1798,7 @@ pub fn emit_return( let (outputs, returned, point) = (plan.outputs.clone(), plan.returned, plan.point_size_default); let seconds = plan.rotated_seconds.clone(); let depth_clamp = plan.depth_clamp; + let stencil_bits = plan.stencil_bits; let primitive_id = plan.primitive_id; // The private masks: the pixel's ANDed into the function's own `[[sample_mask]]` output // where this return stores one, else stored as that output. @@ -1803,6 +1809,12 @@ pub fn emit_return( let x = cx.operand(fb, v)?; alpha_test(cx, fb, test, x, returned)?; } + // The stencil output's bit, before any output is stored: a fragment the draw does not keep + // is killed. + if let (Some(v), Some(field)) = (v, stencil_bits) { + let x = cx.operand(fb, v)?; + stencil_bit(cx, fb, field, x, returned)?; + } match (v, returned) { (None, Returned::Void) => {} (None, _) => return Err(cx.fail("an entry with outputs returns no value")), @@ -2333,6 +2345,41 @@ fn alpha_test( } } +/// A fragment function's `[[stencil]]` output on a device without stencil export +/// (`RuntimeFact::StencilBitDraws`), field `field` of the returned `x`: where the draw's +/// `PushField::StencilBit` `k` is below 8 and bit `k` of the output is 0, the fragment is killed, +/// and at 8 or more every fragment is kept. The shift takes `k`'s low 3 bits, so no shift reaches +/// the value's width. +fn stencil_bit( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + field: u32, + x: SValue, + returned: Returned, +) -> BResult<()> { + let Some(form) = cx.plan.families.fragment.return_kill() else { + return Err( + cx.fail("a stencil output drawn by bits in a function whose returns cannot kill") + ); + }; + let value = match returned { + Returned::Struct => fb.composite_extract(x, &[field])?, + Returned::Value | Returned::Void => x, + }; + let bit = cx.push_field(fb, PushField::StencilBit)?; + let low = u32_constant(fb, 7)?; + let shift = fb.binary(BinOp::BitwiseAnd, bit, low)?; + let shifted = fb.binary(BinOp::ShiftRightLogical, value, shift)?; + let one = u32_constant(fb, 1)?; + let held = fb.binary(BinOp::BitwiseAnd, shifted, one)?; + let zero = u32_constant(fb, 0)?; + let lacks = fb.binary(BinOp::IEqual, held, zero)?; + let eight = u32_constant(fb, 8)?; + let tested = fb.binary(BinOp::ULessThan, bit, eight)?; + let kill = fb.binary(BinOp::LogicalAnd, tested, lacks)?; + crate::lower::fragment::kill_if(fb, kill, form) +} + /// How the entry's returns drop a positive NaN depth, or `None` in a function looping over its /// covered samples, where a kill would drop every sample's outputs. fn nan_drop(cx: &mut EmitCx<'_>) -> BResult> { diff --git a/crates/metal2vulkan/src/lower/stage_io/plan.rs b/crates/metal2vulkan/src/lower/stage_io/plan.rs index f0c20f1a1..7031cee5e 100644 --- a/crates/metal2vulkan/src/lower/stage_io/plan.rs +++ b/crates/metal2vulkan/src/lower/stage_io/plan.rs @@ -2094,16 +2094,19 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { if let OutputRole::ImageblockData(_) = &o.role { return Err(Unsupported::not_implemented(Feature::Imageblocks).into()); } - // A stencil output needs stencil export. + // A stencil output on a device without stencil export is no output: each return keeps + // the fragment only where the output holds the bit the draw pushes, and the consumer + // draws once per stencil bit (`RuntimeFact::StencilBitDraws`). if matches!(o.role, OutputRole::Stencil) && cx.stage == Stage::Fragment && !cx.profile.fields().fragment.stencil_export { - return Err(Unsupported::needs( - Feature::StencilExport, - Capability::Extension(VkExtension::ExtShaderStencilExport), - ) - .into()); + int_scalar(io_form(cx, ty)?)?; + cx.families.stage_io.stencil_bits = Some(o.field); + cx.push.insert(PushField::StencilBit); + cx.facts.insert(RuntimeFact::StencilBitDraws); + cx.precision.insert(PrecisionNote::StencilOutputOverlap); + continue; } // An output to a color the pass lacks is stored nowhere, as plain Metal drops it: no // output variable, so the pipeline writes no location without an attachment. So is one to a @@ -2300,6 +2303,15 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { .map_err(|e| e.at_attachment(Attachment::Color(attachment)))?; cx.families.stage_io.rotated_seconds.push(second); } + // A stencil output drawn by bits runs the function once more for each bit, so a color it + // writes is written again: kept to one write only with blending and the logic operation off + // on every attachment and no color read, which is not built. + let sp = &cx.families.stage_io; + if sp.stencil_bits.is_some() + && (sp.interface.outputs.iter()).any(|o| matches!(o.role, IoRole::Color { .. })) + { + return Err(stencil_export_refused()); + } // The indices a draw of one amplification stores though the function writes none: `Layer` // in a pass of at least two layers, and `ViewportIndex` under mappings that offset the // viewport, each the amplification's offset held below its count as an index the function @@ -2827,7 +2839,7 @@ fn output(cx: &mut SelectCx<'_>, o: &OutputBinding, ty: AirTypeId) -> Result { let f = io_form(cx, ty)?; int_scalar(f)?; @@ -3000,6 +3012,18 @@ fn half_color(e: &crate::air::Entry, ty: AirTypeId) -> bool { matches!(scalar, Some(Type::Half)) } +/// The refusal of a stencil output on a device without `VK_EXT_shader_stencil_export` where its +/// draws by bits (`RuntimeFact::StencilBitDraws`) do not give Metal's answer: a function that also +/// writes a color or memory, whose returns cannot kill a fragment, or of a pipeline whose draws do +/// not take the repeats (a mesh pipeline, one made for indirect command buffers). +pub(crate) fn stencil_export_refused() -> Error { + Unsupported::needs( + Feature::StencilExport, + Capability::Extension(VkExtension::ExtShaderStencilExport), + ) + .into() +} + /// The refusal of a private alpha test the translation has not built (`PrivateRenderField`'s /// `AlphaTest`): a fragment function under the test that writes no color 0, or one that is not /// four `float` or `half` lanes. diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 754d210fb..f0e709218 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -2113,6 +2113,27 @@ pub enum PrecisionNote { /// Validation derives no tolerance from it: a difference stays a mismatch, which the note /// explains. RestrictedDepthUpload, + /// A fragment function writes `[[stencil]]` on a device without + /// `VK_EXT_shader_stencil_export` (`RuntimeFact::StencilBitDraws`): each draw of its pipeline + /// is drawn once with a stencil reference of 0, which clears the stencil bits its + /// depth-stencil state can replace and runs its other stencil operations, then once for each + /// of those bits, keeping the fragments whose output has that bit and replacing it with 1, + /// and, where the draw writes depth under a depth compare other than always or never, once + /// more for the depth. Fragments of one draw that overlap leave the OR of their values: a + /// sample two fragments of one draw reach under `Replace` stores the bitwise OR of their + /// outputs' low 8 bits within the write mask, where Metal stores the later fragment's value. + /// On an RTX 3090 (NVIDIA 620.70.06), two triangles of one draw whose outputs are `0x35` and + /// then `0x4a` store `0x7f` where both reach, where Metal stores the later fragment's `0x4a`. + /// Under a depth test that writes, each fragment's stencil operation is also chosen against + /// the depth from before the draw, where Metal tests a later fragment against the depth an + /// earlier one wrote. A draw whose fragments cover each sample at most once (a quad of two + /// triangles, one fullscreen triangle) stores Metal's values. + /// Static per function: recorded on the fragment stage of every such function on every device + /// without the extension. + /// + /// Validation derives no tolerance from it: a difference stays a mismatch, which the note + /// explains. + StencilOutputOverlap, } /// Which lowering strategies a module used, with their word costs. diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index c508e755a..0ced86f65 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -58,6 +58,7 @@ use crate::pipeline::descriptor::{ LinkedFunctions, LinkedList, MeshPipelineDescriptor, RenderPipelineDescriptor, VertexDescriptor, }; +use crate::pipeline::facts::RuntimeFact; use crate::pipeline::interface::{SlotInterface, StageInterface}; use crate::pipeline::sym::{SlotClass, SlotRef, Stage, VaryingKey}; use crate::reflection; @@ -3091,6 +3092,11 @@ fn lower_bounded( // The function's own side effects; the `ExecutionStatus` buffer's words (the resident-miss // count's) are the product's. let writes_memory = crate::spirv::requirements::writes_memory(&module)?; + // A stencil output drawn by bits runs the function once more for each bit, so its memory + // writes would be made again. + if writes_memory && plan.facts.contains(&RuntimeFact::StencilBitDraws) { + return Err(crate::lower::stage_io::stencil_export_refused()); + } // A fragment function's texture slots read only at the fragment's own pixel. let own_pixel_textures = crate::spirv::requirements::own_pixel_textures(&module, m)?; // The levels of its bound view each texture slot's reads reach. diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index 717c526f7..a5810862f 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -541,6 +541,7 @@ impl Device { } None => None, }; + refuse_stencil_bits(fragment.as_ref())?; let compiled: Vec<&CompiledFunction> = object .iter() .chain(std::iter::once(&mesh)) @@ -833,6 +834,9 @@ impl Device { if let Some(f) = &fragment { check_call_stack(f.artifact(), d.max_fragment_call_stack_depth)?; } + if d.support_indirect_command_buffers { + refuse_stencil_bits(fragment.as_ref())?; + } let compiled: Vec<&CompiledFunction> = std::iter::once(&vertex).chain(&fragment).collect(); let artifacts: Vec<&FunctionArtifact> = compiled.iter().map(|c| c.artifact()).collect(); let linked = link(&artifacts, &LinkInputs::render_variant(d, v), p)?; @@ -1413,6 +1417,16 @@ fn check_open_cl_mode(a: &FunctionArtifact, given: bool) -> Result<(), Error> { Ok(()) } +/// A fragment stage whose stencil output is drawn by bits (`RuntimeFact::StencilBitDraws`) in a +/// pipeline whose draws do not take the repeats, a mesh pipeline or one made for indirect command +/// buffers, refuses the output as a device without stencil export does (`Feature::StencilExport`). +fn refuse_stencil_bits(fragment: Option<&CompiledFunction>) -> Result<(), Error> { + match fragment.is_some_and(|f| (f.artifact().facts).contains(&RuntimeFact::StencilBitDraws)) { + true => Err(crate::lower::stage_io::stencil_export_refused()), + false => Ok(()), + } +} + /// The stage of artifact `a` has the call stack its pipeline's `maxCallStackDepth` for it, /// `given`, sizes: a `Compiled` stage whose stack was sized for another depth is /// `InvalidDescriptor(MaxCallStackDepth)` (a `Function` stage is compiled under `given`). diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 3caf2ff49..52511f4cd 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -607,6 +607,22 @@ pub enum RuntimeFact { /// them in its own slots' memory or ordered after the last one that used it. The kernel's own /// bytes decide it, never a device fact. PrivateArena { slot_bytes: u32 }, + /// The fragment function writes `[[stencil]]` on a profile without + /// `VK_EXT_shader_stencil_export` (`FragmentCaps::stencil_export`): it stores no stencil + /// reference, and keeps a fragment only where its output's low 8 bits hold the bit + /// `PushField::StencilBit` names, every fragment at 8 or more. The consumer draws each draw of + /// its pipeline first at 8, under the draw's own depth-stencil state but a reference of 0 on + /// both faces; then at each bit `k` of the stencil write masks of the faces whose operations + /// include `Replace`, under a reference of 255, each face's write mask cut to bit `k`, its + /// `Replace` operations kept and its others `Keep`, and no depth write; and, where the state + /// writes depth under a compare other than `Always` and `Never`, the first draw writes none + /// and a last one at 8 writes it under stencil write masks of 0. Under a stencil compare of + /// `Always` or `Never` on both faces that stores Metal's values, but where fragments of one + /// draw meet at a sample (`PrecisionNote::StencilOutputOverlap`). The function writes no color + /// and no memory, and its pipeline is no mesh pipeline and is not made for indirect command + /// buffers, so each draw takes the repeats; anything else refuses the output + /// (`Feature::StencilExport`). + StencilBitDraws, } impl RuntimeFact { @@ -703,6 +719,7 @@ impl RuntimeFact { RuntimeFact::AddressAlignment { .. } => "AddressAlignment", RuntimeFact::GridTiles => "GridTiles", RuntimeFact::PrivateArena { .. } => "PrivateArena", + RuntimeFact::StencilBitDraws => "StencilBitDraws", } } } diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index b5d617846..76c82d659 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -861,6 +861,11 @@ pub enum PushField { /// Residual bind offset of a descriptor-form slot: the bind offset minus the descriptor base, /// modulo 2^32. SlotBindOffset(SlotRef), + /// The stencil bit a fragment function that writes `[[stencil]]` on a device without + /// `VK_EXT_shader_stencil_export` keeps its fragment for (`RuntimeFact::StencilBitDraws`): one + /// `u32`, `k`. Below 8 the function discards a fragment whose output's bit `k` is 0; at 8 or + /// more it keeps every fragment. Ordered before the slot addresses, as `FetchedColor` is. + StencilBit, /// Under the identity domains, the element of the set-1 sampled-texture array /// through which a fragment function reads color attachment `color` (`[[color(n)]]`): one /// `u32`, the index of an element holding a 2D view of the attachment's level and slice diff --git a/crates/metal2vulkan/src/tests/engine_stencil.rs b/crates/metal2vulkan/src/tests/engine_stencil.rs index be0313006..4fb9304ca 100644 --- a/crates/metal2vulkan/src/tests/engine_stencil.rs +++ b/crates/metal2vulkan/src/tests/engine_stencil.rs @@ -1,21 +1,31 @@ //! A fragment function's `[[stencil]]` output end to end: the direct `FragStencilRefEXT` where the -//! device has stencil export, and elsewhere a refusal naming the extension, of the function and of -//! its render pipeline. The public fixture `fragment_depth_stencil` returns a depth and a stencil. -//! No GPU is used. +//! device has stencil export, and elsewhere the output drawn by bits +//! (`RuntimeFact::StencilBitDraws`): no stencil reference, the bit test against +//! `PushField::StencilBit`, the static note `PrecisionNote::StencilOutputOverlap`; and the +//! refusals naming the extension where draws by bits do not give Metal's answer: a function that +//! also writes a color or memory, a pipeline made for indirect command buffers, a mesh pipeline. +//! The public fixture `fragment_depth_stencil` returns a depth and a stencil; the engine fixture +//! `stx_stencil` and `stx_stencil_ms` hold a stencil alone, one beside memory writes, and one beside +//! a color. No GPU is used. //! -//! `llvm-as` assembles the fixture; a missing tool skips visibly. +//! `llvm-as` assembles the fixtures; a missing tool skips visibly. use crate::budget::Budget; use crate::device::requirements::VkExtension; use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::error::{Capability, Error, Feature, Needs}; -use crate::library::Library; +use crate::library::{FunctionArtifact, Library}; use crate::metal::PixelFormat; -use crate::pipeline::descriptor::{FunctionDescriptor, RenderPipelineDescriptor, StageSource}; +use crate::pipeline::descriptor::{ + FunctionDescriptor, MeshPipelineDescriptor, RenderPipelineDescriptor, StageSource, +}; +use crate::pipeline::facts::{Mechanism, RuntimeFact}; use crate::pipeline::stage_io::StageBuiltin; +use crate::pipeline::sym::PushField; use crate::pipeline::testing::{ compile, engine_dir, fixtures_dir, link_and_validate, llvm_assemble, AssembleError, }; +use crate::pipeline::{PrecisionNote, RuntimeDependency}; use crate::spirv::testing::committed_profiles; fn assemble(path: &std::path::Path) -> Option> { @@ -45,81 +55,207 @@ fn needs_export() -> (Feature, Needs) { ) } +/// Whether `result` is the refusal naming the extension. +fn refused(result: Result, what: &str) { + match result { + Err(Error::Unsupported(u)) => assert_eq!((u.feature, u.needs), needs_export(), "{what}"), + Err(other) => panic!("{what}: {other}"), + Ok(_) => panic!("{what}: not refused"), + } +} + +/// The stencil output drawn by bits: no stencil reference stored, the fact and the bit's push +/// field stated, and the note recorded. +fn assert_drawn_by_bits(a: &FunctionArtifact, what: &str) { + assert!( + !a.interface.io.builtins.contains(&StageBuiltin::StencilRef), + "{what}: {:?}", + a.interface.io.builtins + ); + assert!( + a.facts.contains(&RuntimeFact::StencilBitDraws), + "{what}: {:?}", + a.facts + ); + let pushed = (a.interface.push.fields.iter()).any(|f| f.field == PushField::StencilBit); + assert!(pushed, "{what}: {:?}", a.interface.push); + assert!( + a.precision.contains(&PrecisionNote::StencilOutputOverlap), + "{what}: {:?}", + a.precision + ); +} + /// On every committed profile the output is the direct `FragStencilRefEXT` where the device has -/// stencil export, the module passing L3, and is otherwise refused naming the extension alone. +/// stencil export, and is drawn by bits elsewhere, the module passing L3 in both forms. #[test] -fn the_stencil_output_takes_the_extension_or_a_refusal_naming_it() { +fn the_stencil_output_takes_the_extension_or_draws_by_bits() { let Some(bc) = stencil_fixture() else { return; }; - // [exported, refused] + // [exported, by bits] let mut forms = [0usize; 2]; for (stem, p) in committed_profiles().expect("profiles") { - let result = compile(&bc, ENTRY, &p); + let a = compile(&bc, ENTRY, &p).unwrap_or_else(|e| panic!("{stem}: {e}")); if p.fields().fragment.stencil_export { forms[0] += 1; - let a = result.unwrap_or_else(|e| panic!("{stem}: {e}")); assert!( a.interface.io.builtins.contains(&StageBuiltin::StencilRef), "{stem}: {:?}", a.interface.io.builtins ); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); + assert!(!a.facts.contains(&RuntimeFact::StencilBitDraws), "{stem}"); + assert!( + !a.precision.contains(&PrecisionNote::StencilOutputOverlap), + "{stem}" + ); } else { forms[1] += 1; - match result { - Err(Error::Unsupported(u)) => { - assert_eq!((u.feature, u.needs), needs_export(), "{stem}") - } - other => panic!("{stem}: {:?}", other.map(|_| ())), - } + assert_drawn_by_bits(&a, &stem); } + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); } // The committed profiles cover each kind of device. assert!(forms.iter().all(|&n| n > 0), "{forms:?}"); } +/// The device of committed profile `stem` under `policy`. +fn device(stem: &str, policy: DevicePolicy) -> Device { + 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"); + let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); + Device::from_queries(desc, policy).expect("device") +} + +fn function(bc: &[u8], name: &str) -> StageSource { + StageSource::Function(FunctionDescriptor::new( + Library::from_air(bc) + .expect("library") + .function(name) + .expect("function"), + )) +} + /// A render pipeline of `stage_io_vertex_position` and the fixture's fragment, on a device without -/// stencil export (`nvidia-rtx50-linux`), is refused naming the extension, with a combined -/// depth/stencil attachment and without one, at one sample and at four. +/// stencil export (`nvidia-rtx50-linux`), under the runtime's identity domains and the resident +/// tables, with a combined depth/stencil attachment and without one, at one sample and at four: +/// made, its fragment stage depending on `StencilBitDraws` through a push field and noting the +/// overlap; and refused naming the extension where it is made for indirect command buffers. #[test] -fn a_render_pipeline_without_stencil_export_is_refused_naming_it() { +fn a_render_pipeline_without_stencil_export_draws_the_output_by_bits() { let (Some(io), Some(stencil)) = ( assemble(&engine_dir().join("stage_io.ll")), stencil_fixture(), ) else { return; }; - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/nvidia-rtx50-linux.json"); - let text = std::fs::read_to_string(path).expect("profile"); - let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device"); - assert!(!dev.profile().fields().fragment.stencil_export); - let function = |bc: &[u8], name: &str| { - StageSource::Function(FunctionDescriptor::new( - Library::from_air(bc) - .expect("library") - .function(name) - .expect("function"), - )) - }; - for attached in [true, false] { - for samples in [1, 4] { - let mut d = RenderPipelineDescriptor::new(function(&io, "stage_io_vertex_position")); - d.fragment = Some(function(&stencil, ENTRY)); - if attached { - d.depth_format = Some(PixelFormat::Depth32FloatStencil8); - d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); - } - d.raster_sample_count = samples; - let what = format!("attached {attached}, {samples} samples"); - match dev.compile_render_pipeline(&d, &Budget::standard()) { - Err(Error::Unsupported(u)) => { - assert_eq!((u.feature, u.needs), needs_export(), "{what}") + for policy in [DevicePolicy::default(), DevicePolicy::RESIDENT_TABLES] { + let dev = device("nvidia-rtx50-linux", policy); + assert!(!dev.profile().fields().fragment.stencil_export); + for attached in [true, false] { + for samples in [1, 4] { + let mut d = + RenderPipelineDescriptor::new(function(&io, "stage_io_vertex_position")); + d.fragment = Some(function(&stencil, ENTRY)); + if attached { + d.depth_format = Some(PixelFormat::Depth32FloatStencil8); + d.stencil_format = Some(PixelFormat::Depth32FloatStencil8); } - other => panic!("{what}: {:?}", other.map(|_| ())), + d.raster_sample_count = samples; + let what = format!("{policy:?}, attached {attached}, {samples} samples"); + let pipeline = dev + .compile_render_pipeline(&d, &Budget::standard()) + .unwrap_or_else(|e| panic!("{what}: {e}")); + let bits = + RuntimeDependency::new(RuntimeFact::StencilBitDraws, Mechanism::PushConstant); + assert!(pipeline.dependencies.contains(&bits), "{what}"); + let notes = &pipeline.stages[1].precision_notes; + assert!( + notes.contains(&PrecisionNote::StencilOutputOverlap), + "{what}" + ); + d.support_indirect_command_buffers = true; + refused( + dev.compile_render_pipeline(&d, &Budget::standard()), + &format!("{what}, made for indirect command buffers"), + ); } } } } + +/// Without stencil export, a function that writes its stencil and a color +/// (`stx_stencil_ms_color`), and one that writes its stencil and memory (`stx_stencil_in_order`), +/// refuse the output naming the extension; one that writes its stencil alone +/// (`stx_stencil_by_pixel`), one beside its depth (`stx_stencil_with_depth`) and one that discards +/// (`stx_stencil_discard`) draw it by bits. +#[test] +fn without_stencil_export_a_function_that_writes_a_color_or_memory_refuses_the_output() { + let (Some(stx), Some(ms)) = ( + assemble(&engine_dir().join("stx_stencil.ll")), + assemble(&engine_dir().join("stx_stencil_ms.ll")), + ) else { + return; + }; + let mut seen = 0; + for (stem, p) in committed_profiles().expect("profiles") { + if p.fields().fragment.stencil_export { + continue; + } + seen += 1; + refused( + compile(&ms, "stx_stencil_ms_color", &p), + &format!("{stem}: a color"), + ); + let memory = compile(&stx, "stx_stencil_in_order", &p); + if p.fields().fragment.pixel_interlock { + refused(memory, &format!("{stem}: memory")); + } else { + // The function's raster order group is refused first, without the interlock. + match memory { + Err(Error::Unsupported(u)) => { + assert_eq!(u.feature, Feature::RasterOrderGroups, "{stem}: memory") + } + Err(other) => panic!("{stem}: memory: {other}"), + Ok(_) => panic!("{stem}: memory: not refused"), + } + } + for entry in [ + "stx_stencil_by_pixel", + "stx_stencil_with_depth", + "stx_stencil_discard", + ] { + let what = format!("{stem}: {entry}"); + let a = compile(&stx, entry, &p).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_drawn_by_bits(&a, &what); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + } + } + assert!(seen > 0, "no committed profile lacks stencil export"); +} + +/// A mesh pipeline whose fragment function writes its stencil, on a device with mesh shading and +/// without stencil export, refuses the output naming the extension. +#[test] +fn without_stencil_export_a_mesh_pipeline_refuses_the_output() { + let (Some(outputs), Some(stx)) = ( + super::engine_mesh::fixture("mesh_outputs"), + assemble(&engine_dir().join("stx_stencil.ll")), + ) else { + return; + }; + let mut seen = 0; + for (stem, p) in super::engine_mesh::mesh_profiles() { + if p.fields().fragment.stencil_export { + continue; + } + seen += 1; + let dev = device(&stem, DevicePolicy::RESIDENT_TABLES); + let mut d = MeshPipelineDescriptor::new(function(&outputs, "mesh_outputs_points")); + d.fragment = Some(function(&stx, "stx_stencil_by_pixel")); + d.stencil_format = Some(PixelFormat::Stencil8); + refused(dev.compile_mesh_pipeline(&d, &Budget::standard()), &stem); + } + assert!(seen > 0, "no mesh profile lacks stencil export"); +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 39d866106..6f50c9297 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1567,6 +1567,7 @@ field metal2vulkan-runtime::Metrics.staging_buffer_allocations pub staging_buffe field metal2vulkan-runtime::Metrics.staging_region_allocations pub staging_region_allocations: SiteAllocations field metal2vulkan-runtime::Metrics.staging_sleeps pub staging_sleeps: u64 field metal2vulkan-runtime::Metrics.stamps_not_available pub stamps_not_available: u64 +field metal2vulkan-runtime::Metrics.stencil_bit_draws pub stencil_bit_draws: u64 field metal2vulkan-runtime::Metrics.submissions pub submissions: u64 field metal2vulkan-runtime::Metrics.submissions_during_frees pub submissions_during_frees: u64 field metal2vulkan-runtime::Metrics.submit_call_max_nanos pub submit_call_max_nanos: u64 @@ -8376,6 +8377,7 @@ variant metal2vulkan-runtime::DrawKind::FetchedAttachment FetchedAttachment variant metal2vulkan-runtime::DrawKind::FillMode FillMode variant metal2vulkan-runtime::DrawKind::LineWidth LineWidth variant metal2vulkan-runtime::DrawKind::PatchIndexBuffer PatchIndexBuffer +variant metal2vulkan-runtime::DrawKind::StencilOutput StencilOutput variant metal2vulkan-runtime::DrawKind::Viewport Viewport variant metal2vulkan-runtime::DrawKind::Viewports Viewports variant metal2vulkan-runtime::DrawKind::VisibilityResultInterrupt VisibilityResultInterrupt @@ -8575,6 +8577,7 @@ variant metal2vulkan-runtime::PrecisionNote::SimdgroupAccessOrder SimdgroupAcces variant metal2vulkan-runtime::PrecisionNote::SnormMinimumKept SnormMinimumKept variant metal2vulkan-runtime::PrecisionNote::SparseResidency SparseResidency variant metal2vulkan-runtime::PrecisionNote::SrgbTexelDecode SrgbTexelDecode +variant metal2vulkan-runtime::PrecisionNote::StencilOutputOverlap StencilOutputOverlap variant metal2vulkan-runtime::PrecisionNote::SwizzledOpaqueBlackBorder SwizzledOpaqueBlackBorder variant metal2vulkan-runtime::PrecisionNote::TessellationFactorEdgeCases TessellationFactorEdgeCases variant metal2vulkan-runtime::PrecisionNote::TessellationFactorInstance TessellationFactorInstance @@ -9893,6 +9896,7 @@ variant metal2vulkan::pipeline::PrecisionNote::SimdgroupAccessOrder SimdgroupAcc variant metal2vulkan::pipeline::PrecisionNote::SnormMinimumKept SnormMinimumKept variant metal2vulkan::pipeline::PrecisionNote::SparseResidency SparseResidency variant metal2vulkan::pipeline::PrecisionNote::SrgbTexelDecode SrgbTexelDecode +variant metal2vulkan::pipeline::PrecisionNote::StencilOutputOverlap StencilOutputOverlap variant metal2vulkan::pipeline::PrecisionNote::SwizzledOpaqueBlackBorder SwizzledOpaqueBlackBorder variant metal2vulkan::pipeline::PrecisionNote::TessellationFactorEdgeCases TessellationFactorEdgeCases variant metal2vulkan::pipeline::PrecisionNote::TessellationFactorInstance TessellationFactorInstance @@ -9939,6 +9943,7 @@ variant metal2vulkan::pipeline::PushField::SlotBounds SlotBounds(SlotRef) variant metal2vulkan::pipeline::PushField::SlotGuestBase SlotGuestBase(SlotRef) variant metal2vulkan::pipeline::PushField::StageInRegion StageInRegion variant metal2vulkan::pipeline::PushField::StageInStride StageInStride(u32) +variant metal2vulkan::pipeline::PushField::StencilBit StencilBit variant metal2vulkan::pipeline::PushField::TailWord TailWord variant metal2vulkan::pipeline::PushField::TessellationFactorAddress TessellationFactorAddress variant metal2vulkan::pipeline::PushField::TessellationFactorInstanceStride TessellationFactorInstanceStride @@ -10036,6 +10041,7 @@ variant metal2vulkan::pipeline::RuntimeFact::SparseTextureWrites SparseTextureWr variant metal2vulkan::pipeline::RuntimeFact::SrgbTexture SrgbTexture { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::StageInRegion StageInRegion variant metal2vulkan::pipeline::RuntimeFact::StageInStride StageInStride { layout: u32 } +variant metal2vulkan::pipeline::RuntimeFact::StencilBitDraws StencilBitDraws variant metal2vulkan::pipeline::RuntimeFact::StorageTextureFormat StorageTextureFormat { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::StorageTextureIntegerChannels StorageTextureIntegerChannels { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::StorageTextureLevelViews StorageTextureLevelViews { slot: SlotRef } diff --git a/docs/API.md b/docs/API.md index d6bff181a..face45465 100644 --- a/docs/API.md +++ b/docs/API.md @@ -938,7 +938,13 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: its channels rotated. A raster order group on a color input, or on a color output of an attachment the function reads, orders that read alone and takes no interlock; a group on anything else needs the pixel interlock (`Unsupported{RasterOrderGroups}`). A `[[stencil]]` output uses - `VK_EXT_shader_stencil_export`; a device without it refuses the function + `VK_EXT_shader_stencil_export`; on a device without it the function discards a fragment whose + output lacks the bit its push field names (`PushField::StencilBit`, every fragment kept at 8 or + more) and states `RuntimeFact::StencilBitDraws`: the runtime draws each draw once and then once + for each bit its depth-stencil state can replace (`metal2vulkan-degrade-stencil-output-overlap`). + There a function that also writes a color or memory, one whose returns cannot discard (an + interlocked body, a loop over its covered samples), a mesh pipeline and a pipeline made for + indirect command buffers refuse the output (`Unsupported{StencilExport}` naming the extension). - `[[barycentric_coord]]` reads `BaryCoordKHR` or `BaryCoordNoPerspKHR`, whose vertex order is Vulkan's first-vertex order and Metal's for every primitive type. A `float3` read takes the @@ -1931,6 +1937,26 @@ bound. of these copies. Cost: a depth uploaded outside `[0, 1]` is the device's, and so is every read, sample, comparison and copy of it; one within it is copied exactly, except a denormal or `-0.0`, which a device may store as `+0.0` (`metal2vulkan-degrade-depth-denormals`). +- `metal2vulkan-degrade-stencil-output-overlap` (precision). + `PrecisionNote::StencilOutputOverlap`: A fragment function that writes `[[stencil]]`, on a + device without `VK_EXT_shader_stencil_export`, recorded on its fragment stage on every such + device (`RuntimeFact::StencilBitDraws`). `metal2vulkan-runtime` draws each draw of its pipeline + once with a stencil reference of 0, which clears the stencil bits its depth-stencil state can + replace and runs its other stencil operations, then once for each of those bits (the low 8 of + the write masks of the faces that replace), keeping the fragments whose output holds that bit, + under the reference 255, that bit's write mask, `Replace` kept and every other operation + `Keep`, and no depth write; and, where the draw writes depth under a depth compare other than + always or never, once more for the depth, with stencil write masks of 0, the first draw then + writing none. Cost: fragments of one draw that overlap leave the OR of their values. Where two + fragments of one draw reach one sample under `Replace`, the sample stores the bitwise OR of + their outputs' low 8 bits within the write mask, where Metal stores the later fragment's value. + Measured on an RTX 3090 (NVIDIA 620.70.06) under the validation layer: two triangles of one + draw whose outputs are `0x35` and then `0x4a` store `0x7f` on the 32 texels both reach, where + Metal stores the later fragment's `0x4a`, and `0x35` on the 32 that one reaches. Under a depth + test that writes, each fragment's stencil operation is also chosen against the depth from + before the draw, where Metal tests a later fragment against the depth an earlier one wrote. A + draw whose fragments reach each sample at most once (a quad of two triangles, one fullscreen + triangle) stores Metal's values. - `metal2vulkan-degrade-cube-gradient-footprint` (precision). `PrecisionNote::CubeGradientFootprint`: An explicit-gradient sample of a cube texture takes Metal's footprint in the form Vulkan's rule reads, in every stage on every device. Cost: the diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index d7ed8e7e8..3b53136b4 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -116,7 +116,7 @@ Columns: | `ClipDistance` | Clip or cull distances | devices without VkFeature::ShaderClipDistance; devices without VkLimit::MaxClipDistances | `device` | 2: `crates/metal2vulkan/src/lower/mesh/mod.rs (select, 2 sites)` | `rare`: clip distances on a device without them | | `DualSourceBlending` | Dual-source blending | devices without VkFeature::DualSrcBlend; devices without VkLimit::MaxFragmentDualSrcAttachments | `device` | 3: `crates/metal2vulkan/src/metal/state.rs (blend_factor)`, `crates/metal2vulkan/src/pipeline/link/graphics.rs (check_outputs)` (+1) | `rare`: dual-source blending on a device without it | | `Barycentrics` | Barycentric coordinates | devices without VkFeature::FragmentShaderBarycentric | `device` | 2: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)` | `rare`: barycentric coordinates | -| `StencilExport` | Stencil export | devices without VkExtension::ExtShaderStencilExport | `device` | 1: `crates/metal2vulkan/src/lower/stage_io/plan.rs (entry)` | `rare`: stencil from the shader | +| `StencilExport` | Stencil export | devices without VkExtension::ExtShaderStencilExport | `device` | 1: `crates/metal2vulkan/src/lower/stage_io/plan.rs (stencil_export_refused)` | `rare`: stencil from the shader | | `SampleRateShading` | Per-sample shading | devices without VkFeature::SampleRateShading; devices without a capability the site computes (`needs`); every device (not implemented) | `ours` | 3: `crates/metal2vulkan/src/pipeline/link/graphics.rs (sample_invocations, 3 sites)` | `rare`: per-sample shading | | `PullModelInterpolation` | Metal's pull-model interpolation (`interpolant` fragment inputs and their `interpolate_at_center`, `_centroid`, `_sample` and `_offset` functions)... | devices without VkProperty::InterpolateAtOffsetCentered; devices without VkProperty::InterpolateAtOffsetFromSevenSixteenths; devices without a capability the site computes (`lacks`); every device (not implemented) | `ours` | 5: `crates/metal2vulkan/src/lower/fragment/interpolate.rs (select, 2 sites)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant, 2 sites)` (+1) | `rare`: interpolant inputs read at the centroid, a sample or an offset | | `DivergentInterpolation` | Metal's pull-model interpolation at a sample or an offset (`interpolate_at_sample`, `interpolate_at_offset`) outside the fragment function's first... | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant_reads)` | `rare`: an interpolant read at a sample or an offset in a branch, a loop or after a discard | @@ -439,7 +439,7 @@ Each refusal's sites, with the function that builds it. - `feature::ClipDistance`: `crates/metal2vulkan/src/lower/mesh/mod.rs (select, 2 sites)` - `feature::DualSourceBlending`: `crates/metal2vulkan/src/metal/state.rs (blend_factor)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (check_outputs)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (rotated_blend)` - `feature::Barycentrics`: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)` -- `feature::StencilExport`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (entry)` +- `feature::StencilExport`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (stencil_export_refused)` - `feature::SampleRateShading`: `crates/metal2vulkan/src/pipeline/link/graphics.rs (sample_invocations, 3 sites)` - `feature::PullModelInterpolation`: `crates/metal2vulkan/src/lower/fragment/interpolate.rs (select, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant_reads)` - `feature::DivergentInterpolation`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (interpolant_reads)`