Drop the exact tile store: a loaded snorm or RGB9E5Float attachment keeps the device's load and store

One work packet, landed as 7 commits (c18e40911e..53fcb867b4 on archive/development-linear-2026-10-28), in order:

* Drop the exact tile store: a loaded snorm or RGB9E5Float attachment keeps the device's load and store

The owner's ruling (2026-10-27): the GPU's native answers are the contract,
with no exact emulation. TileStorePolicy and DevicePolicy::tile_store go,
with the load pass's rewrite of a signed normalized attachment's minimum
codes and an RGB9E5Float attachment's unnormalized words, and the
unused-bits module's two rules that served only it. The load pass keeps the
extended-range, padded and bfloat attachments, whose raw codes no device
holds as Metal's (capability). snorm-minimum-kept and shared-exponent-kept
still announce the native answer at each such draw; DriverFact::TileStoreIsMetals
still keeps them quiet on MoltenVK.

Docs: the ledger row and docs/API.md's policy bullet go; the catalogue
entries and the notices' docs drop the switch. The validation lane tests the
one form.

Verified: cargo clippy --workspace --all-targets --all-features -D warnings;
nextest of bind::unused_bits, tests::fast_paths, tests::owned_divisions,
api_surface and the runtime's degradation and catalogue tests (49 passed).

* Drop the exact color resolve: the device's average resolves every attachment it can

The owner's ruling (2026-10-27): the GPU's native answers are the contract.
ResolvePolicy and DevicePolicy::resolve go, with the crate-owned resolve
drawn after the pass for a format of Metal's rules on a device whose average
is not measured to be Metal's. The device's AVERAGE in the pass is the one
form there, announced device-rounded-resolve as before. The crate-owned
resolve keeps the resolves no device's average can write: an extended-range
attachment's raw codes, a resolve into the attachment's format's sRGB twin
(VUID-VkSubpassDescription-pResolveAttachments-00850), and a fetching pass's
sample planes, read in place of merging them back.

Docs: the ledger row and docs/API.md's policy bullet go; the shader-resolve,
device-rounded-resolve and unmeasured-resolve entries describe what remains
(unmeasured-resolve's cost text with them).

Validation: the lanes ran under exact_answers, so their expectations follow
the device's resolve: resolve_kind is device-rounded-resolve wherever the
average is not measured to be Metal's; the exact form's tests
(color_resolves_against_metals_rules, the caller's-image copy path, its cost
scout) go; the Maps-form and probe-6 resolves hold Metal's texels where the
fact holds and the announced bound elsewhere; shader-resolve's lane site
moves to the extended-range resolve lane.

Verified: cargo clippy --workspace --all-targets --all-features -D warnings,
plain and under --cfg m2v_gpu; nextest of fast_paths, the degradation and
catalogue tests, the runtime's resolve, sample-plane, framebuffer-fetch and
stand-in tests, and api_surface (129 passed). The device lanes were not run.

* Drop the depth twin: every Depth32Float texture is its D32_SFLOAT depth image

The owner's ruling: promise the GPU's native arithmetic, no exact emulation.
A Depth32Float texture the program only reads was held in an R32_SFLOAT
image with a D32_SFLOAT twin for comparisons, on a driver not measured to
keep every float in a depth image (plan_depth_twin), and a multisampled one
in R32_SFLOAT under MultisampleDepthTwinPolicy::Exact. Both forms exist only
to keep Metal's texel bits; the native form is the depth image, whose
possible clamp or denormal flush the existing notices already announce at
the write (restricted-depth-upload, depth-denormals).

Removed:
- MultisampleDepthTwinPolicy and DevicePolicy::multisample_depth_twin, its
  FAST-PATHS row, its known-gap paragraph and its fast_paths choice.
- image_plan::plan_images, plan_depth_twin, holds_depth_in_colour,
  holds_multisample_depth_in_colour, ImageFacts::depth_loss and
  ImageFacts::multisample_depth_twin.
- The twin image of a texture (Image::twin), its copies in replace_region,
  blits and host copies, Owner::HeapTwin and the heap plan's twin (heap_extent
  now takes the image alone; check_heap_base the route alone; Mine is gone).
- The depth-twin degrade kind (Degradation::DepthTwin) and its docs/API.md
  catalogue entry.
- The bind side: TextureFacts::depth_twin, TextureShape::Texture::depth_twin,
  ImageViewDesc::twin and sampled_view's twin argument.
- A sparse Depth32Float texture is no longer refused for needing a twin.
- copy_unit refuses any depth format held in colour (none is now).

Tests: the twin tests are replaced by one that holds a Depth32Float texture
in its D32_SFLOAT image on every committed profile (single-sampled,
array, cube, render target, 2 and 4 samples); the heap and copy-plan unit
tests follow the one-image forms. The validation lanes that expected a twin
(texture_blits' upload lane, clear_reach, resolves' read-only depth pass,
texture_fills, heap_textures) now expect the depth image and its notices;
conformance's fill cases allow Depth32Float's digest unchecked where
restricted-depth-upload fires, as Depth32Float_Stencil8's already is.

RUNTIME_VERSION 1656: what a run of an unchanged pipeline does with such a
texture changes.

Verified: cargo clippy --workspace --all-targets --all-features -D warnings,
plain and with --cfg m2v_gpu; nextest of the translator and runtime
image_plan, heap, copy_plan, texture_facts, families, texture, degradation,
catalogue, fast_paths, profile, api_surface, bind and driver_facts tests
(973 passed). Device lanes not run.

* Drop the magnitude stand-in and the sign strip: a stored signed depth is tested natively

On the owner's ruling to promise the GPU's native arithmetic, a render target's
32-bit float depth that may hold a negative value or a NaN is no longer
switched on to render over a magnitude stand-in, and no pass strips the signs
of the words it did not write. The device's depth test compares the stored
value as it is and its pass keeps every bit; the runtime announces that
answer.

What goes:
- texture/signed_depth.rs, with the switch-on flags, the stand-in plans, the
  write-backs and the sign strips in render.rs and render_pass.rs;
- Cause::Magnitude in attachment_stand_in.rs;
- the translator's DepthMagnitudeModule (bind/depth_magnitude.rs) and the
  DepthStencilCopy::{DepthMagnitude, MagnitudeBits} draws;
- OwnedModule::DepthMagnitude;
- copy_plan's holds_unlike_its_stand_in;
- WorkCounts' signed_depth_switch_ons, magnitude_stand_in_passes,
  magnitude_write_backs and sign_strips (and their counters).

What stays, describing the native answer:
- signed-depth-test is announced where a write (a host upload, a blit, a copy,
  a written NaN clear, a new target's pattern loaded) may store such a value in
  a render target's Depth32Float or Depth32Float_Stencil8 depth on a device
  that keeps it and whose test is not Metal's (no
  DriverFact::DepthTestComparesMagnitudes);
- where the device's test is Metal's own (MoltenVK), signed-depth-test is
  announced only at a pass that loads and stores the depth and sets a state
  with depth writes but draws under none, which keeps the signs.

The denormal notice no longer mentions the stand-in.

Docs:
- FAST-PATHS drops "A stored negative or NaN depth is tested by its magnitude"
  and the matching known gap;
- FAST-PATHS also drops "A Depth16Unorm depth whose code the fragment stage
  writes is tested after the stage" (the shader write is the translator's to
  remove);
- API.md's depth-denormals and signed-depth-test entries now state the native
  answer;
- doc comments the earlier steps left past 100 columns are reflowed, and the
  remaining depth-twin mentions (bind docs, fast_paths' comment, three
  conformance known-gap todos) are dropped.

Validation:
- depth_denormals' lanes check every read, sample and comparison against
  Metal's, the depth tests only where the device's test is Metal's own, and
  the notices where they now fall;
- the sign-strip lane is deleted;
- texture_blits expects signed-depth-test at the render-target upload.

Verified: clippy with all targets and all features, plain and with
--cfg m2v_gpu, across the workspace; rustdoc with -D warnings; the runtime's
nextest suite (1150 passed); the translator's touched tests (fast_paths,
catalogue, degradation, api_surface, depth_stencil_copy, owned_divisions,
profile, driver_facts, bind, policy: 671 passed); validation and conformance
non-device tests in the touched areas (230 passed). Device lanes were not run.

* Re-bless the API signatures and regenerate the refusal surface

The lane's removals leave the public surface without:
- MultisampleDepthTwinPolicy, TileStorePolicy and ResolvePolicy, with their
  DevicePolicy fields;
- TextureFacts::depth_twin, TextureShape::Texture's depth_twin and
  ImageViewDesc::twin;
- DepthMagnitudeModule and depth_magnitude_module;
- DepthStencilCopy::{DepthMagnitude, MagnitudeBits};
- Degradation::DepthTwin;
- WorkCounts' signed_depth_switch_ons, magnitude_stand_in_passes,
  magnitude_write_backs and sign_strips.

The refusal surface loses four sites:
- the sparse depth-twin refusal (SparseHeaps, texture.rs plan_sparse_texture);
- the host heap's twin refusal (HeapTextureMemory, heap.rs host_heap_plan);
- the heap twin's DetachTextures site (heap.rs heap_texture_at);
- the sign strip's SeparateMultisampledDepthStencil site
  (signed_depth.rs sample_strip).

Verified: python3 scripts/api-signatures/signatures.py --bless and
python3 scripts/refusal-surface/refusal_surface.py, then the api_signatures,
refusal, api_surface, published_crates, fast_paths and degradation_catalogue
tests (81 passed).

* Format the policy import lists after the half switches' removal

The rebase onto development (where the half-precision lane removed three policies) kept both lanes' removals; cargo fmt re-flows the shortened lists.

Verified: clippy (workspace, all targets, all features) clean; 709 touched tests (fast_paths, api_surface, api_signatures, catalogue, degradation, profile, bind, image_plan, published_crates, policy) pass.

* Re-pin the runtime sources at the landing tip

The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
This commit is contained in:
Anees Iqbal committed 2026-10-28 17:24:20 +02:00
1 parent e87d6e558f
commit b7a62be64b
101 files changed
+1239 -5702

No files matched your search

@@ -117,9 +117,9 @@ format-footprints-two-plane-ten-bit * refused case/MTLPixelFormatRGB10A8_2P/Type
half-texel-nans-r16f RADV divergent case/words/nearest-sample 515 elements differ (U16), the largest difference 33279 Metal's `texture2d<half>` never widens, so a 16-bit float texel's NaN comes back as its own bits (verified: this case's own recording of plain Metal on an M3 Max, macOS 27.0.1). Ours reads the image as `f32` lanes and rounds them (`lower::texture::metal_texel_nans` keeps the device's decode for a half-channel class, which is exact only on a device that widens a half texel exactly), and this device's **sampler** canonicalizes a 16-bit float texel's NaN to 0xFFC00000, its own negative quiet NaN, so every NaN lane of a nearest sample reads 0xFE00 where Metal reads the texel's code. Its image **loads** keep the texel's bits, so `case/words/read` and `case/words/read-through-sample` are exact here, where all three sites differ on MoltenVK. The runtime announces `device-nan-encoding` for it. Open: read a 16-bit float texture's `half` result through an unsigned-integer alias of the image, the read side of the `StorageImageClass::HalfBits` write path, so no device decode sees the texel; on the orchestrator's todo list.
half-texel-nans-rg16f RADV divergent case/words/nearest-sample 1025 elements differ (U16), the largest difference 33279 Metal's `texture2d<half>` never widens, so a 16-bit float texel's NaN comes back as its own bits (verified: this case's own recording of plain Metal on an M3 Max, macOS 27.0.1). Ours reads the image as `f32` lanes and rounds them (`lower::texture::metal_texel_nans` keeps the device's decode for a half-channel class, which is exact only on a device that widens a half texel exactly), and this device's **sampler** canonicalizes a 16-bit float texel's NaN to 0xFFC00000, its own negative quiet NaN, so every NaN lane of a nearest sample reads 0xFE00 where Metal reads the texel's code. Its image **loads** keep the texel's bits, so `case/words/read` and `case/words/read-through-sample` are exact here, where all three sites differ on MoltenVK. The runtime announces `device-nan-encoding` for it. Open: read a 16-bit float texture's `half` result through an unsigned-integer alias of the image, the read side of the `StorageImageClass::HalfBits` write path, so no device decode sees the texel; on the orchestrator's todo list.
half-texel-nans-rgba16f RADV divergent case/words/nearest-sample 2045 elements differ (U16), the largest difference 33279 Metal's `texture2d<half>` never widens, so a 16-bit float texel's NaN comes back as its own bits (verified: this case's own recording of plain Metal on an M3 Max, macOS 27.0.1). Ours reads the image as `f32` lanes and rounds them (`lower::texture::metal_texel_nans` keeps the device's decode for a half-channel class, which is exact only on a device that widens a half texel exactly), and this device's **sampler** canonicalizes a 16-bit float texel's NaN to 0xFFC00000, its own negative quiet NaN, so every NaN lane of a nearest sample reads 0xFE00 where Metal reads the texel's code. Its image **loads** keep the texel's bits, so `case/words/read` and `case/words/read-through-sample` are exact here, where all three sites differ on MoltenVK. The runtime announces `device-nan-encoding` for it. Open: read a 16-bit float texture's `half` result through an unsigned-integer alias of the image, the read side of the `StorageImageClass::HalfBits` write path, so no device decode sees the texel; on the orchestrator's todo list.
sample-fills-d32-2 RADV divergent case/samples/d32-2 1 line differs: Metal "after s0 y1: | 3e800000 3e800000 | 00000001 3f800000 | 00000001 3f800000 | 3e800000 3e800000 | 3e800000 3e800000", ours "after s0 y1: | 3e800000 3e800000 | 00000000 3f800000 | 00000000 3f800000 | 3e800000 3e800000 | 3e800000 3e800000" Metal's fill stores every depth value as given, a denormal included, so sample 0 of texel (1,1) holds 0x00000001 (verified: the carried probe `ms.m` on an M3 Max, macOS 27.0.1, which this case replays). Ours stores 0x00000000: this driver stores a denormal a GPU write gives a `D32_SFLOAT` depth image as a zero and keeps only a CPU store's, which is why it has no `DriverFact::DepthImageKeepsDenormals` (`runtime_lane::depth_denormals`, measured 2026-10-10 on the Radeon 780M and reproduced on the RX 7900 XTX 2026-10-24), and a multisampled image takes no CPU store, so the fill has no exact form on this device. The runtime announces `depth-denormals` for the write, which the case declares at its notices site; the depth words still compare exactly there, which is what this row records. Open: hold a multisampled `Depth32Float` texture's texels in a colour twin, as a read-only depth texture's are already held (`texture.rs`'s depth twin), so no depth image sees the value; on the orchestrator's todo list.
sample-fills-d32-4 RADV divergent case/samples/d32-4 1 line differs: Metal "after s0 y1: | 3e800000 3e800000 3e800000 3e800000 | 00000001 3f800000 00000000 3e800000 | 00000001 3f800000 00000000 3e800000 | 3e800000 3e800000 3e800000 3e800000 | 3e800000 3e800000 3e800000 3e800000", ours "after s0 y1: | 3e800000 3e800000 3e800000 3e800000 | 00000000 3f800000 00000000 3e800000 | 00000000 3f800000 00000000 3e800000 | 3e800000 3e800000 3e800000 3e800000 | 3e800000 3e800000 3e800000 3e800000" Metal's fill stores every depth value as given, a denormal included, so sample 0 of texel (1,1) holds 0x00000001 (verified: the carried probe `ms.m` on an M3 Max, macOS 27.0.1, which this case replays). Ours stores 0x00000000: this driver stores a denormal a GPU write gives a `D32_SFLOAT` depth image as a zero and keeps only a CPU store's, which is why it has no `DriverFact::DepthImageKeepsDenormals` (`runtime_lane::depth_denormals`, measured 2026-10-10 on the Radeon 780M and reproduced on the RX 7900 XTX 2026-10-24), and a multisampled image takes no CPU store, so the fill has no exact form on this device. The runtime announces `depth-denormals` for the write, which the case declares at its notices site; the depth words still compare exactly there, which is what this row records. Open: hold a multisampled `Depth32Float` texture's texels in a colour twin, as a read-only depth texture's are already held (`texture.rs`'s depth twin), so no depth image sees the value; on the orchestrator's todo list.
sample-fills-d32s8-4 RADV divergent case/samples/d32s8-4 1 line differs: Metal "after s0 y1: | 3e800000 3e800000 3e800000 3e800000 | 00000001 3f800000 00000000 3e800000 | 00000001 3f800000 00000000 3e800000 | 3e800000 3e800000 3e800000 3e800000 | 3e800000 3e800000 3e800000 3e800000", ours "after s0 y1: | 3e800000 3e800000 3e800000 3e800000 | 00000000 3f800000 00000000 3e800000 | 00000000 3f800000 00000000 3e800000 | 3e800000 3e800000 3e800000 3e800000 | 3e800000 3e800000 3e800000 3e800000" Metal's fill stores every depth value as given, a denormal included, so sample 0 of texel (1,1) holds 0x00000001 (verified: the carried probe `ms.m` on an M3 Max, macOS 27.0.1, which this case replays). Ours stores 0x00000000: this driver stores a denormal a GPU write gives a `D32_SFLOAT` depth image as a zero and keeps only a CPU store's, which is why it has no `DriverFact::DepthImageKeepsDenormals` (`runtime_lane::depth_denormals`, measured 2026-10-10 on the Radeon 780M and reproduced on the RX 7900 XTX 2026-10-24), and a multisampled image takes no CPU store, so the fill has no exact form on this device. The runtime announces `depth-denormals` for the write, which the case declares at its notices site; the depth words still compare exactly there, which is what this row records. Open: hold a multisampled `Depth32Float` texture's texels in a colour twin, as a read-only depth texture's are already held (`texture.rs`'s depth twin), so no depth image sees the value; on the orchestrator's todo list.
sample-fills-d32-2 RADV divergent case/samples/d32-2 1 line differs: Metal "after s0 y1: | 3e800000 3e800000 | 00000001 3f800000 | 00000001 3f800000 | 3e800000 3e800000 | 3e800000 3e800000", ours "after s0 y1: | 3e800000 3e800000 | 00000000 3f800000 | 00000000 3f800000 | 3e800000 3e800000 | 3e800000 3e800000" Metal's fill stores every depth value as given, a denormal included, so sample 0 of texel (1,1) holds 0x00000001 (verified: the carried probe `ms.m` on an M3 Max, macOS 27.0.1, which this case replays). Ours stores 0x00000000: this driver stores a denormal a GPU write gives a `D32_SFLOAT` depth image as a zero and keeps only a CPU store's, which is why it has no `DriverFact::DepthImageKeepsDenormals` (`runtime_lane::depth_denormals`, measured 2026-10-10 on the Radeon 780M and reproduced on the RX 7900 XTX 2026-10-24), and a multisampled image takes no CPU store, so the fill has no exact form on this device. The runtime announces `depth-denormals` for the write, which the case declares at its notices site; the depth words still compare exactly there, which is what this row records.
sample-fills-d32-4 RADV divergent case/samples/d32-4 1 line differs: Metal "after s0 y1: | 3e800000 3e800000 3e800000 3e800000 | 00000001 3f800000 00000000 3e800000 | 00000001 3f800000 00000000 3e800000 | 3e800000 3e800000 3e800000 3e800000 | 3e800000 3e800000 3e800000 3e800000", ours "after s0 y1: | 3e800000 3e800000 3e800000 3e800000 | 00000000 3f800000 00000000 3e800000 | 00000000 3f800000 00000000 3e800000 | 3e800000 3e800000 3e800000 3e800000 | 3e800000 3e800000 3e800000 3e800000" Metal's fill stores every depth value as given, a denormal included, so sample 0 of texel (1,1) holds 0x00000001 (verified: the carried probe `ms.m` on an M3 Max, macOS 27.0.1, which this case replays). Ours stores 0x00000000: this driver stores a denormal a GPU write gives a `D32_SFLOAT` depth image as a zero and keeps only a CPU store's, which is why it has no `DriverFact::DepthImageKeepsDenormals` (`runtime_lane::depth_denormals`, measured 2026-10-10 on the Radeon 780M and reproduced on the RX 7900 XTX 2026-10-24), and a multisampled image takes no CPU store, so the fill has no exact form on this device. The runtime announces `depth-denormals` for the write, which the case declares at its notices site; the depth words still compare exactly there, which is what this row records.
sample-fills-d32s8-4 RADV divergent case/samples/d32s8-4 1 line differs: Metal "after s0 y1: | 3e800000 3e800000 3e800000 3e800000 | 00000001 3f800000 00000000 3e800000 | 00000001 3f800000 00000000 3e800000 | 3e800000 3e800000 3e800000 3e800000 | 3e800000 3e800000 3e800000 3e800000", ours "after s0 y1: | 3e800000 3e800000 3e800000 3e800000 | 00000000 3f800000 00000000 3e800000 | 00000000 3f800000 00000000 3e800000 | 3e800000 3e800000 3e800000 3e800000 | 3e800000 3e800000 3e800000 3e800000" Metal's fill stores every depth value as given, a denormal included, so sample 0 of texel (1,1) holds 0x00000001 (verified: the carried probe `ms.m` on an M3 Max, macOS 27.0.1, which this case replays). Ours stores 0x00000000: this driver stores a denormal a GPU write gives a `D32_SFLOAT` depth image as a zero and keeps only a CPU store's, which is why it has no `DriverFact::DepthImageKeepsDenormals` (`runtime_lane::depth_denormals`, measured 2026-10-10 on the Radeon 780M and reproduced on the RX 7900 XTX 2026-10-24), and a multisampled image takes no CPU store, so the fill has no exact form on this device. The runtime announces `depth-denormals` for the write, which the case declares at its notices site; the depth words still compare exactly there, which is what this row records.
primitive-type-restart-indices NVIDIA GeForce RTX 5080 Laptop GPU divergent case/MTLPrimitiveTypeLine/MTLIndexTypeUInt16/texels 2 elements differ (U32), the largest difference 3 Metal rasterizes a line by the diamond-exit rule and this driver's Bresenham mode breaks one tie the other way. The line of vertices 0 and 1 runs exactly through the boundary point (3.5, 1.0), a vertex of the diamonds of both pixels either side of it: Metal draws the lower pixel (row 1 column 3) and leaves row 0 column 3 at the pass's clear, and this driver draws row 0 column 3 and leaves row 1 column 3. Those two texels, and nothing else, are the whole of each cell's difference -- the mark word alone, since the fragment's vertex id is 0 either way. Vulkan's Bresenham diamond is the open set |p - x| + |q - y| < 0.5, so a line that only touches a vertex exits no diamond and the specification requires no fragment for either pixel; both choices conform, and llvmpipe (LLVM 23.1.1, Mesa 26.2.4) makes Metal's. The runtime already asks every line-rasterizing pipeline for VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT (`pipeline/graphics.rs`), which is what took these four cells from 7, 7, 5 and 13 texels to these two: without it a strictLines device covers the whole rectangle of the line's width. There is no Vulkan control over the tie, so this is the driver's own and not the runtime's. RADV and ANV unrun. docs/FAST-PATHS.md carries the gap.
primitive-type-restart-indices NVIDIA GeForce RTX 5080 Laptop GPU divergent case/MTLPrimitiveTypeLine/MTLIndexTypeUInt32/texels 2 elements differ (U32), the largest difference 4 Metal rasterizes a line by the diamond-exit rule and this driver's Bresenham mode breaks one tie the other way. The line of vertices 0 and 1 runs exactly through the boundary point (3.5, 1.0), a vertex of the diamonds of both pixels either side of it: Metal draws the lower pixel (row 1 column 3) and leaves row 0 column 3 at the pass's clear, and this driver draws row 0 column 3 and leaves row 1 column 3. Those two texels, and nothing else, are the whole of each cell's difference -- the mark word alone, since the fragment's vertex id is 0 either way. Vulkan's Bresenham diamond is the open set |p - x| + |q - y| < 0.5, so a line that only touches a vertex exits no diamond and the specification requires no fragment for either pixel; both choices conform, and llvmpipe (LLVM 23.1.1, Mesa 26.2.4) makes Metal's. The runtime already asks every line-rasterizing pipeline for VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT (`pipeline/graphics.rs`), which is what took these four cells from 7, 7, 5 and 13 texels to these two: without it a strictLines device covers the whole rectangle of the line's width. There is no Vulkan control over the tie, so this is the driver's own and not the runtime's. RADV and ANV unrun. docs/FAST-PATHS.md carries the gap.
primitive-type-restart-indices NVIDIA GeForce RTX 5080 Laptop GPU divergent case/MTLPrimitiveTypeLineStrip/MTLIndexTypeUInt16/texels 2 elements differ (U32), the largest difference 5 Metal rasterizes a line by the diamond-exit rule and this driver's Bresenham mode breaks one tie the other way. The line of vertices 0 and 1 runs exactly through the boundary point (3.5, 1.0), a vertex of the diamonds of both pixels either side of it: Metal draws the lower pixel (row 1 column 3) and leaves row 0 column 3 at the pass's clear, and this driver draws row 0 column 3 and leaves row 1 column 3. Those two texels, and nothing else, are the whole of each cell's difference -- the mark word alone, since the fragment's vertex id is 0 either way. Vulkan's Bresenham diamond is the open set |p - x| + |q - y| < 0.5, so a line that only touches a vertex exits no diamond and the specification requires no fragment for either pixel; both choices conform, and llvmpipe (LLVM 23.1.1, Mesa 26.2.4) makes Metal's. The runtime already asks every line-rasterizing pipeline for VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT (`pipeline/graphics.rs`), which is what took these four cells from 7, 7, 5 and 13 texels to these two: without it a strictLines device covers the whole rectangle of the line's width. There is no Vulkan control over the tie, so this is the driver's own and not the runtime's. RADV and ANV unrun. docs/FAST-PATHS.md carries the gap.
Can't render this file because it is too large.
@@ -453,20 +453,18 @@ impl Case for SampleFills {
));
}
// What a multisample fill and its read-back announce on a device that needs them: the
// drawn depth copy, a depth texture's twin and its denormals, and shared storage in
// drawn depth copy, a depth texture's denormals, and shared storage in
// system memory. Metal announces none of them, so the notices site differs on such a
// device, and the difference is justified where one of these fired.
use metal2vulkan_runtime::Degradation as D;
for kind in [
D::DrawnDepthCopy,
D::DepthTwin,
D::DepthDenormals,
D::SharedInSystemMemory,
D::ShadowedTextureView,
// A `Depth32Float` target a write may give a negative value or a NaN, whose test and
// store the device does not take as Metal's: the runtime renders it over a magnitude
// stand-in and announces the corners. Announced on lavapipe for the four-sample d32
// rows. Declared only; every depth word still compares exactly.
// store the device does not take as Metal's. Announced on lavapipe for the
// four-sample d32 rows. Declared only; every depth word still compares exactly.
D::SignedDepthTest,
] {
allowances.push(notice_allowance(kind.code()));
@@ -80,9 +80,8 @@ const PADDED_FORMATS: [PixelFormat; 2] = [PixelFormat::BGR10XR, PixelFormat::BGR
/// - **The two-plane extended-range pair.** The runtime refuses it for a sparse heap
/// (`NotImplemented(Format)`), so a case over it would be a `Refused` row standing for an open
/// product question rather than a measurement of Metal's tail arithmetic.
/// - **Depth and stencil formats.** The runtime refuses a `Depth32Float` sparse texture that would
/// need a depth twin (`NotImplemented(SparseHeaps)`) and refuses a dual-plane format outright.
/// Their *tile* is recorded in [`crate::cases::sparse_tiles`], where no texture is made.
/// - **Depth and stencil formats.** The runtime refuses a dual-plane format outright. Their *tile*
/// is recorded in [`crate::cases::sparse_tiles`], where no texture is made.
/// - **Sample counts other than 1, 2 and 4**, and a multisample texture of more than one level,
/// which Metal describes none of.
pub const EXCLUDED: &str = "see this module's documentation";
@@ -714,11 +714,12 @@ impl Case for TextureFills {
fn allowances(&self) -> Vec<Allowance> {
let mut allowances = Vec::new();
if self.raw == 260 {
// `Depth32Float_Stencil8`'s patterns are depth outside [0, 1]. Where the device's
// uploads announce that it may store such a value clamped, the format's bytes are not
// Metal's to match: the lane skips the format there, and here the digest goes
// unchecked, named, counted and reported, with that notice as the justification.
if matches!(self.raw, 252 | 260) {
// A 32-bit float depth's patterns may be depth outside [0, 1]
// (`Depth32Float_Stencil8`'s are). Where the device's uploads announce that it may
// store such a value clamped, the format's bytes are not Metal's to match: the lane
// skips the format there, and here the digest goes unchecked, named, counted and
// reported, with that notice as the justification.
allowances.push(Allowance::new(
format!("case/{}", site(self.raw)),
Loosening::Unchecked,
@@ -730,20 +731,19 @@ impl Case for TextureFills {
));
}
// What this work announces on a device that needs it, which is the lane's own list: a
// fill of a color packed where fills ignore the color, a depth or block-compressed
// texture's twin and its precision, a two-plane texture shadowed in a heap's bytes and a
// fill of a color packed where fills ignore the color, a block-compressed texture's twin
// and its precision, a two-plane texture shadowed in a heap's bytes and a
// mipmapped one whose later levels lie apart from the shadow, a float depth's denormals
// and the combined format's clamp, and shared storage in system memory. Metal announces
// none of them, so the notices site differs on such a device, and the difference is
// justified where one of these fired. The format's own digest still compares, and only
// `Depth32Float_Stencil8`'s goes unchecked, above.
// the 32-bit float depth formats' go unchecked, above.
use metal2vulkan_runtime::Degradation as D;
for kind in [
D::UnpackedFillColor,
D::ShadowedTexture,
D::HeapTwoPlaneLayout,
D::RestrictedDepthUpload,
D::DepthTwin,
D::DecodedBlockTwin,
D::CarriedDecodedTwin,
D::DecodedTexelPrecision,
@@ -405,9 +405,7 @@ fn child(side: &str, options: &Options) {
requirement_images_made {} arena_pools_made {} owned_descriptor_pools {} \
draws_settled {} stage_tables_read {} graphics_pipelines_looked_up {} \
draws_pushing_set_zero {} set_zero_writes_pushed {} set_zero_sets_reused {} \
set_zero_sets_found {} draw_shapes_reused {} signed_depth_switch_ons {} \
sign_strips {} \
magnitude_stand_in_passes {} \
set_zero_sets_found {} draw_shapes_reused {} \
completed_waits {} bare_starts {} submit_infos {} finales_folded {} \
finales_apart {} pending_none {} pending_one {} pending_two_three {} \
pending_four_more {}",
@@ -433,9 +431,6 @@ fn child(side: &str, options: &Options) {
c.set_zero_sets_reused,
c.set_zero_sets_found,
c.draw_shapes_reused,
c.signed_depth_switch_ons,
c.sign_strips,
c.magnitude_stand_in_passes,
c.completed_waits,
c.bare_starts,
c.submit_infos,
@@ -1742,10 +1742,6 @@ impl Gpu for Runtime {
c.linear_passes_through_copies,
),
("kept_bytes_passes", c.kept_bytes_passes),
("signed_depth_switch_ons", c.signed_depth_switch_ons),
("magnitude_stand_in_passes", c.magnitude_stand_in_passes),
("magnitude_write_backs", c.magnitude_write_backs),
("sign_strips", c.sign_strips),
("color_group_passes", c.color_group_passes),
("color_group_twins", c.color_group_twins),
("color_group_draws_skipped", c.color_group_draws_skipped),
@@ -57,12 +57,6 @@
//! were, and the crate-owned resolve (`color_resolve.rs`) reads the samples the pass stores, so
//! the pass renders it through the image its texture keeps, copied into where the pass loads it
//! (`Load`), and never back (`resolve::keep_samples`).
//! - **A render target's depth that may hold a negative value or a NaN**
//! (`texture/signed_depth.rs`), which a pass loads: it renders over its magnitude stand-in, the
//! image its texture keeps for the queue (`kept_backing`), whose words the pass writes from the
//! depth's before it and merges back after it where it stores the depth and may have written
//! it: its depth test is Metal's, and so is what it keeps, but for the merge's corner, which
//! `signed-depth-test` names.
//! - **A pass's hidden depth and stencil**. In a pass without a depth/stencil attachment, plain
//! Metal tests a draw whose state uses depth or the stencil against a hidden depth of `float`,
//! 1.0 at the pass's start, and a stencil of 0, kept per sample through the pass. Such a draw
@@ -155,11 +149,6 @@ pub(super) enum Cause {
/// buffer keeps its bytes (`kept_bytes.rs`, which announces it, `dont-care-stand-in`): copied
/// into where the pass loads it, and never back.
KeptBytes,
/// A render target's 32-bit float depth that may hold a negative value or a NaN, which the
/// pass loads: it renders over the magnitude stand-in its texture keeps for the queue, written
/// from the depth before the pass and merged back after it (`texture/signed_depth.rs`), not
/// by the stand-in's own copies.
Magnitude,
/// A multisampled color attachment the pass stores nothing of (`MultisampleResolve`) whose
/// samples a resolve the runtime draws after the pass reads, which the pass must store for it
/// (`resolve::keep_samples`): it renders through the image its texture keeps for the queue,
@@ -436,11 +425,11 @@ pub(super) fn stand_in_as(
if stored {
usage |= ImageUsageFlags::STORAGE;
}
// The exact color resolve reads a multisampled color attachment as an input attachment
// (`color_resolve.rs`), as does the resolve into the attachment's format's sRGB twin, whose
// encoding no device's average writes (`color_resolve::twin_resolved`).
// The crate-owned color resolve reads a multisampled extended-range color attachment as an
// input attachment (`color_resolve.rs`), as does the resolve into the attachment's format's
// sRGB twin, whose encoding no device's average writes (`color_resolve::twin_resolved`).
let resolved = multisampled
&& (color_resolve::shader_rules(device, pixel_format, format, target.samples).is_some()
&& (color_resolve::shader_rules(pixel_format, target.samples).is_some()
|| color_resolve::twin_resolved(pixel_format, target.samples));
if color && (framebuffer_fetch::through_inputs(profile) || resolved) {
usage |= ImageUsageFlags::INPUT_ATTACHMENT;
+1 -1
View File
@@ -1401,7 +1401,7 @@ const KEPT_VIEWS: usize = 256;
/// weakly, so it keeps none alive:
///
/// - **A view** of a texture slot is a function of the texture (its storage, image, decoded and
/// depth twins and record are fixed as it is made; its usage shadow is made once and kept), the
/// twin and record are fixed as it is made; its usage shadow is made once and kept), the
/// view's description, whether the binding is a storage one, and its images' views, which an
/// image keeps once made until it lets them all go under its views lock (a rebind's or a
/// storage form's new `VkImage`, a detach's stand-in, a reattach). Each letting go counts in
+41 -92
View File
@@ -21,10 +21,7 @@
//! value outside `[0, 1]` undefined without `VK_EXT_depth_range_unrestricted`
//! (`VUID-vkCmdCopyBufferToImage-pRegions-07931`), and such a copy into a depth image announces
//! `restricted-depth-upload` where the device's driver is not measured to keep such a value
//! (`DriverFact::DepthImageKeepsValuesOutsideUnitRange`). A texture with a depth twin takes a
//! copy in both its images, its texels kept in colour; a copy out of it into a depth texture
//! without a twin reads its twin, and one into it from such a texture writes its `R32_SFLOAT`
//! image through a scratch buffer of the encoder.
//! (`DriverFact::DepthImageKeepsValuesOutsideUnitRange`).
//! - **Textures over buffers**. A copy that names a texture over a buffer runs on the buffer's
//! bytes at Metal's layout, whatever else holds the texels (an aliasing image, or a shadow image
//! the next encoder that uses it copies in from the bytes): one buffer-to-buffer copy of its
@@ -85,7 +82,7 @@ use super::sample_interleave;
use super::sample_planes;
use super::shadow::Covered;
use super::sparse::emulated::{Scrub, Written};
use super::texture::{buffer_image_copy, texture_aspects, texture_region, twin_copy, Texture};
use super::texture::{buffer_image_copy, texture_aspects, texture_region, Texture};
use super::tracker::Access;
use super::two_planes;
use super::values::{Origin, Region, ResourceOptions, Size, StorageMode};
@@ -383,8 +380,7 @@ fn image_copy(region: &ImageCopyRegion) -> vk::ImageCopy {
/// Whether two regions of one texture's texels share texels: of one level, layer and texel,
/// unless one lies in a depth/stencil image's depth and the other in its stencil, which Vulkan
/// keeps apart. Any other two aspects are the same texels (a texture's colour image and its
/// depth twin's depth hold one texture's).
/// keeps apart.
fn regions_meet(a: &ImageRegion, b: &ImageRegion) -> bool {
let meet = |a0: u32, an: u32, b0: u32, bn: u32| {
u64::from(a0) < u64::from(b0) + u64::from(bn)
@@ -542,8 +538,8 @@ impl BlitCommandEncoder {
)?;
// A depth written as the single-sample path writes one announces as it
// does.
destination_texture.degrade_depth_upload(CALL, aspect, true, true);
destination_texture.degrade_depth_denormals(CALL, aspect, false, true);
destination_texture.degrade_depth_upload(CALL, aspect, true);
destination_texture.degrade_depth_denormals(CALL, aspect, false);
copy.announce(this.core().device(), CALL, destination_texture);
let format = destination_texture.pixel_format();
copy.announce_staging(this.core().device(), format, true);
@@ -609,8 +605,8 @@ impl BlitCommandEncoder {
let plan = plan_copy(CALL, texture, &region, &unit, &layout, source_buffer, true)?;
let written: Vec<ImageRegion> = plan.regions.iter().map(|r| r.image).collect();
this.buffer_texture_copy(source_buffer, texture, plan, true)?;
texture.degrade_depth_upload(CALL, unit.aspect, true, true);
texture.degrade_depth_denormals(CALL, unit.aspect, false, true);
texture.degrade_depth_upload(CALL, unit.aspect, true);
texture.degrade_depth_denormals(CALL, unit.aspect, false);
// Into a texture Metal keeps compressed: the texels its blit writes.
if let Some(rule) = rule_of(texture) {
this.compressed_image(texture, &written, &[rule])?;
@@ -911,10 +907,6 @@ impl BlitCommandEncoder {
.iter()
.map(|region| buffer_image_region(&image_buffer_region(image_plan, *region)))
.collect();
// A copy into a texture with a depth twin writes the twin too.
let twin = texture.twin_image().filter(|_| into_texture);
let twin_regions: Vec<vk::BufferImageCopy> =
regions.iter().copied().map(twin_copy).collect();
let buffer_use = if into_texture {
reads(buffer, plan.span.clone())
} else {
@@ -941,15 +933,6 @@ impl BlitCommandEncoder {
vk::ImageLayout::GENERAL,
&regions,
);
if let Some(twin) = twin {
device.cmd_copy_buffer_to_image(
raw,
raw_buffer,
twin,
vk::ImageLayout::GENERAL,
&twin_regions,
);
}
} else {
device.cmd_copy_image_to_buffer(
raw,
@@ -1008,15 +991,6 @@ impl BlitCommandEncoder {
vk::ImageLayout::GENERAL,
&regions,
);
if let Some(twin) = twin {
device.cmd_copy_buffer_to_image(
raw,
through,
twin,
vk::ImageLayout::GENERAL,
&twin_regions,
);
}
} else {
device.cmd_copy_image_to_buffer(
raw,
@@ -1321,13 +1295,10 @@ impl BlitCommandEncoder {
}
/// Record checked copies between two textures. `copies` run between the images [`pair`]
/// presents, a texture with a depth twin by its twin, each in its texture's aspect. Each image
/// holding the destination's texels ([`held`]: both of a texture with a twin) takes them from
/// an image of the source Vulkan copies into it (colour into colour, a depth or stencil aspect
/// into the same aspect of the same format, regions of one size), else through a scratch
/// buffer of the encoder out of the image the source's texels are read from. So out of a
/// texture with a twin into a depth texture without one they read its twin, and into it from a
/// depth texture they write its twin directly and its image through the buffer.
/// presents, each in its texture's aspect. The image holding the destination's texels
/// ([`held`]) takes them from the source's image where Vulkan copies them into it (colour into
/// colour, a depth or stencil aspect into the same aspect of the same format, regions of one
/// size), else through a scratch buffer of the encoder.
pub(super) fn texture_copies(
&mut self,
call: &'static str,
@@ -1444,11 +1415,11 @@ impl BlitCommandEncoder {
.map(|copy| (copy.src.aspect.into(), Written::of(&copy.src)))
.collect();
let fresh_reads = FreshUnwritten::reads(self.core().device(), source, &boxes)?;
// Each image of the destination takes the regions from an image of the source that
// Vulkan copies into it, else through a scratch buffer from the source's texels.
// The destination's image takes the regions from the source's where Vulkan copies them
// into it, else through a scratch buffer from the source's texels.
let from = held(source, first.src.aspect)?;
let into = held(destination, first.dst.aspect)?;
let mut direct = Vec::with_capacity(into.len());
let mut direct = Vec::with_capacity(1);
let mut staged = Vec::new();
// The regions in each image's texels: a 2-bit PVRTC texture's carrier halves them across
// (`pvrtc::image_region`).
@@ -1466,15 +1437,13 @@ impl BlitCommandEncoder {
let one_extent = in_images.iter().all(|copy| copy.src.size == copy.dst.size);
let samples = source.record().samples;
let mut bits = Vec::new();
for to in &into {
match from
.iter()
.find(|from| from.copies_into(to))
.filter(|_| !overlap && one_extent)
{
for to in [into] {
match Some(&from).filter(|from| from.copies_into(&to) && !overlap && one_extent) {
Some(from) => {
let mut regions: Vec<ImageCopyRegion> =
in_images.iter().map(|copy| from.region(to, copy)).collect();
let mut regions: Vec<ImageCopyRegion> = in_images
.iter()
.map(|copy| from.region(&to, copy))
.collect();
// Into a multisampled float image whose NaNs the device's copy converts:
// the regions at one origin in both images by the sample planes' copies,
// which move every sample's bits; the rest, or all where those cannot run,
@@ -1510,12 +1479,12 @@ impl BlitCommandEncoder {
let regions: Vec<vk::ImageCopy> = regions.iter().map(image_copy).collect();
direct.push((from.image, to.image, regions));
// A depth that may hold a negative value or a NaN, copied as it is.
if to.aspect == ImageAspectFlags::DEPTH && source.may_hold_signed_depth() {
destination.degrade_signed_depth(call, true);
if to.aspect == ImageAspectFlags::DEPTH {
destination.degrade_signed_depth(call);
}
}
}
None => staged.push(*to),
None => staged.push(to),
}
}
for copy in &bits {
@@ -1535,8 +1504,7 @@ impl BlitCommandEncoder {
self.core().retain(bits);
}
// Multisampled images, which Vulkan copies into no buffer, copy through colour images
// of their samples instead, by copies or by draws (`sample_copy.rs`). A multisampled
// texture has no twin, so its one image takes them.
// of their samples instead, by copies or by draws (`sample_copy.rs`).
if samples > 1 && !staged.is_empty() {
let side = |texture, held: &Held| sample_copy::Side {
texture,
@@ -1550,21 +1518,21 @@ impl BlitCommandEncoder {
let regions: Vec<(ImageRegion, ImageRegion)> = in_images
.iter()
.map(|copy| {
let copy = from[0].region(to, copy);
let copy = from.region(to, copy);
(copy.src, copy.dst)
})
.collect();
let copy = sample_copy::plan(
self.core().command_buffer(),
&regions,
side(source, &from[0]),
side(source, &from),
side(destination, to),
samples,
)?;
uses.extend(copy.uses.iter().cloned());
stages |= copy.stages;
destination.degrade_depth_upload(call, to.aspect, true, true);
destination.degrade_depth_denormals(call, to.aspect, false, true);
destination.degrade_depth_upload(call, to.aspect, true);
destination.degrade_depth_denormals(call, to.aspect, false);
planned.push(copy);
}
self.command_in_reading(stages, &uses, (&fresh_reads, &[]), |device, raw| {
@@ -1608,8 +1576,8 @@ impl BlitCommandEncoder {
false => Some(
through_buffer(
&in_images,
&from[0],
image_block_extent(from[0].format, source.pixel_format()).unwrap_or([1, 1]),
&from,
image_block_extent(from.format, source.pixel_format()).unwrap_or([1, 1]),
&staged,
)
.map_err(|refusal| copy_error(call, refusal))?,
@@ -1629,7 +1597,7 @@ impl BlitCommandEncoder {
reads_source.push(source.image_use(levels, layers, read(), false)?);
}
reads_source.push(writes(&scratch, 0..length));
let (image, out_of) = (from[0].image, &staging.out_of);
let (image, out_of) = (from.image, &staging.out_of);
self.command_reading(&reads_source, (&fresh_reads, &[]), |device, raw| {
// SAFETY: the encoder's command buffer is recording; the image and the
// scratch buffer are live and retained until it completes, the image is in
@@ -1646,9 +1614,8 @@ impl BlitCommandEncoder {
})?;
uses.push(reads(&scratch, 0..length));
for (to, _) in &staging.into {
let signed = source.may_hold_signed_depth();
destination.degrade_depth_upload(call, to.aspect, signed, true);
destination.degrade_depth_denormals(call, to.aspect, false, true);
destination.degrade_depth_upload(call, to.aspect, true);
destination.degrade_depth_denormals(call, to.aspect, false);
}
Some((scratch, through))
}
@@ -1789,8 +1756,8 @@ impl BlitCommandEncoder {
)
.map_err(copy_problem)?;
if into_texture {
texture.degrade_depth_upload(call, image_unit.aspect, true, true);
texture.degrade_depth_denormals(call, image_unit.aspect, false, true);
texture.degrade_depth_upload(call, image_unit.aspect, true);
texture.degrade_depth_denormals(call, image_unit.aspect, false);
}
self.buffer_texture_copy(buffer, texture, plan, into_texture)?;
}
@@ -2173,12 +2140,11 @@ pub(super) fn check_slice_level(
Ok(())
}
/// The plan's view of two textures: a texture with a depth twin by its twin, which holds its
/// texels as a depth image (`texture_copies` writes its image too); a texture buffer by none.
/// The plan's view of two textures: a texture by its image's plan, a texture buffer by none.
fn pair<'a>(source: &'a Texture, destination: &'a Texture) -> Result<CopyPair<'a>, Error> {
let image = |texture: &'a Texture| match texture.texels() {
Some(_) => Ok(None),
None => texture.depth_plan().map(Some),
None => texture.image_plan().map(Some),
};
Ok(CopyPair {
src: source.record(),
@@ -2239,29 +2205,12 @@ impl Held {
}
}
/// The images holding `texture`'s texels, the one its texels are read from first: a texture that
/// holds a depth format's texels in a colour image ([`Texture::holds_depth_in_colour`]) holds them
/// in colour in its image, and a depth twin beside it, where it has one, in `aspect` (depth); any
/// other texture in `aspect` of its image.
fn held(texture: &Texture, aspect: ImageAspectFlags) -> Result<Vec<Held>, Error> {
let image = Held {
/// The image holding `texture`'s texels, in `aspect`.
fn held(texture: &Texture, aspect: ImageAspectFlags) -> Result<Held, Error> {
Ok(Held {
image: texture.raw_image()?,
aspect: match texture.holds_depth_in_colour() {
true => ImageAspectFlags::COLOR,
false => aspect,
},
aspect,
format: texture.image_plan()?.format,
};
Ok(match texture.twin_image() {
Some(twin) => vec![
image,
Held {
image: twin,
aspect,
format: texture.depth_plan()?.format,
},
],
None => vec![image],
})
}
@@ -97,7 +97,7 @@ pub(crate) enum Owned {
ImageOwnMemory = 0,
/// A linear image in a buffer's memory (`Owner::Buffer`).
ImageInBuffer = 1,
/// An image in a heap's memory (`Owner::Heap`, `Owner::HeapTwin`).
/// An image in a heap's memory (`Owner::Heap`).
ImageInHeap = 2,
/// A heap's shadow or unaliased image, a view's shadow, a sparse image (its own memory).
ImageOther = 3,
@@ -1,32 +1,27 @@
//! Metal's exact multisample color resolve, drawn after the pass.
//! The crate-owned multisample color resolve, drawn after the pass, where the device's resolve in
//! the pass cannot write Metal's answer at all or costs more.
//!
//! Vulkan's `AVERAGE` resolve leaves the average's rounding, and an sRGB average's space, to the
//! device, and of the drivers measured only MoltenVK's from 1.4.1 on Apple's GPUs writes Metal's
//! answer (`DriverFact::ColorResolveAverageIsMetals`, measured at 2 and 4 samples). Under
//! `ResolvePolicy::Exact` every other device resolves a color attachment whose format has Metal's
//! closed rule at its count (`bind::ColorResolveFormat::of` and `resolves`: unorm, snorm, sRGB,
//! 32-bit float and packed 16-bit unorm formats at every count, and 16-bit float, `RG11B10Float`
//! and `RGB9E5Float` ones at 2 and 4 samples) by the crate-owned exact resolve
//! (`bind::color_resolve_modules`), and so does every device at more than 4 samples, where Apple's
//! GPUs have no texture and the integer rules measured at 2 and 4 are applied unmeasured. Under
//! `ResolvePolicy::Device`, the default, such an attachment resolves by the device's average in
//! the pass, as does, under either value, a format without a closed rule at its count (the 16-bit
//! float, `RG11B10Float` and `RGB9E5Float` formats past 4 samples, and a format no rule covers):
//! Metal's own resolve where the fact holds ([`average_is_metals`]: MoltenVK resolves every such
//! format by Metal's multisample resolve store action), elsewhere a recorded near-equivalent,
//! announced as `device-rounded-resolve`.
//! A color attachment resolves by the device's `AVERAGE` in its pass, which leaves the average's
//! rounding, and an sRGB average's space, to the device: Metal's own resolve where the driver's
//! is Metal's ([`average_is_metals`], `DriverFact::ColorResolveAverageIsMetals`: MoltenVK from
//! 1.4.1 on Apple's GPUs resolves every format by Metal's multisample resolve store action,
//! measured at 2 and 4 samples), elsewhere a recorded near-equivalent, announced as
//! `device-rounded-resolve`. The crate-owned resolve (`bind::color_resolve_modules`, of Metal's
//! closed rules for a format at its count, `bind::ColorResolveFormat::of` and `resolves`: unorm,
//! snorm, sRGB, 32-bit float and packed 16-bit unorm formats at every count, and 16-bit float,
//! `RG11B10Float` and `RGB9E5Float` ones at 2 and 4 samples) draws the three resolves below.
//!
//! An extended-range attachment (`BGR10_XR`, `BGRA10_XR`, their `_sRGB` twins and
//! `RGB10A2Unorm_sRGB`, the forms Metal multisamples) is held in its raw format's codes, which no
//! device's resolve averages, so it resolves by the crate-owned resolve at every count and under
//! either policy ([`extended`]: `bind::ColorResolveFormat::extended_range`, whose docs state
//! device's resolve averages, so it resolves by the crate-owned resolve at every count
//! ([`extended`]: `bind::ColorResolveFormat::extended_range`, whose docs state
//! Metal's measured rule and the near-equivalents of the channels the codes cannot give, announced
//! as `extended-range-resolve`), from any source below; an image that takes neither input
//! attachment usage nor a copy is refused, as no other resolve reads it.
//!
//! **A resolve into the attachment's format's sRGB twin** ([`twin_rules`], `resolve.rs`), which
//! Metal resolves in the resolve texture's encoding, takes the crate-owned resolve on every device
//! and under either policy: a subpass's resolve attachment is of its color attachment's own format
//! Metal resolves in the resolve texture's encoding, takes the crate-owned resolve on every
//! device: a subpass's resolve attachment is of its color attachment's own format
//! (`VUID-VkSubpassDescription-pResolveAttachments-00850`), so no device's average writes the
//! twin's encoding. Its rules are the resolve attachment's format's, and the attachment is read in
//! the format whose codes it holds -- the UNORM member of the pair either way, which an sRGB
@@ -37,7 +32,7 @@
//! [`twin_read_view`]), and samples it can neither read nor copy are not built
//! (`NotImplemented(Render)`).
//!
//! The choice is made with the attachment's resolve ([`exact`], `resolve.rs`), so the pass's
//! The choice is made with the attachment's resolve ([`of_resolve`], `resolve.rs`), so the pass's
//! shape (`render_target.rs`) leaves such a resolve out of its subpass from its first instance:
//! the pass's last instance stores the attachment's samples, and after the pass one render pass
//! instance of the resolve's own pass per attachment draws a triangle over the render area that
@@ -49,9 +44,9 @@
//! their copy format. The planes are not merged back into the attachment unless Metal keeps
//! its samples (`Store`, `StoreAndMultisampleResolve`), no instance of no draws follows to
//! resolve, and a memoryless attachment the pass only fetches and resolves needs no backing
//! (`render.rs`). This is the cheaper path on a driver whose average is Metal's too, and under
//! `ResolvePolicy::Device`, so such an attachment resolves from its planes there as well
//! ([`resolve_planes`]): its pass has one subpass, whose resolve references render pass
//! (`render.rs`). This is the cheaper path on every device, a driver whose average is Metal's
//! included, so such an attachment whose format has Metal's rules at its count resolves from its
//! planes ([`resolve_planes`]): its pass has one subpass, whose resolve references render pass
//! compatibility ignores (`render_target.rs`).
//! - **From the attachment** otherwise: its level and layer as the resolve pass's input
//! attachment 0, loaded and stored. An 8-bit sRGB attachment whose image takes its UNORM twin's
@@ -71,8 +66,7 @@
//! (`RuntimeDriverDefect::MultisampledCopiesConvertFloatNans`), which the resolve counts as 0
//! whatever its bits. A caller's image has the transfer usage the runtime's texture of its
//! descriptor has (`texture/wrapped.rs`), so only an image of a format the device copies no
//! image of has neither usage: it resolves by the device's average, announced as
//! `device-rounded-resolve`.
//! image of has neither usage.
//!
//! From any source, an 8-bit sRGB resolve writes its result through the resolve attachment's view
//! in its UNORM twin where that image takes one ([`raw_view`],
@@ -111,7 +105,7 @@ use super::Device;
use crate::shader_cache::driver::Making;
use ash::vk;
use metal2vulkan::bind::{color_resolve_modules, ColorResolveFormat, PlanesCopy, ResolveSource};
use metal2vulkan::device::{DriverFact, FormatUsage, ResolvePolicy};
use metal2vulkan::device::{DriverFact, FormatUsage};
use metal2vulkan::error::{Feature, Unsupported};
use metal2vulkan::metal::format::ExtendedRange;
use metal2vulkan::metal::PixelFormat;
@@ -124,19 +118,6 @@ use std::sync::{Arc, Mutex};
/// The most samples of a texture on Apple's GPUs, so the most whose resolve Metal measures.
pub(super) const METAL_SAMPLES: u32 = 4;
/// The exact resolve of a color attachment of `format` at `samples` samples on `device`: its
/// format's rules under `ResolvePolicy::Exact`, where the format has them and the device's average
/// is not measured to be Metal's at that count (the module docs). `None` where the device resolves
/// it in the pass.
pub(super) fn exact(device: &Device, format: Format, samples: u32) -> Option<ColorResolveFormat> {
if device.compile_device().policy().resolve != ResolvePolicy::Exact {
return None;
}
// Rules that hold at that count: the float formats' at 2 and 4 samples only.
let rules = ColorResolveFormat::of(format).filter(|rules| rules.resolves(samples))?;
(samples > 1 && !average_is_metals(device, samples)).then_some(rules)
}
/// Whether `device`'s own `AVERAGE` resolve of a color attachment of `samples` samples writes
/// Metal's resolve, whatever its format: `DriverFact::ColorResolveAverageIsMetals`, at a count
/// Apple's GPUs make (MoltenVK's resolve is Metal's multisample resolve store action).
@@ -149,25 +130,17 @@ pub(super) fn average_is_metals(device: &Device, samples: u32) -> bool {
}
/// The resolve of a multisampled color attachment of the extended-range format `pf`, held in its
/// raw format's codes, which no device's resolve averages: the crate-owned one at every count and
/// under either `ResolvePolicy` (the module docs). `None` for another format.
/// raw format's codes, which no device's resolve averages: the crate-owned one at every count (the
/// module docs). `None` for another format.
pub(super) fn extended(pf: PixelFormat) -> Option<ColorResolveFormat> {
ExtendedRange::of(pf).and_then(ColorResolveFormat::extended_range)
}
/// The crate-owned resolve of a color attachment of pixel format `pf`, held in `format`, at
/// `samples` on `device`: an extended-range format's ([`extended`]) at every count past one, else
/// [`exact`].
pub(super) fn shader_rules(
device: &Device,
pf: PixelFormat,
format: Format,
samples: u32,
) -> Option<ColorResolveFormat> {
match extended(pf) {
Some(rules) => (samples > 1).then_some(rules),
None => exact(device, format, samples),
}
/// The crate-owned resolve of a color attachment of pixel format `pf` at `samples`, where it
/// resolves the attachment's own samples into its own format: an extended-range format's
/// ([`extended`]) at every count past one. `None` where the device resolves it in the pass.
pub(super) fn shader_rules(pf: PixelFormat, samples: u32) -> Option<ColorResolveFormat> {
extended(pf).filter(|_| samples > 1)
}
/// The crate-owned resolve of the color attachment `source`, where the runtime resolves it so:
@@ -180,7 +153,7 @@ pub(super) fn of_attachment(
source: &Target,
) -> Result<Option<ColorResolveFormat>, Error> {
let pf = source.texture.pixel_format();
match shader_rules(device, pf, source.format, source.samples) {
match shader_rules(pf, source.samples) {
Some(rules) if takes_input(source)? || copied(device, source)? => Ok(Some(rules)),
Some(_) if extended(pf).is_some() => Err(Error::Unsupported(Unsupported::not_implemented(
Feature::Format,
@@ -191,7 +164,7 @@ pub(super) fn of_attachment(
/// The crate-owned resolve of a color attachment resolving into its format's sRGB twin, whose
/// encoding Metal resolves in (`resolve.rs`): the resolve attachment's format's rules at
/// `samples`, on every device and under either `ResolvePolicy`, since a subpass's resolve
/// `samples`, on every device, since a subpass's resolve
/// attachment is of its color attachment's own format and so no device's average writes the twin's
/// encoding. `None` where that format has no rule at the count.
fn twin_rules(into: &Target, samples: u32) -> Option<ColorResolveFormat> {
@@ -216,10 +189,10 @@ pub(super) fn of_resolve(
.ok_or(Error::NotImplemented(RuntimeGap::Render))
}
/// Whether the exact resolve may read the color attachment `source`, whose image takes no input
/// attachment usage, from a copy of its samples (the module docs): its image takes transfer reads,
/// and the device copies images of its format both ways, which the scratch image the copy writes
/// needs.
/// Whether the crate-owned resolve may read the color attachment `source`, whose image takes no
/// input attachment usage, from a copy of its samples (the module docs): its image takes transfer
/// reads, and the device copies images of its format both ways, which the scratch image the copy
/// writes needs.
fn copied(device: &Device, source: &Target) -> Result<bool, Error> {
let usage = source.texture.image_plan()?.usage;
let profile = device.compile_device().profile();
@@ -234,19 +207,19 @@ fn copied(device: &Device, source: &Target) -> Result<bool, Error> {
}
/// Whether a multisampled color attachment of `format` at `samples` that the sample planes may
/// hold as a pass ends resolves from them by the exact resolve whatever its device's average and
/// its device's `ResolvePolicy`: its format has Metal's rules at that count. Its pass is of one subpass, whose resolve references
/// render pass compatibility ignores, so its last instance may leave the subpass's resolve out
/// (`render_target.rs`).
/// hold as a pass ends resolves from them by the crate-owned resolve whatever its device's
/// average: its format has Metal's rules at that count. Its pass is of one subpass, whose resolve
/// references render pass compatibility ignores, so its last instance may leave the subpass's
/// resolve out (`render_target.rs`).
pub(super) fn from_planes(format: Format, samples: u32) -> bool {
ColorResolveFormat::of(format).is_some_and(|rules| rules.resolves(samples))
}
/// Resolve each color attachment of `layout` (a pass's, as it ends) whose
/// sample planes hold its samples, its last instance leaving it out of the draws' subpass
/// (`last_storage`), by the exact resolve from them where [`from_planes`] says so: neither merged
/// back for the device's resolve nor resolved in one more instance. Not in a layered pass: the
/// planes hold one layer.
/// (`last_storage`), by the crate-owned resolve from them where [`from_planes`] says so: neither
/// merged back for the device's resolve nor resolved in one more instance. Not in a layered pass:
/// the planes hold one layer.
pub(super) fn resolve_planes(layout: &mut PassLayout, last_storage: &[u32]) {
if layout.layers > 1 {
return;
@@ -268,10 +241,10 @@ pub(super) fn resolve_planes(layout: &mut PassLayout, last_storage: &[u32]) {
}
/// Whether a multisampled color attachment of `pf` may resolve into its format's sRGB twin, which
/// the crate-owned resolve reads it for on every device and under either `ResolvePolicy`
/// (`resolve.rs`): the twin's format has Metal's rules at `samples`. Its image, and the stand-in
/// a pass renders it into (`attachment_stand_in.rs`), take the input attachment usage that
/// resolve reads them through where it is free.
/// the crate-owned resolve reads it for on every device (`resolve.rs`): the twin's format has
/// Metal's rules at `samples`. Its image, and the stand-in a pass renders it into
/// (`attachment_stand_in.rs`), take the input attachment usage that resolve reads them through
/// where it is free.
pub(super) fn twin_resolved(pf: PixelFormat, samples: u32) -> bool {
samples > 1
&& srgb_twin(pf)
@@ -293,13 +266,12 @@ pub(super) fn twin_read_view(pf: PixelFormat, format: Format, samples: u32) -> O
/// `plan` with input attachment usage, where the runtime may resolve its image by the crate-owned
/// resolve reading it as an input attachment: a multisampled color attachment whose format and
/// samples [`shader_rules`] resolves on `device`, or one whose format's sRGB twin it resolves into
/// whatever the device and the policy ([`twin_resolved`]). `None` where it has the usage already,
/// or needs none.
pub(super) fn input_candidate(plan: &ImagePlan, device: &Device) -> Option<ImagePlan> {
/// samples [`shader_rules`] resolves, or one whose format's sRGB twin it resolves into whatever
/// the device ([`twin_resolved`]). `None` where it has the usage already, or needs none.
pub(super) fn input_candidate(plan: &ImagePlan) -> Option<ImagePlan> {
let usage = plan.usage;
let samples = plan.samples.as_raw();
let resolved = shader_rules(device, plan.pixel_format, plan.format, samples).is_some()
let resolved = shader_rules(plan.pixel_format, samples).is_some()
|| twin_resolved(plan.pixel_format, samples);
let candidate = usage.contains(ImageUsageFlags::COLOR_ATTACHMENT)
&& !usage.contains(ImageUsageFlags::INPUT_ATTACHMENT)
+4 -28
View File
@@ -289,21 +289,11 @@ pub(super) fn copy_unit(
if !is_depth_stencil(pf) {
return colour_unit(pf);
}
// A texture holding a depth format's texels in a colour image
// (`image_plan::holds_depth_in_colour`: one with a depth twin, and a multisampled
// `Depth32Float` one under `MultisampleDepthTwinPolicy::Exact`) holds them in an `R32_SFLOAT`
// image, Metal's 4 bytes a texel in its colour aspect; `Depth32Float` has no stencil to name.
// A depth format's texels lie in its depth and stencil aspects, never in colour.
if mapping.aspects == ImageAspectFlags::COLOR {
if pf != PixelFormat::Depth32Float || mapping.format != Format::R32_SFLOAT {
return Err(CopyRefusal::Unsupported(
Unsupported::not_implemented(Feature::Format).naming_format(pf),
));
}
return Ok(CopyUnit {
bytes: 4,
extent: [1, 1],
aspect: ImageAspectFlags::COLOR,
});
return Err(CopyRefusal::Unsupported(
Unsupported::not_implemented(Feature::Format).naming_format(pf),
));
}
// The stencil view of a combined depth/stencil texture (`X32Stencil8` of
// `Depth32FloatStencil8`) copies the stencil of the image it shares, a byte a texel, whatever
@@ -545,20 +535,6 @@ impl HostLayout {
})
}
/// Whether the host bytes `host` of 32-bit float texels (a depth's) hold, in a row, a word
/// whose magnitude stand-in (`bind::DepthMagnitudeModule::stand_in`, a denormal's the smallest
/// normal where `flush`) is not itself: a negative value, -0 included, a NaN, or where `flush`
/// a denormal; a depth test of the device's compares such a value otherwise than Metal's.
pub(super) fn holds_unlike_its_stand_in(&self, host: &[u8], flush: bool) -> bool {
let n = self.row_bytes as usize;
self.rows().any(|(h, _)| {
host[h..h + n].as_chunks::<4>().0.iter().any(|word| {
let bits = u32::from_le_bytes(*word);
metal2vulkan::bind::DepthMagnitudeModule::stand_in(bits, flush) != bits
})
})
}
/// Unpacks `packed` into the host bytes `host`, leaving the bytes between rows untouched;
/// rows that overlap are written in order, image by image and row by row, so the later
/// row's bytes stay.
+72 -121
View File
@@ -76,7 +76,7 @@ use super::values::ResourceOptions;
use crate::error::EncoderCall;
use metal2vulkan::bind::PlanDiagnostic;
use metal2vulkan::cache::SpecializationKey;
use metal2vulkan::device::{DriverFact, FunctionStorage, ResolvePolicy, VkProperty};
use metal2vulkan::device::{DriverFact, FunctionStorage, VkProperty};
use metal2vulkan::metal::PixelFormat;
use metal2vulkan::pipeline::{
ComputePipeline, PrecisionNote, Reconvergence, RenderPipeline, SlotRef, SpecKey, StageModule,
@@ -255,26 +255,25 @@ degradations! {
/// dma-bufs where the device makes no image over a dma-buf of the texture's own pages (the
/// notice names why). A heap's texture is a shadow of the heap's bytes in its range in
/// three more shapes, each announced with its own reason (`texture/heap.rs`). A
/// single-sample depth or stencil texture held with no depth twin, whose texels fit the
/// bytes its image takes, on a device whose driver lays such images apart from the memory
/// they are bound to
/// single-sample depth or stencil texture whose texels fit the bytes its image takes, on a
/// device whose driver lays such images apart from the memory they are bound to
/// ([`metal2vulkan::device::DriverFact::DepthStencilImagesLieApart`]): one no such shadow
/// serves, a multisampled one or a depth twin among them, lies apart from those bytes
/// instead (`heap-depth-stencil-apart`). A texture the device binds no image of to the
/// heap's memory where the heap places it: its optimal image takes no memory type of the
/// heap's and no linear image of the device serves (a `Shared` heap's depth texture on
/// MoltenVK), or the heap lies over host pages that no linear image over them serves, or
/// its images ask more than Metal's answer for the texture (every 4:2:2 texture among
/// them) and a shadow of its rows serves. And a heap's `RGB10A8_2P_XR10` texture, or its
/// sRGB twin, of a 1D, 2D, 1D array, 2D array or 3D type, of any level count, of one
/// sample, whose moves fit the device: its image holds each texel's colour word and alpha
/// byte side by side where Metal keeps two planes in the heap's bytes, so the image is a
/// shadow of those planes (a mipmapped one's levels past the first, and a 1D array's
/// texels, lie in the image alone: `heap-two-plane-layout`). Where Metal's layout of the
/// texture in the heap's bytes is measured and the moves fit the device, the first two
/// shadow Metal's tiles there (the texture's elements, a multisample texture's samples)
/// rather than its rows, and so do two textures that would otherwise need no shadow: one
/// whose image the driver keeps GPU-optimized where Metal's texture is not
/// serves, a multisampled one among them, lies apart from those bytes instead
/// (`heap-depth-stencil-apart`). A texture the device binds no image of to the heap's
/// memory where the heap places it: its optimal image takes no memory type of the heap's
/// and no linear image of the device serves (a `Shared` heap's depth texture on MoltenVK),
/// or the heap lies over host pages that no linear image over them serves, or its images
/// ask more than Metal's answer for the texture (every 4:2:2 texture among them) and a
/// shadow of its rows serves. And a heap's `RGB10A8_2P_XR10` texture, or its sRGB twin, of
/// a 1D, 2D, 1D array, 2D array or 3D type, of any level count, of one sample, whose moves
/// fit the device: its image holds each texel's colour word and alpha byte side by side
/// where Metal keeps two planes in the heap's bytes, so the image is a shadow of those
/// planes (a mipmapped one's levels past the first, and a 1D array's texels, lie in the
/// image alone: `heap-two-plane-layout`). Where Metal's layout of the texture in the heap's
/// bytes is measured and the moves fit the device, the first two shadow Metal's tiles there
/// (the texture's elements, a multisample texture's samples) rather than its rows, and so
/// do two textures that would otherwise need no shadow: one whose image the driver keeps
/// GPU-optimized where Metal's texture is not
/// ([`metal2vulkan::device::DriverFact::DepthStencilImagesStayGpuOptimized`]), and a
/// multisample texture whose image lies in memory of its own.
ShadowedTexture = "shadowed-texture", Performance,
@@ -532,10 +531,10 @@ degradations! {
ResolveScratch = "resolve-scratch", Performance,
"the pass resolves into a scratch image, whose render area is copied into the \
texture after the pass";
/// A multisample color resolve drawn after the pass by Metal's exact rules, where the
/// device's `AVERAGE` resolve is not measured to be Metal's, under
/// [`metal2vulkan::device::ResolvePolicy::Exact`] or from a fetching pass's sample planes
/// (`color_resolve.rs`); or a
/// A multisample color resolve drawn after the pass by the crate-owned resolve: of an
/// extended-range attachment, whose codes no device's resolve averages, into the
/// attachment's format's sRGB twin, whose encoding no device's resolve writes, or from a
/// fetching pass's sample planes (`color_resolve.rs`); or a
/// stencil resolved by `DepthResolvedSample` after `Min` or `Max`, which no Vulkan
/// resolve mode states, or a `Min` or `Max` depth on a device without the mode, drawn
/// after the pass (`depth_stencil_resolve.rs`).
@@ -744,15 +743,11 @@ degradations! {
and end";
/// A multisample color resolve averages through Vulkan's `AVERAGE` mode, which leaves
/// the rounding of the average (and the sRGB encoding) to the device, on a device not
/// measured to round as Metal does: under [`metal2vulkan::device::ResolvePolicy::Device`],
/// the default, any color attachment but one a fetching pass's sample planes hold as it
/// ends (resolved from them by Metal's rule); under
/// [`metal2vulkan::device::ResolvePolicy::Exact`] a format without Metal's closed rule at
/// its count (the 16-bit float, `RG11B10Float` and `RGB9E5Float` formats past 4 samples,
/// and a format no rule covers), or an attachment whose image the exact resolve can
/// neither read nor copy: an image without input attachment usage of a format the device
/// does not copy (`color_resolve.rs`). Not where `DriverFact::ColorResolveAverageIsMetals`
/// holds, for any format: MoltenVK's resolve is Metal's own.
/// measured to round as Metal does: any color attachment but an extended-range one, one
/// resolving into its format's sRGB twin, and one a fetching pass's sample planes hold as
/// it ends (each resolved after the pass, `color_resolve.rs`). Not where
/// `DriverFact::ColorResolveAverageIsMetals` holds, for any format: MoltenVK's resolve is
/// Metal's own.
/// Measured against Metal's rules at 2 and 4 samples
/// (`runtime_lane::resolve_rounding::the_device_resolve_rounds_as_announced`, which holds
/// the bound) on RADV (Mesa 26.0.8, the Radeon 780M and the RX 7900 XTX), ANV (Mesa
@@ -779,9 +774,8 @@ degradations! {
/// resolved by `DepthResolvedSample` after `Min` or `Max` (`depth_stencil_resolve.rs`),
/// whose pick among equal depths is measured at 2 and 4 samples.
UnmeasuredResolve = "unmeasured-resolve", Precision,
"the resolve applies the rules Metal's resolve follows at 2 and 4 samples (or the \
device's average, for a format without them), which no Metal answer confirms at \
this count";
"the resolve is the device's average, or after the pass the rules Metal's resolve \
follows at 2 and 4 samples, which no Metal answer confirms at this count";
/// A multisample resolve of an extended-range color attachment whose resolve Metal
/// averages from values finer than the codes the attachment holds (`BGRA10_XR`'s alpha,
/// an `_sRGB` twin's color, `RGB10A2Unorm_sRGB`'s channels;
@@ -859,20 +853,12 @@ degradations! {
UnlistedArgumentSampler = "unlisted-argument-sampler", Precision,
"a function reading the state through its ID in an argument buffer reads the \
neutral sampler, where Metal's reads the state";
/// A `Depth32Float` texture the program only reads or samples, on a device whose driver
/// is not measured to keep every `float` in a depth image (`device/driver_facts.rs`: a
/// denormal, and without `VK_EXT_depth_range_unrestricted` a value outside `[0, 1]`), is
/// held in an `R32_SFLOAT` image with a `D32_SFLOAT` twin for the comparisons the device
/// makes (`image_plan.rs`).
DepthTwin = "depth-twin", Performance,
"a second image of its size, which every copy into it writes too; a copy into it \
from a depth texture without a twin goes through a scratch buffer";
/// An upload (`replace_region`, a blit from a buffer) into the 32-bit float depth of a
/// texture's depth image, on a device without `VK_EXT_depth_range_unrestricted` enabled,
/// where Vulkan leaves a value outside `[0, 1]` undefined, whose driver is not measured to
/// keep one (`DriverFact::DepthImageKeepsValuesOutsideUnitRange`): a texture without a
/// twin. And a render pass's NaN clear depth on such a device, which Metal stores as
/// `0x7fc00000`, cleared to 1.0 (`nan_clear.rs`).
/// keep one (`DriverFact::DepthImageKeepsValuesOutsideUnitRange`). And a render pass's NaN
/// clear depth on such a device, which Metal stores as `0x7fc00000`, cleared to 1.0
/// (`nan_clear.rs`).
RestrictedDepthUpload = "restricted-depth-upload", Precision,
"a value outside [0, 1] may be stored clamped to [0, 1], where Metal's keeps it, so \
reads, samples, comparisons and depth tests of it can differ";
@@ -930,7 +916,7 @@ degradations! {
/// stencil images apart from the memory they are bound to
/// ([`metal2vulkan::device::DriverFact::DepthStencilImagesLieApart`]) that no shadow of the
/// heap's bytes serves: a multisampled texture, which Vulkan copies to and from no buffer,
/// one whose texels do not fit its bytes, or one with a depth twin. The texture aliases
/// or one whose texels do not fit its bytes. The texture aliases
/// none of the heap's other resources, where Metal's lies in the heap's bytes.
HeapDepthStencilApart = "heap-depth-stencil-apart", Precision,
"the texture's texels lie apart from the heap's bytes: a write through a buffer or \
@@ -1043,8 +1029,8 @@ degradations! {
/// (never a device's own texture, whose layout nothing shows), on a device whose driver
/// keeps depth and stencil images GPU-optimized whatever their create info
/// ([`metal2vulkan::device::DriverFact::DepthStencilImagesStayGpuOptimized`]), that no
/// shadow of Metal's tiles in the heap's bytes serves (a multisample texture, a depth twin,
/// a format whose layout is not measured; `texture/heap.rs`): Metal lays the texture out
/// shadow of Metal's tiles in the heap's bytes serves (a multisample texture, a format
/// whose layout is not measured; `texture/heap.rs`): Metal lays the texture out
/// without its compression metadata, and the runtime's image keeps it.
OptimizedDepthStencilTexture = "optimized-depth-stencil-texture", Precision,
"the texture's image keeps the GPU-optimized layout Metal drops with the property \
@@ -1054,8 +1040,7 @@ degradations! {
answers Metal's own size and alignment for the descriptor wherever the runtime \
models them, and the larger of the images' and Metal's for a texture whose images \
need more bytes or a coarser alignment that no shadow of the heap's bytes holds it \
to (a depth twin among them), where a heap sized by Metal's answers holds fewer \
such textures";
to, where a heap sized by Metal's answers holds fewer such textures";
/// A texture of an IOSurface plane of more than one row under 16 bytes a row
/// (`Buffer::new_texture_with_iosurface_plane`, `linear_plan.rs`): Metal's GPU writes its
/// rows 16 bytes apart and reads every row past the first as memory-dependent bytes
@@ -1293,9 +1278,7 @@ degradations! {
/// blit), where the device's pass keeps the bytes its draws do not write. Announced at
/// every draw, an indirect command buffer's executed commands' too, naming every such
/// attachment of the pass. Not where `DriverFact::TileStoreIsMetals` holds (MoltenVK's
/// pass is a Metal pass, whose tile store rewrites the codes as Metal's does), nor under
/// [`metal2vulkan::device::TileStorePolicy::Exact`] for an attachment the load pass
/// (`render/unused_bits_load.rs`) rewrites.
/// pass is a Metal pass, whose tile store rewrites the codes as Metal's does).
SnormMinimumKept = "snorm-minimum-kept", Precision,
"the texels the pass's draws do not write keep their bytes; Metal's pass rewrites a \
channel's minimum code (-128, or -32768 for 16 bits) as the code above it (-127, \
@@ -1311,9 +1294,7 @@ degradations! {
/// normalized, none other changed), where the device's pass keeps the bytes its draws do
/// not write. Announced at every draw, an indirect command buffer's executed commands'
/// too, naming every such attachment of the pass. Not where `DriverFact::TileStoreIsMetals`
/// holds (MoltenVK's pass is a Metal pass), nor under
/// [`metal2vulkan::device::TileStorePolicy::Exact`] for an attachment the load pass
/// (`render/unused_bits_load.rs`) rewrites.
/// holds (MoltenVK's pass is a Metal pass).
SharedExponentKept = "shared-exponent-kept", Precision,
"the texels the pass's draws do not write keep their words; Metal's pass normalizes \
a word whose largest mantissa is below 256 (its exponent above 0) in each tile a \
@@ -1489,9 +1470,7 @@ degradations! {
/// A render pass that loads a color attachment of an extended-range, padded 10-bit or
/// bfloat format (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`,
/// `RG10Unorm_X12` and their sRGB twins, `RGB10A2Unorm_sRGB`, `R16Bfloat`, `RG16Bfloat`
/// and `RGBA16Bfloat`), or under
/// [`metal2vulkan::device::TileStorePolicy::Exact`] of a
/// signed normalized format or `RGB9E5Float`, stores it and draws, whose load pass
/// and `RGBA16Bfloat`), stores it and draws, whose load pass
/// (`render/unused_bits_load.rs`) rewrites every 32 x 32 tile of its render area: Metal's
/// pass rewrites only the tiles a draw's primitives reach (on
/// an Apple M4 and an Apple M3 Max, alike), and every tile only where a color
@@ -1505,8 +1484,7 @@ degradations! {
clamped to [384, 894], so an out-of-range raw alpha reads back changed, a padded \
word's low six bits zeroed (an sRGB twin's code moved through Metal's table), a \
bfloat code moved through half (out of half's range to an infinity or zero, a NaN \
to 0x7fc0) and, under the exact tile store, a signed normalized minimum code raised \
and an RGB9E5Float word normalized; the tiles a draw reaches are Metal's";
to 0x7fc0); the tiles a draw reaches are Metal's";
/// A draw in a render pass over a rasterization-rate map of no layers that was made after
/// the device released a map of one or more layers, or reset from one of layers
/// (`rate_mapped_pass.rs`). The draw
@@ -1802,7 +1780,7 @@ degradations! {
/// which the runtime models (`texture/heap_tiled.rs`), and which no shadow of the
/// texture's bytes holds it to (`texture/heap::held_to_metal`): not a multisample texture,
/// whose image lies in memory of its own, nor one whose planes or Metal's tiles fit its
/// bytes, and not one held with a depth twin. The answer is then the larger of the two,
/// bytes. The answer is then the larger of the two,
/// since no image binds at Metal's offsets. Every other such texture answers Metal's
/// numbers and announces nothing here. Not where `optimized-depth-stencil-texture` says
/// why.
@@ -1924,18 +1902,12 @@ degradations! {
/// ANV; a host copy keeps it) or whose depth test compares one otherwise than Metal's (no
/// `DriverFact::DepthTestKeepsDenormals`: every driver measured but MoltenVK on an Apple
/// M4). Metal's texel keeps it, and its depth test compares a positive one above zero and
/// a negative one not below zero. Where the driver stores it and only its depth test
/// differs, a single-sample `Depth32Float` render target's passes test the smallest normal
/// in its place (`texture/signed_depth.rs`): Metal's answer but for a fragment at exactly
/// 2^-126, which passes `Equal` and fails `Greater` against it, where Metal's fails and
/// passes; the payload says so. A draw at a denormal depth stores zero on Metal too, and
/// a negative one not below zero. A draw at a denormal depth stores zero on Metal too, and
/// announces nothing.
DepthDenormals = "depth-denormals", Precision,
"a denormal depth may read, sample and copy out as a zero, or the depth test may \
compare it as zero (a positive one) or below zero (a negative one), where Metal \
keeps it and compares a positive one above zero and a negative one not below it; a \
render target whose passes test the smallest normal in its place differs only for a \
fragment at exactly 2^-126";
keeps it and compares a positive one above zero and a negative one not below it";
/// A depth test that may compare a negative value or a NaN stored in the 32-bit float depth
/// of a render target as it is, or a pass with depth writes that may store such a value
/// with its sign. Metal's depth test compares the fragment's depth with the stored value's
@@ -1943,29 +1915,18 @@ degradations! {
/// fragment at 0.5, and a stored NaN orders above +inf (probe `depthkeep`, the M3 Max under
/// macOS 27.0.1: 270 of 270 outcomes); and a pass that sets a depth/stencil state with
/// depth writes stores each texel no fragment wrote without its sign (probe `depthstore`).
/// Vulkan's compares the stored value as it is, and its pass keeps it. A single-sample
/// `Depth32Float` render target that a write may give such a value, or whose new texture's
/// pattern (a NaN with the sign set) a pass loads before a write covered it
/// (`fresh_unwritten.rs`), renders the passes that load its depth over its magnitude
/// stand-in (`texture/signed_depth.rs`), whose tests and stores are Metal's, and announces
/// only the corners: a pass that writes its depth over the stand-in, whose merge keeps a
/// stored NaN where a draw wrote exactly +inf, its stand-in, over it; a pass that loads it
/// through another image (separate depth and stencil textures' scratch image, a stand-in
/// for custom sample positions); and a write that switches it on while another command
/// buffer is uncommitted, whose passes encoded before it test and store the value as it is.
/// A multisampled or `Depth32Float_Stencil8` target takes no stand-in: its words are
/// stripped of their signs after a pass with depth writes, Metal's stores, and its test,
/// which compares the value as it is, is announced at the write (a blit's copy into its
/// depth, or the pass that loads its new pattern), on a device that keeps such a value
/// there (`VK_EXT_depth_range_unrestricted` enabled, or
/// Vulkan's compares the stored value as it is, and its pass keeps it. Announced at a write
/// that may give a render target's depth such a value (a `replace_region` whose bytes hold
/// one, a blit into its depth, a pass's written NaN clear), or at the pass that loads a new
/// texture's pattern (a NaN with the sign set) before a write covered it
/// (`fresh_unwritten.rs`), on a device that keeps such a value there
/// (`VK_EXT_depth_range_unrestricted` enabled, or
/// `DriverFact::DepthImageKeepsValuesOutsideUnitRange`; elsewhere `restricted-depth-upload`
/// is announced), as is a strip the device does not make. A denormal tested over the
/// smallest normal is `depth-denormals`'. A device whose depth test compares magnitudes as
/// Metal's (`DriverFact::DepthTestComparesMagnitudes`: MoltenVK, whose test and store are
/// the GPU's own Metal ones) renders every target's depth in place, strips a switched-on
/// depth's signs after a pass that sets a state with depth writes but draws under none,
/// which its pass leaves signed, and announces it only for a switch while another command
/// buffer is uncommitted. A render pass's NaN clear depth, which Metal stores as
/// is announced). A device whose depth test compares magnitudes as Metal's
/// (`DriverFact::DepthTestComparesMagnitudes`: MoltenVK, whose test and store are the GPU's
/// own Metal ones) announces it instead at a pass that loads and stores the depth and sets
/// a state with depth writes but draws under none, which its pass leaves signed. A render
/// pass's NaN clear depth, which Metal stores as
/// `0x7fc00000` and tests above every value, is written into the depth before the pass and
/// loaded (`nan_clear.rs`); where the device writes no such word (a memoryless depth, a
/// multisampled one without maintenance8's colour copies or an exact `FragDepth`, a pass
@@ -1974,10 +1935,9 @@ degradations! {
SignedDepthTest = "signed-depth-test", Precision,
"a depth test against the stored value, or the value a pass with depth writes stores, \
can differ from Metal's in the pass or target named: the device compares a negative \
value below zero and a NaN by its own rule and keeps the value's sign, or a pass's \
merge keeps a stored NaN where a draw wrote +inf over it, where Metal compares the \
value's magnitude, orders a NaN above every value, stores the value without its sign \
and stores the draw's; or a NaN clear depth is stored and tested as 1.0, where Metal \
value below zero and a NaN by its own rule and keeps the value's sign, where Metal \
compares the value's magnitude, orders a NaN above every value and stores the value \
without its sign; or a NaN clear depth is stored and tested as 1.0, where Metal \
stores 0x7fc00000";
/// The device's first sparse texture made (`Heap::new_texture` in a sparse heap) on a
/// device whose driver's first sparse resource waits for the work submitted before it on
@@ -3990,11 +3950,15 @@ impl Device {
"no device's resolve averages the codes {:?} holds",
color.target.format
),
None => format!(
"the device's `AVERAGE` resolve of {:?} at {} samples is not \
measured to be Metal's",
color.target.format, color.target.samples
),
None if color.resolve.as_ref().is_some_and(|r| r.twin) => {
"no device's resolve writes a resolve texture in another \
format's encoding"
.to_owned()
}
None => "a fetching pass's sample planes hold its samples as it \
ends, which the resolve reads where the device's would read \
them merged back"
.to_owned(),
},
match copied {
true => {
@@ -4108,10 +4072,6 @@ impl Device {
&& !color_resolve::average_is_metals(self, color.target.samples)
});
if let Some(color) = rounded {
// Under the device's resolve, a format of Metal's rule at its count resolves by that
// rule under the exact one.
let switch = self.compile_device().policy().resolve == ResolvePolicy::Device
&& color_resolve::from_planes(color.target.format, color.target.samples);
self.degrade(Degradation::DeviceRoundedResolve, || {
(
format!(
@@ -4121,15 +4081,8 @@ impl Device {
),
format!(
"Vulkan's `AVERAGE` resolve of {:?} leaves the average's rounding, and \
what a NaN or infinite sample makes of it, to the device{}",
what a NaN or infinite sample makes of it, to the device",
color.target.format,
match switch {
true => {
"; `ResolvePolicy::Exact` resolves it by Metal's rule after the \
pass"
}
false => "",
}
),
)
});
@@ -4646,13 +4599,11 @@ impl Device {
});
} else if matches!(
stand_in.cause,
Cause::Linear | Cause::KeptBytes | Cause::Magnitude | Cause::KeptSamples
Cause::Linear | Cause::KeptBytes | Cause::KeptSamples
) {
// Announced where `linear_attachment.rs` or `kept_bytes.rs` chose the kept image; a
// magnitude stand-in's pass tests and keeps the depth as Metal's
// (`texture/signed_depth.rs`, which announces what it does not). An image that
// keeps an attachment's samples for a resolve after the pass makes the pass
// Metal's, which no notice names (`resolve::keep_samples`).
// Announced where `linear_attachment.rs` or `kept_bytes.rs` chose the kept image.
// An image that keeps an attachment's samples for a resolve after the pass makes
// the pass Metal's, which no notice names (`resolve::keep_samples`).
} else if memoryless
&& (index.is_some_and(fetched) || (index.is_none() && shadow) || !chosen)
{
@@ -47,13 +47,6 @@
//! and the bits draw's `round(depth * 65535)` recovers every one of the 65536 codes
//! (`bind::depth_stencil_copy`'s module docs carry the margin and the exhaustive check).
//!
//! - **The magnitude draws** ([`DepthDraw::magnitude`], [`DepthDraw::magnitude_bits`]): a
//! multisampled depth stored without its signs after a pass with depth writes
//! (`texture/signed_depth.rs`): the `FragDepth` draw of [`DepthStencilCopy::DepthMagnitude`],
//! from a sampled copy of the depth, exact or announced as the draw above is; or the bits draw of
//! [`DepthStencilCopy::MagnitudeBits`], between two `R32_UINT` colour images of the depth's
//! bits that maintenance8's copies move to and from it, exact.
//!
//! - **The depth stand-in's copies** (`depth_stand_in.rs`): a pass's depth samples into an
//! `R32_SFLOAT` stand-in, multisampled or sample planes, by a dispatch of
//! `bind::depth_split_module` ([`DepthSplit`]), and back by the `FragDepth` draw of
@@ -421,10 +414,8 @@ impl Device {
match copy {
DepthStencilCopy::DepthBits
| DepthStencilCopy::StencilBits
| DepthStencilCopy::MagnitudeBits
| DepthStencilCopy::Depth16Bits => true,
DepthStencilCopy::Depth
| DepthStencilCopy::DepthMagnitude
| DepthStencilCopy::Depth16Code
| DepthStencilCopy::StencilPlane { .. }
| DepthStencilCopy::StencilExport { .. }
@@ -914,64 +905,6 @@ impl DepthDraw {
DepthDraw::of_view(device, copy, view, destination, area, feature)
}
/// The draw that writes the depth `source`'s depth aspect holds at each pixel and sample of
/// `area`, without its sign ([`DepthStencilCopy::DepthMagnitude`]), into `destination`'s
/// depth there: a multisampled depth's strip by draws (`texture/signed_depth.rs`).
pub(super) fn magnitude(
device: &Device,
source: &Target,
destination: &Target,
area: DrawArea,
feature: &Feature,
) -> Result<DepthDraw, Error> {
let depth =
|target: &Target| image_aspects(target.format).contains(ImageAspectFlags::DEPTH);
if source.samples != destination.samples || !depth(source) || !depth(destination) {
return Err(internal(
"a depth's magnitude between targets of other samples or without depth",
));
}
let view = aspect_view(source, ImageAspectFlags::DEPTH)?;
DepthDraw::of_view(
device,
DepthStencilCopy::DepthMagnitude,
view,
destination,
area,
feature,
)
}
/// The bits draw that writes the bits `source`, a multisampled `R32_UINT` colour target of a
/// 32-bit float depth's bits, holds at each pixel and sample of `area` without the sign bit
/// ([`DepthStencilCopy::MagnitudeBits`]) into `destination`, another, there: a multisampled
/// depth's strip through colour copies (`texture/signed_depth.rs`).
pub(super) fn magnitude_bits(
device: &Device,
source: &Target,
destination: &Target,
area: DrawArea,
feature: &Feature,
) -> Result<DepthDraw, Error> {
if source.samples != destination.samples
|| source.format != Format::R32_UINT
|| destination.format != Format::R32_UINT
{
return Err(internal(
"a magnitude bits copy between targets of other samples or formats",
));
}
let view = aspect_view(source, ImageAspectFlags::COLOR)?;
DepthDraw::of_view(
device,
DepthStencilCopy::MagnitudeBits,
view,
destination,
area,
feature,
)
}
/// The draw of `copy` reading `view` into `destination` over `area`.
fn of_view(
device: &Device,
@@ -1511,8 +1511,6 @@ impl Device {
&properties.description,
limits.buffer_image_granularity,
linear_color_attachment,
compile.policy().multisample_depth_twin
== metal2vulkan::device::MultisampleDepthTwinPolicy::Exact,
);
// SAFETY: as above; the device is live, made with `enabled` enabled, and `loader_word`
// is its loader word.
+2 -3
View File
@@ -1293,8 +1293,7 @@ pub enum RuntimeGap {
/// the heap's. Memory of its own would lose the heap's aliasing. (A texture whose linear image
/// needs extended usage is checked format by format, not refused with it.) In a heap over host
/// pages, also a texture no linear image over the pages serves and no shadow of the heap's
/// bytes holds, and one with a depth twin. A multisample texture there is made in memory of
/// its own.
/// bytes holds. A multisample texture there is made in memory of its own.
HeapTextureMemory,
/// A visible-function table of more entries than one buffer of the device's
/// `max_buffer_length` holds words for, or than its size word holds: the runtime keeps a
@@ -1745,7 +1744,7 @@ pub enum RuntimeGap {
/// A texture over a no-copy buffer's or heap's bytes (a heap's texture, or a texture over
/// the buffer or over one of the heap's buffers) that no stand-in of zero bytes presents
/// exactly while they are detached (a texture of a multi-planar format, a two-plane YCbCr
/// texture's converted texels, a texture with a depth twin, a multisample texture):
/// texture's converted texels, a multisample texture):
/// `detach_backing` of the bytes, and its making over them while they are detached. Also made
/// over detached bytes: a rotated texture, and one over a surface's two planes. And
/// `detach_backing` while a texture is being made over the bytes, or `rebind_bytes_no_copy` of
@@ -1455,8 +1455,8 @@ impl FeatureRow {
F::ResourceHeaps | F::PlacementHeap => RowState::Exact,
// Sparse textures: a sparse texture of the row's format as `Heap::new_texture` makes it
// (the format's Sparse answer, the device's support), then what every sparse texture
// still lacks (a view of a format whose tile is not its texture's, a depth twin, a cube
// or multisampled texture's tile map), then access counters, which are not scheduled.
// still lacks (a view of a format whose tile is not its texture's, a cube or
// multisampled texture's tile map), then access counters, which are not scheduled.
F::SparseTextures => first([
formats(f, &[FormatRow::RGBA8Unorm], FormatCapability::Sparse),
gap(G::SparseHeaps),
@@ -447,7 +447,7 @@ impl Device {
Some(candidate) => self.if_free(plan, candidate, texture_type)?,
None => plan,
};
let plan = match color_resolve::input_candidate(&plan, self) {
let plan = match color_resolve::input_candidate(&plan) {
Some(candidate) if plan.usage.contains(ImageUsageFlags::TRANSIENT_ATTACHMENT) => {
self.if_made(plan, candidate, texture_type)?
}
@@ -54,9 +54,9 @@
//! depth test compares the stored value's magnitude, which lies above every depth, and a pass with
//! depth writes stores it without its sign (our probe `fd32`, the M3 Max under macOS 27.0.1). A
//! command's read observes nothing of it. A pass that loads its depth where its attachment's level
//! reaches an unwritten texel ([`FreshUnwritten::loads_signed_depth`]) switches the depth on as it
//! is planned, before it decides its magnitude stand-in, as a write that may store such a value
//! does (`texture/signed_depth.rs`), and the texture is no longer noted.
//! reaches an unwritten texel ([`FreshUnwritten::loads_signed_depth`]) announces it as a write that
//! may store such a value does (`signed-depth-test`, where the device's test is not Metal's), and
//! the texture is no longer noted.
use super::device::lock;
use super::error::Error;
@@ -241,7 +241,7 @@ pub(super) enum FreshKind {
NansConverted,
/// Metal's pattern itself, copied into a render target's 32-bit float depth: a NaN with the
/// sign set, which every read gives as Metal's, and which Metal's depth test compares by its
/// magnitude. Only a pass that loads it observes it, and switches the depth on
/// magnitude. Only a pass that loads it observes it, and announces it
/// ([`FreshUnwritten::loads_signed_depth`]); nothing is announced for it here.
SignedDepth,
}
+7 -176
View File
@@ -44,17 +44,6 @@
//! and decodes them as Metal does (the variant; [`holds_srgb_twin`]).
//! - **Exactness.** A texture is held only in an exact representation: 24-bit depth held as
//! 32-bit float depth (`FormatEmulation::DepthWidened`) is refused, naming the format it needs.
//! - **Depth twins**. On a device whose depth images its driver is not measured to keep every
//! `float` in ([`DepthImageFacts`]: without `VK_EXT_depth_range_unrestricted` and the driver's
//! fact that its depth images keep values outside `[0, 1]`, or without its fact that they keep
//! denormals), a `Depth32Float` texture the program only reads or samples (shader-read usage, no
//! render target, not memoryless) is held in an `R32_SFLOAT` image, which keeps any `float` a
//! copy writes, where a depth image may store a value outside `[0, 1]` clamped or a denormal as
//! zero (ANV and RADV do); its depth twin ([`plan_depth_twin`]), a `D32_SFLOAT` image of the same
//! shape, holds the same texels for the comparisons the device makes (the shader makes the
//! others; [`plan_images`]). Where the device lacks either format's sampling or copies
//! the texture keeps its depth image; a texture over a buffer, a shared texture and a texture
//! over the caller's image ([`plan_image`]) have no twin.
//!
//! The device's image limits for the result (`vkGetPhysicalDeviceImageFormatProperties2`) are
//! checked by [`check_image_limits`].
@@ -103,14 +92,11 @@ pub(super) struct ImageFacts<'a> {
/// image of a format whose linear tiling has `LINEAR_COLOR_ATTACHMENT_NV` renders, where
/// every color attachment of the render pass instance is linear (`linear_attachment.rs`).
pub(super) linear_attachments: bool,
/// `MultisampleDepthTwinPolicy::Exact`: a multisampled `Depth32Float` texture the program
/// only reads is held in a colour image ([`holds_multisample_depth_in_colour`]).
pub(super) multisample_depth_twin: bool,
}
/// What a device's driver is measured to keep in a `D32_SFLOAT` image, of the `float`s Metal's
/// `Depth32Float` texel holds (`device/driver_facts.rs`): an unmeasured driver keeps neither, so
/// its read-only textures take the exact path, a colour image.
/// `Depth32Float` texel holds (`device/driver_facts.rs`): an unmeasured driver keeps neither, and
/// a write that may store such a value announces it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct DepthImageFacts {
/// `DriverFact::DepthImageKeepsDenormals`.
@@ -121,8 +107,7 @@ pub(super) struct DepthImageFacts {
/// `DriverFact::DepthTestKeepsDenormals`.
pub(super) test_denormals: bool,
/// `DriverFact::DepthTestComparesMagnitudes`: the depth test is Metal's for every value a
/// `D32_SFLOAT` image holds, so no target renders over a magnitude stand-in
/// (`texture/signed_depth.rs`).
/// `D32_SFLOAT` image holds (`Texture::degrade_signed_depth`).
pub(super) test_magnitudes: bool,
}
@@ -139,28 +124,6 @@ impl DepthImageFacts {
}
impl ImageFacts<'_> {
/// Why a `D32_SFLOAT` image may not hold a `Depth32Float` texel as Metal does: the device lacks
/// `VK_EXT_depth_range_unrestricted` and its driver is not measured to keep a value outside
/// `[0, 1]`, so it may store one clamped, or its driver is not measured to keep a denormal,
/// or both; `None` where it keeps every one.
pub(super) fn depth_loss(&self) -> Option<&'static str> {
match (self.depth_clamps(), self.depth_images.denormals) {
(false, true) => None,
(true, true) => Some(
"the device lacks VK_EXT_depth_range_unrestricted, so a depth image may store a \
value outside [0, 1] clamped",
),
(false, false) => {
Some("the device's driver is not measured to keep a denormal in a depth image")
}
(true, false) => Some(
"the device lacks VK_EXT_depth_range_unrestricted, so a depth image may store a \
value outside [0, 1] clamped, and its driver is not measured to keep a denormal \
there",
),
}
}
/// Why a denormal a write stores in a `D32_SFLOAT` image (`on_host`: a host copy, which keeps
/// it on every driver measured) may answer otherwise than Metal's: the driver stores one a
/// write on the GPU gives it as a zero (no `DriverFact::DepthImageKeepsDenormals`), or its
@@ -515,68 +478,7 @@ pub(super) fn plan_image(
memoryless: bool,
facts: &ImageFacts<'_>,
) -> Result<ImagePlan, ImageRefusal> {
plan_held(layout, usage, memoryless, facts, false).map_err(|r| r.naming(layout.pixel_format))
}
/// The images of a texture of `layout` with Metal `usage` on a device with `facts`, whatever
/// memory holds it (`memoryless` for `MTLStorageModeMemoryless`): [`plan_image`]'s image, and no
/// twin, except for a texture with a depth twin ([`plan_depth_twin`]), whose image holds its texels
/// in `R32_SFLOAT` beside the twin.
pub(super) fn plan_images(
layout: &TextureLayout,
usage: TextureUsage,
memoryless: bool,
facts: &ImageFacts<'_>,
) -> Result<(ImagePlan, Option<ImagePlan>), ImageRefusal> {
let twin = plan_depth_twin(layout, usage, memoryless, facts);
let colour =
twin.is_some() || holds_multisample_depth_in_colour(layout, usage, memoryless, facts);
let plan = plan_held(layout, usage, memoryless, facts, colour)
.map_err(|r| r.naming(layout.pixel_format))?;
Ok((plan, twin))
}
/// Whether a multisampled `Depth32Float` texture of `layout` with Metal `usage` (`memoryless` for
/// `MTLStorageModeMemoryless`) holds its texels in an `R32_SFLOAT` image on a device with `facts`
/// (`MultisampleDepthTwinPolicy::Exact`), as a single-sampled one of it does
/// ([`plan_depth_twin`]): the program only reads or samples it (shader-read usage and no render
/// target, so no pass writes it and no comparison reads it, Metal having none of a multisampled
/// depth texture), the device's depth images may not keep its texels
/// ([`ImageFacts::depth_loss`]), and the device holds a multisampled `R32_SFLOAT` image it
/// samples and copies. `false` under the default, and for every other texture.
///
/// `plan_depth_twin` leaves a multisampled texture out on the reading that one without a render
/// target usage has no writer; `BlitCommandEncoder::fill_texture` is one, and Metal's fill stores
/// the pattern's bytes as given. The texture takes no depth twin beside the colour image: nothing
/// compares it, and no copy writes a multisampled depth image from a colour one.
fn holds_multisample_depth_in_colour(
layout: &TextureLayout,
usage: TextureUsage,
memoryless: bool,
facts: &ImageFacts<'_>,
) -> bool {
let usage = effective_usage(usage);
facts.multisample_depth_twin
&& layout.pixel_format == PixelFormat::Depth32Float
&& layout.samples > 1
&& !memoryless
&& usage.contains(TextureUsage::SHADER_READ)
&& !usage.contains(TextureUsage::RENDER_TARGET)
&& facts.depth_loss().is_some()
&& facts.optimal(Format::R32_SFLOAT).contains(
FormatFeatureFlags2::SAMPLED_IMAGE
| FormatFeatureFlags2::TRANSFER_SRC
| FormatFeatureFlags2::TRANSFER_DST,
)
}
/// Whether `plan`'s texels are in a colour image although its pixel format is a depth format: a
/// `Depth32Float` texture held in `R32_SFLOAT`, which keeps every `float` a copy writes where the
/// device's depth images may not ([`plan_depth_twin`] for a single-sampled one, with the
/// `D32_SFLOAT` twin beside it; [`holds_multisample_depth_in_colour`] for a multisampled one, with
/// no twin). `false` for every other plan, a depth plan among them.
pub(super) fn holds_depth_in_colour(plan: &ImagePlan) -> bool {
plan.pixel_format == PixelFormat::Depth32Float && plan.format == Format::R32_SFLOAT
plan_held(layout, usage, memoryless, facts).map_err(|r| r.naming(layout.pixel_format))
}
/// The flags a 3D image rendered into needs: 2D-array compatible, for the 2D view of its depth
@@ -594,14 +496,12 @@ fn render_3d_flags(profile: &DeviceProfile) -> ImageCreateFlags {
}
}
/// [`plan_image`]'s plan, with `colour_depth` for a texture with a depth twin, sampled as
/// `R32Float` is.
/// [`plan_image`]'s plan.
fn plan_held(
layout: &TextureLayout,
usage: TextureUsage,
memoryless: bool,
facts: &ImageFacts<'_>,
colour_depth: bool,
) -> Result<ImagePlan, ImageRefusal> {
let pf = layout.pixel_format;
let profile = facts.profile;
@@ -717,17 +617,12 @@ fn plan_held(
}
let wants = |bit: TextureUsage| usage.contains(bit);
// A texture with a depth twin holds its texels as `R32Float` would.
let held = match colour_depth {
true => PixelFormat::R32Float,
false => pf,
};
// An 8-bit sRGB format the device cannot sample is sampled through its UNORM twin's view,
// whose raw codes the shader decodes as Metal does ([`holds_srgb_twin`]).
let sampled = vk_format(held, &[FormatUsage::SampledImage].into(), profile)
let sampled = vk_format(pf, &[FormatUsage::SampledImage].into(), profile)
.ok()
.or_else(|| {
srgb_raw_twin(held)
srgb_raw_twin(pf)
.and_then(|twin| vk_format(twin, &[FormatUsage::SampledImage].into(), profile).ok())
});
// Apple's private `BlockWritesOnly` (0x10000) is a usage Metal writes through as through
@@ -1006,70 +901,6 @@ fn plan_held(
})
}
/// The depth twin of a texture of `layout` with Metal `usage` (`memoryless` for
/// `MTLStorageModeMemoryless`) on a device with `facts`: a `D32_SFLOAT` image of the texture's
/// shape that comparisons sample and copies write, beside the `R32_SFLOAT` image the texture holds
/// its texels in. A single-sample `Depth32Float` texture with shader-read usage and no render
/// target, not memoryless, on a device whose depth image may not hold its texels
/// ([`ImageFacts::depth_loss`]: without `VK_EXT_depth_range_unrestricted` enabled or a driver
/// measured to keep a value outside `[0, 1]`, or without a driver measured to keep a denormal),
/// whose `R32_SFLOAT` is sampled and copied and whose
/// `D32_SFLOAT` is sampled and copied into, has one; `None` for every other. A multisampled
/// texture takes no twin: nothing compares it, and no copy writes a multisampled depth image from
/// a colour one ([`holds_multisample_depth_in_colour`] holds its texels in colour alone).
fn plan_depth_twin(
layout: &TextureLayout,
usage: TextureUsage,
memoryless: bool,
facts: &ImageFacts<'_>,
) -> Option<ImagePlan> {
let pf = layout.pixel_format;
let usage = effective_usage(usage);
let copies = FormatFeatureFlags2::TRANSFER_SRC | FormatFeatureFlags2::TRANSFER_DST;
let holds = pf == PixelFormat::Depth32Float
&& layout.samples == 1
&& !memoryless
&& usage.contains(TextureUsage::SHADER_READ)
&& !usage.contains(TextureUsage::RENDER_TARGET)
&& facts.depth_loss().is_some()
&& facts
.optimal(Format::R32_SFLOAT)
.contains(FormatFeatureFlags2::SAMPLED_IMAGE | copies)
&& facts
.optimal(Format::D32_SFLOAT)
.contains(FormatFeatureFlags2::SAMPLED_IMAGE | FormatFeatureFlags2::TRANSFER_DST);
if !holds {
return None;
}
let mapping = vk_format(pf, &[FormatUsage::SampledImage].into(), facts.profile).ok()?;
let samples = sample_count(layout.samples)?;
let (image_type, mut flags) = image_type(layout.texture_type)?;
if cube_compatible(layout) {
flags |= ImageCreateFlags::CUBE_COMPATIBLE;
}
let mut usage_flags = ImageUsageFlags::SAMPLED | ImageUsageFlags::TRANSFER_DST;
if facts
.optimal(mapping.format)
.contains(FormatFeatureFlags2::TRANSFER_SRC)
{
usage_flags |= ImageUsageFlags::TRANSFER_SRC;
}
(mapping.format == Format::D32_SFLOAT).then(|| ImagePlan {
pixel_format: pf,
flags,
image_type,
format: mapping.format,
extent: layout.extent,
levels: layout.levels,
layers: layout.layers,
samples,
usage: usage_flags,
view_formats: Vec::new(),
mapping,
unavailable: TextureUsage::empty(),
})
}
/// The formats of the views the runtime makes of a texture of `pf` for the Vulkan usages in
/// `usage` on `profile`: its sampled representation, its storage view (the alias, or the direct
/// format), and its attachment format (the direct format, or the view of its word where the device
+1 -3
View File
@@ -101,9 +101,7 @@ impl Texture {
/// where the texels are a buffer's bytes the runtime copies into and out of an image of its
/// own (a texture buffer, a texture over a no-copy buffer's host pages, or a texture over
/// another buffer that does not alias it), or another image's texels it so copies (a view of
/// another component layout on a device whose views reinterpret none). A texture with a depth
/// twin gives its `R32_SFLOAT` image, which holds its texels; its comparisons read the twin,
/// which a write into the image does not reach.
/// another component layout on a device whose views reinterpret none).
///
/// A texture over a buffer's bytes whose image aliases them gives a linear image of
/// `VK_IMAGE_TILING_LINEAR`, bound to the buffer's memory, the runtime's own: such a texture's
+5 -5
View File
@@ -76,11 +76,11 @@
//! filled with it and copied in, a multisampled one by an `R32_UINT` image cleared to it (an
//! integer clear converts nothing) and copied in by maintenance8's depth/colour copy, or, where
//! those copies are missing or run wrong, drawn in by the `FragDepth` draw where the driver's
//! fragment depth stores every value unchanged (`depth_copy::drawn`). The write switches the
//! texture on (`texture/signed_depth.rs`): the pass's depth test then compares the NaN as Metal's
//! does, over its magnitude stand-in or by a device whose test is Metal's own, and announces it
//! otherwise (`signed-depth-test`). Written before anything the pass copies its depth out with
//! (separate depth and stencil textures' scratch, a stand-in), which loads the word with the rest.
//! fragment depth stores every value unchanged (`depth_copy::drawn`). The pass's depth test then
//! compares the NaN as the device's does: Metal's where its test is Metal's own, and elsewhere as
//! it is, announced (`signed-depth-test`). Written before anything the pass copies its depth out
//! with (separate depth and stencil textures' scratch, a stand-in), which loads the word with the
//! rest.
//! Where it cannot be written, the pass clears to 1.0, the value Metal's test orders a NaN
//! nearest, announced (`signed-depth-test`; on a device that may clamp a depth outside `[0, 1]`,
//! `restricted-depth-upload`): a memoryless depth; a pass that does not store it on a device that
@@ -83,10 +83,6 @@ pub(super) enum OwnedModule {
/// `bind::shadow_merge_module`: a shadowed texture's writes merged into its buffer's bytes
/// after a command that also wrote them another way (`shadow_merge.rs`).
ShadowMerge,
/// `bind::depth_magnitude_module`: a 32-bit float depth's magnitude stand-in, written before a
/// pass that renders over it, and the pass's words merged back into the depth after it
/// (`signed_depth.rs`).
DepthMagnitude,
/// `bind::shadow_copy_back_module` of one view of a texel (`ShadowTexelView`): a shadowed
/// texture's texels stored back into its buffer's rows by a dispatch, where the device copies
/// back faster so (`shadow_copy_back.rs`). Its shadow's unsigned-integer view is its sampled
@@ -162,8 +158,7 @@ pub(super) enum OwnedModule {
/// surface's two planes (`ycbcr.rs`), its write shadow bound as a storage image.
YCbCrWrite,
/// `bind::unused_bits_module` of one format held as one kind of words: an extended-range,
/// padded 10-bit or bfloat texture's words (or, under `TileStorePolicy::Exact`, a signed
/// normalized or `RGB9E5Float` one's) in the tiles a mask names rewritten as Metal's tile
/// padded 10-bit or bfloat texture's words in the tiles a mask names rewritten as Metal's tile
/// store leaves them, before a pass that loads it and draws (`render/unused_bits_load.rs`).
UnusedBits(PixelFormat, TexelWords),
/// `bind::tiled_texels_module`: a heap texture's elements moved between its image's tight
@@ -325,12 +320,6 @@ impl OwnedModule {
let push_bytes = metal2vulkan::bind::ShadowMergeModule::PUSH_BYTES;
Ok((module.spirv.to_vec(), 3, push_bytes))
}
OwnedModule::DepthMagnitude => {
let module = metal2vulkan::bind::depth_magnitude_module(device.compile_device())
.map_err(Error::Compile)?;
let push_bytes = metal2vulkan::bind::DepthMagnitudeModule::PUSH_BYTES;
Ok((module.spirv.to_vec(), 2, push_bytes))
}
OwnedModule::ShadowCopyBack(view) => {
let module =
metal2vulkan::bind::shadow_copy_back_module(device.compile_device(), view)
@@ -561,7 +550,6 @@ pub(super) struct OwnedKernels {
draw_merge_starts: Option<OwnedKernel>,
flat_dispatch: Option<OwnedKernel>,
shadow_merge: Option<OwnedKernel>,
depth_magnitude: Option<OwnedKernel>,
shadow_copy_backs: HashMap<ShadowTexelView, OwnedKernel>,
shadow_merge_images: HashMap<ShadowMergeRead, OwnedKernel>,
shadow_merge_kept_images: HashMap<ShadowTexelView, OwnedKernel>,
@@ -613,7 +601,6 @@ impl OwnedKernels {
self.draw_merge_starts,
self.flat_dispatch,
self.shadow_merge,
self.depth_magnitude,
self.mesh_scan,
self.mesh_object_arguments,
self.mesh_arguments_mesh,
@@ -755,7 +742,6 @@ impl OwnedKernels {
}
OwnedModule::FlatDispatch => &mut self.flat_dispatch,
OwnedModule::ShadowMerge => &mut self.shadow_merge,
OwnedModule::DepthMagnitude => &mut self.depth_magnitude,
OwnedModule::ShadowCopyBack(_)
| OwnedModule::ShadowMergeImage(_)
| OwnedModule::ShadowMergeKeptImage(_)
+42 -99
View File
@@ -94,8 +94,9 @@
//! Metal's 1 or 0 for `Boolean` ones.
//! - **Resolves** (`resolve.rs`) happen at the end of the pass's subpass; a late store action
//! must resolve exactly where the attachment has a resolve texture (measured). A color resolve
//! whose device's average is not Metal's is drawn after the pass instead, by the exact resolve
//! (`color_resolve.rs`). A resolve into
//! no device's average writes (an extended-range attachment's, one into its format's sRGB
//! twin) is drawn after the pass instead, by the crate-owned resolve (`color_resolve.rs`). A
//! resolve into
//! a texture whose image is no attachment goes through a scratch image, copied after the pass.
//! The encoder may replace an attachment's resolve target until the pass ends
//! (`render/late_resolve.rs`).
@@ -335,7 +336,6 @@ use super::shadow_stencil::ShadowStencil;
use super::sparse::emulated::Scrub;
use super::tessellation::{FactorBuffer, Factors};
use super::texture::held_depth;
use super::texture::signed_depth::{self, MagnitudeCopies, SignStrip};
use super::texture::Texture;
use super::tracker::{self, Access, Barrier, GeometryWrites, IndirectReads, UnorderedWrites, Use};
use super::used_resources::EncoderKind;
@@ -1496,14 +1496,13 @@ pub(crate) struct RenderLowering {
/// commands or a tile dispatch: a `Clear` load clears over whole tiles (`clear_reach.rs`).
called: bool,
/// A depth/stencil state with depth writes was set in the pass, or an indirect command
/// buffer's commands that set their own ran in it: a depth it renders over its
/// magnitude stand-in is merged back after it (`texture/signed_depth.rs`).
/// buffer's commands that set their own ran in it.
depth_writes: bool,
/// A draw that records a command (not one of no vertices, indices or instances; an indirect
/// one whatever its arguments), or such an execution, ran in the pass under a state with
/// depth writes, which hands the device's pass that state: where it did not though
/// `depth_writes` holds, a depth whose device's pass is Metal's own is stripped of its signs
/// after it (`texture/signed_depth.rs`, `SignStrip`).
/// `depth_writes` holds, a depth whose device's pass is Metal's own keeps its signs, where
/// Metal's pass stores its words without them (`Texture::degrade_kept_signs`).
drew_depth_writes: bool,
/// The pass draws: a draw call drew vertices, indices, patches or meshes through a pipeline
/// that rasterizes, an execution of render commands or a tile dispatch ran: its draws reach
@@ -3084,7 +3083,7 @@ impl RenderLowering {
self.core
.check_device("set_depth_stencil_state", state.device())?;
}
// One boolean: a depth over its magnitude stand-in is merged back where it is set.
// One boolean: a pass that sets one but draws under none keeps a depth's signs.
self.depth_writes |= state.is_some_and(|s| s.descriptor().depth_write_enabled);
self.state.set_depth_stencil(state);
Ok(())
@@ -4097,9 +4096,15 @@ impl RenderLowering {
// A pass that changes no texel records nothing, but holds its attachments until its
// command buffer completes (`render/untouched.rs`); not the first group of a pass of
// several color groups, whose later groups' colors its layout leaves out.
if grouped.is_none()
&& untouched::changes_nothing(&layout, (called, depth_writes), &instances)
{
// A pass that loads and stores its depth and set a state with depth writes, drawing
// under none, keeps its words' signs on a device whose pass is Metal's own, where Metal
// stores them without.
if depth_writes && !drew_depth_writes {
if let Some(own) = kept_signs(&layout) {
own.texture.degrade_kept_signs();
}
}
if grouped.is_none() && untouched::changes_nothing(&layout, called, &instances) {
core.device().shared().counts.untouched_pass_skipped();
let targets: Vec<Texture> = (layout.colors.iter().flatten())
.map(|color| color.target.texture.clone())
@@ -4550,9 +4555,7 @@ impl RenderLowering {
// And copied in where its `DontCare` load is bounded to the draws' tiles, as a color's.
let depth_stencil_copies = |back: bool| {
let ds = layout.depth_stencil.as_ref()?;
// A magnitude stand-in's copies are its own (`texture/signed_depth.rs`).
let own =
(ds.stand_in.as_ref()).filter(|s| s.copies() && s.cause != Cause::Magnitude)?;
let own = (ds.stand_in.as_ref()).filter(|s| s.copies())?;
let stores = |store: StoreAction| {
matches!(
store,
@@ -4679,75 +4682,6 @@ impl RenderLowering {
scratch(&|index, c| stored(c) && !merged.iter().any(|&(at, _)| at == index));
copied_back.extend(depth_stencil_copies(true));
let stand_ins_out = StandInCopies::plan_aspects(&copied_back, false)?;
// A depth rendered over its magnitude stand-in: the stand-in written from it before the
// pass, and the pass's words merged back after it where the pass stores the depth and a
// state with depth writes was set in it or commands that set their own ran
// (`depth_writes`, `texture/signed_depth.rs`).
let magnitude = match layout.depth_stencil.as_ref() {
Some(DepthStencilTarget {
target,
depth: Some(depth),
stand_in: Some(own),
..
}) if own.cause == Cause::Magnitude => {
let stored = matches!(
depth.store,
StoreAction::Store | StoreAction::CustomSampleDepthStore
);
let back = stored && depth_writes;
let copies = MagnitudeCopies::plan(&device, target, &own.own, layout.extent, back)?;
device.shared().counts.magnitude_stand_in_pass(back);
if back {
signed_depth::degrade_write_back(&device, &own.own);
}
Some(copies)
}
_ => None,
};
// A switched-on depth rendered in place, or through another image copied back into it
// (separate depth and stencil textures' scratch, an attachment stand-in), not over its
// magnitude stand-in: where the pass loads and stores it and a state with depth writes
// was set in it, the device's pass leaves the words it did not write signed (on a device
// whose pass is Metal's own, where no draw ran under one), which Metal stores without
// their signs; they are stripped after the pass and its copies back
// (`texture/signed_depth.rs`). A strip the device does not make is announced.
let strip = match layout.depth_stencil.as_ref() {
Some(
ds @ DepthStencilTarget {
depth: Some(depth), ..
},
) if depth_writes
&& depth.load == LoadAction::Load
&& matches!(
depth.store,
StoreAction::Store
| StoreAction::StoreAndMultisampleResolve
| StoreAction::CustomSampleDepthStore
) =>
{
let own = match (&ds.separate, &ds.stand_in) {
(Some(separate), _) => separate.depth.as_ref(),
(None, Some(stand_in)) => (stand_in.cause != Cause::Magnitude
&& stand_in.copies())
.then_some(&stand_in.own),
(None, None) => Some(&ds.target),
};
match own.filter(|own| own.texture.strips_signs(drew_depth_writes)) {
Some(own) => match SignStrip::plan(core.command_buffer(), own, layout.extent) {
Ok(strip) => {
device.shared().counts.sign_strip();
Some(strip)
}
Err(error) => {
signed_depth::degrade_strip(&device, own, &error);
None
}
},
None => None,
}
}
_ => None,
};
// A clear holding a `half` or small-float NaN: written before the pass as Metal writes
// it, through a scratch image of an integer format, and loaded in the pass
// (`nan_clear.rs`). After the stand-ins' copies, which keep the attachment's own load.
@@ -5126,9 +5060,6 @@ impl RenderLowering {
if let Some(copies) = stand_ins_in {
copies.record(&mut core);
}
if let Some(copies) = &magnitude {
copies.record_in(&mut core);
}
// What the merged colors hold once copied in, before any step writes them.
for (_, merge) in &merged {
merge.record_keep(&mut core);
@@ -5167,7 +5098,7 @@ impl RenderLowering {
// encoder named it so far (its draws' bindings, the steps recorded ahead of the pass), no
// step of the pass uses it but as the attachment, and no step after the instances reads or
// writes it: no depth resolve drawn after them, in a pass of its own or in a resolving
// instance, no sign strip, no shader-side depth or stencil test, and no execution of
// instance, no shader-side depth or stencil test, and no execution of
// render commands or draw whose pipeline is being made, whose pass records later.
// The tile dispatches' pipelines, where every making finished made: a pass of one still
// being made, or failed, records later too (`render/pending_tile.rs`).
@@ -5186,7 +5117,6 @@ impl RenderLowering {
&& !resolve_after
&& later_resolves.is_empty()
&& picked_resolve.is_none()
&& strip.is_none()
&& depth_stand_in.is_none()
&& shadow.is_none()
&& !core.named_keys().contains(&key)
@@ -5554,14 +5484,6 @@ impl RenderLowering {
if let Some(copies) = stand_ins_out {
copies.record(&mut core);
}
if let Some(copies) = magnitude {
copies.record_back(&mut core);
core.retain(copies);
}
if let Some(strip) = strip {
strip.record(&mut core);
core.retain(strip);
}
for (_, merge) in &merged {
merge.record_merge(&mut core);
}
@@ -6843,7 +6765,7 @@ impl RenderLowering {
/// draw reaches back through the channels' values, so a minimum code (-128, or -32768) the
/// draws do not write is stored as the code above it, where such an attachment keeps it. Not
/// on a driver whose pass stores it so too (`DriverFact::TileStoreIsMetals`: MoltenVK's pass
/// is a Metal pass), nor for an attachment the load pass rewrites (`TileStorePolicy::Exact`).
/// is a Metal pass).
fn degrade_snorm_minimum(device: &Device, kept: &[String]) {
if kept.is_empty() {
return;
@@ -6865,8 +6787,7 @@ impl RenderLowering {
/// Metal's pass, once it draws, writes each tile a draw reaches back through its texels'
/// values, so a word the draws do not write whose largest mantissa is below 256 under an
/// exponent above 0 is stored normalized, where such an attachment keeps it. Not on a driver
/// whose pass stores it so too (`DriverFact::TileStoreIsMetals`), nor for an attachment the
/// load pass rewrites (`TileStorePolicy::Exact`).
/// whose pass stores it so too (`DriverFact::TileStoreIsMetals`).
fn degrade_shared_exponent(device: &Device, kept: &[String]) {
if kept.is_empty() {
return;
@@ -11891,6 +11812,28 @@ pub(super) fn reads_handles(plan: &metal2vulkan::bind::BindingPlan) -> bool {
}
/// An `Invalid` draw problem of `call`.
/// The texture a pass of `layout` loads and stores its depth into, where it does: the separate
/// depth texture, the texture of a stand-in its copies serve, or the attachment's own; `None` for
/// a pass that does not load and store a depth (`Texture::degrade_kept_signs`).
fn kept_signs(layout: &PassLayout) -> Option<&Target> {
let ds = layout.depth_stencil.as_ref()?;
let depth = ds.depth.as_ref()?;
let stores = matches!(
depth.store,
StoreAction::Store
| StoreAction::StoreAndMultisampleResolve
| StoreAction::CustomSampleDepthStore
);
if depth.load != LoadAction::Load || !stores {
return None;
}
match (&ds.separate, &ds.stand_in) {
(Some(separate), _) => separate.depth.as_ref(),
(None, Some(stand_in)) => stand_in.copies().then_some(&stand_in.own),
(None, None) => Some(&ds.target),
}
}
fn draw_problem(call: &'static str, problem: DrawProblem) -> Error {
invalid(call, Problem::Draw(problem))
}
@@ -553,8 +553,7 @@ impl RenderLowering {
self.degrade_extended_range_execution();
// Its commands write the extended-range colors' codes alone: the shadows end.
self.end_extended_shadows();
// Commands that set their own depth/stencil states may write the depth: a depth over its
// magnitude stand-in is merged back (`texture/signed_depth.rs`).
// Commands that set their own depth/stencil states may write the depth.
self.depth_writes |= !icb.descriptor().inherit_depth_stencil_state;
// And its commands hand the device's pass the states they draw under: their own, which
// may write the depth, or the encoder's.
@@ -1,14 +1,14 @@
//! A render pass that changes no texel records nothing.
//!
//! - **Metal** keeps every attachment's texels in a pass without a draw call that clears nothing
//! and sets no depth/stencil state with depth writes: a `Load` keeps them, a `DontCare` load of
//! - **Metal** keeps every attachment's texels in a pass without a draw call that clears nothing:
//! a `Load` keeps them, a `DontCare` load of
//! an attachment the pass stores keeps them in a pass without a draw (`clear_reach.rs`, on the M3
//! Max and an M4), and a store writes back only what the pass's tiles hold, which no draw
//! touched. A `DontCare` store stores nothing, and resolves are the
//! only other writes a pass makes. A pass that loads and stores a depth and sets a state with
//! depth writes stores its words without their signs, draw or none (probe `depthstore`,
//! `texture/signed_depth.rs`), and a `Clear` load of a NaN depth stores Metal's NaN word
//! (`nan_clear.rs`).
//! only other writes a pass makes. A `Clear` load of a NaN depth stores Metal's NaN word
//! (`nan_clear.rs`). (A pass that loads and stores a depth and sets a state with depth writes
//! stores Metal's words without their signs, draw or none, probe `depthstore`; the device's
//! pass keeps them, announced `signed-depth-test` where the depth may hold a sign.)
//! - **The runtime** ends such a pass without recording it ([`changes_nothing`]): no render pass
//! instance, load or store, no copy of a shadow or a stand-in, and none of the tracker's uses of
//! its attachments, so nothing waits on it. A render pass instance would load and store every
@@ -22,9 +22,8 @@
//! recorded into, and every attachment (but the runtime's hidden depth) loads with `Load` or
//! `DontCare` and stores with `Store` or `DontCare` (an unknown store action stores nothing, as
//! Metal's `DontCare`), resolving into nothing. A `Clear` load clears in a pass without a draw
//! call, and a resolve writes its texture: such a pass records as before. So does one that set
//! a depth/stencil state with depth writes (`depth_writes`: its depth's signs stripped after it,
//! or its magnitude stand-in merged back), one whose depth's `Clear` held a NaN (loaded in the
//! call, and a resolve writes its texture: such a pass records as before. So does one whose
//! depth's `Clear` held a NaN (loaded in the
//! pass, Metal's word written before it, `AspectTarget::written_nan`), and one that
//! loads separate depth and stencil textures with `DontCare` (`depth_stencil_scratch.rs`),
//! whose answer in a pass without a draw is not measured (`clear_reach.rs` gives none).
@@ -36,15 +35,10 @@ use crate::render_pass::PassLayout;
use crate::render_values::{LoadAction, StoreAction};
/// Whether a pass of `layout` changes no texel, nor anything else a later command sees (the
/// module docs): `called` false (no draw call), `depth_writes` false (no depth/stencil state with
/// depth writes set in it), `instances` one that nothing recorded into, and its attachments' load
/// and store actions as settled (an unknown store made `DontCare`) keeping every texel, no depth
/// written with a NaN before it.
pub(super) fn changes_nothing(
layout: &PassLayout,
(called, depth_writes): (bool, bool),
instances: &[Instance],
) -> bool {
/// module docs): `called` false (no draw call), `instances` one that nothing recorded into, and its
/// attachments' load and store actions as settled (an unknown store made `DontCare`) keeping every
/// texel, no depth written with a NaN before it.
pub(super) fn changes_nothing(layout: &PassLayout, called: bool, instances: &[Instance]) -> bool {
let keeps = |load: LoadAction, store: StoreAction| {
matches!(load, LoadAction::Load | LoadAction::DontCare)
&& matches!(store, StoreAction::Store | StoreAction::DontCare)
@@ -72,5 +66,5 @@ pub(super) fn changes_nothing(
keeps(aspect.load, aspect.store) && measured(aspect.load) && !aspect.written_nan
})
});
!called && !depth_writes && unrecorded && layout.visibility.is_none() && colors && depth_stencil
!called && unrecorded && layout.visibility.is_none() && colors && depth_stencil
}
@@ -1,5 +1,4 @@
//! The load pass of an extended-range, padded 10-bit or bfloat color attachment, and under the
//! exact tile store of a signed normalized or `RGB9E5Float` one.
//! The load pass of an extended-range, padded 10-bit or bfloat color attachment.
//!
//! - **Metal's answer** (on an Apple M4 under macOS 27.0.1 and on the consumer's Apple M3 Max under
//! macOS 26.7, alike; on both). An Apple GPU stores a render pass's attachments a 32 x 32 tile at
@@ -54,17 +53,14 @@
//! tiles there no draw reaches are rewritten here where Metal keeps them; but where capture
//! replay found the tiles the draws' primitives reach (`render/capture.rs`, Metal's, announced by
//! the command buffer where a primitive's reach was not measured).
//! - **The exact tile store** (`TileStorePolicy::Exact`). The same pass, once it draws, writes a
//! single-sampled signed normalized or `RGB9E5Float` attachment's tiles back through their
//! - **A signed normalized or `RGB9E5Float` attachment** keeps the device's load and store. The
//! same pass, once it draws, writes a single-sampled such attachment's tiles back through their
//! values (an Apple M3 Max under macOS 27.0.1): a channel's minimum code (-128, or -32768) is
//! stored as the code above it, and a word whose largest mantissa is below 256 under an exponent
//! above 0 normalized (`bind::unused_bits_module` of the format). Under the exact tile store the
//! load pass takes such an attachment as it takes an extended-range one, where the driver's pass
//! does not store them so already (`DriverFact::TileStoreIsMetals`: MoltenVK's pass is a Metal
//! pass); under the default, `TileStorePolicy::Device`, it leaves them to the device's load and
//! store, and a draw announces `snorm-minimum-kept` or `shared-exponent-kept`
//! ([`snorm_minimum_kept`], [`shared_exponent_kept`]), as it does for one the load pass does not
//! take.
//! above 0 normalized. The device's pass keeps such a code or word, and a draw announces
//! `snorm-minimum-kept` or `shared-exponent-kept` ([`snorm_minimum_kept`],
//! [`shared_exponent_kept`]), but on a driver whose pass stores them as Metal's
//! (`DriverFact::TileStoreIsMetals`: MoltenVK's pass is a Metal pass).
//! - **Not here** (`degrade_unused_bits` announces `extended-range-bits-kept` at each draw): a
//! multisampled attachment (no copy reaches its samples), a texture held as a shadow of another
//! image or of a heap's bytes, a sparse one, and one whose image the device does not copy both
@@ -89,7 +85,7 @@ use crate::tracker::{Access, Barrier, Use, UseRange};
use crate::values::ResourceOptions;
use ash::vk;
use metal2vulkan::bind::{TexelWords, UnusedBitsModule};
use metal2vulkan::device::{DriverFact, TileStorePolicy};
use metal2vulkan::device::DriverFact;
use metal2vulkan::metal::format::ExtendedRange;
use metal2vulkan::metal::{PixelFormat, TextureType};
use metal2vulkan::vk::{ImageType, ImageUsageFlags};
@@ -262,19 +258,9 @@ fn own(color: &ColorTarget) -> &Target {
}
/// Whether the load pass rewrites a texture of `texture`'s format: an extended-range, padded or
/// bfloat one's always, and a signed normalized ([`SNORM_MINIMUM`]) or `RGB9E5Float` one's under
/// the exact tile store (`TileStorePolicy::Exact`) on a driver whose store is not Metal's already
/// (`DriverFact::TileStoreIsMetals`).
/// bfloat one's.
fn rewrites(texture: &Texture) -> bool {
let format = texture.pixel_format();
if ExtendedRange::of(format).is_some() {
return true;
}
let device = texture.device();
let stored = SNORM_MINIMUM.contains(&format) || format == PixelFormat::RGB9E5Float;
stored
&& device.compile_device().policy().tile_store == TileStorePolicy::Exact
&& !metals_store(device)
ExtendedRange::of(texture.pixel_format()).is_some()
}
/// Whether `device`'s render pass stores a signed normalized minimum code and an `RGB9E5Float`
@@ -388,41 +374,35 @@ const SNORM_MINIMUM: [PixelFormat; 6] = [
];
/// Whether `color` is a single-sampled attachment of a signed normalized format
/// ([`SNORM_MINIMUM`]), loaded and not discarded at the store, where the load pass does not take
/// it: Metal's pass, once it draws, writes each tile a draw reaches back through the channels'
/// values, so a minimum code (-128, or -32768) is stored as the code above it, where the device's
/// pass keeps the bytes its draws do not write (`degrade_snorm_minimum`, which reads
/// `DriverFact::TileStoreIsMetals`: a driver whose pass stores them as Metal's). The load pass
/// rewrites them under the exact tile store (`TileStorePolicy::Exact`) where it takes the
/// attachment.
/// ([`SNORM_MINIMUM`]), loaded and not discarded at the store: Metal's pass, once it draws, writes
/// each tile a draw reaches back through the channels' values, so a minimum code (-128, or -32768)
/// is stored as the code above it, where the device's pass keeps the bytes its draws do not write
/// (`degrade_snorm_minimum`, which reads `DriverFact::TileStoreIsMetals`: a driver whose pass
/// stores them as Metal's).
pub(super) fn snorm_minimum_kept(color: &ColorTarget) -> bool {
let target = own(color);
let discarded = color.store == StoreAction::DontCare && !color.late_store;
SNORM_MINIMUM.contains(&target.texture.pixel_format())
&& target.samples == 1
&& color.load == LoadAction::Load
&& !color.memoryless
&& !discarded
&& takes(color, true).is_none()
kept_through_store(color, |format| SNORM_MINIMUM.contains(&format))
}
/// Whether `color` is a single-sampled `RGB9E5Float` attachment, loaded and not discarded at the
/// store, where the load pass does not take it: Metal's pass, once it draws, writes each tile a
/// draw reaches back through its texels' values, so a word whose largest mantissa is below 256
/// under an exponent above 0 (one no Metal write leaves) is stored normalized, its mantissas
/// shifted up as its exponent steps down, where the device's pass keeps the bytes its draws do
/// not write (`degrade_shared_exponent`, which reads `DriverFact::TileStoreIsMetals`). The load
/// pass rewrites them under the exact tile store (`TileStorePolicy::Exact`) where it takes the
/// attachment.
/// store: Metal's pass, once it draws, writes each tile a draw reaches back through its texels'
/// values, so a word whose largest mantissa is below 256 under an exponent above 0 (one no Metal
/// write leaves) is stored normalized, its mantissas shifted up as its exponent steps down, where
/// the device's pass keeps the bytes its draws do not write (`degrade_shared_exponent`, which reads
/// `DriverFact::TileStoreIsMetals`).
pub(super) fn shared_exponent_kept(color: &ColorTarget) -> bool {
kept_through_store(color, |format| format == PixelFormat::RGB9E5Float)
}
/// Whether `color` is a single-sampled attachment of a format `of` takes, loaded and not
/// discarded at the store.
fn kept_through_store(color: &ColorTarget, of: impl Fn(PixelFormat) -> bool) -> bool {
let target = own(color);
let discarded = color.store == StoreAction::DontCare && !color.late_store;
target.texture.pixel_format() == PixelFormat::RGB9E5Float
of(target.texture.pixel_format())
&& target.samples == 1
&& color.load == LoadAction::Load
&& !color.memoryless
&& !discarded
&& takes(color, true).is_none()
}
/// The color attachments of a pass's layout that each of a draw's kept-attachment notices names, as
@@ -431,7 +411,7 @@ pub(super) fn shared_exponent_kept(color: &ColorTarget) -> bool {
/// ([`metals_store`]), the signed normalized ones ([`snorm_minimum_kept`],
/// `degrade_snorm_minimum`) and the `RGB9E5Float` ones ([`shared_exponent_kept`],
/// `degrade_shared_exponent`). They read the layout's colors, their textures' formats, samples,
/// shadows and image plans, and the device's tile store policy and driver facts; all but the
/// shadows and image plans, and the device's driver facts; all but the
/// layout are fixed at creation, so an encoder decides them once for each layout it records
/// under.
#[derive(Debug, Default, PartialEq)]
@@ -525,10 +505,8 @@ pub(super) fn record(
rewrites only the tiles a draw's primitives reach (or every tile where a \
color attachment is cleared): in tiles no draw reaches the unused bits are \
made canonical and BGRA10_XR alpha codes clamped to [384, 894], a padded \
word's low six bits zeroed (an _sRGB twin's code through Metal's table), a \
bfloat code moved through half and, under the exact tile store, a signed \
normalized minimum code raised and an RGB9E5Float word normalized, where \
Metal keeps those texels' bytes"
word's low six bits zeroed (an _sRGB twin's code through Metal's table) and \
a bfloat code moved through half, where Metal keeps those texels' bytes"
.to_owned(),
)
});
+13 -51
View File
@@ -18,13 +18,13 @@
//! `Depth32Float`, `Depth16Unorm`, `Stencil8` and `Depth32Float_Stencil8` of shader-read usage
//! alone cleared, loaded, drawn and stored as a render target is, and left as they were under a
//! `DontCare` store): one texture through a stand-in, separate depth and stencil textures through
//! their combined scratch image (`depth_stencil_scratch.rs`). A memoryless one, one whose format
//! the device does not copy both ways, and a `Depth32Float` texture held in a color image beside
//! its depth twin are not built (`NotImplemented(Render)`). Every attachment has one sample
//! count, which the pipelines drawn must have. Metal renders into the smallest attachment's
//! extent, further limited by a nonzero `renderTargetWidth` and `renderTargetHeight` (measured:
//! an 8x8 color and a 4x4 depth attachment, or an 8x8 one under a 4x4 target size, render 4x4). A
//! pass without attachments needs both target sizes, and rasterizes `defaultRasterSampleCount`
//! their combined scratch image (`depth_stencil_scratch.rs`). A memoryless one, and one whose
//! format the device does not copy both ways, are not built (`NotImplemented(Render)`). Every
//! attachment has one sample count, which the pipelines drawn must have. Metal renders into the
//! smallest attachment's extent, further limited by a nonzero `renderTargetWidth` and
//! `renderTargetHeight` (measured: an 8x8 color and a 4x4 depth attachment, or an 8x8 one under a
//! 4x4 target size, render 4x4). A pass without attachments needs both target sizes, and
//! rasterizes `defaultRasterSampleCount`
//! samples (0, the default, is `Invalid`, as Metal ends the process there). Past 16384 on a side
//! Metal makes its encoder and fails the command buffer from the pass on (measured): the encoder
//! records into the device's largest framebuffer within it, and the command buffer's commit runs
@@ -114,7 +114,7 @@ use super::render_values::{
use super::resolve::{self, DepthStencilResolve, Resolve, Wanted};
use super::sample_planes::Planes;
use super::sample_positions::{self, Sixteenths};
use super::texture::{signed_depth, Texture};
use super::texture::Texture;
use super::tile_pass::{self, TilePass, TileRefusal};
use super::view_plan::ViewRecord;
use super::Device;
@@ -860,13 +860,6 @@ pub(super) fn degrade_depth_clear(device: &Device, layout: &PassLayout) {
}
let facts = (device.shared().textures).facts(device.compile_device().profile());
if let Some(loss) = facts.denormal_loss(false) {
// Where the device stores it, a later pass that loads the depth tests it over the
// smallest normal (`texture/signed_depth.rs`); this one tests it as the device does.
if facts.depth_images.denormals {
let own = ds.stand_in.as_ref().map_or(&ds.target, |s| &s.own);
own.texture
.switch_on_signed_depth("render_command_encoder", true);
}
device.degrade(Degradation::DepthDenormals, || {
let format = ds.target.texture.pixel_format();
let why = format!("a pass clears its depth to the denormal {cleared:e}: {loss}");
@@ -1876,9 +1869,7 @@ fn target(
}
// A view of another format renders in that format (`attachment_format`); a texture without
// `RenderTarget` usage, through its stand-in, in its own (the module docs), which for a depth
// or stencil attachment must hold the aspect: a `Depth32Float` texture held in an
// `R32_SFLOAT` image beside a depth twin (`image_plan.rs`) copies into no depth stand-in
// exactly.
// or stencil attachment must hold the aspect.
let holds = |format: metal2vulkan::vk::Format| match which {
Attachment::Color(_) => true,
Attachment::Depth => format.block().is_some_and(|b| b.depth.is_some()),
@@ -2070,7 +2061,7 @@ fn depth_stencil(
let written_nan = nan == Some(NanDepth::Written);
if written_nan {
if let Some(target) = &depth {
target.texture.degrade_signed_depth(call, true);
target.texture.degrade_signed_depth(call);
}
}
let depth_load = match written_nan {
@@ -2078,14 +2069,11 @@ fn depth_stencil(
false => d.load_action,
};
// A new texture's depth pattern, a NaN with the sign set, that the pass loads before a write
// covered it: Metal's test compares its magnitude, so the depth is switched on as a write that
// may store one switches it, before the pass decides its magnitude stand-in below
// covered it: Metal's test compares its magnitude, the device's the value as it is
// (`fresh_unwritten.rs`).
if let Some(target) = depth.as_ref().filter(|_| d.load_action == LoadAction::Load) {
if FreshUnwritten::loads_signed_depth(device, target)?
&& !target.texture.switch_on_fresh_pattern()
{
target.texture.degrade_signed_depth("new_texture", true);
if FreshUnwritten::loads_signed_depth(device, target)? {
target.texture.degrade_signed_depth("new_texture");
}
}
let clear_depth = match nan {
@@ -2176,39 +2164,13 @@ fn depth_stencil(
// through a stand-in made for them, each aspect copied in where the pass loads it and back
// where it stores it (`attachment_stand_in.rs`), as plain Metal renders it at them; so does
// one without depth/stencil attachment usage.
// A depth that may hold a negative value or a NaN, which the pass loads, renders over its
// magnitude stand-in, so the device's depth test answers as Metal's
// (`texture/signed_depth.rs`): one flag read where the pass loads its depth.
let signed = depth
.as_ref()
.filter(|t| depth_load == LoadAction::Load && t.texture.renders_over_magnitude());
let cause = match separate.is_none() {
false => None,
true if unattachable(&target)? => Some(Cause::Unattachable),
true if positioned_stand_in(device, descriptor, &target)? => Some(Cause::Positions),
true if signed.is_some() => Some(Cause::Magnitude),
true => None,
};
// Through another image, the pass tests the depth as it is.
if let Some(own) = signed.filter(|_| cause != Some(Cause::Magnitude)) {
let through = match separate.is_some() {
true => "the scratch image of separate depth and stencil textures",
false => "a stand-in for the pass's custom sample positions",
};
signed_depth::degrade_through(device, own, through);
}
let (target, stand_in) = match cause {
// The image its texture keeps for the queue, which the pass's copies fill first.
Some(Cause::Magnitude) => {
let queue = maker.command_queue().id();
let stood = attachment_stand_in::kept_backing(maker, &target, queue, true)?;
let own = StandIn {
own: target,
cause: Cause::Magnitude,
area: None,
};
(stood, Some(own))
}
Some(cause) => {
let stood = attachment_stand_in::stand_in(maker, &target, true)?;
let own = StandIn {
+4 -4
View File
@@ -49,7 +49,7 @@
//! own encoding would store 0x2c; alpha takes 0x20 either way. Both `BGRA8` pairs and both
//! directions alike, at 2 and 4 samples (the counts an M3 Max makes of these formats), each case
//! deterministic over four to six processes. So the runtime resolves it by the crate-owned
//! resolve in the resolve texture's format, under either `ResolvePolicy` (`color_resolve.rs`): a
//! resolve in the resolve texture's format (`color_resolve.rs`): a
//! subpass resolve writes only the attachment's own format
//! (`VUID-VkSubpassDescription-pResolveAttachments-00850`), so no device's average resolves
//! across the pair. The other channel order of the family, whose probes covered samples that
@@ -137,12 +137,12 @@
//! - **Color** through the subpass's resolve attachments. Vulkan averages a resolve of a
//! normalized or floating-point format (`VK_RESOLVE_MODE_AVERAGE_BIT`) and leaves the
//! average's rounding to the device, so a device may differ from Metal by one unit at a tie
//! (the exact path is a resolve shader). A resolve into the attachment's format's sRGB twin
//! (`device-rounded-resolve`). A resolve into the attachment's format's sRGB twin
//! takes no subpass resolve at all: the resolve attachment of a subpass is of the color
//! attachment's own format, so only the crate-owned resolve writes the twin's encoding.
//! - **The samples a resolve after the pass reads.** A resolve the runtime draws after the pass
//! (`color_resolve.rs`: the twin's, an extended-range attachment's, and every one under
//! `ResolvePolicy::Exact`) reads the samples the pass stores, so the pass stores them
//! (`color_resolve.rs`: the twin's and an extended-range attachment's) reads the samples the
//! pass stores, so the pass stores them
//! (`render_target::color_ops`) where Metal's `MultisampleResolve` stores nothing of the
//! attachment and leaves its texture as it was. Such a pass renders the attachment through the
//! image its texture keeps for the queue, the samples copied into it where the pass loads them
@@ -200,34 +200,30 @@ fn copy_units_are_metals_pixels_blocks_and_aspects() {
}
}
/// A texture with a depth twin holds `Depth32Float` in an `R32_SFLOAT` image: Metal's 4 bytes a
/// texel in its colour aspect, with any option (plain Metal copies `Depth32Float`'s depth with
/// `StencilFromDepthStencil`); no other format held in colour as depth.
/// A depth format's texels lie in its depth and stencil aspects: a colour image of one is no
/// layout a copy names, refused `NotImplemented(Format)` with any option.
#[test]
fn depth_held_in_colour_copies_metals_four_bytes() {
fn depth_held_in_colour_is_refused() {
let (_, device) = lavapipe();
let sampled = [FormatUsage::SampledImage].into();
let colour: FormatMapping =
vk_format(PixelFormat::R32Float, &sampled, device.profile()).unwrap();
assert_eq!(colour.aspects, ImageAspectFlags::COLOR);
for option in [
BlitOption::None,
BlitOption::DepthFromDepthStencil,
BlitOption::StencilFromDepthStencil,
] {
let unit = copy_unit(PixelFormat::Depth32Float, &colour, option).unwrap();
assert_eq!(
(unit.bytes, unit.extent, unit.aspect),
(4, [1, 1], ImageAspectFlags::COLOR),
"{option:?}"
);
}
match copy_unit(PixelFormat::Depth16Unorm, &colour, BlitOption::None) {
Err(CopyRefusal::Unsupported(u)) => assert_eq!(
(u.feature, u.needs),
(Feature::Format, Needs::NotImplemented)
),
other => panic!("{other:?}"),
for pf in [PixelFormat::Depth32Float, PixelFormat::Depth16Unorm] {
for option in [
BlitOption::None,
BlitOption::DepthFromDepthStencil,
BlitOption::StencilFromDepthStencil,
] {
match copy_unit(pf, &colour, option) {
Err(CopyRefusal::Unsupported(u)) => assert_eq!(
(u.feature, u.needs),
(Feature::Format, Needs::NotImplemented),
"{pf:?} {option:?}"
),
other => panic!("{pf:?} {option:?}: {other:?}"),
}
}
}
}
@@ -59,7 +59,6 @@ pub(super) fn all_audits(
storage_multisample: enabled.has(VkFeature::ShaderStorageImageMultisample),
depth_images: crate::image_plan::DepthImageFacts::of(&enabled.driver_facts()),
linear_attachments: false,
multisample_depth_twin: false,
};
let limits = any_limits;
let memo: RefCell<BTreeMap<PixelFormat, FormatAnswers>> = RefCell::default();
@@ -102,7 +101,6 @@ pub(super) fn format_capabilities(
storage_multisample: enabled.has(VkFeature::ShaderStorageImageMultisample),
depth_images: crate::image_plan::DepthImageFacts::of(&enabled.driver_facts()),
linear_attachments: false,
multisample_depth_twin: false,
};
let sparse = Err(Missing::Gap(RuntimeGap::SparseHeaps));
answers(pf, &image, &any_limits, sparse).capabilities()
@@ -844,7 +842,6 @@ fn formats_without_a_made_multisample_texture_or_a_modelled_resolve_answer_neith
storage_multisample: enabled.has(VkFeature::ShaderStorageImageMultisample),
depth_images: crate::image_plan::DepthImageFacts::of(&enabled.driver_facts()),
linear_attachments: false,
multisample_depth_twin: false,
};
let found = |pf| {
let sparse = Err(Missing::Gap(RuntimeGap::SparseHeaps));
@@ -929,7 +926,6 @@ fn extended_range_formats_answer_the_shaders_filter_and_blend() {
storage_multisample: enabled.has(VkFeature::ShaderStorageImageMultisample),
depth_images: crate::image_plan::DepthImageFacts::of(&enabled.driver_facts()),
linear_attachments: false,
multisample_depth_twin: false,
};
for pf in formats {
let sparse = Err(Missing::Gap(RuntimeGap::SparseHeaps));
@@ -994,7 +990,6 @@ fn srgb_formats_held_as_their_unorm_twin_answer_the_twins_filter() {
storage_multisample: enabled.has(VkFeature::ShaderStorageImageMultisample),
depth_images: crate::image_plan::DepthImageFacts::of(&enabled.driver_facts()),
linear_attachments: false,
multisample_depth_twin: false,
};
for pf in [
PixelFormat::R8UnormSRGB,
@@ -1064,7 +1059,6 @@ fn listed_formats_answer_at_most_their_apple9_cell() {
storage_multisample: enabled.has(VkFeature::ShaderStorageImageMultisample),
depth_images: crate::image_plan::DepthImageFacts::of(&enabled.driver_facts()),
linear_attachments: false,
multisample_depth_twin: false,
};
for row in FormatRow::ALL {
for &pf in row.formats() {
+32 -91
View File
@@ -420,14 +420,11 @@ fn a_heap_s_texture_buffer_takes_its_row_at_16_bytes_as_metal_s_does() {
}
}
/// A texture with a depth twin takes the twin's bytes of a heap past its image's, at the twin's
/// alignment, inside the answered size, so a texture at any multiple of the answered alignment has
/// each image at a multiple of its own and the next texture's bytes after both; a texture without
/// one takes its image's, in whole granularity pages; on a device whose driver answers a compressed
/// image's size short of its compression data (ANV on Xe-LP GPUs), each image and the texture also
/// take whole 256-byte chunks.
/// A heap texture takes its image's bytes of a heap, in whole granularity pages, at the image's
/// alignment or the granularity's; on a device whose driver answers a compressed image's size short
/// of its compression data (ANV on Xe-LP GPUs), the image also takes whole 256-byte chunks.
#[test]
fn a_depth_twin_lies_past_its_image_inside_the_heap_texture_s_bytes() {
fn a_heap_texture_takes_its_image_s_bytes_in_whole_pages() {
use crate::texture::heap::heap_extent;
use crate::texture::ImagePlacement;
use crate::SizeAndAlign;
@@ -445,37 +442,19 @@ fn a_depth_twin_lies_past_its_image_inside_the_heap_texture_s_bytes() {
ImagePlacement::new(granularity, &BTreeSet::from([short]))
};
let answer = |size, align| SizeAndAlign { size, align };
// RADV's shape on the Radeon 780M: 64 KiB alignment for the larger images, 4 KiB for the small.
let image = requirements(16512, 4096);
let twin = requirements(16384, 65536);
let (got, offset) = heap_extent(&image, Some(&twin), pages(1024));
assert_eq!(offset, Some(65536));
assert_eq!(got, answer(65536 + 16384, 65536));
// The twin's start meets its alignment wherever the texture lies.
for at in [0, 1, 7].map(|n| n * got.align) {
assert!((at + offset.unwrap()).is_multiple_of(twin.alignment));
}
// A granularity coarser than both alignments rounds the twin's offset and the size.
let (small, twin_small) = (requirements(1000, 256), requirements(900, 256));
// A granularity coarser than the image's alignment rounds its alignment and size.
let small = requirements(1000, 256);
for placement in [pages(4096), chunks(4096)] {
let (got, offset) = heap_extent(&small, Some(&twin_small), placement);
assert_eq!((got, offset), (answer(8192, 4096), Some(4096)));
assert_eq!(heap_extent(&small, placement), answer(4096, 4096));
}
// Without a twin: the image alone, in whole pages.
// The image alone, in whole pages.
let lone = requirements(16512, 128);
let (got, offset) = heap_extent(&lone, None, pages(1024));
assert_eq!((got, offset), (answer(17408, 1024), None));
assert_eq!(heap_extent(&lone, pages(1024)), answer(17408, 1024));
// ANV's compressed 4x4 `RGBA8Unorm` image on an Xe-LP GPU: 4112 bytes at 64 KiB, in whole
// chunks there, and with a twin past it.
// chunks there.
let compressed = requirements(4112, 65536);
let (got, offset) = heap_extent(&compressed, None, chunks(1));
assert_eq!((got, offset), (answer(4352, 65536), None));
let (got, offset) = heap_extent(&compressed, Some(&requirements(4112, 65536)), chunks(1));
assert_eq!((got, offset), (answer(65536 + 4352, 65536), Some(65536)));
assert_eq!(
heap_extent(&compressed, None, pages(1)).0,
answer(4112, 65536)
);
assert_eq!(heap_extent(&compressed, chunks(1)), answer(4352, 65536));
assert_eq!(heap_extent(&compressed, pages(1)), answer(4112, 65536));
}
/// A heap texture's footprint is Metal's answer, not the running driver's granularity. A heap's
@@ -510,48 +489,35 @@ fn a_heap_texture_s_footprint_takes_no_granularity_padding() {
// asks exactly: the answer is Metal's, where the padded placement answers a 1024 alignment.
let metal = answer(16384, 128);
let image = requirements(16384, 128);
assert_eq!(heap_extent(&image, None, nvidia).0, answer(16384, 1024));
assert_eq!(heap_extent(&image, None, nvidia.in_heap()).0, metal);
assert!(images_fit(
heap_extent(&image, None, nvidia.in_heap()).0,
metal
));
assert_eq!(heap_extent(&image, nvidia), answer(16384, 1024));
assert_eq!(heap_extent(&image, nvidia.in_heap()), metal);
assert!(images_fit(heap_extent(&image, nvidia.in_heap()), metal));
// The 64x64 `RGBA8Unorm` 7-level texture the replay found at 23552 bytes where Metal answers
// 22528: its image asks 22784 (llvmpipe answered that one for the same descriptor), which the
// padding carries to a whole page. Without the padding the footprint is the image's own, 256
// bytes past Metal's answer, which does not fit it: a shadow of the texture's bytes holds it.
let seven = requirements(22784, 128);
let metal_seven = answer(22528, 128);
assert_eq!(heap_extent(&seven, None, nvidia).0, answer(23552, 1024));
assert_eq!(
heap_extent(&seven, None, nvidia.in_heap()).0,
answer(22784, 128)
);
assert_eq!(heap_extent(&seven, nvidia), answer(23552, 1024));
assert_eq!(heap_extent(&seven, nvidia.in_heap()), answer(22784, 128));
assert!(!images_fit(
heap_extent(&seven, None, nvidia.in_heap()).0,
heap_extent(&seven, nvidia.in_heap()),
metal_seven
));
// An image whose own alignment is coarser than Metal's, and one that asks more bytes (the
// 5000-texel `Type1D` the replay found at 160768 bytes where Metal answers 32768), do not fit
// Metal's answer: a shadow of the texture's bytes holds those to it.
let coarse = heap_extent(&requirements(16384, 1024), None, nvidia.in_heap()).0;
let coarse = heap_extent(&requirements(16384, 1024), nvidia.in_heap());
assert_eq!(coarse, answer(16384, 1024));
assert!(!images_fit(coarse, metal));
let wide = heap_extent(&requirements(160768, 128), None, nvidia.in_heap()).0;
let wide = heap_extent(&requirements(160768, 128), nvidia.in_heap());
assert!(!images_fit(wide, answer(32768, 128)));
// A depth twin still lies past the image inside the texture's bytes, at its own alignment,
// with no page of the granularity's between them.
let (got, offset) = heap_extent(&image, Some(&requirements(16384, 256)), nvidia.in_heap());
assert_eq!((got, offset), (answer(32768, 256), Some(16384)));
// The aux map's chunks survive: ANV's compressed 4x4 `RGBA8Unorm` image on an Xe-LP GPU asks
// 4112 bytes and writes compression data to the end of the chunk it falls in.
let short = RuntimeDriverDefect::ImageSizeShortOfCompressionData;
let anv = ImagePlacement::new(64, &BTreeSet::from([short]));
let compressed = requirements(4112, 65536);
assert_eq!(
heap_extent(&compressed, None, anv.in_heap()).0,
answer(4352, 65536)
);
assert_eq!(heap_extent(&compressed, anv.in_heap()), answer(4352, 65536));
}
/// A heap texture takes Metal's answer, which is the number a program sizes a heap and places its
@@ -563,8 +529,7 @@ fn a_heap_texture_s_footprint_takes_no_granularity_padding() {
/// The whole decision over the plan's own numbers, every shape the plan can hand it. An image
/// already in memory of its own takes none of the heap's bytes, so it is held whatever it needs; a
/// 4:2:2 texture is never held by its image, because its bytes lie where Metal's linear rows do
/// and not where its image lays them; a texture held with a depth twin is held by neither, since
/// no shadow of the texture's bytes moves the twin's; a multisample texture is held by a shadow
/// and not where its image lays them; a multisample texture is held by a shadow
/// whether or not a shadow of rows fits it, because its image lies in memory of its own either
/// way.
#[test]
@@ -577,7 +542,6 @@ fn a_heap_texture_is_held_to_metal_s_answer_by_its_image_or_by_a_shadow() {
let plain = HeapTextureShape {
apart: false,
four_two_two: false,
twin: false,
multisample: false,
shadowable: true,
};
@@ -612,20 +576,7 @@ fn a_heap_texture_is_held_to_metal_s_answer_by_its_image_or_by_a_shadow() {
assert_eq!(held_to_metal(past, metal, shape), HeldToMetal::Shadow);
assert_eq!(held_to_metal(metal, metal, shape), HeldToMetal::Images);
}
// A depth twin's bytes lie past the image's inside the texture's and no shadow moves them: a
// texture whose images do not fit is held by neither, whatever else its shape says.
for (multisample, shadowable) in [(false, false), (false, true), (true, false), (true, true)] {
let shape = HeapTextureShape {
twin: true,
multisample,
shadowable,
..plain
};
assert_eq!(held_to_metal(past, metal, shape), HeldToMetal::Nothing);
assert_eq!(held_to_metal(metal, metal, shape), HeldToMetal::Images);
}
// An image in memory of its own takes none of the heap's bytes: held whatever it needs, and a
// depth twin never goes with one.
// An image in memory of its own takes none of the heap's bytes: held whatever it needs.
let apart = HeapTextureShape {
apart: true,
..plain
@@ -676,17 +627,17 @@ fn every_image_alignment_measured_fits_a_heap_s_base() {
alignment,
memory_type_bits: 1,
};
let (answer, _) = heap_extent(&image, None, pages);
let answer = heap_extent(&image, pages);
assert_eq!(answer.align, alignment);
assert_eq!(
check_heap_base(bound, None, answer.align),
check_heap_base(bound, answer.align),
Ok(()),
"{alignment:#x}"
);
}
let past = 2 * HEAP_BASE_ALIGNMENT;
assert_eq!(
check_heap_base(bound, None, past),
check_heap_base(bound, past),
Err(Error::NotImplemented(RuntimeGap::HeapTextureAlignment {
alignment: past
}))
@@ -707,16 +658,10 @@ fn every_image_alignment_measured_fits_a_heap_s_base() {
/// past Metal's (`heap-texture-larger-than-metal`) for a texture no shadow holds, and a
/// multisample depth image already asks 256 KiB on RADV.
///
/// A depth twin's image always binds to the heap's memory (`heap_image` of `Mine::Twin` reaches
/// neither shadow route), so a texture held with one is held to the base whatever its own route
/// says.
///
/// `AliasRoute::Shadow` binds nothing there either: `heap_texture_at` sends it and
/// `AliasRoute::MemoryShadow` to the one arm (`heap_shadow_image`, whose `new_heap_shadow` places
/// an image of its own and makes the heap's bytes its copies' source alone), and nothing at that
/// dispatch tells the two apart. It is never held with a depth twin, whose image would bind: a
/// twinned texture's own image is a colour one (`plan_images` plans it so), which the route's
/// `!colour(&optimal)` test leaves out. The route is reached only on a driver that lays depth and
/// dispatch tells the two apart. The route is reached only on a driver that lays depth and
/// stencil images apart from their memory (MoltenVK, measured), whose image alignments are
/// Metal's and well inside the base, so no texture of it meets this bound: what the rule decides
/// for it is the placement offset `placement_align`'s own test covers, held to Metal's alignment
@@ -731,7 +676,7 @@ fn the_heap_s_base_holds_only_a_texture_whose_image_binds_to_its_memory() {
let refused = Err(Error::NotImplemented(RuntimeGap::HeapTextureAlignment {
alignment: past,
}));
let holds_base = |route, twin| check_heap_base(route, twin, past) == refused;
let holds_base = |route| check_heap_base(route, past) == refused;
let own = [
AliasRoute::Tiled,
AliasRoute::Lossless,
@@ -749,24 +694,20 @@ fn the_heap_s_base_holds_only_a_texture_whose_image_binds_to_its_memory() {
AliasRoute::Apart,
];
for route in own {
assert_eq!(check_heap_base(route, None, past), Ok(()), "{route:?}");
assert_eq!(check_heap_base(route, past), Ok(()), "{route:?}");
assert!(route.in_own_memory(), "{route:?}");
// A depth twin of such a texture binds to the heap's memory, so the base holds it.
assert!(holds_base(route, Some(AliasRoute::Direct)), "{route:?}");
assert!(holds_base(route, Some(AliasRoute::Apart)), "{route:?}");
// An alignment the base meets is no refusal either way.
assert_eq!(
check_heap_base(route, None, HEAP_BASE_ALIGNMENT),
check_heap_base(route, HEAP_BASE_ALIGNMENT),
Ok(()),
"{route:?}"
);
}
for route in bound {
assert!(holds_base(route, None), "{route:?}");
assert!(holds_base(route), "{route:?}");
assert!(!route.in_own_memory(), "{route:?}");
assert!(holds_base(route, Some(AliasRoute::Direct)), "{route:?}");
assert_eq!(
check_heap_base(route, None, HEAP_BASE_ALIGNMENT),
check_heap_base(route, HEAP_BASE_ALIGNMENT),
Ok(()),
"{route:?}"
);
@@ -3,12 +3,11 @@
use super::super::blit_plan::BufferImageRegion;
use super::super::chroma_pairs::{holds_pairs, CARRIER as PAIRS_CARRIER};
use super::super::copy_plan::{copy_unit, BlitOption, CopyUnit, ImageRegion};
use super::super::copy_plan::{copy_unit, BlitOption, ImageRegion};
use super::super::driver_defects;
use super::super::image_plan::{
block_family, check_image_limits, compatible, cube_compatible, holds_depth_in_colour,
holds_srgb_twin, plan_image, plan_images, sample_count, srgb_twin, DepthImageFacts, ImageFacts,
ImagePlan, ImageRefusal,
block_family, check_image_limits, compatible, cube_compatible, holds_srgb_twin, plan_image,
sample_count, srgb_twin, DepthImageFacts, ImageFacts, ImagePlan, ImageRefusal,
};
use super::super::memory::MemoryClass;
use super::super::pvrtc::{holds_blocks, image_buffer_region, image_region, CARRIERS};
@@ -61,19 +60,6 @@ pub(super) fn facts<'a>(desc: &'a DeviceDescription, device: &'a Device) -> Imag
storage_multisample: desc.has(VkFeature::ShaderStorageImageMultisample),
depth_images: DepthImageFacts::of(&desc.driver_facts()),
linear_attachments: false,
multisample_depth_twin: false,
}
}
/// [`facts`] with a multisampled `Depth32Float` texture held in colour
/// (`MultisampleDepthTwinPolicy::Exact`).
fn facts_holding_multisample_depth<'a>(
desc: &'a DeviceDescription,
device: &'a Device,
) -> ImageFacts<'a> {
ImageFacts {
multisample_depth_twin: true,
..facts(desc, device)
}
}
@@ -979,126 +965,53 @@ fn multisampled_depth_targets_take_custom_sample_positions() {
);
}
/// A `Depth32Float` texture the program only reads or samples holds its texels in an `R32_SFLOAT`
/// image beside a `D32_SFLOAT` twin of its shape on every committed profile whose depth image its
/// driver is not measured to keep every `float` in: without `VK_EXT_depth_range_unrestricted` and
/// the driver's fact that its depth images keep values outside `[0, 1]`, the Xe-LP ANV ones among
/// them, or without its fact that they keep denormals, RADV's among them; and in its depth
/// image, as `plan_image` plans it, elsewhere: NVIDIA's and lavapipe, with the extension, and
/// MoltenVK without it. A render target (`Unknown` usage counts as one), a memoryless or
/// multisampled texture and another depth format have no twin.
/// A `Depth32Float` texture is held in a `D32_SFLOAT` depth image on every committed profile,
/// whatever its driver is measured to keep in one: a texture the program only reads or samples,
/// single-sampled or multisampled, as a render target is. A value the depth image may not keep is
/// announced at the write that stores it (`restricted-depth-upload`, `depth-denormals`).
#[test]
fn depth_twins_hold_the_texels_in_colour_where_a_depth_image_may_not() {
fn a_depth32float_texture_is_held_in_its_depth_image_on_every_profile() {
use PixelFormat as P;
let read = TextureUsage::SHADER_READ;
let mut twinned = Vec::new();
let mut planned = 0;
for (name, desc, device) in committed() {
let facts = facts(&desc, &device);
let unrestricted = device
.profile()
.enabled()
.extensions
.contains(&VkExtension::ExtDepthRangeUnrestricted);
let kept = facts.depth_images;
let exact = (unrestricted || kept.outside_unit_range) && kept.denormals;
assert_eq!(facts.depth_loss().is_none(), exact, "{name}");
for (ty, array) in [
(TextureType::Type2D, 1),
(TextureType::Type2DArray, 3),
(TextureType::Cube, 1),
for (ty, samples, array, usage) in [
(TextureType::Type2D, 1, 1, read),
(TextureType::Type2DArray, 1, 3, read),
(TextureType::Cube, 1, 1, read),
(
TextureType::Type2D,
1,
1,
read | TextureUsage::RENDER_TARGET,
),
(TextureType::Type2DMultisample, 2, 1, read),
(TextureType::Type2DMultisample, 4, 1, read),
] {
let l = layout(ty, P::Depth32Float, 1, array);
let (plan, twin) = plan_images(&l, read, false, &facts).expect(&name);
let Some(twin) = twin else {
assert!(exact, "{name}: {ty:?}");
assert_eq!(plan, plan_image(&l, read, false, &facts).unwrap(), "{name}");
let l = layout(ty, P::Depth32Float, samples, array);
let Ok(plan) = plan_image(&l, usage, false, &facts) else {
continue;
};
assert!(!exact, "{name}: {ty:?}");
assert_eq!(
(plan.pixel_format, plan.format, plan.mapping.aspects),
(P::Depth32Float, Format::R32_SFLOAT, ImageAspectFlags::COLOR),
"{name}: {ty:?}"
);
let copies = ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST;
assert!(
plan.usage.contains(ImageUsageFlags::SAMPLED | copies),
"{name}: {ty:?}"
);
assert_eq!(
(twin.pixel_format, twin.format, twin.mapping.aspects),
(P::Depth32Float, Format::D32_SFLOAT, ImageAspectFlags::DEPTH),
"{name}: {ty:?}"
"{name}: {ty:?} {samples} {usage:?}"
);
assert_eq!(
(
twin.image_type,
twin.flags,
twin.extent,
twin.levels,
twin.layers,
twin.samples
),
(
plan.image_type,
plan.flags,
plan.extent,
plan.levels,
plan.layers,
plan.samples
),
"{name}: {ty:?}"
copy_unit(P::Depth32Float, &plan.mapping, BlitOption::None)
.map(|unit| unit.aspect)
.ok(),
Some(ImageAspectFlags::DEPTH),
"{name}: {ty:?} {samples}"
);
assert!(
twin.usage
.contains(ImageUsageFlags::SAMPLED | ImageUsageFlags::TRANSFER_DST),
"{name}: {ty:?}"
);
if ty == TextureType::Type2D {
twinned.push(name.clone());
}
}
let flat = layout(TextureType::Type2D, P::Depth32Float, 1, 1);
for (what, l, usage, memoryless) in [
(
"a render target",
flat,
read | TextureUsage::RENDER_TARGET,
false,
),
("Unknown usage", flat, TextureUsage::empty(), false),
("memoryless", flat, TextureUsage::RENDER_TARGET, true),
(
"multisampled",
layout(TextureType::Type2DMultisample, P::Depth32Float, 4, 1),
read,
false,
),
(
"Depth16Unorm",
layout(TextureType::Type2D, P::Depth16Unorm, 1, 1),
read,
false,
),
] {
if let Ok((_, twin)) = plan_images(&l, usage, memoryless, &facts) {
assert_eq!(twin, None, "{name}: {what}");
}
planned += 1;
}
}
for stem in ["intel-irisxe-rplp-anv", "amd-780m-radv", "amd-rdna3-radv"] {
assert!(twinned.iter().any(|n| n == stem), "{stem}: {twinned:?}");
}
// Drivers measured to keep every `float` in a depth image: NVIDIA's and lavapipe with the
// extension, at every release, MoltenVK without it.
for stem in [
"nvidia-rtx5080-laptop",
"gate-lavapipe",
"lavapipe",
"moltenvk-m3",
] {
assert!(!twinned.iter().any(|n| n == stem), "{stem}: {twinned:?}");
}
assert!(
planned > 0,
"no committed profile plans a Depth32Float texture"
);
}
/// A memoryless texture is a transient attachment, on lavapipe (whose framebuffer fetch reads
@@ -1558,11 +1471,10 @@ fn extended_range_textures_hold_their_bytes_raw() {
TextureUsage::RENDER_TARGET,
TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ,
] {
let memoryless = plan_images(&l, target, true, &facts);
let memoryless = plan_image(&l, target, true, &facts);
match renders {
true => {
let (plan, twin) = memoryless.expect(&what);
assert!(twin.is_none(), "{what}");
let plan = memoryless.expect(&what);
assert_eq!(plan.format, raw, "{what}");
assert!(
plan.usage.contains(
@@ -1583,9 +1495,8 @@ fn extended_range_textures_hold_their_bytes_raw() {
.optimal(Format::R8G8B8A8_UNORM)
.contains(FormatFeatureFlags2::COLOR_ATTACHMENT)
{
let (plan, twin) = plan_images(&l, TextureUsage::RENDER_TARGET, true, &facts)
let plan = plan_image(&l, TextureUsage::RENDER_TARGET, true, &facts)
.unwrap_or_else(|e| panic!("{name}: a memoryless ARGB8Unorm texture: {e:?}"));
assert!(twin.is_none(), "{name}");
assert_eq!(plan.format, Format::R8G8B8A8_UNORM, "{name}");
assert!(
plan.usage.contains(
@@ -2000,8 +1911,6 @@ fn padded_formats_are_held_raw_from_every_creator() {
"{name} {pf:?}: {:?}",
plan.usage
);
let (images, twin) = plan_images(&l, usage, false, &facts).expect(&name);
assert_eq!((images, twin), (plan, None), "{name}");
}
}
}
@@ -2032,7 +1941,7 @@ fn decoded_twins_are_planned_in_their_texels_format() {
};
assert_eq!(zero, start, "{pf:?}");
let l = layout(TextureType::Type2DArray, pf, 1, 3);
let Ok((plan, _)) = plan_images(&l, TextureUsage::SHADER_READ, false, &facts) else {
let Ok(plan) = plan_image(&l, TextureUsage::SHADER_READ, false, &facts) else {
continue;
};
planned += 1;
@@ -2218,133 +2127,3 @@ fn astc_carriers_hold_each_level_s_blocks() {
}
assert!(carried > 0, "no committed device holds ASTC in a carrier");
}
/// A multisampled `Depth32Float` texture the program only reads is held in its depth image under
/// the default, as before, and in a multisampled `R32_SFLOAT` image of its shape under
/// `MultisampleDepthTwinPolicy::Exact` on every committed profile whose depth image its driver is
/// not measured to keep every `float` in; in its depth image elsewhere. It takes no `D32_SFLOAT`
/// twin beside it under either value: Metal reads a `depth2d_ms` and compares nothing, and no copy
/// writes a multisampled depth image from a colour one. A render target, a memoryless texture, a
/// single-sampled one (which has the twin of its own row) and another depth format are held as
/// before under both values.
#[test]
fn the_switch_holds_a_multisampled_depth_texture_s_texels_in_colour() {
use PixelFormat as P;
let read = TextureUsage::SHADER_READ;
let mut held = Vec::new();
for (name, desc, device) in committed() {
let default = facts(&desc, &device);
let switched = facts_holding_multisample_depth(&desc, &device);
let exact = default.depth_loss().is_none();
for samples in [2, 4] {
let l = layout(TextureType::Type2DMultisample, P::Depth32Float, samples, 1);
// Under the default: the depth image, as `plan_image` plans it.
let Ok((plan, twin)) = plan_images(&l, read, false, &default) else {
continue;
};
assert!(twin.is_none(), "{name}: {samples} samples, default");
assert_eq!(
plan,
plan_image(&l, read, false, &default).unwrap(),
"{name}: {samples} samples, default"
);
assert_eq!(
(plan.pixel_format, plan.format),
(P::Depth32Float, Format::D32_SFLOAT),
"{name}: {samples} samples, default"
);
// Under the switch: the colour image where the device's depth images may lose the
// texels and it holds a multisampled `R32_SFLOAT` it samples and copies.
let (switched_plan, switched_twin) =
plan_images(&l, read, false, &switched).expect(&name);
assert!(switched_twin.is_none(), "{name}: {samples} samples, switch");
let colour = switched_plan.format == Format::R32_SFLOAT;
if !colour {
assert_eq!(
switched_plan, plan,
"{name}: {samples} samples: no colour image, so the plan is the default's"
);
continue;
}
assert!(
!exact,
"{name}: {samples} samples: a colour image without a loss"
);
assert_eq!(
(
switched_plan.pixel_format,
switched_plan.mapping.aspects,
switched_plan.extent,
switched_plan.levels,
switched_plan.layers,
switched_plan.samples
),
(
P::Depth32Float,
ImageAspectFlags::COLOR,
plan.extent,
plan.levels,
plan.layers,
plan.samples
),
"{name}: {samples} samples"
);
assert!(
switched_plan.usage.contains(ImageUsageFlags::SAMPLED),
"{name}: {samples} samples"
);
assert!(
!switched_plan
.usage
.contains(ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT),
"{name}: {samples} samples: a read-only texture keeps no attachment usage"
);
// The plan every blit and binding reads the choice by (`Texture::holds_depth_in_colour`
// for the facts and `blit_texture::held` for the images a copy moves).
assert!(
holds_depth_in_colour(&switched_plan) && !holds_depth_in_colour(&plan),
"{name}: {samples} samples"
);
// Every copy of the texture's texels moves them in colour, 4 bytes a texel, as a
// texture with a depth twin's are: a fill of its samples
// (`blit_fill::sample_fill` through `blit_texture::unit`) and a copy between textures
// (`blit_plan::pair_unit`) alike.
assert_eq!(
copy_unit(P::Depth32Float, &switched_plan.mapping, BlitOption::None).ok(),
Some(CopyUnit {
bytes: 4,
extent: [1, 1],
aspect: ImageAspectFlags::COLOR
}),
"{name}: {samples} samples"
);
assert_eq!(
copy_unit(P::Depth32Float, &plan.mapping, BlitOption::None)
.map(|unit| unit.aspect)
.ok(),
Some(ImageAspectFlags::DEPTH),
"{name}: {samples} samples, default"
);
held.push(format!("{name} {samples}"));
}
// A render target, a memoryless texture and another depth format are held as before.
for (usage, memoryless, pf) in [
(TextureUsage::RENDER_TARGET | read, false, P::Depth32Float),
(read, true, P::Depth32Float),
(read, false, P::Depth32FloatStencil8),
] {
let l = layout(TextureType::Type2DMultisample, pf, 4, 1);
let before = plan_images(&l, usage, memoryless, &default);
let after = plan_images(&l, usage, memoryless, &switched);
assert_eq!(
before.ok(),
after.ok(),
"{name}: {pf:?} {usage:?} memoryless {memoryless}"
);
}
}
assert!(
!held.is_empty(),
"no committed profile holds a multisampled depth texture in colour under the switch"
);
}
@@ -85,15 +85,9 @@ fn cpu_copies_read_a_tightly_packed_buffer() {
#[test]
fn the_granularity_is_a_whole_power_of_two() {
let (_, desc, _) = committed().into_iter().next().unwrap();
assert_eq!(TextureState::new(&desc, 0, false, false).granularity(), 1);
assert_eq!(
TextureState::new(&desc, 1024, false, false).granularity(),
1024
);
assert_eq!(
TextureState::new(&desc, 1000, false, false).granularity(),
1024
);
assert_eq!(TextureState::new(&desc, 0, false).granularity(), 1);
assert_eq!(TextureState::new(&desc, 1024, false).granularity(), 1024);
assert_eq!(TextureState::new(&desc, 1000, false).granularity(), 1024);
}
#[test]
@@ -60,13 +60,11 @@ fn a_texture_s_kept_facts_are_the_ones_worked_out_again_and_a_view_s_its_own() {
kept_as_worked_out(&view, "a view made after its texture's facts were kept");
kept_as_worked_out(&color, "a texture after a view of it was made");
assert_eq!(color.facts(), first, "kept once made");
// A depth texture's twin is made with its image: its facts say so from the first read.
// A depth texture's facts are kept as worked out from the first read.
let depth = texture(
&device,
PixelFormat::Depth32Float,
TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET,
);
let facts = depth.facts();
assert_eq!(facts.depth_twin, depth.twin_image().is_some());
kept_as_worked_out(&depth, "a depth texture");
}
+111 -303
View File
@@ -51,14 +51,6 @@
//! it from the caller's layout to `GENERAL` and back.
//! - **Shared textures** (`texture/shared.rs`): a `Private` texture made shareable, whose
//! in-process handle opens new textures over the same image.
//! - **Depth twins**. A `Depth32Float` texture the program only reads or samples, on a device whose
//! depth images its driver is not measured to keep every `float` in (without
//! `VK_EXT_depth_range_unrestricted`, or keeping a denormal), holds its texels in an
//! `R32_SFLOAT` image, which keeps any `float`, and the same texels in a `D32_SFLOAT` twin
//! ([`image_plan`](super::image_plan)), which the views a comparison the device makes reads
//! present. Every copy
//! into the texture writes both (`replace_region`, the blit encoder's copies), and reads come
//! from its image; the twin shares the image's resource identity.
//! - **Not yet:** blits of textures over buffers are refused `NotImplemented`.
use super::address::{ObjectsToken, RangeToken};
@@ -87,8 +79,7 @@ use super::heap::{Heap, HeapProblem, HeapType};
use super::heap_sets;
use super::host_bytes::HostBytes;
use super::image_plan::{
check_image_limits, holds_depth_in_colour, plan_image, plan_images, DepthImageFacts,
ImageFacts, ImagePlan, ImageRefusal,
check_image_limits, plan_image, DepthImageFacts, ImageFacts, ImagePlan, ImageRefusal,
};
use super::in_place::{self, PagesClass, Refusal, ShadowCause, Verdict};
use super::key_hash::KeyMap;
@@ -180,7 +171,6 @@ pub(super) mod requirements;
#[cfg(unix)]
mod rotation;
mod shared;
pub(super) mod signed_depth;
mod staging_copy;
pub(super) mod stand_in;
pub(super) mod storage_form;
@@ -211,8 +201,6 @@ pub(super) struct TextureState {
depth_images: DepthImageFacts,
/// `ImageFacts::linear_attachments`.
linear_attachments: bool,
/// `ImageFacts::multisample_depth_twin`.
multisample_depth_twin: bool,
/// How the runtime places an image in a memory block of its own.
placement: ImagePlacement,
/// The verdicts of `generate_mipmaps`' per-format checks (`mipmap.rs`).
@@ -263,19 +251,15 @@ pub(super) struct TextureState {
impl TextureState {
/// The texture state of a device enabling `description`, whose `bufferImageGranularity` is
/// `buffer_image_granularity`, `linearColorAttachment` where `linear_attachments`, and a
/// multisampled `Depth32Float` texture held in colour where `multisample_depth_twin`
/// (`MultisampleDepthTwinPolicy::Exact`).
/// `buffer_image_granularity`, and `linearColorAttachment` where `linear_attachments`.
pub(super) fn new(
description: &DeviceDescription,
buffer_image_granularity: u64,
linear_attachments: bool,
multisample_depth_twin: bool,
) -> TextureState {
TextureState {
formats: description.formats.clone(),
linear_attachments,
multisample_depth_twin,
storage_multisample: description.has(VkFeature::ShaderStorageImageMultisample),
depth_images: DepthImageFacts::of(&description.driver_facts()),
placement: ImagePlacement::new(
@@ -317,7 +301,6 @@ impl TextureState {
storage_multisample: self.storage_multisample,
depth_images: self.depth_images,
linear_attachments: self.linear_attachments,
multisample_depth_twin: self.multisample_depth_twin,
}
}
@@ -570,9 +553,6 @@ struct Image {
/// The objects of exact color resolves into the image that its passes made, kept for its next
/// pass of the same views (`color_resolve.rs`).
resolves: KeptResolves,
/// The image's depth twin: a `D32_SFLOAT` image of the same texels, which the views a
/// comparison reads present, for an `R32_SFLOAT` image holding a `Depth32Float` texture.
twin: Option<Box<Image>>,
/// The image's decoded twin (`texture/decoded_twin.rs`): a BC1 to BC5 image's texels as
/// Metal decodes them, which its sampled views present, on a device whose driver is not
/// measured to decode them so; an ASTC or PVRTC carrier's.
@@ -591,13 +571,6 @@ struct Image {
/// (`two_planes/buffer_rows.rs`): plane 0 of each slice laid out as Metal lays it, made at
/// the first such write.
between: OnceLock<Buffer>,
/// Its 32-bit float depth may hold a value whose magnitude stand-in is not itself (a negative
/// value, a NaN, or, where the device's depth test compares a denormal as zero, a denormal),
/// which a write that may store one set: a pass that loads it renders over its magnitude
/// stand-in, or its words are stripped of their signs after a pass with depth writes whose
/// stores the device's pass leaves signed (`signed_depth.rs`). Set once, never cleared; only
/// on an image with a form ([`Texture::magnitude_form`]).
signed_depth: AtomicBool,
/// While the bytes of its texture are detached (`detach.rs`): the stand-in it presents
/// (`stand_in.rs`), whose read image is its `VkImage` meanwhile, and, for an image in memory of
/// its own, its own image and views, which a reattach swaps back. Locked under `views`.
@@ -1084,7 +1057,7 @@ impl Image {
}
/// The image, shared (by its texture, or the runtime's holder of it): registered with the
/// device's first moves where its move, or its depth twin's, waits (`texture/first_move.rs`).
/// device's first moves where its move waits (`texture/first_move.rs`).
fn shared(self) -> Arc<Image> {
let image = Arc::new(self);
if image.move_waits() {
@@ -1100,11 +1073,9 @@ impl Image {
self.device.shared().textures.first_moves.register(fresh);
}
/// Whether its move, or its depth twin's or one of its decoded twins', waits for a
/// submission.
/// Whether its move, or one of its decoded twins', waits for a submission.
fn move_waits(&self) -> bool {
lock(&self.first_move).is_some()
|| (self.twin.as_ref()).is_some_and(|twin| lock(&twin.first_move).is_some())
|| (self.decoded.as_ref()).is_some_and(|d| lock(&d.image.first_move).is_some())
|| (self.second.get()).is_some_and(|d| lock(&d.image.first_move).is_some())
}
@@ -1245,7 +1216,7 @@ impl Drop for Image {
let owned = match &self.owner {
Owner::Runtime { .. } => Owned::ImageOwnMemory,
Owner::Buffer { .. } => Owned::ImageInBuffer,
Owner::Heap(_) | Owner::HeapTwin => Owned::ImageInHeap,
Owner::Heap(_) => Owned::ImageInHeap,
_ => Owned::ImageOther,
};
shared.counts.churn.released(owned);
@@ -1337,11 +1308,6 @@ impl Fresh for Image {
let own = lock(&self.first_move)
.take()
.filter(|first| self.holds(first.image));
let twin = (self.twin.as_ref()).and_then(|twin| {
lock(&twin.first_move)
.take()
.filter(|first| twin.holds(first.image))
});
let decoded = (self.decoded.as_deref().into_iter())
.chain(self.second.get().map(Box::as_ref))
.filter_map(|decoded| {
@@ -1349,17 +1315,16 @@ impl Fresh for Image {
.take()
.filter(|first| decoded.image.holds(first.image))
});
own.into_iter().chain(twin).chain(decoded).collect()
own.into_iter().chain(decoded).collect()
}
fn give_back(&self, moves: Vec<FirstMove>) {
for first in moves {
let twin = (self.twin.as_deref()).filter(|twin| twin.raw.get() == first.image);
let decoded = (self.decoded.as_deref().into_iter())
.chain(self.second.get().map(Box::as_ref))
.map(|decoded| &decoded.image)
.find(|decoded| decoded.raw.get() == first.image);
let image = twin.or(decoded).unwrap_or(self);
let image = decoded.unwrap_or(self);
// A rebind may have swapped another `VkImage` in meanwhile, whose move it noted.
if image.holds(first.image) {
let mut waiting = lock(&image.first_move);
@@ -1412,10 +1377,6 @@ pub(super) enum Owner {
/// the image goes with it, the memory stays the heap's, and an automatic heap takes the range
/// back.
Heap(Box<heap::HeapPlace>),
/// The runtime made the depth twin of a heap texture in the heap's memory, inside the texture's
/// range (`texture/heap.rs`): the image goes with it; the memory and the range are the
/// texture's image's.
HeapTwin,
/// The runtime made a heap's depth or stencil image in memory of its own, a shadow of the
/// heap's bytes in the texture's range (`texture/heap.rs`): the image and its memory go with
/// it, and an automatic heap takes the range back.
@@ -1459,9 +1420,7 @@ impl Owner {
Owner::HeapShadow(shadow) => (true, Some(&shadow.placement)),
Owner::HeapUnaliased(unaliased) => (true, Some(&unaliased.placement)),
Owner::ViewShadow(shadow) => (true, Some(&shadow.placement)),
Owner::Buffer { .. } | Owner::Sparse(_) | Owner::Heap(_) | Owner::HeapTwin => {
(true, None)
}
Owner::Buffer { .. } | Owner::Sparse(_) | Owner::Heap(_) => (true, None),
Owner::Caller(_) => (false, None),
}
}
@@ -1520,17 +1479,16 @@ fn image_error(call: &'static str, refusal: ImageRefusal) -> Error {
}
}
/// `plan`, the image of a texture of `layout` and Metal `usage` (with a depth twin where `twin`),
/// with the storage usage a texture without `ShaderWrite` or `ShaderAtomic` lacks, and the
/// sampled usage one without `ShaderRead` lacks, each where `take` takes it: the candidate is the
/// image the texture with the usage would have, offered (`take(plan, candidate)`, which answers
/// the plan to go on with) only where it keeps the image's format and twin and has every usage
/// `plan` has. Plain Metal writes and reads such a texture (`Device::with_undeclared_usage`).
/// `plan`, the image of a texture of `layout` and Metal `usage`, with the storage usage a texture
/// without `ShaderWrite` or `ShaderAtomic` lacks, and the sampled usage one without `ShaderRead`
/// lacks, each where `take` takes it: the candidate is the image the texture with the usage would
/// have, offered (`take(plan, candidate)`, which answers the plan to go on with) only where it
/// keeps the image's format and has every usage `plan` has. Plain Metal writes and reads such a
/// texture (`Device::with_undeclared_usage`).
fn undeclared_usage(
mut plan: ImagePlan,
layout: &TextureLayout,
usage: TextureUsage,
twin: bool,
facts: &ImageFacts<'_>,
mut take: impl FnMut(ImagePlan, ImagePlan) -> Result<ImagePlan, Error>,
) -> Result<ImagePlan, Error> {
@@ -1551,14 +1509,10 @@ fn undeclared_usage(
continue;
}
// A texture over memory it is given takes the usage too, of a padded format among them.
let Ok((candidate, candidate_twin)) = plan_images(layout, usage | metal, false, facts)
else {
let Ok(candidate) = plan_image(layout, usage | metal, false, facts) else {
continue;
};
if candidate.format != plan.format
|| candidate_twin.is_some() != twin
|| !candidate.usage.contains(vk | plan.usage)
{
if candidate.format != plan.format || !candidate.usage.contains(vk | plan.usage) {
continue;
}
plan = take(plan, candidate)?;
@@ -1733,12 +1687,8 @@ impl Device {
.shared()
.textures
.facts(self.compile_device().profile());
let (mut plan, twin) = plan_images(&layout, descriptor.image_usage(), false, &facts)
let mut plan = plan_image(&layout, descriptor.image_usage(), false, &facts)
.map_err(|refusal| image_error(call, refusal))?;
if twin.is_some() {
// A depth twin would need its own memory bound alike.
return Err(Error::NotImplemented(RuntimeGap::SparseHeaps));
}
// An ASTC, ETC2, EAC or 4:2:2 carrier's samples read a decoded twin, which tiles GPU
// commands map would leave behind (`astc.rs`, `etc.rs`, `chroma_pairs.rs`).
if super::astc::decode_of(&plan).is_some()
@@ -1912,14 +1862,12 @@ impl Device {
views: Mutex::new(KeyMap::default()),
own_views: Mutex::new(KeyMap::default()),
resolves: KeptResolves::new(),
twin: None,
decoded: None,
second: OnceLock::new(),
form: Default::default(),
kept_outside: AtomicBool::new(false),
host_shadow: Mutex::default(),
between: OnceLock::new(),
signed_depth: AtomicBool::new(false),
detached: Mutex::new(None),
first_move: Mutex::new(Some(first)),
host_copies: false,
@@ -2041,14 +1989,12 @@ impl Device {
views: Mutex::new(KeyMap::default()),
own_views: Mutex::new(KeyMap::default()),
resolves: KeptResolves::new(),
twin: None,
decoded: None,
second: OnceLock::new(),
form: Default::default(),
kept_outside: AtomicBool::new(false),
host_shadow: Mutex::default(),
between: OnceLock::new(),
signed_depth: AtomicBool::new(false),
detached: Mutex::new(None),
first_move: Mutex::new(Some(first)),
host_copies: false,
@@ -2081,23 +2027,22 @@ impl Device {
tile_map.buffer.fill_first_from(staging, length)
}
/// `plan`, the image of a texture of `layout` and Metal `usage` (with a depth twin where
/// `twin`), with the storage usage a texture without `ShaderWrite` or `ShaderAtomic` lacks,
/// and the sampled usage one without `ShaderRead` lacks, each where it costs the image
/// nothing (`if_free`: the same memory size and alignment): plain Metal writes and reads such
/// a texture (an M4 under macOS 27.0.1; its validation stops them), and a valid program's
/// texture keeps its compression. The candidate is the image the texture with the usage would
/// have, taken only where it keeps the image's format and twin; elsewhere a binding that needs
/// the usage is the runtime's gap (`Feature::UndeclaredTextureUsage`, `binding_view`).
/// `plan`, the image of a texture of `layout` and Metal `usage`, with the storage usage a
/// texture without `ShaderWrite` or `ShaderAtomic` lacks, and the sampled usage one without
/// `ShaderRead` lacks, each where it costs the image nothing (`if_free`: the same memory size
/// and alignment): plain Metal writes and reads such a texture (an M4 under macOS 27.0.1; its
/// validation stops them), and a valid program's texture keeps its compression. The candidate
/// is the image the texture with the usage would have, taken only where it keeps the image's
/// format; elsewhere a binding that needs the usage is the runtime's gap
/// (`Feature::UndeclaredTextureUsage`, `binding_view`).
fn with_undeclared_usage(
&self,
plan: ImagePlan,
layout: &TextureLayout,
usage: TextureUsage,
twin: bool,
facts: &ImageFacts<'_>,
) -> Result<ImagePlan, Error> {
undeclared_usage(plan, layout, usage, twin, facts, |plan, candidate| {
undeclared_usage(plan, layout, usage, facts, |plan, candidate| {
self.if_free(plan, candidate, layout.texture_type)
})
}
@@ -2152,39 +2097,28 @@ impl Device {
.textures
.facts(self.compile_device().profile());
let mut usage = descriptor.own_image_usage();
let (mut plan, mut twin) = plan_images(&layout, usage, memoryless, &facts)
let mut plan = plan_image(&layout, usage, memoryless, &facts)
.map_err(|refusal| image_error(call, refusal))?;
// An image whose copies would rewrite texels Metal keeps is made uncompressed.
if let Some(exact) = self.copy_exact_usage(descriptor, &layout, plan.format, usage) {
usage = exact;
(plan, twin) = plan_images(&layout, usage, memoryless, &facts)
plan = plan_image(&layout, usage, memoryless, &facts)
.map_err(|refusal| image_error(call, refusal))?;
}
let plan = match memoryless {
true => plan,
false => self.with_undeclared_usage(plan, &layout, usage, twin.is_some(), &facts)?,
false => self.with_undeclared_usage(plan, &layout, usage, &facts)?,
};
let plan = self.with_free_usage(plan, layout.texture_type)?;
let mut image = self.new_texture_image(plan, &layout, descriptor, hazard)?;
let image = self.new_texture_image(plan, &layout, descriptor, hazard)?;
// A multisampled depth the device renders faster out of `GENERAL` rests in the attachment
// layout between the passes that hold it (`texture/held_depth.rs`).
let private = storage == StorageMode::Private;
if private && twin.is_none() && held_depth::eligible(self, &image.plan) {
if private && held_depth::eligible(self, &image.plan) {
let raw = image.raw.get();
let held = held_depth::HeldImage::of_plan(image.identity.key, raw, &image.plan);
self.shared().textures.held.insert(held);
}
if let Some(twin) = twin {
let twin = self.new_texture_image(twin, &layout, descriptor, hazard)?;
image.twin = Some(Box::new(twin));
self.degrade_depth_twin(&layout, &facts, true);
} else if image.plan.pixel_format == PixelFormat::Depth32Float
&& image.plan.format == Format::R32_SFLOAT
{
// A multisampled `Depth32Float` texture held in colour, with no twin beside it
// (`MultisampleDepthTwinPolicy::Exact`).
self.degrade_depth_twin(&layout, &facts, false);
}
let image = match memoryless {
true => {
self.degrade_block_decode(&layout);
@@ -2319,8 +2253,7 @@ impl Device {
// compressed, and its memory is the buffer's, so the usage costs it nothing.
// Else the image without it, and else the shadow, with it where that costs the
// shadow nothing.
let wider =
undeclared_usage(plan.clone(), layout, usage, false, &facts, |_, w| Ok(w))?;
let wider = undeclared_usage(plan.clone(), layout, usage, &facts, |_, w| Ok(w))?;
// The plans a linear image aliasing the bytes is tried with, the first the device
// makes: with the feedback loop usage a draw takes that reads the texture its own
// pass renders through a snapshot (`feedback_candidate`,
@@ -2356,7 +2289,7 @@ impl Device {
}
}
};
let plan = self.with_undeclared_usage(plan, layout, usage, false, &facts)?;
let plan = self.with_undeclared_usage(plan, layout, usage, &facts)?;
if !plan
.usage
.contains(ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST)
@@ -2721,14 +2654,12 @@ impl Device {
views: Mutex::new(KeyMap::default()),
own_views: Mutex::new(KeyMap::default()),
resolves: KeptResolves::new(),
twin: None,
decoded: None,
second: OnceLock::new(),
form: Default::default(),
kept_outside: AtomicBool::new(false),
host_shadow: Mutex::default(),
between: OnceLock::new(),
signed_depth: AtomicBool::new(false),
detached: Mutex::new(None),
first_move: Mutex::new(None),
host_copies: false,
@@ -2770,14 +2701,12 @@ impl Device {
views: Mutex::new(KeyMap::default()),
own_views: Mutex::new(KeyMap::default()),
resolves: KeptResolves::new(),
twin: None,
decoded: None,
second: OnceLock::new(),
form: Default::default(),
kept_outside: AtomicBool::new(false),
host_shadow: Mutex::default(),
between: OnceLock::new(),
signed_depth: AtomicBool::new(false),
detached: Mutex::new(None),
first_move: Mutex::new(None),
host_copies: false,
@@ -3175,14 +3104,12 @@ impl Device {
views: Mutex::new(KeyMap::default()),
own_views: Mutex::new(KeyMap::default()),
resolves: KeptResolves::new(),
twin: None,
decoded: None,
second: OnceLock::new(),
form: Default::default(),
kept_outside: AtomicBool::new(false),
host_shadow: Mutex::default(),
between: OnceLock::new(),
signed_depth: AtomicBool::new(false),
detached: Mutex::new(None),
first_move: Mutex::new(None),
host_copies,
@@ -3435,8 +3362,7 @@ impl Device {
/// (`heap_tiled::fresh_pattern`, all ones) exactly into an image of `format`: each of the
/// image's copy units is a stencil one, a depth one of `pf`'s depth bytes (a 32-bit float
/// depth on a device whose depth images keep a copied value outside `[0, 1]`,
/// `ImageFacts::depth_clamps`; its NaN too), or a colour one of them (a depth twin's
/// `R32_SFLOAT` image).
/// `ImageFacts::depth_clamps`; its NaN too).
fn ones_write(&self, format: Format, pf: PixelFormat) -> bool {
let facts = self
.shared()
@@ -3456,7 +3382,6 @@ impl Device {
ImageAspectFlags::DEPTH => {
bytes == depth && (depth == 2 || !facts.depth_clamps())
}
ImageAspectFlags::COLOR => bytes == depth,
_ => false,
}
})
@@ -3535,34 +3460,6 @@ impl Device {
}
impl Device {
/// Announce `depth-twin` for a texture of `layout` whose texels are held in an `R32_SFLOAT`
/// image on a device with `facts`: why the texture is
/// (`plan_depth_twin` and `holds_multisample_depth_in_colour` hold the texels there only
/// where the facts state a loss), and, where `twin`, that a comparison reads the `D32_SFLOAT`
/// twin beside it. A multisampled texture has no twin: Metal reads a `depth2d_ms` and
/// compares nothing.
pub(super) fn degrade_depth_twin(
&self,
layout: &TextureLayout,
facts: &ImageFacts<'_>,
twin: bool,
) {
let loss = facts.depth_loss().unwrap_or_default();
self.degrade(Degradation::DepthTwin, || {
let [width, height, depth] = layout.extent;
let object = format!(
"{:?} {:?} texture of {width}x{height}x{depth}",
layout.pixel_format, layout.texture_type
);
let compared = match twin {
true => ", and the comparisons the device makes read a D32_SFLOAT twin",
false => ", which every read of it reads",
};
let why = format!("{loss}: its texels are held in an R32_SFLOAT image{compared}");
(object, why)
});
}
/// Announce `compressed-texel-decode` for a texture of `layout` in a BC format made on a
/// device whose driver is not measured to decode its texels as Metal does (the format's
/// [`block_decode_fact`]).
@@ -3651,8 +3548,7 @@ impl Heap {
/// a multiple of [`Device::heap_texture_size_and_align`]'s alignment, taking that call's size
/// of the heap, its bytes the heap's memory as they are; its options are the heap's (a tracking
/// mode named other than the heap's becomes the heap's, as plain Metal makes it). A texture
/// buffer is a buffer of the heap's there with the texture over its bytes, and a texture the
/// device holds with a depth twin takes the twin's bytes too. Refused: what
/// buffer is a buffer of the heap's there with the texture over its bytes. Refused: what
/// `heap_texture_size_and_align` refuses; a storage or CPU cache mode other than the heap's
/// (`Invalid`, as Metal ends the process); a heap whose memory the image cannot lie in
/// (`NotImplemented(HeapTextureMemory)`); no room (`OutOfMemory(Heap)`).
@@ -3690,9 +3586,8 @@ impl Heap {
/// refuses); a texture whose unmapped texels the runtime cannot zero: a single-sampled one of a
/// format the device copies nothing into, a multisampled one of a format it does not clear and
/// render (`NotImplemented(SparseTileMaps)`), or past its framebuffers
/// (`Unsupported(Feature::RenderTargetSize)`); a `Depth32Float` texture that would need a depth twin
/// (`NotImplemented(SparseHeaps)`); a two-plane extended-range format (`RGB10A8_2P_XR10` and
/// its twin, `NotImplemented(Format)`).
/// (`Unsupported(Feature::RenderTargetSize)`); a two-plane extended-range format
/// (`RGB10A8_2P_XR10` and its twin, `NotImplemented(Format)`).
///
/// Refused for a placement heap, whose textures take an offset (`Invalid`, as for its
/// buffers).
@@ -4035,18 +3930,6 @@ pub(super) fn transfer_barrier(
}
}
/// `copy`, a copy between a buffer and the `R32_SFLOAT` image of a texture with a depth twin,
/// as the twin takes it: the same texels in its depth aspect.
pub(super) fn twin_copy(copy: vk::BufferImageCopy) -> vk::BufferImageCopy {
vk::BufferImageCopy {
image_subresource: vk::ImageSubresourceLayers {
aspect_mask: vk::ImageAspectFlags::DEPTH,
..copy.image_subresource
},
..copy
}
}
/// The Vulkan copy region of `region`, from the start of a tightly packed buffer.
pub(super) fn buffer_image_copy(region: &ImageRegion) -> vk::BufferImageCopy {
let [x, y, z] = region.origin;
@@ -4454,13 +4337,6 @@ impl Texture {
Ok(image.linear && lock(&image.detached).is_none())
}
/// The plan of the image holding the texture's texels in its format's aspects: its depth
/// twin's for a texture with one, else its image's. Refused as [`image`](Self::image) is.
pub(super) fn depth_plan(&self) -> Result<&ImagePlan, Error> {
let image = self.image()?;
Ok(image.twin.as_ref().map_or(image.plan(), |twin| twin.plan()))
}
/// The bytes of device memory the runtime placed the texture's image in: `None` for an image
/// in a buffer's, a heap's or the caller's memory, a sparse image (bound by unit), and where
/// [`image`](Self::image) refuses. A shadowed view's image is in memory of its own
@@ -4473,7 +4349,6 @@ impl Texture {
| Owner::Caller(_)
| Owner::Sparse(_)
| Owner::Heap(_)
| Owner::HeapTwin
| Owner::HeapShadow(_)
| Owner::HeapUnaliased(_) => None,
}
@@ -4507,36 +4382,18 @@ impl Texture {
Ok(self.image()?.raw.get())
}
/// Whether the texture's texels are in a colour image: a `Depth32Float` texture held in
/// `R32_SFLOAT`, which keeps every `float` a copy writes where the device's depth images may
/// not ([`holds_depth_in_colour`] for which plans those are). `false` for every other
/// texture.
pub(super) fn holds_depth_in_colour(&self) -> bool {
self.image()
.is_ok_and(|image| holds_depth_in_colour(image.plan()))
}
/// The `VkImage` of the texture's depth twin, or `None` for a texture without one.
pub(super) fn twin_image(&self) -> Option<vk::Image> {
Some(self.image().ok()?.twin.as_ref()?.raw.get())
}
/// Announce what `call`'s upload into `aspect` of the texture's image may store otherwise than
/// Metal's, in the depth of a 32-bit float depth image: on a device without
/// `VK_EXT_depth_range_unrestricted` enabled whose driver is not measured to keep a value
/// outside `[0, 1]` there (`ImageFacts::depth_clamps`), `restricted-depth-upload`. On any
/// other, an upload that may store a negative value or a NaN (`signed`) in a render target's
/// depth, which a depth test reads, switches it on to render over its magnitude stand-in, so
/// the device's test answers as Metal's, which compares the value's magnitude
/// (`texture/signed_depth.rs`; `encoding` where a command buffer of the program's records the
/// upload); a target that takes no stand-in announces `signed-depth-test`. A texture with a
/// depth twin holds its texels in colour (its twin's clamping is announced with the twin).
/// depth, which a depth test reads, `signed-depth-test`
/// ([`degrade_signed_depth`](Self::degrade_signed_depth)).
pub(super) fn degrade_depth_upload(
&self,
call: &'static str,
aspect: ImageAspectFlags,
signed: bool,
encoding: bool,
) {
let Ok(image) = self.image() else {
return;
@@ -4561,84 +4418,91 @@ impl Texture {
(format!("a {format:?} texture"), why)
});
} else if signed {
self.degrade_signed_depth(call, encoding);
self.degrade_signed_depth(call);
}
}
/// Switch the texture's depth on for `call`'s write into it, which may store a negative value
/// or a NaN, on a device that keeps such a value in a depth image (`texture/signed_depth.rs`;
/// `encoding` where a command buffer of the program's records the write): a render target's
/// 32-bit float depth, which a depth test reads and a pass with depth writes stores. One whose
/// device's depth test then answers as Metal's (it takes the magnitude stand-in, or the
/// device's test is Metal's own, `DriverFact::DepthTestComparesMagnitudes`) announces
/// nothing; one that takes no stand-in (multisampled, or a combined depth/stencil format)
/// announces `signed-depth-test`, as the device's test compares the value as it is, where
/// Metal's compares its magnitude, and names whether its passes' stores are Metal's (the
/// strip) or keep the sign.
pub(super) fn degrade_signed_depth(&self, call: &'static str, encoding: bool) {
let Ok(image) = self.image() else {
/// Announce `signed-depth-test` for `call`'s write into the texture, which may store a negative
/// value or a NaN, on a device that keeps such a value in a depth image: a render target's
/// 32-bit float depth, which a depth test reads and a pass with depth writes stores. Metal's
/// test compares the stored value's magnitude, and Metal's pass with depth writes stores the
/// words no fragment wrote without their signs; the device's test compares the value as it
/// is, and its pass keeps every bit. Not where the device's depth test and pass are Metal's
/// own (`DriverFact::DepthTestComparesMagnitudes`: MoltenVK), where only a pass that sets a
/// state with depth writes but draws under none differs
/// ([`degrade_kept_signs`](Self::degrade_kept_signs)).
pub(super) fn degrade_signed_depth(&self, call: &'static str) {
let Some(facts) = self.keeps_signed_depth() else {
return;
};
if facts.test_magnitudes {
return;
}
let format = self.pixel_format();
self.device().degrade(Degradation::SignedDepthTest, || {
let why = format!(
"{call} may store a negative or NaN depth in a render target's depth image, which \
the device's depth test compares as it is, where Metal's compares its magnitude, \
and which a pass with depth writes keeps with its sign, where Metal stores it \
without"
);
(format!("a {format:?} texture"), why)
});
}
/// Announce `signed-depth-test` for a pass that loads and stores the texture's depth and sets
/// a depth/stencil state with depth writes but draws under none, on a device whose depth test
/// and pass are Metal's own (`DriverFact::DepthTestComparesMagnitudes`: MoltenVK, which hands
/// the state to the GPU's pass only with a draw): the pass keeps the signs of a negative or
/// NaN depth, where Metal's stores the words without them. Measured through MoltenVK on the
/// M3 Max: an indirect draw whose arguments draw no instances hands it the state.
pub(crate) fn degrade_kept_signs(&self) {
let Some(facts) = self.keeps_signed_depth() else {
return;
};
if !facts.test_magnitudes {
return;
}
let format = self.pixel_format();
self.device().degrade(Degradation::SignedDepthTest, || {
let why = "a pass that loads and stores a render target's depth, which may hold a \
negative or NaN value, sets a depth/stencil state with depth writes but \
draws under none, so it keeps the value's sign, where Metal stores it \
without"
.to_owned();
(format!("a {format:?} texture"), why)
});
}
/// The facts of the device's depth images where the texture is a render target whose image
/// holds a 32-bit float depth that keeps a negative value or a NaN (the device does not clamp
/// such an upload, `ImageFacts::depth_clamps`); `None` for any other texture.
fn keeps_signed_depth(&self) -> Option<DepthImageFacts> {
let image = self.image().ok()?;
let float_depth = matches!(
image.plan().format,
Format::D32_SFLOAT | Format::D32_SFLOAT_S8_UINT
);
if !float_depth
|| !self.usage().contains(TextureUsage::RENDER_TARGET)
|| self.switch_on_signed_depth(call, encoding)
{
return;
if !float_depth || !self.usage().contains(TextureUsage::RENDER_TARGET) {
return None;
}
let device = self.device();
let profile = device.compile_device().profile();
let facts = device.shared().textures.facts(profile);
if facts.depth_clamps() {
return;
}
let stripped = self.magnitude_form().is_some();
let format = self.pixel_format();
device.degrade(Degradation::SignedDepthTest, || {
let why = match (facts.depth_images.test_magnitudes, stripped) {
(false, true) => format!(
"{call} may store a negative or NaN depth in a render target's depth image, \
which the device's depth test compares as it is, where Metal's compares its \
magnitude: a multisampled or combined depth/stencil target renders over no \
magnitude stand-in (a pass with depth writes stores it without its sign, as \
Metal's)"
),
(false, false) => format!(
"{call} may store a negative or NaN depth in a render target's depth image, \
which the device's depth test compares as it is, where Metal's compares its \
magnitude, and which a pass with depth writes keeps with its sign, where \
Metal stores it without"
),
(true, _) => format!(
"{call} may store a negative or NaN depth in a render target's depth image, \
which a pass with depth writes that draws under none keeps with its sign, \
where Metal stores it without"
),
};
(format!("a {format:?} texture"), why)
});
let facts = device
.shared()
.textures
.facts(device.compile_device().profile());
(!facts.depth_clamps()).then_some(facts.depth_images)
}
/// Announce `depth-denormals` for `call`'s write into `aspect` of the texture's image that may
/// store a denormal (`on_host`: by a host copy): the 32-bit float depth of a depth image, on
/// a device whose driver may store it or test it otherwise than Metal's
/// ([`ImageFacts::denormal_loss`]). A texture with a depth twin holds its texels in colour.
/// Where the driver stores it and only its depth test compares it otherwise, a render target
/// that takes a magnitude stand-in is switched on (`texture/signed_depth.rs`, `encoding` as
/// [`degrade_depth_upload`](Self::degrade_depth_upload) takes it): its passes test the
/// smallest normal in a denormal's place, Metal's answer but for a fragment at exactly 2^-126,
/// which the notice names. A host copy's denormal on a driver whose GPU copies store one as a
/// zero switches it on too, but the stand-in's copies read it as a zero: the notice names the
/// loss.
/// ([`ImageFacts::denormal_loss`]).
pub(super) fn degrade_depth_denormals(
&self,
call: &'static str,
aspect: ImageAspectFlags,
on_host: bool,
encoding: bool,
) {
let Ok(image) = self.image() else {
return;
@@ -4656,24 +4520,9 @@ impl Texture {
let Some(loss) = facts.denormal_loss(on_host) else {
return;
};
let stored = on_host || facts.depth_images.denormals;
let switched = stored
&& self.usage().contains(TextureUsage::RENDER_TARGET)
&& self.switch_on_signed_depth(call, encoding)
&& self.takes_magnitude_stand_in();
// The stand-in's copies keep a denormal only where the device's GPU copies do.
let tested = switched && facts.depth_images.denormals;
device.degrade(Degradation::DepthDenormals, || {
let format = self.pixel_format();
let why = match tested {
true => format!(
"{call} may store a denormal depth in a render target, whose passes test it \
over the smallest normal, as the device's depth test compares a stored \
denormal as zero: a fragment at exactly 2^-126 passes `Equal` and fails \
`Greater` against it, where Metal's fails and passes"
),
false => format!("{call} may store a denormal depth: {loss}"),
};
let why = format!("{call} may store a denormal depth: {loss}");
(format!("a {format:?} texture"), why)
});
}
@@ -4687,20 +4536,13 @@ impl Texture {
desc: &ImageViewDesc,
storage: bool,
) -> Result<vk::ImageView, Error> {
let mut image: &Image = self.image()?;
let image: &Image = self.image()?;
// A sampled view of a texture with a decoded twin presents the twin.
if !storage {
if let Some(view) = self.decoded_view(call, image, desc)? {
return Ok(view);
}
}
// A view a comparison reads presents the texture's depth twin.
if desc.twin {
image = image
.twin
.as_deref()
.ok_or_else(|| internal("a depth twin's view of a texture without one"))?;
}
let view = binding_view(image.plan(), &self.0.record.bound(), desc, storage)
.map_err(|refusal| view_error(call, refusal))?;
image.view(&view)
@@ -4730,12 +4572,6 @@ impl Texture {
pub(super) fn worked_out_facts(&self) -> TextureFacts {
let record = self.0.record.bound();
let mut facts = texture_facts(&record);
// A `Depth32Float` texture whose texels are in an `R32_SFLOAT` image: a sampled view
// reads the colour image, and a compared one the depth twin a single-sampled one has
// beside it (`image_plan::plan_depth_twin`). A multisampled one has no twin and no
// comparison to serve: Metal reads a `depth2d_ms` and compares nothing
// (`MultisampleDepthTwinPolicy::Exact`).
facts.depth_twin = self.holds_depth_in_colour();
facts.sparse = self.is_sparse();
// A two-plane YCbCr texture whose planes a function may read in place.
facts.ycbcr_in_place = self.0.planes_in_place.map(|p| p.words);
@@ -5474,9 +5310,7 @@ impl Texture {
/// `VK_EXT_depth_range_unrestricted` Vulkan leaves a copied value outside `[0, 1]` undefined
/// (`VUID-vkCmdCopyBufferToImage-pRegions-07931`), and a device may store such a value clamped:
/// an upload into a depth image there announces `restricted-depth-upload` unless the device's
/// driver is measured to keep it (`DriverFact::DepthImageKeepsValuesOutsideUnitRange`). A
/// texture with a depth twin keeps it: its image is `R32_SFLOAT`, and its twin, which its
/// comparisons read, takes the same bytes.
/// driver is measured to keep it (`DriverFact::DepthImageKeepsValuesOutsideUnitRange`).
pub fn replace_region(
&self,
region: Region,
@@ -5578,19 +5412,7 @@ impl Texture {
// Bytes that hold a negative or NaN depth, which a depth test compares otherwise.
let signed = image_region.aspect == ImageAspectFlags::DEPTH
&& host.holds_negative_or_nan(bytes.slice());
self.degrade_depth_upload(CALL, image_region.aspect, signed, false);
// Bytes whose magnitude stand-in is not themselves (-0, a negative denormal, and, where the
// device's depth test compares a denormal as zero, a positive one) switch a render
// target's depth on too (`texture/signed_depth.rs`): none of them is announced as a sign.
if image_region.aspect == ImageAspectFlags::DEPTH
&& !signed
&& self.usage().contains(TextureUsage::RENDER_TARGET)
{
let flush = signed_depth::test_flushes_denormals(self.device());
if host.holds_unlike_its_stand_in(bytes.slice(), flush) {
self.switch_on_signed_depth(CALL, false);
}
}
self.degrade_depth_upload(CALL, image_region.aspect, signed);
// Bytes that hold a denormal depth, announced as the copy below stores them.
let denormal =
image_region.aspect == ImageAspectFlags::DEPTH && host.holds_denormal(bytes.slice());
@@ -5613,13 +5435,13 @@ impl Texture {
};
if truth.host_write(copy, &packed)? {
if denormal {
self.degrade_depth_denormals(CALL, image_region.aspect, true, false);
self.degrade_depth_denormals(CALL, image_region.aspect, true);
}
return truth.decode_written(&image_region, || packed.into_owned());
}
}
if denormal {
self.degrade_depth_denormals(CALL, image_region.aspect, false, false);
self.degrade_depth_denormals(CALL, image_region.aspect, false);
}
// Packed into the staging buffer from the caller's bytes.
if truth.takes_staging_copies()
@@ -5648,11 +5470,7 @@ impl Texture {
buffer_offset: copy.buffer_offset + start,
..copy
};
let mut copies = vec![(truth.raw.get(), copy)];
// The depth twin takes the same texels.
if let Some(twin) = self.twin_image() {
copies.push((twin, twin_copy(copy)));
}
let copies = vec![(truth.raw.get(), copy)];
let staged = TexelCopy::new(source, host.packed_len(), copies, Box::new(staging));
// The decoded twin's texels of the region, after the copy.
let regions = std::slice::from_ref(&image_region);
@@ -5674,7 +5492,7 @@ impl Texture {
bytes.pack(&host, packed);
// As above: the copy below writes the image these bytes.
truth.shadow_written(&image_region, &unit, packed);
let (buffer, twin, image) = (staging.raw, self.twin_image(), truth.raw.get());
let (buffer, image) = (staging.raw, truth.raw.get());
// The decoded twin's texels of the region, after the copy; the submission is waited for.
let decode = truth.decode_pass(std::slice::from_ref(&image_region), PassScratch::Own)?;
truth.submit_copy(|raw, command_buffer| {
@@ -5689,16 +5507,6 @@ impl Texture {
vk::ImageLayout::GENERAL,
&[copy],
);
// The depth twin takes the same texels.
if let Some(twin) = twin {
raw.cmd_copy_buffer_to_image(
command_buffer,
buffer,
twin,
vk::ImageLayout::GENERAL,
&[twin_copy(copy)],
);
}
}
transfer_barrier(raw, command_buffer, false);
if let Some(decode) = &decode {
@@ -663,7 +663,7 @@ impl FirstFill {
}
}
/// A host call's copy of texels into an image (and into its depth twin), staged: `replace_region`'s
/// A host call's copy of texels into an image, staged: `replace_region`'s
/// where the image takes no host copies (`Texture::replace_region`).
pub(crate) struct TexelCopy {
source: vk::Buffer,
+115 -234
View File
@@ -13,28 +13,26 @@
//! model has none. It depends on the device and the descriptor alone, never on what was
//! allocated.
//!
//! The texture is held to that answer in one of two ways ([`images_fit`]). Where the images the
//! The texture is held to that answer in one of two ways ([`images_fit`]). Where the image the
//! runtime makes of the descriptor (the plan `new_texture` makes, with the usage the runtime
//! adds itself, `with_free_usage`, and a depth twin past it) ask no more bytes and no coarser
//! alignment, the image is bound at the texture's offset of the heap's memory. Their footprint
//! is the images' own: a heap's image takes **no** `bufferImageGranularity` padding, because the
//! heap's own buffer covers its memory from end to end, so no padding can put the image in a
//! granularity page no buffer lies in and the padding would only widen the answer
//! (`texture::ImagePlacement::in_heap`; every NVIDIA profile in `validation/profiles` states a
//! granularity of 1024 bytes where Metal answers 128). Where the driver answers a compressed
//! image's size short of its compression data (ANV on Intel's Xe-LP GPUs) the footprint still
//! takes whole 256-byte chunks of the aux map's, so no other resource lies in a chunk the image
//! writes. Where the images ask more, the texture is a shadow of its bytes with its image in
//! memory of its own (Metal's tiles where they serve, else rows) and takes Metal's answer all
//! the same; where no shadow serves, the answer is the larger of the two and the device
//! announces `heap-texture-larger-than-metal` once (a measured route's answer is refused
//! instead, `NotImplemented(HeapTextureMemory)`: its bytes are no layout the device's image
//! holds).
//! The usage changes Metal's answer only through whether Metal compresses the texture
//! (`heap_tiled::metal_keeps_uncompressed`, a colour texture of `ShaderWrite`, `PixelFormatView`
//! or `ShaderAtomic` usage stays uncompressed, a depth or stencil texture of no usage does), and
//! the runtime plans an image Metal keeps uncompressed so its driver keeps it so (`image_plan`),
//! so the image is no larger than Metal's answer.
//! adds itself, `with_free_usage`) asks no more bytes and no coarser alignment, the image is
//! bound at the texture's offset of the heap's memory. Its footprint is the image's own: a heap's
//! image takes **no** `bufferImageGranularity` padding, because the heap's own buffer covers its
//! memory from end to end, so no padding can put the image in a granularity page no buffer lies
//! in and the padding would only widen the answer (`texture::ImagePlacement::in_heap`; every
//! NVIDIA profile in `validation/profiles` states a granularity of 1024 bytes where Metal answers
//! 128). Where the driver answers a compressed image's size short of its compression data (ANV on
//! Intel's Xe-LP GPUs) the footprint still takes whole 256-byte chunks of the aux map's, so no
//! other resource lies in a chunk the image writes. Where the images ask more, the texture is a
//! shadow of its bytes with its image in memory of its own (Metal's tiles where they serve, else
//! rows) and takes Metal's answer all the same; where no shadow serves, the answer is the larger
//! of the two and the device announces `heap-texture-larger-than-metal` once (a measured route's
//! answer is refused instead, `NotImplemented(HeapTextureMemory)`: its bytes are no layout the
//! device's image holds). The usage changes Metal's answer only through whether Metal compresses
//! the texture (`heap_tiled::metal_keeps_uncompressed`, a colour texture of `ShaderWrite`,
//! `PixelFormatView` or `ShaderAtomic` usage stays uncompressed, a depth or stencil texture of no
//! usage does), and the runtime plans an image Metal keeps uncompressed so its driver keeps it so
//! (`image_plan`), so the image is no larger than Metal's answer.
//! - **Multisample textures over host pages**, and in any heap whose memory its optimal image does
//! not take where the device's linear images cannot hold it (an NVIDIA GPU's `Shared` heap; a
//! depth texture of a `Shared` heap on MoltenVK, whose optimal depth images take no host-visible
@@ -94,13 +92,13 @@
//! out as Metal does. Where no such shadow serves it — a multisample texture whose samples the
//! device does not move, a texture whose levels of all its parts pass the moves one shadow holds
//! (`HeapTiledCopies::fit`: 16, so a two-aspect texture of 9 levels asks 18) or whose moves pass
//! the device's limits, a depth twin, a layout not measured — its image keeps that layout, so
//! the device's limits, a layout not measured — its image keeps that layout, so
//! the heap's bytes are not Metal's layout of its texels, and the device announces
//! `optimized-depth-stencil-texture` once. The **answer** there is Metal's own still wherever
//! the runtime models it and the texture is held to it ([`held_to_metal`]: a shadow of the
//! heap's bytes in rows, or an image apart from them that takes none of its bytes, such as a
//! multisample texture's); it is the larger of the images' and Metal's only for a texture no
//! shadow holds to Metal's answer, a depth twin among them, which is the cost that notice names.
//! shadow holds to Metal's answer, which is the cost that notice names.
//! - **The heap's memory.** A heap's buffer lies at a multiple of [`HEAP_BASE_ALIGNMENT`] of its
//! memory (256 KiB, the largest image alignment measured), of a type optimal images take where
//! its storage class has one, else of one linear images take ([`HeapTypes::heap_memory`],
@@ -136,14 +134,6 @@
//! Metal's tracking at the granularity of the heap orders a buffer's write before an
//! overlapping texture's read. A new texture holds what its bytes held: the image is moved to
//! the `GENERAL` layout and not cleared.
//! - **Depth twins**. A `Depth32Float` texture the device holds with a depth twin takes both images
//! of the heap: the image at the texture's offset and the twin past it, at the next multiple of
//! the twin's alignment ([`heap_extent`]), so the answered size covers both and the texture's
//! bytes are its range alone, as Metal's placement and aliasing rules need (a Metal heap probe on
//! the M3 Max and an M4: two `Depth32Float` textures side by side keep their texels, and a buffer
//! filled over the first changes every texel of it and none of the second's). Each image takes
//! the heap's memory or its linear tiling as above. Both are the heap buffer's resource to hazard
//! tracking, and `depth-twin` is announced as for `new_texture`.
//! - **Depth and stencil images apart**. On a driver that lays depth and stencil images apart from
//! the memory they are bound to ([`DriverFact::DepthStencilImagesLieApart`]: MoltenVK, measured),
//! a heap's single-sample depth or stencil texture of a format whose layout is measured
@@ -156,8 +146,8 @@
//! uncompressed tiles, announced `heap-texture-lossless-layout` per texture. So is one whose
//! image the heap's memory takes none of, as below, and one whose image the driver keeps
//! GPU-optimized where Metal's is not, a multisample one too (its samples, above). Any other such
//! image, its own or its twin, is a shadow of the heap's bytes in rows (`AliasRoute::Shadow`), or,
//! where no shadow serves (a depth twin), aliases none of the heap's other resources, and the
//! image is a shadow of the heap's bytes in rows (`AliasRoute::Shadow`), or, where no shadow
//! serves, aliases none of the heap's other resources, and the
//! device announces `heap-depth-stencil-apart` once when it makes one.
//! - **Heaps over the device's memory**. A texture whose image is bound in such a heap's memory
//! lies there in the driver's layout. On a driver whose single-sample colour images lie as Metal
@@ -192,8 +182,8 @@
//! near-equivalent (`heap-texture-hides-aliased-writes`). The first two keep Metal's visibility
//! contract, not a byte layout: a write through a buffer or texture over the texture's bytes
//! changes every texel it covers, and the texture's writes show in those bytes, in the device's
//! layout for the image, as Metal's are in its GPU's. Depth and stencil images and depth twins
//! keep their optimal images: a buffer's write over ANV's changed every texel (the heap depth
//! layout for the image, as Metal's are in its GPU's. Depth and stencil images keep their
//! optimal images: a buffer's write over ANV's changed every texel (the heap depth
//! lane).
//! - **Texture buffers**. A heap's texture buffer is a buffer of the heap's at the texture's
//! offset, its row of texels long, with the texture buffer over its bytes as
@@ -228,7 +218,7 @@ use crate::degradation::Degradation;
use crate::device::lock;
use crate::error::{internal, invalid, nil, vulkan, Error, MemoryKind, Nil, Problem, RuntimeGap};
use crate::heap::{Heap, HeapProblem, HeapType, SizeAndAlign, WeakHeap};
use crate::image_plan::{check_image_limits, plan_images, ImagePlan};
use crate::image_plan::{check_image_limits, plan_image, ImagePlan};
use crate::key_hash::KeyMap;
use crate::linear_plan::{check_linear_limits, linear_lack, LinearLack, LINEAR_ALIGNMENT};
use crate::memory::{Memory, MemoryClass, Placement};
@@ -492,7 +482,7 @@ impl HeapShadow {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AliasRoute {
/// As an image bound to memory: on a driver whose compressed images hide no write through
/// an alias, a depth or stencil image, a depth twin, or a linear image for the heap's memory.
/// an alias, a depth or stencil image, or a linear image for the heap's memory.
Direct,
/// An optimal colour image of host-transfer usage, which the driver keeps uncompressed
/// (`heap-texture-host-transfer`).
@@ -511,7 +501,7 @@ pub(crate) enum AliasRoute {
Shadow,
/// A depth or stencil image the driver lays apart from its memory that no shadow serves (a
/// multisampled image, which Vulkan copies to no buffer, or texels that do not fit the
/// texture's bytes; a depth twin), a near-equivalent (`heap-depth-stencil-apart`).
/// texture's bytes), a near-equivalent (`heap-depth-stencil-apart`).
Apart,
/// A texture whose image the device binds to none of the heap's memory: its optimal image
/// takes no memory type of the heap's and no linear image serves (a `Shared` heap's depth
@@ -576,18 +566,7 @@ impl AliasRoute {
}
}
/// Whose image of a heap texture an image is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mine {
/// The texture's own; a shadow of the heap's bytes may serve it where the texture is held
/// with no depth twin (`shadows`), and Metal keeps it losslessly compressed where
/// `compressed` (`heap_tiled::metal_compresses_layout`).
Texture { shadows: bool, compressed: bool },
/// The texture's depth twin.
Twin,
}
/// One image a heap texture takes of a heap: the texture's own, or its depth twin.
/// The image a heap texture takes of a heap.
struct HeapImage {
plan: ImagePlan,
/// Linear where the heap's memory is not memory the image's optimal tiling takes
@@ -627,9 +606,6 @@ struct HeapBinding {
struct HeapPlan {
layout: TextureLayout,
image: HeapImage,
/// The texture's depth twin, at this offset from the texture's: past the image's bytes, at a
/// multiple of its own alignment, inside the texture's size.
twin: Option<(HeapImage, u64)>,
size_and_align: SizeAndAlign,
/// Metal's own answer for the descriptor where the runtime knows it
/// (`heap_tiled::metal_heap_layout`, `Device::metal_heap_answer`), whatever this device
@@ -1214,33 +1190,23 @@ fn sized_as(descriptor: &TextureDescriptor) -> Option<TextureDescriptor> {
})
}
/// What a heap texture whose image has the memory requirements `image`, and its depth twin `twin`
/// where it has one, takes of a heap on a device that places images as `placement` does: the image
/// at the texture's offset and the twin past it, at the next multiple of its alignment, each placed
/// as `placement` places an image; the texture's alignment the largest of theirs and its size in
/// `placement`'s units over both, so each image's offset meets its own alignment wherever the
/// texture lies. `Device::heap_plan` passes `ImagePlacement::in_heap`, the images' own alignments
/// and sizes in whole chunks of compression data where the driver writes them past the size (so
/// no other resource lies in a chunk the image writes) and no `bufferImageGranularity` padding,
/// which separates a heap's image from nothing: the heap's own buffer covers its memory from end
/// to end. With the twin's offset from the texture's.
/// What a heap texture whose image has the memory requirements `image` takes of a heap on a
/// device that places images as `placement` does: the image at the texture's offset, placed as
/// `placement` places an image; the texture's alignment the image's and its size in
/// `placement`'s units. `Device::heap_plan` passes `ImagePlacement::in_heap`, the image's own
/// alignment and size in whole chunks of compression data where the driver writes them past the
/// size (so no other resource lies in a chunk the image writes) and no `bufferImageGranularity`
/// padding, which separates a heap's image from nothing: the heap's own buffer covers its memory
/// from end to end.
pub(crate) fn heap_extent(
image: &vk::MemoryRequirements,
twin: Option<&vk::MemoryRequirements>,
placement: ImagePlacement,
) -> (SizeAndAlign, Option<u64>) {
) -> SizeAndAlign {
let image = placement.place(*image);
let mut align = image.alignment;
let mut end = image.size;
let twin_offset = twin.map(|twin| {
let twin = placement.place(*twin);
align = align.max(twin.alignment);
let offset = end.next_multiple_of(twin.alignment);
end = offset + twin.size;
offset
});
let size = end.next_multiple_of(placement.size_unit);
(SizeAndAlign { size, align }, twin_offset)
SizeAndAlign {
size: image.size.next_multiple_of(placement.size_unit),
align: image.alignment,
}
}
/// Whether a heap texture whose images take `images` of the heap ([`heap_extent`]) lies inside
@@ -1263,8 +1229,6 @@ pub(crate) struct HeapTextureShape {
/// A 4:2:2 texture, always a shadow of the heap's bytes: its bytes lie where Metal's linear
/// rows do (`heap_plane_layout`), never where its image lays them.
pub(crate) four_two_two: bool,
/// It is held with a depth twin, whose bytes no shadow of the texture's moves.
pub(crate) twin: bool,
/// More than one sample: no copy of rows shadows its image, which lies in memory of its own
/// instead, as one the heap's memory cannot hold.
pub(crate) multisample: bool,
@@ -1298,47 +1262,33 @@ pub(crate) fn held_to_metal(
if shape.apart || (!shape.four_two_two && images_fit(images, metal)) {
return HeldToMetal::Images;
}
// A depth twin's bytes lie past the image's inside the texture's, and no shadow moves them.
if shape.twin {
return HeldToMetal::Nothing;
}
match shape.multisample || shape.shadowable {
true => HeldToMetal::Shadow,
false => HeldToMetal::Nothing,
}
}
/// Whether a heap texture whose own image takes `route`, held with a depth twin of `twin`, is
/// held to the heap's base at all ([`check_heap_base`]): an image of it binds into the heap's own
/// memory, which starts at a multiple of [`HEAP_BASE_ALIGNMENT`] alone, so an image whose
/// alignment passes that base has no offset there to bind at.
/// Whether a heap texture whose image takes `route` is held to the heap's base at all
/// ([`check_heap_base`]): an image of it binds into the heap's own memory, which starts at a
/// multiple of [`HEAP_BASE_ALIGNMENT`] alone, so an image whose alignment passes that base has no
/// offset there to bind at.
///
/// A texture whose every image lies in memory of its own ([`AliasRoute::in_own_memory`]) binds
/// nothing to the heap's memory: the heap's bytes hold the texture's own layout there and the
/// encoders move its elements to and from the image, or nothing of them
/// ([`AliasRoute::Unaliased`]). Wherever the heap's memory starts, such a texture is made, so the
/// alignment it answers is no bound on the base and refusing it would refuse a texture Metal
/// makes — the rule [`placement_align`] follows for the offset inside the heap. A depth twin's
/// image always binds to the heap's memory (`heap_image` of `Mine::Twin` reaches neither shadow
/// route), so one image of a twinned texture binds there whatever the texture's own route says.
/// A twinned texture is itself on no shadow route, by a gate of its own for each: `MemoryShadow`
/// asks `Mine::Texture { shadows: true, .. }`, which a twin clears, and `Shadow` asks `own`
/// alone but needs `!colour(&optimal)`, which the `R32_SFLOAT` image `plan_images` plans beside
/// a twin fails.
fn holds_heap_base(route: AliasRoute, twin: Option<AliasRoute>) -> bool {
!route.in_own_memory() || twin.is_some_and(|twin| !twin.in_own_memory())
/// makes — the rule [`placement_align`] follows for the offset inside the heap.
fn holds_heap_base(route: AliasRoute) -> bool {
!route.in_own_memory()
}
/// Whether a heap texture whose own image takes `route`, held with a depth twin of `twin`, and
/// whose answer is of alignment `align`, lies at a multiple of that alignment wherever a heap's
/// memory starts: refused past [`HEAP_BASE_ALIGNMENT`] (`RuntimeGap::HeapTextureAlignment`) where
/// an image of it binds into the heap's memory and nowhere else ([`holds_heap_base`]).
pub(crate) fn check_heap_base(
route: AliasRoute,
twin: Option<AliasRoute>,
align: u64,
) -> Result<(), Error> {
if holds_heap_base(route, twin) && align > HEAP_BASE_ALIGNMENT {
/// Whether a heap texture whose image takes `route`, and whose answer is of alignment `align`, lies
/// at a multiple of that alignment wherever a heap's memory starts: refused past
/// [`HEAP_BASE_ALIGNMENT`] (`RuntimeGap::HeapTextureAlignment`) where an image of it binds into the
/// heap's memory and nowhere else ([`holds_heap_base`]).
pub(crate) fn check_heap_base(route: AliasRoute, align: u64) -> Result<(), Error> {
if holds_heap_base(route) && align > HEAP_BASE_ALIGNMENT {
return Err(Error::NotImplemented(RuntimeGap::HeapTextureAlignment {
alignment: align,
}));
@@ -1485,14 +1435,13 @@ impl Device {
/// `heapTextureSizeAndAlignWithDescriptor:`: the bytes and alignment a texture of
/// `descriptor` takes of a heap on this device (the module docs). Metal's answer wherever the
/// runtime models it, so a program may size a heap and place its resources by Metal's
/// numbers; the device's images' own footprint, with a depth twin's bytes after the image's
/// where it has one and whole chunks of compression data where the driver writes them past an
/// image's size, where the model has none or no shadow holds the texture to Metal's answer
/// (then announced `heap-texture-larger-than-metal`). The image of a descriptor with
/// `allow_gpu_optimized_contents` off is one of `PixelFormatView` usage, as Metal lays out a
/// color texture with it off (the module docs). A texture of the descriptor fits at any
/// multiple of the alignment in any heap with room. A texture buffer takes Metal's answer: its
/// row of texels, at a multiple of 16 bytes.
/// numbers; the device's image's own footprint, with whole chunks of compression data where
/// the driver writes them past an image's size, where the model has none or no shadow holds the
/// texture to Metal's answer (then announced `heap-texture-larger-than-metal`). The image of a
/// descriptor with `allow_gpu_optimized_contents` off is one of `PixelFormatView` usage, as
/// Metal lays out a color texture with it off (the module docs). A texture of the descriptor
/// fits at any multiple of the alignment in any heap with room. A texture buffer takes Metal's
/// answer: its row of texels, at a multiple of 16 bytes.
///
/// A format the translator holds **no image** of, whose footprint its own structure decides
/// (`metal::format::footprint`: ASTC's 4x2 and 8x4 footprints, `BGRA4Unorm`,
@@ -1713,9 +1662,8 @@ impl Device {
Ok(self.heap_plan(call, &private, layout)?.size_and_align)
}
/// The images a heap texture of `descriptor` (checked as `layout`, not a texture buffer)
/// takes and what it takes of a heap, for `call`: its image, and its depth twin past it where
/// the device holds the texture with one.
/// The image a heap texture of `descriptor` (checked as `layout`, not a texture buffer)
/// takes and what it takes of a heap, for `call`.
fn heap_plan(
&self,
call: &'static str,
@@ -1727,7 +1675,7 @@ impl Device {
.textures
.facts(self.compile_device().profile());
let usage = descriptor.image_usage();
let (plan, twin) = plan_images(&layout, usage, false, &facts)
let plan = plan_image(&layout, usage, false, &facts)
.map_err(|refusal| image_error(call, refusal))?;
// A heap texture's samples read what its bytes hold, which an ASTC carrier's decoded twin
// would decode as it is placed (`astc.rs`): refused. The size query answers Metal's model
@@ -1737,28 +1685,22 @@ impl Device {
}
// An image whose copies would rewrite texels a CPU copy keeps is made uncompressed; the
// texture still takes the compressed image's bytes of the heap, as Metal's does.
let (plan, twin, compressed) =
let (plan, compressed) =
match self.copy_exact_usage(descriptor, &layout, plan.format, usage) {
Some(exact) => {
let (exact_plan, exact_twin) = plan_images(&layout, exact, false, &facts)
let exact_plan = plan_image(&layout, exact, false, &facts)
.map_err(|refusal| image_error(call, refusal))?;
(exact_plan, exact_twin, Some(plan))
(exact_plan, Some(plan))
}
None => (plan, twin, None),
None => (plan, None),
};
let class = buffer_class(call, Modes::of(descriptor.resource_options)?)?;
let free = self.with_free_usage(plan.clone(), layout.texture_type)?;
// A texture held with a depth twin is no shadow of the heap's bytes in rows: `shadows`
// is what holds `AliasRoute::MemoryShadow` out of one (`Shadow` is held out by its own
// image being a colour one there, `heap_image`).
let mine = Mine::Texture {
shadows: twin.is_none(),
compressed: metal_compresses_layout(
&layout,
effective_usage(descriptor.usage),
descriptor.allow_gpu_optimized_contents,
),
};
let metal_compresses = metal_compresses_layout(
&layout,
effective_usage(descriptor.usage),
descriptor.allow_gpu_optimized_contents,
);
// A two-plane texture's image is larger than Metal's answer: it lies in memory of its
// own, a shadow of its planes in the heap's bytes where Metal's layout of them is
// measured.
@@ -1776,13 +1718,19 @@ impl Device {
route,
}
} else {
match self.heap_image(free.clone(), plan, layout.texture_type, class, mine) {
match self.heap_image(
free.clone(),
plan,
layout.texture_type,
class,
metal_compresses,
) {
// A multisample texture where neither its optimal image takes the heap's memory
// nor the device's linear images can hold it (an NVIDIA GPU's `Shared` heap; a
// `Shared` heap's depth texture on MoltenVK, whose optimal images take no
// host-visible memory): its optimal image in memory of its own, as over host
// pages, a shadow of its samples in Metal's tiles there where one serves (below).
Err(error) if linear_refusal(&error) && twin.is_none() && layout.samples > 1 => {
Err(error) if linear_refusal(&error) && layout.samples > 1 => {
let requirements = self.planned_requirements(
&free,
layout.texture_type,
@@ -1798,27 +1746,15 @@ impl Device {
made => made?,
}
};
// The twin takes none of the runtime's free usage, as `new_texture`'s, and is no
// texture's image: its bytes alias nothing a program reads.
let twin = match twin {
Some(twin) => {
Some(self.heap_image(twin.clone(), twin, layout.texture_type, class, Mine::Twin)?)
}
None => None,
};
// The images' own footprint: a heap's image takes neither the granularity padding nor a
// The image's own footprint: a heap's image takes neither the granularity padding nor a
// page of its own (`ImagePlacement::in_heap`).
let placement = self.shared().textures.placement().in_heap();
let (mut size_and_align, twin_offset) = heap_extent(
&image.requirements,
twin.as_ref().map(|twin| &twin.requirements),
placement,
);
let mut size_and_align = heap_extent(&image.requirements, placement);
if let Some(compressed) = compressed {
let free = self.with_free_usage(compressed, layout.texture_type)?;
let requirements =
self.planned_requirements(&free, layout.texture_type, vk::ImageTiling::OPTIMAL)?;
let (answer, _) = heap_extent(&requirements, None, placement);
let answer = heap_extent(&requirements, placement);
size_and_align = SizeAndAlign {
size: size_and_align.size.max(answer.size),
align: size_and_align.align.max(answer.align),
@@ -1863,7 +1799,6 @@ impl Device {
AliasRoute::Unaliased | AliasRoute::Planes | AliasRoute::Lossless
),
four_two_two: chroma_pairs::is_four_two_two(layout.pixel_format),
twin: twin.is_some(),
multisample: layout.samples > 1,
shadowable: shadowable(&image.plan, metal.size),
};
@@ -1902,7 +1837,7 @@ impl Device {
// keeps losslessly compressed, its uncompressed tiles), and it takes Metal's answer.
let shadowed = matches!(image.route, AliasRoute::Shadow | AliasRoute::MemoryShadow)
|| self.keeps_optimized_layout(descriptor, &layout);
if shadowed && twin.is_none() {
if shadowed {
let tiles = shadow_tiles(&layout, image.plan.format, &metal_layout);
if let (Some(tiles), Some(answer)) = (tiles, metal_answer) {
let serves = (tiles.tiles())
@@ -1917,7 +1852,7 @@ impl Device {
// A multisample texture in memory of its own is a shadow of its samples in Metal's tiles
// there (a compressed one's uncompressed tiles), where the device moves them
// (`heap_tiled.rs`): its bytes are Metal's, and it takes Metal's answer.
if image.route == AliasRoute::Lossless && layout.samples > 1 && twin.is_none() {
if image.route == AliasRoute::Lossless && layout.samples > 1 {
let shadow = self.sample_tiles(&layout, &image.plan, &metal_layout, metal_answer)?;
if let Some((plan, tiles, answer)) = shadow {
image.plan = plan;
@@ -1928,11 +1863,7 @@ impl Device {
}
// Only a texture an image of binds into the heap's own memory is held to the heap's base,
// and the routes decide that (`holds_heap_base`).
check_heap_base(
image.route,
twin.as_ref().map(|twin| twin.route),
size_and_align.align,
)?;
check_heap_base(image.route, size_and_align.align)?;
// The size answered is the optimized texture's where the driver keeps the layout, but for
// a shadow of Metal's tiles.
if image.route != AliasRoute::Tiled {
@@ -1947,7 +1878,6 @@ impl Device {
Ok(HeapPlan {
layout,
image,
twin: twin.zip(twin_offset),
size_and_align,
metal_answer,
metal_layout,
@@ -2053,14 +1983,14 @@ impl Device {
/// where its optimal image takes the heap's memory, else `linear`, the same image without the
/// runtime's free usage, where the device's linear images can do all the optimal one can for
/// the texture, else `optimal` in memory of its own as a shadow of the heap's bytes
/// ([`AliasRoute::MemoryShadow`]) where `mine` lets one serve it and it does ([`shadowable`]),
/// else refused as the device's lack (`Unsupported(Feature::HeapTextureTiling)`).
/// ([`AliasRoute::MemoryShadow`]) where one serves it ([`shadowable`]), else refused as the
/// device's lack (`Unsupported(Feature::HeapTextureTiling)`).
///
/// The texture's own colour image (`own`, not a depth twin) on a driver whose compressed
/// images hide writes through an alias
/// A colour image on a driver whose compressed images hide writes through an alias
/// ([`DriverFact::CompressedImagesHideAliasedWrites`]), where its optimal image takes the
/// heap's memory, takes `optimal`, which the driver may compress, where Metal keeps the
/// texture losslessly compressed and the device's policy keeps the driver's compression
/// texture losslessly compressed (`compressed`, `heap_tiled::metal_compresses_layout`) and
/// the device's policy keeps the driver's compression
/// (`HeapCompressionPolicy::Compressed`, the default; [`AliasRoute::Compressed`]); else in
/// order: `optimal` with host-transfer usage, where the device enabled `hostImageCopy` (the
/// driver keeps such an image's bytes, [`DriverFact::HostTransferImagesKeepTheirBytes`]), the
@@ -2072,9 +2002,8 @@ impl Device {
linear: ImagePlan,
texture_type: TextureType,
class: MemoryClass,
mine: Mine,
compressed: bool,
) -> Result<HeapImage, Error> {
let own = matches!(mine, Mine::Texture { .. });
// The heap's memory (the same for every heap of the storage: `heap_requirements`), and
// the image's optimal tiling where it takes that memory, else its linear tiling.
let types = self.heap_types()?;
@@ -2085,11 +2014,7 @@ impl Device {
self.planned_requirements(&optimal, texture_type, vk::ImageTiling::OPTIMAL)?;
if !takes(requirements.memory_type_bits) {
return match self.linear_heap_image(linear, texture_type, &takes, AliasRoute::Direct) {
Err(error)
if linear_refusal(&error)
&& matches!(mine, Mine::Texture { shadows: true, .. })
&& shadowable(&optimal, requirements.size) =>
{
Err(error) if linear_refusal(&error) && shadowable(&optimal, requirements.size) => {
Ok(HeapImage {
plan: optimal,
tiling: vk::ImageTiling::OPTIMAL,
@@ -2110,7 +2035,7 @@ impl Device {
optimal.layers,
);
let shadowed =
own && optimal.samples == SampleCountFlags::COUNT_1 && length <= requirements.size;
optimal.samples == SampleCountFlags::COUNT_1 && length <= requirements.size;
return Ok(HeapImage {
plan: optimal,
tiling: vk::ImageTiling::OPTIMAL,
@@ -2122,9 +2047,8 @@ impl Device {
},
});
}
let hides = own
&& colour(&optimal)
&& facts.contains(&DriverFact::CompressedImagesHideAliasedWrites);
let hides =
colour(&optimal) && facts.contains(&DriverFact::CompressedImagesHideAliasedWrites);
if !hides {
return Ok(HeapImage {
plan: optimal,
@@ -2133,13 +2057,6 @@ impl Device {
route: AliasRoute::Direct,
});
}
let compressed = matches!(
mine,
Mine::Texture {
compressed: true,
..
}
);
let policy = self.compile_device().policy().heap_compression;
if compressed && policy == HeapCompressionPolicy::Compressed {
return Ok(HeapImage {
@@ -2381,16 +2298,14 @@ impl Device {
return self.heap_texture_at((call, heap), &bytes, p, place, options, descriptor);
}
let (_, _, type_index) = bytes.memory();
let images = std::iter::once(&p.image).chain(p.twin.as_ref().map(|(twin, _)| twin));
for image in images {
// A shadowed or unaliased image lies in memory of its own, so the heap's memory
// type is no bound on it. `AliasRoute::Shadow` is given only where that type already
// took the image's (`heap_image`'s `takes`, which holds of every type of the class
// the heap's buffer lies in), so passing it over refuses nothing this would.
let own_memory = image.route.in_own_memory();
if !own_memory && image.requirements.memory_type_bits & (1 << type_index) == 0 {
return Err(image.memory_refusal());
}
// A shadowed or unaliased image lies in memory of its own, so the heap's memory type is
// no bound on it. `AliasRoute::Shadow` is given only where that type already took the
// image's (`heap_image`'s `takes`, which holds of every type of the class the heap's
// buffer lies in), so passing it over refuses nothing this would.
let image = &p.image;
let own_memory = image.route.in_own_memory();
if !own_memory && image.requirements.memory_type_bits & (1 << type_index) == 0 {
return Err(image.memory_refusal());
}
let offset = heap_offset(heap, call, p.size_and_align, p.placement(), offset)?;
// A placement heap's texture answers aliasable from the start, as Metal's does.
@@ -2410,8 +2325,8 @@ impl Device {
/// image to and from them (one sample) and its planes fit the answered size, as `p`'s shadow
/// already is. An optimal image bound to imported host memory is no route: drivers lay it apart
/// from the memory (MoltenVK's lies in a texture of its own, its imported memory being a
/// buffer), or ask a dedicated allocation (RADV). Elsewhere, and for a texture with a depth
/// twin, `NotImplemented(HeapTextureMemory)`.
/// buffer), or ask a dedicated allocation (RADV). Elsewhere
/// `NotImplemented(HeapTextureMemory)`.
///
/// Over pages imported as dma-bufs (`dma_buf.rs`, where the device refused their pointer),
/// where the linear image would be: an image of the driver's `DRM_FORMAT_MOD_LINEAR` layout at
@@ -2435,9 +2350,6 @@ impl Device {
descriptor: &TextureDescriptor,
bytes: &Buffer,
) -> Result<HeapPlan, Error> {
if p.twin.is_some() {
return Err(Error::NotImplemented(RuntimeGap::HeapTextureMemory));
}
if p.layout.samples > 1 {
// A shadow of its samples in Metal's tiles serves it over host pages as in any heap.
if p.image.route == AliasRoute::Tiled {
@@ -2447,7 +2359,7 @@ impl Device {
.shared()
.textures
.facts(self.compile_device().profile());
let (plan, _) = plan_images(&p.layout, descriptor.image_usage(), false, &facts)
let plan = plan_image(&p.layout, descriptor.image_usage(), false, &facts)
.map_err(|refusal| image_error(call, refusal))?;
let plan = self.with_free_usage(plan, p.layout.texture_type)?;
let answer = Some(p.size_and_align);
@@ -2500,7 +2412,7 @@ impl Device {
.shared()
.textures
.facts(self.compile_device().profile());
let (linear, _) = plan_images(&p.layout, descriptor.image_usage(), false, &facts)
let linear = plan_image(&p.layout, descriptor.image_usage(), false, &facts)
.map_err(|refusal| image_error(call, refusal))?;
let SizeAndAlign { size, align } = p.size_and_align;
// A driver that lays depth and stencil images apart from their memory makes no linear
@@ -2722,7 +2634,7 @@ impl Device {
.shared()
.textures
.facts(self.compile_device().profile());
let (plan, _) = plan_images(&p.layout, descriptor.image_usage(), false, &facts)
let plan = plan_image(&p.layout, descriptor.image_usage(), false, &facts)
.map_err(|refusal| image_error(call, refusal))?;
let optimal = self.with_free_usage(plan, p.layout.texture_type)?;
let serves = self.tiles_serve(&optimal, tiled, p.size_and_align.size);
@@ -2967,14 +2879,12 @@ impl Device {
views: Mutex::new(KeyMap::default()),
own_views: Mutex::new(KeyMap::default()),
resolves: KeptResolves::new(),
twin: None,
decoded: None,
second: std::sync::OnceLock::new(),
form: Default::default(),
kept_outside: AtomicBool::new(false),
host_shadow: Mutex::default(),
between: OnceLock::new(),
signed_depth: AtomicBool::new(false),
detached: Mutex::new(None),
first_move: Mutex::new(None),
host_copies: false,
@@ -3010,14 +2920,12 @@ impl Device {
views: Mutex::new(KeyMap::default()),
own_views: Mutex::new(KeyMap::default()),
resolves: KeptResolves::new(),
twin: None,
decoded: None,
second: std::sync::OnceLock::new(),
form: Default::default(),
kept_outside: AtomicBool::new(false),
host_shadow: Mutex::default(),
between: OnceLock::new(),
signed_depth: AtomicBool::new(false),
detached: Mutex::new(Some(DetachedImage {
stand_in,
own: None,
@@ -3195,8 +3103,7 @@ impl Device {
}
/// The texture of plan `p` bound at `place` of its heap, whose buffer is `bytes`, with
/// `options` (the heap's), in the `GENERAL` layout and holding what its bytes held; its depth
/// twin, where it has one, inside the same range.
/// `options` (the heap's), in the `GENERAL` layout and holding what its bytes held.
fn heap_texture_at(
&self,
(call, heap): (&'static str, &Heap),
@@ -3216,7 +3123,7 @@ impl Device {
true => Some(self.stand_in(&p.image.plan)?),
false => None,
};
// Both images are the heap buffer's resource to hazard tracking.
// The image is the heap buffer's resource to hazard tracking.
let binding = HeapBinding {
memory,
options,
@@ -3235,9 +3142,7 @@ impl Device {
}
_ => None,
};
let twin = p.twin;
let route = p.image.route;
let twin_route = twin.as_ref().map(|(twin, _)| twin.route);
let host = binding.host;
let metal_layout = p.metal_layout;
let tiles = metal_layout.tiles().filter(|_| route == AliasRoute::Tiled);
@@ -3245,11 +3150,6 @@ impl Device {
let made = (place, options, descriptor);
self.heap_tiled_image(bytes, p.image, &p.layout, tiled.clone(), made)?
} else if matches!(route, AliasRoute::Shadow | AliasRoute::MemoryShadow) {
// Neither route's texture is held with a depth twin, whose image this arm would
// drop: only the final arm makes one. `MemoryShadow` tests
// `Mine::Texture { shadows: true, .. }`, which a twin clears; `Shadow` tests `own`
// alone and is held out of a twinned texture by `!colour(&optimal)` instead, its own
// image being the `R32_SFLOAT` one `plan_images` plans beside the twin.
self.heap_shadow_image(bytes, p.image, &p.layout, place, options, descriptor)?
} else if route == AliasRoute::Planes {
self.heap_planes_image(bytes, p.image, &p.layout, place, options, descriptor)?
@@ -3285,8 +3185,7 @@ impl Device {
// never the heap.
*lock(&place.memory) = bytes.memory_hold();
let owner = Owner::Heap(Box::new(place));
let image_size = twin.as_ref().map_or(size, |&(_, offset)| offset);
let mut image = match (&stand_in, dma_buf_image) {
match (&stand_in, dma_buf_image) {
(Some(stand_in), _) => {
self.detached_heap_image(&binding, p.image, owner, Arc::clone(stand_in))
}
@@ -3304,20 +3203,8 @@ impl Device {
pages,
)
}
_ => self.bind_heap_image(&binding, p.image, at, image_size, owner)?,
};
if let Some((twin, offset)) = twin {
let twin_size = size - offset;
let made =
self.bind_heap_image(&binding, twin, at + offset, twin_size, Owner::HeapTwin);
image.twin = Some(Box::new(made?));
let facts = self
.shared()
.textures
.facts(self.compile_device().profile());
self.degrade_depth_twin(&p.layout, &facts, true);
_ => self.bind_heap_image(&binding, p.image, at, size, owner)?,
}
image
};
// An image bound in the heap's own memory, which only the runtime's writes change, takes
// a decoded twin where its format needs one (`texture/decoded_twin.rs`); one over the
@@ -3330,15 +3217,9 @@ impl Device {
// An image in memory of its own presents the stand-in too, keeping its own (its copies
// took it), before its texture is made.
if let Some(stand_in) = stand_in {
if image.twin.is_some() {
return Err(Error::NotImplemented(RuntimeGap::DetachTextures));
}
drop(image.present_stand_in(stand_in));
}
self.degrade_alias_route(route, &p.layout);
if let Some(twin_route) = twin_route {
self.degrade_alias_route(twin_route, &p.layout);
}
let image = match twinned {
true => self.with_decoded_twin(image, &p.layout, descriptor, false)?,
false => {
@@ -9,7 +9,7 @@
//! (`render_target::depth_layout`); this keeps it there between passes too, until a command
//! needs it in `GENERAL`.
//! - **Which.** A device's own `Private` texture ([`eligible`]): multisampled, of a depth or
//! depth/stencil format, not memoryless (`TRANSIENT_ATTACHMENT`), with no depth twin. No host
//! depth/stencil format, not memoryless (`TRANSIENT_ATTACHMENT`). No host
//! copy reaches it (Metal refuses the CPU a private texture's bytes), and never a heap's, a
//! caller's image or a texture over a buffer, whose images other resources reach. Its `VkImage`
//! is its own for good. The registry ([`HeldImages`]) knows each by its key from its making to
@@ -43,8 +43,8 @@
//! - **Made.** The making moves the image to `GENERAL` and writes zeros over every texel on the
//! host ([`start`]), as Metal's new `Shared` and `Managed` textures read zero: no first move
//! waits for a submission (`first_move.rs`), and nothing waits for the GPU.
//! - **Copied.** `replace_region` copies the caller's bytes into the image on the host (and into
//! its depth twin), straight from them where they are laid out packed
//! - **Copied.** `replace_region` copies the caller's bytes into the image on the host, straight
//! from them where they are laid out packed
//! (`HostLayout::is_packed`), else from packed bytes, and `get_bytes` copies the image's texels
//! out, into the
//! caller's bytes where they are laid out packed (`HostLayout::is_packed`), else into packed
@@ -59,7 +59,7 @@
//! lock a detach takes to present a stand-in (`detach.rs`), so it never reaches a `VkImage` that
//! went.
use super::{twin_copy, Image};
use super::Image;
use crate::device::lock;
use crate::error::{vulkan, Error};
use crate::exit_guard;
@@ -207,19 +207,16 @@ unsafe fn write(
impl Image {
/// Whether its CPU copies run on the host: it was made with host-transfer usage, moved and
/// zeroed on the host (the module docs), and so was its depth twin where it has one. With a
/// decoded twin too: a read copies the BC image's blocks, and a write's decode into the twin is
/// made on the CPU and copied into the twin on the host at once (`Image::decode_written`).
/// zeroed on the host (the module docs). With a decoded twin too: a read copies the BC image's
/// blocks, and a write's decode into the twin is made on the CPU and copied into the twin on
/// the host at once (`Image::decode_written`).
pub(super) fn takes_host_copies(&self) -> bool {
self.host_copies
&& self.device.shared().host_copies.is_some()
&& (self.twin.as_ref()).is_none_or(|twin| twin.host_copies)
self.host_copies && self.device.shared().host_copies.is_some()
}
/// Copy `bytes`, laid out as `copy` reads them from a buffer, into the image on the host,
/// and into its depth twin the same texels; the image [takes host
/// copies](Self::takes_host_copies). Whether it did: not while the image presents a
/// stand-in (its texture's bytes detached meanwhile), whose image takes none.
/// Copy `bytes`, laid out as `copy` reads them from a buffer, into the image on the host;
/// the image [takes host copies](Self::takes_host_copies). Whether it did: not while the image
/// presents a stand-in (its texture's bytes detached meanwhile), whose image takes none.
pub(super) fn host_write(
&self,
copy: vk::BufferImageCopy,
@@ -234,22 +231,17 @@ impl Image {
if detached.is_some() {
return Ok(false);
}
// SAFETY: the image and its twin are live, made with host-transfer usage and in
// `GENERAL` since they were made; the caller checked the copy against the image's plan
// and `bytes` against its layout. The lock keeps the image's own `VkImage` presented.
unsafe {
write(functions, device, self.raw.get(), bytes, &[copy])?;
if let Some(twin) = &self.twin {
write(functions, device, twin.raw.get(), bytes, &[twin_copy(copy)])?;
}
}
// SAFETY: the image is live, made with host-transfer usage and in `GENERAL` since it
// was made; the caller checked the copy against the image's plan and `bytes` against its
// layout. The lock keeps the image's own `VkImage` presented.
unsafe { write(functions, device, self.raw.get(), bytes, &[copy])? };
drop(detached);
shared.counts.host_texel_copy();
Ok(true)
}
/// [`host_write`](Self::host_write) of `copies`, each reading `bytes` at its offset, into
/// disjoint texels of an image without a depth twin (a decoded twin), on up to `threads`
/// disjoint texels of an image (a decoded twin), on up to `threads`
/// threads at once: the Vulkan specification makes host copies race only where they access
/// overlapping image memory, which disjoint texels never share. Whether it did: not while
/// the image presents a stand-in.
@@ -265,7 +257,7 @@ impl Image {
};
let device = shared.vk().handle();
let detached = lock(&self.detached);
if detached.is_some() || self.twin.is_some() {
if detached.is_some() {
return Ok(false);
}
let image = self.raw.get();
@@ -20,7 +20,7 @@
//! (`host_copy::reaches_format`), so the defect alone is what moved it, and it copies on no
//! staging queue either. It must be an image of the runtime's own in memory of its own, not
//! shareable (a shared texture's bytes another process may write), of one sample and one colour
//! aspect, without a depth twin, not a two-plane texture, and not a carrier holding another
//! aspect, not a two-plane texture, and not a carrier holding another
//! format's blocks or a 4:2:2 texture's texels (`pvrtc.rs`, `astc.rs`, `chroma_pairs.rs`), whose
//! CPU copies name regions in the carrier's units and not the texture's. A heap's texture, a
//! texture over a buffer, a sparse one, the caller's and a shared one are left out: another
@@ -294,7 +294,7 @@ impl Image {
} => {}
_ => return None,
}
if self.twin.is_some() || self.plan().samples != SampleCountFlags::COUNT_1 {
if self.plan().samples != SampleCountFlags::COUNT_1 {
return None;
}
if image_aspects(self.plan().format) != ImageAspectFlags::COLOR
@@ -269,14 +269,12 @@ impl Device {
views: Mutex::new(KeyMap::default()),
own_views: Mutex::new(KeyMap::default()),
resolves: KeptResolves::new(),
twin: None,
decoded: None,
second: OnceLock::new(),
form: Default::default(),
kept_outside: AtomicBool::new(false),
host_shadow: Mutex::default(),
between: OnceLock::new(),
signed_depth: AtomicBool::new(false),
detached: Mutex::new(None),
first_move: Mutex::new(None),
host_copies: false,
@@ -316,7 +316,7 @@ impl Device {
let usage = texture_usage(descriptor.usage, descriptor.swizzle);
let plan = plan_image(layout, usage, false, &facts)
.map_err(|refusal| image_error(call, refusal))?;
let plan = self.with_undeclared_usage(plan, layout, usage, false, &facts)?;
let plan = self.with_undeclared_usage(plan, layout, usage, &facts)?;
if !plan
.usage
.contains(ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST)
File diff suppressed because it is too large. Load diff
@@ -6,7 +6,7 @@
//!
//! - **Which images** ([`Device::stages`]). A new `Shared` or `Managed` texture's image in memory
//! of its own, of a color format (a queue of transfers alone copies no depth or stencil aspect,
//! so a depth texture and its depth twin, keep the host's or the submission's copies), made for
//! so a depth texture keeps the host's or the submission's copies), made for
//! copies both ways, of one sample (Vulkan copies nothing into a multisampled image; a clear
//! writes its zeros). It is made concurrent among the device's families and the staging queue's,
//! so its uses change no owner: measured on the RTX 3090, 50 clears and 50 copies of a 1080p
@@ -54,10 +54,10 @@ impl Device {
}
impl Image {
/// Whether its CPU copies may run on the staging queue: it was made so, and it has no depth
/// twin (a decoded twin's decode is staged, the module docs).
/// Whether its CPU copies may run on the staging queue: it was made so (a decoded twin's
/// decode is staged, the module docs).
pub(super) fn takes_staging_copies(&self) -> bool {
self.staging_copies && self.twin.is_none()
self.staging_copies
}
/// Whether nothing of a host call's copy into it waits for a batch: no copy staged while it
@@ -240,7 +240,7 @@ impl Device {
/// of its own, presents the stand-in of its plan from now on: called before its texture is
/// made, so nothing names its own `VkImage` first, and after its copies took that image.
/// Nothing where the bytes lie in pages. Refused as `Device::stand_in` refuses, and
/// (`NotImplemented(DetachTextures)`) for an image with a depth twin.
/// (`NotImplemented(DetachTextures)`) for an image with a decoded twin.
pub(in crate::texture) fn stand_in_while_detached(
&self,
bytes: &Buffer,
@@ -249,7 +249,7 @@ impl Device {
if !bytes.detached() {
return Ok(());
}
if image.twin.is_some() || image.decoded.is_some() {
if image.decoded.is_some() {
return Err(Error::NotImplemented(RuntimeGap::DetachTextures));
}
let stand_in = self.stand_in(image.plan())?;
@@ -296,20 +296,17 @@ impl TextureImages {
/// failure leaves everything as it was (an image presenting one already takes it again).
/// Refused (`NotImplemented(DetachTextures)`) where no stand-in presents an image exactly:
/// one of texels its copies convert from the bytes (a two-plane YCbCr texture's), and one
/// with a depth twin, whose comparison views the stand-in does not present, or with a decoded
/// twin, whose sampled views it does not present.
/// with a decoded twin, whose sampled views the stand-in does not present.
pub(crate) fn stand_ins(&self, device: &Device) -> Result<Vec<Arc<StandIn>>, Error> {
if !self.exact {
return Err(Error::NotImplemented(RuntimeGap::DetachTextures));
}
self.images
.iter()
.map(
|image| match image.twin.is_some() || image.decoded.is_some() {
true => Err(Error::NotImplemented(RuntimeGap::DetachTextures)),
false => device.stand_in(image.plan()),
},
)
.map(|image| match image.decoded.is_some() {
true => Err(Error::NotImplemented(RuntimeGap::DetachTextures)),
false => device.stand_in(image.plan()),
})
.collect()
}
@@ -7,7 +7,7 @@
//!
//! - **Which textures.** A texture's own image (not a view's), the runtime's in memory of its own
//! (not shareable, not a heap's, a buffer's or the caller's), `Private`, its hazards tracked,
//! without a depth twin, whose plan [`storage_candidate`] gives `STORAGE`, and whose `VkImage`
//! whose plan [`storage_candidate`] gives `STORAGE`, and whose `VkImage`
//! was never handed out ([`Texture::vk_image`](crate::Texture::vk_image) keeps it for good).
//! Noted once, at the first fetching pass that renders it into a scratch image for want of
//! `STORAGE`. An untracked texture keeps its scratch: the program orders its uses on other
@@ -285,7 +285,6 @@ impl Texture {
);
if !own
|| !image.identity.tracked
|| image.twin.is_some()
|| self.storage_mode() != StorageMode::Private
|| form.taken.get().is_some()
|| form.exported.load(Ordering::Relaxed)
@@ -214,7 +214,7 @@ impl Texture {
let usage = texture_usage(descriptor.usage, descriptor.swizzle);
let plan = plan_image(&layout, usage, false, &facts)
.map_err(|refusal| image_error(CALL, refusal))?;
let plan = device.with_undeclared_usage(plan, &layout, usage, false, &facts)?;
let plan = device.with_undeclared_usage(plan, &layout, usage, &facts)?;
check(&plan)?;
let hazard = options.hazard_tracking_mode()?;
let private = TextureDescriptor {
@@ -202,7 +202,7 @@ impl Device {
let usage = texture_usage(descriptor.usage, descriptor.swizzle);
let plan = plan_image(layout, usage, false, &facts)
.map_err(|refusal| image_error(call, refusal))?;
let plan = self.with_undeclared_usage(plan, layout, usage, false, &facts)?;
let plan = self.with_undeclared_usage(plan, layout, usage, &facts)?;
let copies = ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST;
if !plan.usage.contains(copies) || plan.samples != SampleCountFlags::COUNT_1 {
return Err(Error::NotImplemented(RuntimeGap::Textures));
@@ -20,8 +20,8 @@
//! texture names its own image. A command that writes the texture through the shadow and
//! another way is refused as `shadow.rs` refuses it for an image's shadow.
//! - **Not served.** A texture made resident for a function reading handles (the device's heap
//! sets bind its own image), a sparse texture, a heap's, a texture with a depth twin, and a
//! pair the copies cannot serve stay `NotImplemented(UndeclaredTextureUsage)`.
//! sets bind its own image), a sparse texture, a heap's, and a pair the copies cannot serve stay
//! `NotImplemented(UndeclaredTextureUsage)`.
//! - **Announced** once per device as `undeclared-usage-shadow` (performance), at a shadow's first
//! binding beyond the texture's usage.
//! - **Attachment reads.** A draw's sampled slot binding of a texture that presents a color
@@ -119,9 +119,6 @@ impl Texture {
.map_err(|refusal| view_error(call, refusal))?;
return shadow.image.view(&view);
}
if desc.twin {
return self.bound_view(call, desc, storage);
}
let Some(shadow) = self.slot_shadow(call, storage, attached)? else {
return self.bound_view(call, desc, storage);
};
@@ -239,16 +236,12 @@ impl Texture {
}
let (image, copies, truth) = match &self.0.storage {
Storage::Image(image) => {
if image.twin.is_some() {
return Err(refused());
}
let base = match &image.owner {
Owner::ViewShadow(shadow) => &shadow.base,
Owner::Runtime { .. } | Owner::Caller(_) | Owner::HeapUnaliased(_) => image,
Owner::Buffer { .. }
| Owner::Sparse(_)
| Owner::Heap(_)
| Owner::HeapTwin
| Owner::HeapShadow(_) => return Err(refused()),
};
let image =
@@ -125,7 +125,6 @@ impl Texture {
Owner::Buffer { .. }
| Owner::Sparse(_)
| Owner::Heap(_)
| Owner::HeapTwin
| Owner::HeapShadow(_) => return Err(refused(Some(image.as_ref()))),
};
if self.device().image_takes_view(base, record.pixel_format) {
@@ -629,14 +629,12 @@ impl Device {
views: Mutex::new(KeyMap::default()),
own_views: Mutex::new(KeyMap::default()),
resolves: KeptResolves::new(),
twin: None,
decoded: None,
second: std::sync::OnceLock::new(),
form: Default::default(),
kept_outside: AtomicBool::new(false),
host_shadow: Mutex::default(),
between: OnceLock::new(),
signed_depth: AtomicBool::new(false),
detached: Mutex::new(None),
first_move: Mutex::new(None),
host_copies: false,
+2 -57
View File
@@ -242,10 +242,6 @@ pub(crate) struct Counters {
linear_passes_in_place: AtomicU64,
linear_passes_through_copies: AtomicU64,
kept_bytes_passes: AtomicU64,
signed_depth_switch_ons: AtomicU64,
magnitude_stand_in_passes: AtomicU64,
magnitude_write_backs: AtomicU64,
sign_strips: AtomicU64,
color_group_passes: AtomicU64,
color_group_twins: AtomicU64,
color_group_draws_skipped: AtomicU64,
@@ -1679,29 +1675,6 @@ impl Counters {
self.kept_bytes_passes.fetch_add(1, Ordering::Relaxed);
}
/// A render target's 32-bit float depth was switched on to render over its magnitude
/// stand-in, or to have its words stripped of their signs (`texture/signed_depth.rs`): once
/// per texture image.
pub(crate) fn signed_depth_switch_on(&self) {
self.signed_depth_switch_ons.fetch_add(1, Ordering::Relaxed);
}
/// A pass rendered a depth over its magnitude stand-in (`texture/signed_depth.rs`), and
/// wrote what it changed back into the depth where `written_back`.
pub(crate) fn magnitude_stand_in_pass(&self, written_back: bool) {
self.magnitude_stand_in_passes
.fetch_add(1, Ordering::Relaxed);
if written_back {
self.magnitude_write_backs.fetch_add(1, Ordering::Relaxed);
}
}
/// A depth's words were stored without their signs after a pass with depth writes whose
/// stores the device's pass left signed (`texture/signed_depth.rs`, `SignStrip`).
pub(crate) fn sign_strip(&self) {
self.sign_strips.fetch_add(1, Ordering::Relaxed);
}
/// A render encoder drew one of its pass's later color groups (`render/color_groups.rs`).
pub(crate) fn color_group_pass(&self) {
self.color_group_passes.fetch_add(1, Ordering::Relaxed);
@@ -3127,9 +3100,8 @@ pub struct WorkCounts {
/// backings included.
pub ahead_nanos: u64,
/// Load passes render encoders recorded: one per extended-range, padded 10-bit or bfloat
/// color attachment (and under `TileStorePolicy::Exact` signed normalized or `RGB9E5Float`
/// one) that a pass which draws loads and stores, whose words a dispatch rewrote in the tiles
/// the pass's draws reach before the pass, as Metal's tile store leaves them
/// color attachment that a pass which draws loads and stores, whose words a dispatch rewrote in
/// the tiles the pass's draws reach before the pass, as Metal's tile store leaves them
/// (`render/unused_bits_load.rs`).
pub unused_bits_load_passes: u64,
/// The texels of those passes' regions (the render area rounded up to 32 texels a side,
@@ -3960,29 +3932,6 @@ pub struct WorkCounts {
/// (`DontCare`, `MultisampleResolve`), through the image its texture keeps, so that the buffer
/// keeps its bytes (`kept_bytes.rs`).
pub kept_bytes_passes: u64,
/// Render targets' 32-bit float depths switched on to render over their magnitude stand-in,
/// or to have their words stripped of their signs after a pass with depth writes whose stores
/// the device's pass leaves signed: a write that may store a negative value, a NaN, or a
/// denormal the device's depth test compares as zero, once per texture image
/// (`texture/signed_depth.rs`). None where no such write was made: every other pass renders
/// its depth in place.
pub signed_depth_switch_ons: u64,
/// Passes that loaded such a depth and rendered over its magnitude stand-in: its words copied
/// out, their stand-ins written by a dispatch and copied into the stand-in before the pass.
pub magnitude_stand_in_passes: u64,
/// Those written back into the depth, a pass that stores it and may have written it (a
/// depth/stencil state with depth writes, or an indirect command buffer's own states):
/// the stand-in copied out after the pass, merged into the depth's words by a dispatch, and
/// copied back.
pub magnitude_write_backs: u64,
/// Passes after which such a depth, rendered in place or through another image copied back
/// into it, not over its magnitude stand-in, was stored without its signs, as Metal stores
/// it: the pass set a depth/stencil state with depth writes, and the device's pass left the
/// words signed (every such pass, or, on a device whose depth test and stores are Metal's
/// own, one that drew under none). A single-sample depth's words copied out, stripped by a
/// dispatch and copied back; a multisampled one's samples copied out, stripped by a
/// sample-rate draw of each layer and copied back, or copied out and drawn back stripped.
pub sign_strips: u64,
/// Passes a render encoder drew past its first for a pass of more color attachments than the
/// device draws at once, one per later color group, each of that group's colors over a twin
/// of the depth and stencil (`render/color_groups.rs`).
@@ -5131,10 +5080,6 @@ impl Device {
.linear_passes_through_copies
.load(Ordering::Relaxed),
kept_bytes_passes: counters.kept_bytes_passes.load(Ordering::Relaxed),
signed_depth_switch_ons: counters.signed_depth_switch_ons.load(Ordering::Relaxed),
magnitude_stand_in_passes: counters.magnitude_stand_in_passes.load(Ordering::Relaxed),
magnitude_write_backs: counters.magnitude_write_backs.load(Ordering::Relaxed),
sign_strips: counters.sign_strips.load(Ordering::Relaxed),
color_group_passes: counters.color_group_passes.load(Ordering::Relaxed),
color_group_twins: counters.color_group_twins.load(Ordering::Relaxed),
color_group_draws_skipped: counters.color_group_draws_skipped.load(Ordering::Relaxed),
@@ -1 +1 @@
c3022944d0c738d402be5e2aca9a94778e9a101972d4f84f7315a4838c7841ff
edae53caf8da1803d1376c29fea6c6379d3f650f78fbb5b067d46c05cac19023
@@ -418,10 +418,9 @@ pub(super) fn module_censuses(
/// `VK_EXT_depth_range_unrestricted` enabled whose driver is not measured to keep a value outside
/// `[0, 1]` (`DriverFact::DepthImageKeepsValuesOutsideUnitRange` among the opened description's
/// `driver_facts`, the runtime's own rule), which may store such a value clamped (the runtime's
/// textures announce it, or keep the value in a depth twin's colour image, and this temporary
/// bridge keeps its rows honest the same way). A context whose opened description is unknown
/// records it, the conservative answer. Under a restriction the description carries the executing
/// device's identity, so the facts are its driver's.
/// textures announce it, and this temporary bridge keeps its rows honest the same way). A context
/// whose opened description is unknown records it, the conservative answer. Under a restriction the
/// description carries the executing device's identity, so the facts are its driver's.
pub(super) fn executor_degrades(
environment: &mut serde_json::Value,
context: &VulkanContext,
@@ -299,7 +299,7 @@ fn is_storage(ty: vk::DescriptorType) -> bool {
impl<'a> PlanResources<'a> {
/// Whether the run uploads a texture's 32-bit float depth into a depth image: the executor
/// holds every texture in its own format, with no depth twin.
/// holds every texture in its own format.
pub(super) fn uploads_float_depth(&self) -> bool {
self.images.values().any(|image| image.float_depth)
}
@@ -966,9 +966,8 @@ fn a8_without_a8_unorm_renders_masks_clears_and_blends_as_metal() {
/// A 4-sample render over the lower left half of the target resolves as `R8Unorm`'s does, at the
/// edge too, and as Metal's away from it (229 below it, 0 above), where every texel's samples
/// agree: on the device without `A8_UNORM` (its `R8_UNORM` image's resolve), and with its own
/// where it has the format, whose resolve under the lanes' `ResolvePolicy::Exact` is Metal's 8-bit
/// unorm rule, as `R8Unorm`'s (probe `a8`: an `A8Unorm` resolve is `RGBA8Unorm`'s alpha;
/// `bind::ColorResolveFormat::of`), where the device's average is not Metal's already.
/// where it has the format, which the device's average resolves as it does `R8Unorm` (probe `a8`:
/// an `A8Unorm` resolve is `RGBA8Unorm`'s alpha).
#[test]
fn a8_resolves_as_r8_unorm() {
let messages = Messages::default();
@@ -991,9 +990,7 @@ fn a8_resolves_as_r8_unorm() {
/// One leg of [`a8_resolves_as_r8_unorm`] on `lane`, named `what`.
fn a8_resolve_leg(lane: &Lane, what: &str) {
let kinds =
[PixelFormat::A8Unorm, PixelFormat::R8Unorm].map(|pf| resolve_kind(&lane.device, pf, 4));
assert_eq!(kinds[0], kinds[1], "{what}: the resolve's kind");
let kind = resolve_kind(&lane.device, 4);
let resolved = |pf: PixelFormat| {
let ms = lane.texture(pf, 4, TextureUsage::RENDER_TARGET, 0);
let one = lane.texture(
@@ -1035,7 +1032,7 @@ fn a8_resolve_leg(lane: &Lane, what: &str) {
);
}
}
println!("A8-RESOLVE {what}: as R8Unorm's ({:?})", kinds[0]);
println!("A8-RESOLVE {what}: as R8Unorm's ({kind:?})");
}
/// The fetches of the probe (`a8`'s uses): a read of the byte 153 through `[[color(0)]]`, every
@@ -1230,9 +1227,7 @@ fn a8_alpha_to_coverage_covers_as_rgba8() {
);
one
};
let rounded = [PixelFormat::A8Unorm, PixelFormat::RGBA8Unorm]
.into_iter()
.any(|pf| resolve_kind(&lane.device, pf, 4) == Some(Degradation::DeviceRoundedResolve));
let rounded = resolve_kind(&lane.device, 4) == Some(Degradation::DeviceRoundedResolve);
let codes = u8::from(rounded);
for step in 0..=32u8 {
let alpha = f32::from(step) / 32.0;
@@ -16,8 +16,8 @@
//! ([`DONT_CARE_LOADS`]). A pass without a draw call that clears and resolves nothing records
//! nothing at all, its texels kept ([`a_pass_that_changes_no_texel_records_nothing`]).
use super::degrade_notices::shared_in_system_memory;
use super::degrade_notices::{assert_made_once, forced, made_render_kinds};
use super::degrade_notices::{shared_in_system_memory, twins_depth};
use super::hidden_depth::replayed_but_unrun;
use super::{
buffer_with, layer_reported_nothing_at_all, read_buffer, validated_device, Messages,
@@ -33,9 +33,9 @@ use metal2vulkan::metal::{
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
use metal2vulkan_runtime::{
BlitOption, ClearColor, CommandQueue, Degradation, Device, Error, Library, LoadAction, Origin,
BlitOption, ClearColor, CommandQueue, Degradation, Device, Library, LoadAction, Origin,
PipelineOptions, Region, RenderPassDescriptor, RenderPipelineState, ResourceOptions,
RuntimeGap, ScissorRect, Size, StoreAction, Texture, TextureDescriptor, Viewport,
ScissorRect, Size, StoreAction, Texture, TextureDescriptor, Viewport,
};
use std::collections::BTreeSet;
@@ -1272,7 +1272,6 @@ fn a_dont_care_load_through_a_stand_in_keeps_the_tiles_no_draw_reaches() {
let depth_only = lane.pipeline(&[], (Some(d32), None), 1);
let filled = 0.75f32.to_le_bytes();
let mut kept = Vec::new();
let twin = twins_depth(&lane.device);
for usage in [TextureUsage::RENDER_TARGET, TextureUsage::SHADER_READ] {
let texture = lane.texture(d32, PLAIN, usage);
let mut descriptor = RenderPassDescriptor::new();
@@ -1280,23 +1279,6 @@ fn a_dont_care_load_through_a_stand_in_keeps_the_tiles_no_draw_reaches() {
descriptor.depth_attachment.load_action = LoadAction::Clear;
descriptor.depth_attachment.clear_depth = 0.75;
descriptor.depth_attachment.store_action = StoreAction::Store;
// A read-only `Depth32Float` texture on a device whose depth images may lose a float has
// a depth twin, its texels in an `R32_SFLOAT` image (`depth-twin`), which renders through
// no exact stand-in: its passes are refused.
if twin && usage == TextureUsage::SHADER_READ {
let refused = lane
.queue
.command_buffer()
.unwrap()
.render_command_encoder(&descriptor)
.err();
assert!(
matches!(refused, Some(Error::NotImplemented(RuntimeGap::Render))),
"a depth twin's pass: {refused:?}"
);
println!("dl_d32_scissor40_stand_in: a depth twin's pass is refused, {refused:?}");
continue;
}
lane.run(&descriptor, Draw::None, None);
descriptor.depth_attachment.load_action = LoadAction::DontCare;
lane.run_within(
@@ -1319,12 +1301,10 @@ fn a_dont_care_load_through_a_stand_in_keeps_the_tiles_no_draw_reaches() {
assert_eq!(stand_in, rendered, "dl_d32_scissor40_stand_in");
}
// The textures without `RenderTarget` usage render through stand-ins
// (`undeclared-usage-shadow`); the read-only depth texture has a twin where the device's
// facts give it one; the pipelines' makings announce kinds of their own on some devices; and
// the reads' buffers are `Shared`.
// (`undeclared-usage-shadow`); the pipelines' makings announce kinds of their own on some
// devices; and the reads' buffers are `Shared`.
let mut first = forced(&[
(Degradation::UndeclaredUsageShadow, true),
(Degradation::DepthTwin, twin),
(
Degradation::SharedInSystemMemory,
shared_in_system_memory(&lane.device),
@@ -422,11 +422,7 @@ fn a_state_color_draws_into_the_pass_color_at_its_place_in_the_record() {
));
}
if samples > 1 {
first.extend(resolve_kind(
&lane.device,
PixelFormat::RGBA8Unorm,
samples as u32,
));
first.extend(resolve_kind(&lane.device, samples as u32));
}
let routed = drawn(&lane, &both, &[None, RGBA8], samples);
let own = drawn(&lane, &alone, &[RGBA8], samples);
@@ -28,9 +28,8 @@
//! resource IDs ([`UNLISTED`]),
//! indirect command buffers' commands naming a released state ([`RELEASED_STATES`]) and their host
//! steps ([`HOST_STEPS`]), indirect dispatches' host reads ([`INDIRECT_DISPATCHES`]), indexed draws
//! past their index buffer ([`INDEX_FETCHES`]), depth twins ([`TWINS`]) and uploads into depth
//! images ([`UPLOADS`]), a MoltenVK whose
//! argument-buffer state is unread ([`ARGUMENT_BUFFERS`]), mipmaps within Metal's
//! past their index buffer ([`INDEX_FETCHES`]), uploads into depth images ([`UPLOADS`]), a
//! MoltenVK whose argument-buffer state is unread ([`ARGUMENT_BUFFERS`]), mipmaps within Metal's
//! spread ([`MIPMAPS`]), a heap's depth or stencil texture laid apart from the heap ([`APART`]),
//! a multisample depth or stencil texture without GPU-optimized contents that stays optimized
//! ([`OPTIMIZED`]),
@@ -140,16 +139,15 @@
//! where the compile layer runs the dispatch on no emulated variant, a one-aspect resolve where the
//! device resolves the aspects independently, both properties no device option withholds,
//! uncalibrated GPU times where the device calibrates its timestamps, an unlisted sampler state
//! where the device's and the pipeline's sampler arrays hold its ID, a depth twin where the
//! device's depth images keep every `float`, an upload into a depth image where the device enabled
//! `VK_EXT_depth_range_unrestricted` or its driver keeps a value outside `[0, 1]` without it, and a
//! `Shared` buffer in system memory where the device has unified memory, a heap's depth or stencil
//! texture where the driver lays no such image apart, and a depth or stencil texture without
//! GPU-optimized contents where the driver drops the layout, emulated mesh draws where the
//! device has `VK_EXT_mesh_shader`, a capped anisotropy where the device's samplers take 32
//! or none, and a vertex simdgroup grouping where the driver groups vertices as Apple's GPUs do or
//! the vertex stage has no subgroups) is expected absent there, as the
//! compile layer, the device's description or its driver facts settle it.
//! where the device's and the pipeline's sampler arrays hold its ID, an upload into a depth image
//! where the device enabled `VK_EXT_depth_range_unrestricted` or its driver keeps a value outside
//! `[0, 1]` without it, and a `Shared` buffer in system memory where the device has unified memory,
//! a heap's depth or stencil texture where the driver lays no such image apart, and a depth or
//! stencil texture without GPU-optimized contents where the driver drops the layout, emulated mesh
//! draws where the device has `VK_EXT_mesh_shader`, a capped anisotropy where the device's samplers
//! take 32 or none, and a vertex simdgroup grouping where the driver groups vertices as Apple's
//! GPUs do or the vertex stage has no subgroups) is expected absent there, as the compile layer,
//! the device's description or its driver facts settle it.
use super::absent_reads::ABSENT_READS;
use super::amplified_draws::AMPLIFICATION;
@@ -212,7 +210,7 @@ use super::sample_copies::DRAWN_DEPTH;
use super::shader_stencil::SHADOW;
use super::snorm_tile_store::{SHARED_EXPONENT, SNORM_MINIMUM};
use super::sparse_textures::SPARSE;
use super::texture_blits::{MIPMAPS, TWINS, UPLOADS};
use super::texture_blits::{MIPMAPS, UPLOADS};
use super::tile_dispatches::TILE_DISPATCHES;
use super::topology_classes::UNSIZED_POINTS;
use super::two_plane_copies::TWO_PLANE_COPIES;
@@ -235,8 +233,8 @@ use crate::candidate::engine::variants::compile_compute_for_shape;
use crate::gpu::TEST_DEVICE;
use metal2vulkan::bind::{AstcDecode, SamplerDescriptor};
use metal2vulkan::cache::VariantKey;
use metal2vulkan::device::DecodedTexelsPolicy;
use metal2vulkan::device::VkExtension;
use metal2vulkan::device::{DecodedTexelsPolicy, ResolvePolicy};
use metal2vulkan::device::{DriverFact, DriverWorkaround, OpBits, VkFeature, VkProperty};
use metal2vulkan::device::{SimdClass, Tier};
use metal2vulkan::error::{DriverDeviation, Feature};
@@ -291,16 +289,15 @@ const BLITS: [Degradation; 3] = [
const DISPATCHES: [Degradation; 2] = [Degradation::SplitDispatch, Degradation::EmulatedSimdgroups];
/// The kinds [`passes_degrade_once_per_kind`] takes (the second where the device resolves a
/// combined format's aspects one at a time; the exact resolve and the device's rounded one where
/// the driver's average of `RGBA8Unorm` at 4 samples is not measured as Metal's, or where the
/// device makes a texture of 8 samples; the unmeasured resolve where it makes one).
const PASSES: [Degradation; 7] = [
/// combined format's aspects one at a time; the device's rounded resolve where the driver's
/// average of `RGBA8Unorm` at 4 samples is not measured as Metal's, or where the device makes a
/// texture of 8 samples; the unmeasured resolve where it makes one).
const PASSES: [Degradation; 6] = [
Degradation::SeparateDepthStencil,
Degradation::OneAspectResolve,
Degradation::ResolveScratch,
Degradation::DeviceRoundedResolve,
Degradation::DontCareStore,
Degradation::ShaderResolve,
Degradation::UnmeasuredResolve,
];
@@ -496,7 +493,6 @@ fn every_kind_has_a_site_a_lane_test_takes() {
&HOST_STEPS,
&INDIRECT_DISPATCHES,
&INDEX_FETCHES,
&TWINS,
&UPLOADS,
&MIPMAPS,
&APART,
@@ -1608,7 +1604,8 @@ fn resolves_stencil_alone(device: &Device) -> Option<bool> {
/// 4x `Depth32Float_Stencil8` target whose stencil alone resolves. Each kind is announced once and
/// nothing else, the one-aspect resolve exactly where the device's description resolves that
/// stencil one aspect at a time (lavapipe, which resolves no aspects independently), and
/// `device-rounded-resolve` exactly where the 8x half-float target, which no rule covers, is made.
/// `device-rounded-resolve` exactly where the device's average is not measured to be Metal's at 4
/// samples or an 8x target is made.
#[test]
fn passes_degrade_once_per_kind() {
let (messages, _cache, lane) = lane();
@@ -1624,13 +1621,14 @@ fn passes_degrade_once_per_kind() {
let eight_samples = lane.device.new_texture(&eight).ok();
eight.pixel_format = PixelFormat::RGBA16Float;
let half_eight = lane.device.new_texture(&eight).ok();
let exact = !lane
let rounded = !lane
.device
.properties()
.driver_facts
.contains(&DriverFact::ColorResolveAverageIsMetals);
eprintln!(
"8 samples made: {} (RGBA16Float: {}); exact resolve at 4 samples: {exact}",
"8 samples made: {} (RGBA16Float: {}); the device's rounded resolve at 4 samples: \
{rounded}",
eight_samples.is_some(),
half_eight.is_some()
);
@@ -1656,8 +1654,8 @@ fn passes_degrade_once_per_kind() {
);
lane.run(&descriptor, |_, _, _| {}).unwrap();
}
// A half-float resolve at 4 samples, Metal's closed rule (the exact resolve), and at 8
// where the device makes such a texture, which no rule covers: the device's average.
// A half-float resolve at 4 samples, and at 8 where the device makes such a texture: the
// device's average.
let half = PixelFormat::RGBA16Float;
let descriptor = color_pass(
&lane.msaa(half),
@@ -1713,10 +1711,9 @@ fn passes_degrade_once_per_kind() {
// Where the device's average is Metal's (MoltenVK's is Metal's own resolve) and it
// makes no texture of 8 samples (an Apple GPU: Metal makes none past 4), every resolve
// here is Metal's own and none rounds by the device.
Degradation::ShaderResolve => exact || eight_samples.is_some(),
// Only a format without a rule at its count rounds by the device: the half-float
// resolve of 8 samples.
Degradation::DeviceRoundedResolve => half_eight.is_some(),
Degradation::DeviceRoundedResolve => {
rounded || eight_samples.is_some() || half_eight.is_some()
}
Degradation::UnmeasuredResolve => eight_samples.is_some() || half_eight.is_some(),
_ => true,
})
@@ -2109,10 +2106,9 @@ pub(super) fn clamps_depth_uploads(device: &Device) -> bool {
/// Whether `device` keeps a negative or NaN 32-bit float depth a write stores in a render
/// target's depth image (not [`clamps_depth_uploads`]) and its depth test compares it as it is,
/// where Metal's compares its magnitude (no `DriverFact::DepthTestComparesMagnitudes`): a
/// single-sample `Depth32Float` target then renders a pass that loads it over its magnitude
/// stand-in (`texture/signed_depth.rs`), and a write into a multisampled or combined
/// depth/stencil one announces `signed-depth-test`.
/// where Metal's compares its magnitude (no `DriverFact::DepthTestComparesMagnitudes`): a write
/// that may store such a value in a render target's `Depth32Float` or `Depth32Float_Stencil8`
/// depth then announces `signed-depth-test`.
pub(super) fn signs_depth_tests(device: &Device) -> bool {
let magnitudes = device
.properties()
@@ -2127,53 +2123,18 @@ pub(super) fn shared_in_system_memory(device: &Device) -> bool {
!device.properties().has_unified_memory
}
/// Whether `device` gives a single-sample `Depth32Float` texture of shader-read usage without
/// render target usage a depth twin (`depth-twin`): its depth images may store a value otherwise
/// than Metal's ([`clamps_depth_uploads`], or a driver not measured to keep a denormal there,
/// `DriverFact::DepthImageKeepsDenormals`).
pub(super) fn twins_depth(device: &Device) -> bool {
let keeps = device
.properties()
.driver_facts
.contains(&DriverFact::DepthImageKeepsDenormals);
clamps_depth_uploads(device) || !keeps
}
/// The kind `device` announces for a resolve of a color attachment of `format` at `samples`, a
/// texture the runtime made: `shader-resolve` under `ResolvePolicy::Exact` where the format has
/// Metal's rules at that count (`ColorResolveFormat::of` and `resolves`) and the device's
/// `AVERAGE` is not measured to be Metal's there (`DriverFact::ColorResolveAverageIsMetals`, at
/// most 4 samples): the runtime gives such a target the input attachment usage the exact resolve
/// reads it through where that costs the image nothing, which every driver measured answers so
/// (lavapipe, RADV, ANV and NVIDIA); `device-rounded-resolve` where the device's
/// `AVERAGE` resolves it (one with rules under `ResolvePolicy::Device`, the default, and one
/// without rules there under either) and is not measured to resolve as Metal's; none where it is
/// (the fact holds for every format).
pub(super) fn resolve_kind(
device: &Device,
format: PixelFormat,
samples: u32,
) -> Option<Degradation> {
// Rules that hold at that count: the float formats' at 2 and 4 samples only.
let rules = metal2vulkan::metal::format::direct_format(format)
.and_then(metal2vulkan::bind::ColorResolveFormat::of)
.is_some_and(|rules| rules.resolves(samples));
/// The kind `device` announces for a resolve of a color attachment of a format that is not
/// extended-range, into a texture of its own format, at `samples`, a texture the runtime made:
/// the device's `AVERAGE` resolves it in the pass, `device-rounded-resolve` where that is not
/// measured to resolve as Metal's (`DriverFact::ColorResolveAverageIsMetals`, at most 4 samples);
/// none where it is (the fact holds for every format).
pub(super) fn resolve_kind(device: &Device, samples: u32) -> Option<Degradation> {
let metals = samples <= 4
&& device
.properties()
.driver_facts
.contains(&DriverFact::ColorResolveAverageIsMetals);
let policy = device.compile_device().policy().resolve;
// A format without rules, or any under the device's resolve, resolves by the device's
// average, Metal's own where the fact holds.
match (
metals,
rules && samples > 1 && policy == ResolvePolicy::Exact,
) {
(true, _) => None,
(false, true) => Some(Degradation::ShaderResolve),
(false, false) => Some(Degradation::DeviceRoundedResolve),
}
(!metals).then_some(Degradation::DeviceRoundedResolve)
}
/// Whether `device` copies bytes into a multisampled 32-bit float depth (from a buffer, or from a
@@ -23,12 +23,9 @@
//! Each prints a `DEPTH-DENORMAL` line. Checked: the two controls, the smallest normal and 0.5,
//! read and pass as given on every device; a draw's denormal stores zero on every device, as
//! Metal's; where the driver has `DriverFact::DepthImageKeepsDenormals` the clear's, the CPU's and
//! the blit's read back as given; where it has `DriverFact::DepthTestKeepsDenormals` too, or where
//! the device keeps a value outside `[0, 1]` in a depth image, so that a pass loading a stored
//! denormal tests it over its magnitude stand-in, the smallest normal (`texture/signed_depth.rs`,
//! whose copies keep the denormal on such a driver), each one read back as given tests as Metal's;
//! and `depth-denormals` is announced exactly where the driver lacks either fact (over the
//! stand-in, for a fragment at exactly 2^-126).
//! the blit's read back as given; where it has `DriverFact::DepthTestKeepsDenormals` too, each one
//! read back as given tests as Metal's; and `depth-denormals` is announced exactly where the
//! driver lacks either fact.
//!
//! **Signs**: Metal's depth test compares the fragment's depth with the stored value's magnitude,
//! as the integers of their low 31 bits: a stored -0.5 passes `Equal` for a fragment at 0.5, and a
@@ -36,42 +33,33 @@
//! functions, fragments at 0, 0.5 and 1, 18 stored values, 270 of 270 outcomes; its texel keeps
//! every value's bits through copies, reads, samples and a pass's load and store without depth
//! writes, and `sample_compare` is the IEEE compare of the reference with the texel, neither
//! clamped, 720 of 720). Vulkan's compares the stored value as it is; a render target whose depth
//! may hold such a value renders a pass that loads it over its magnitude stand-in
//! (`texture/signed_depth.rs`). Each of the probe's 18 values is stored by `replace_region` and by
//! a blit from a buffer, read by `get_bytes`, a kernel's read and a nearest sample, compared by
//! `sample_compare` against five references under the eight functions, and depth-tested by the
//! probe's 15 draws, each printing a `PROBED-DEPTH` line where it differs from Metal's. Checked on
//! a device that keeps such a value: every answer Metal's wherever the value was stored as given,
//! the switch-ons and passes over the stand-in counted (`WorkCounts`); and a pass with depth writes
//! over a texture of such values stores the draw's depth where it passed and every other texel
//! without its sign, as Metal's (our probe `depthstore`, the M3 Max under macOS 27.0.1), a pass
//! that sets a state with depth writes and draws nothing stores every texel so, and a pass without
//! depth writes keeps every bit, announcing `signed-depth-test` for the merge's corner (a draw
//! writing exactly +inf over a stored NaN); on a device whose own depth test is Metal's
//! (`DriverFact::DepthTestComparesMagnitudes`: MoltenVK), every answer Metal's with the depth
//! rendered in place, nothing switched on or announced. A target that takes no stand-in (a
//! `Depth32Float_Stencil8`, a 4x multisampled `Depth32Float` and `Depth32Float_Stencil8`) and a
//! depth loaded through separate depth and stencil textures' scratch image, each holding such
//! values, are stored without their signs after a pass that sets a state with depth writes and
//! draws nothing, as Metal stores them, each stripped once (`WorkCounts::sign_strips`;
//! `STRIPPED-DEPTH` lines). An ordinary depth, which never holds such a
//! value, loads in place: nothing switched on, no pass over a stand-in, no image made
//! (`ORDINARY-DEPTH` prints the command buffers its passes begin and submit).
//! clamped, 720 of 720). Vulkan's compares the stored value as it is: a device's depth test is
//! Metal's only where `DriverFact::DepthTestComparesMagnitudes` holds (MoltenVK), and elsewhere a
//! write that may store such a value in a render target's depth announces `signed-depth-test`.
//! Each of the probe's 18 values is stored by `replace_region` and by a blit from a buffer, read by
//! `get_bytes`, a kernel's read and a nearest sample, compared by `sample_compare` against five
//! references under the eight functions, and depth-tested by the probe's 15 draws, each printing a
//! `PROBED-DEPTH` line where it differs from Metal's. Checked on a device that keeps such a value:
//! every read, sample and comparison Metal's wherever the value was stored as given, and every
//! depth test too where the device's test is Metal's own; there, a pass with depth writes over a
//! texture of such values stores the draw's depth where it passed and every other texel without
//! its sign, as Metal's (our probe `depthstore`, the M3 Max under macOS 27.0.1), and a pass that
//! sets a state with depth writes but draws under none, which Metal's stores without the signs,
//! announces `signed-depth-test`; on every such device a pass without depth writes keeps every
//! value. An ordinary depth loads in place: no kept image or stand-in made (`ORDINARY-DEPTH`
//! prints the command buffers its passes begin and submit).
//!
//! **A new target's pattern**: a new `Private` `Depth32Float` or `Depth32Float_Stencil8` render
//! target of 16² reads Metal's pattern, a NaN with the sign set (all ones); a pass that loads it
//! before anything wrote it and draws at 0.5 with depth writes draws everywhere under `Less` and
//! `NotEqual` and nowhere under `Greater` and `Equal`, and stores every texel no fragment wrote as
//! `0x7fffffff` (our probe `fd32`, the M3 Max under macOS 27.0.1, 64² drawn over half). Checked on
//! a device that writes the pattern: each new target switched on once as its pass is planned, a
//! `Depth32Float` tested over its magnitude stand-in where the device's test is not Metal's own,
//! each such pass announcing the merge's corner (`signed-depth-test`), every store Metal's, and a
//! `Depth32Float_Stencil8`'s test announced (`signed-depth-test`) at each pass that loads its
//! pattern where the device's test is not Metal's own. On a device that may clamp the pattern,
//! each target reads zero and draws and stores as over a zero depth, announced
//! (`fresh-pattern-zeroed`) at its first load. A new target cleared first loads its clear in place
//! (`FRESH-SIGNED-DEPTH` lines).
//! a device that writes the pattern: where the device's test is Metal's own, every draw and store
//! Metal's; elsewhere each texel no fragment wrote keeps the pattern, with or without its sign,
//! and each pass that loads it announces `signed-depth-test`. On a device that may clamp the
//! pattern, each target reads zero and draws and stores as over a zero depth, announced
//! (`fresh-pattern-zeroed`) at its first load. A new target cleared first loads its clear,
//! announcing neither (`FRESH-SIGNED-DEPTH` lines).
use super::degrade_notices::{assert_made_once, assert_once_allowing, bound_value_kinds};
use super::degrade_notices::{clamps_depth_uploads, forced, loses_depth_denormals};
@@ -86,7 +74,7 @@ use super::{
use super::{Messages, ScratchCache, WAIT};
use crate::air_library::AirLibrary;
use crate::gpu::TEST_DEVICE;
use metal2vulkan::bind::{DepthMagnitudeModule, SamplerDescriptor};
use metal2vulkan::bind::SamplerDescriptor;
use metal2vulkan::device::{DriverFact, VkFeature};
use metal2vulkan::error::RuntimeDriverDefect;
use metal2vulkan::metal::state::DepthStencilDescriptor;
@@ -110,7 +98,8 @@ use std::collections::BTreeSet;
pub(super) const DEPTH_DENORMALS: [Degradation; 1] = [Degradation::DepthDenormals];
/// The kind a render target's depth that may hold a negative value or a NaN takes where the
/// device's depth test may compare it as it is: here, the merge's corner.
/// device's depth test compares it as it is, or where a pass that sets a state with depth writes
/// but draws under none keeps its sign.
pub(super) const SIGNED_DEPTH_TESTS: [Degradation; 1] = [Degradation::SignedDepthTest];
/// The 18 stored values of the probe `depthkeep`: ±2, ±0.5, the smallest and largest denormal of
@@ -413,31 +402,6 @@ impl Lane {
.collect()
}
/// A pass that loads and stores `depth` (and `stencil`, a separate texture, where given) and
/// sets a depth/stencil state (`Less`, depth writes where `write`), and draws nothing.
fn bare_state_pass(&self, depth: &Texture, stencil: Option<&Texture>, write: bool) {
let mut pass = RenderPassDescriptor::new();
pass.depth_attachment.texture = Some(depth.clone());
pass.depth_attachment.load_action = LoadAction::Load;
pass.depth_attachment.store_action = StoreAction::Store;
if let Some(stencil) = stencil {
pass.stencil_attachment.texture = Some(stencil.clone());
pass.stencil_attachment.load_action = LoadAction::Load;
pass.stencil_attachment.store_action = StoreAction::Store;
}
let command_buffer = self.queue.command_buffer().unwrap();
let mut encoder = command_buffer.render_command_encoder(&pass).unwrap();
let mut state = DepthStencilDescriptor::default();
state.depth_compare_function = CompareFunction::Less;
state.depth_write_enabled = write;
let state = self.device.new_depth_stencil_state(&state).unwrap();
encoder.set_depth_stencil_state(&state).unwrap();
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
}
/// A pass that clears `depth` to `clear` and stores it, and draws nothing.
fn clearing_pass(&self, depth: &Texture, clear: f64) {
let mut pass = RenderPassDescriptor::new();
@@ -613,24 +577,20 @@ fn depth_images_hold_denormals_as_their_drivers_claim() {
let facts = &device.properties().driver_facts;
let keeps = facts.contains(&DriverFact::DepthImageKeepsDenormals);
let tests = facts.contains(&DriverFact::DepthTestKeepsDenormals);
// The uploads into the depth images, the draws' `Shared` buffers, and the white
// pipeline's making.
// The uploads into the depth images (the blit's, into a render target, may store a
// negative value), the draws' `Shared` buffers, and the white pipeline's making.
let mut first = forced(&[
(
Degradation::RestrictedDepthUpload,
clamps_depth_uploads(&device),
),
(Degradation::SignedDepthTest, signs_depth_tests(&device)),
(
Degradation::SharedInSystemMemory,
shared_in_system_memory(&device),
),
(Degradation::DepthDenormals, !(keeps && tests)),
]);
// A render target's depth that holds a denormal its test compares as zero renders a pass
// that loads it over its magnitude stand-in where the device keeps values outside [0, 1]
// and its test is not Metal's already, whose copies keep the denormal where the driver's
// GPU copies do.
let stands_in = signs_depth_tests(&device) && keeps;
let lane = Lane::new(device);
first.extend(made_render_kinds(
&lane.device,
@@ -683,7 +643,7 @@ fn depth_images_hold_denormals_as_their_drivers_claim() {
if keeps {
assert_eq!(held, 16, "{at}: read {read:08x?}");
}
if held == 16 && (tests || stands_in) {
if held == 16 && tests {
let metals = if negative { 0 } else { 16 };
assert_eq!(passed, metals, "{at}: tested");
}
@@ -862,33 +822,31 @@ fn passed(color: &[u8]) -> usize {
/// Each of the probe's 18 values stored by `replace_region` and by a blit into a render target's
/// `Depth32Float`, then read, sampled, compared and depth-tested (the module docs): on a device
/// that keeps such a value in a depth image, each answer is Metal's wherever the value was stored
/// as given (a blit's denormal is a zero on a driver without
/// that keeps such a value in a depth image, each read, sample and comparison is Metal's wherever
/// the value was stored as given (a blit's denormal is a zero on a driver without
/// `DriverFact::DepthImageKeepsDenormals`, and `get_bytes` reads it so; a host copy's is read as a
/// zero by such a driver's GPU copies and reads, announced as `depth-denormals`, and a sample or
/// comparison whose making records `device-texel-denormals` or `device-depth-comparison` may read
/// it so), each texture whose value's magnitude stand-in is not itself switched on once and each of
/// its 15 tests rendered over the stand-in, none written back; a pass with depth writes over a
/// texture holding such values stores its draw's depth where it passed and every other texel
/// without its sign, one that sets a state with depth writes and draws nothing every texel without
/// its sign, and one whose state has no depth writes keeps every bit, as Metal's (probe
/// `depthstore`), announcing `signed-depth-test` for the merge's one corner. A device whose own
/// depth test is Metal's (`DriverFact::DepthTestComparesMagnitudes`) gives the same answers in
/// place: nothing switched on or announced. A device that may clamp such a value announces `restricted-depth-upload` and
/// switches nothing on.
/// it so), and each depth test too where the device's test is Metal's own
/// (`DriverFact::DepthTestComparesMagnitudes`). There, a pass with depth writes over a texture
/// holding such values stores its draw's depth where it passed and every other texel without its
/// sign, as Metal's (probe `depthstore`), and one that sets a state with depth writes but draws
/// under none announces `signed-depth-test`; elsewhere the writes announce it. On every device
/// that keeps such a value, a pass whose state has no depth writes keeps every value. A device
/// that may clamp such a value announces `restricted-depth-upload` instead.
#[test]
fn a_stored_depth_tests_reads_samples_and_compares_as_metal_s() {
fn a_stored_depth_reads_samples_and_compares_as_metal_s() {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
{
let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap();
let name = device.name().to_owned();
// The device keeps such a value, and where its depth test is not Metal's already, its
// render targets take the magnitude stand-in.
// The device keeps such a value, and its depth test is Metal's own or compares it as it
// is.
let keeps = !clamps_depth_uploads(&device);
let takes = signs_depth_tests(&device);
let signs = signs_depth_tests(&device);
let magnitudes = keeps && !signs;
let facts = &device.properties().driver_facts;
let flush = !facts.contains(&DriverFact::DepthTestKeepsDenormals);
let library = device
.new_library_with_air(&llvm_assemble_text(READS).unwrap())
.unwrap();
@@ -897,8 +855,9 @@ fn a_stored_depth_tests_reads_samples_and_compares_as_metal_s() {
let mut allowed = BTreeSet::new();
let mut first = forced(&[
(Degradation::RestrictedDepthUpload, !keeps),
// The merge's corner.
(Degradation::SignedDepthTest, takes),
// The writes where the device's test is not Metal's; the passes that draw under no
// state with depth writes where it is.
(Degradation::SignedDepthTest, keeps),
(
Degradation::DepthDenormals,
loses_depth_denormals(&device, false),
@@ -919,8 +878,8 @@ fn a_stored_depth_tests_reads_samples_and_compares_as_metal_s() {
));
}
// Where a denormal is Metal's: a driver whose GPU copies and reads keep one in a depth
// image (the stand-in's copies too), and of those, a sample or comparison whose making
// records no note that it may read one otherwise.
// image, and of those, a sample or comparison whose making records no note that it may
// read one otherwise.
let kinds = |kernel| {
let descriptor = || function(kernel).function_descriptor();
let mut kinds = made_compute_kinds(&device, descriptor());
@@ -941,19 +900,12 @@ fn a_stored_depth_tests_reads_samples_and_compares_as_metal_s() {
&lane.device,
&white_descriptor(&lane.library),
));
let before = lane.device.work_counts();
let (mut asked, mut metals, mut switched) = (0, 0, 0u64);
let (mut asked, mut metals) = (0, 0);
for route in [Route::ReplaceRegion, Route::BlitFromBuffer] {
for bits in PROBED {
let depth = lane.stored(route, bits);
let seen = lane.observed(&depth, &readers);
let value = f32::from_bits(bits);
// A blit switches every texture on; `replace_region`, one whose bytes hold a
// value whose stand-in is not itself.
let stands_in = DepthMagnitudeModule::stand_in(bits, flush) != bits;
if keeps && (matches!(route, Route::BlitFromBuffer) || stands_in) {
switched += 1;
}
// Metal's answers stand for the value as it was stored.
let kept = keeps && seen.read == bits;
let at = format!("{name} {route:?} {bits:08x}");
@@ -1005,7 +957,9 @@ fn a_stored_depth_tests_reads_samples_and_compares_as_metal_s() {
let denormal = bits & 0x7f80_0000 == 0 && bits & 0x007f_ffff != 0;
if kept && (!denormal || denormals) {
assert!(same_read(seen.kernel_read, bits), "{at}: kernel read");
assert!(wrong_tests.is_empty(), "{at}: {wrong_tests:#?}");
if magnitudes {
assert!(wrong_tests.is_empty(), "{at}: {wrong_tests:#?}");
}
}
if kept && (!denormal || sampled_denormals) {
assert!(same_read(seen.sampled, bits), "{at}: nearest sample");
@@ -1015,11 +969,11 @@ fn a_stored_depth_tests_reads_samples_and_compares_as_metal_s() {
}
}
}
// The merge: values whose stand-ins a draw at 0.5 under `Less`, writing its depth, passes
// against where their magnitude lies above 0.5. Metal stores the draw's depth there and
// every other texel without its sign (probe `depthstore`); a pass that sets a state with
// depth writes and draws nothing stores every texel so, and one whose state has none
// keeps every bit. Each texture is switched on by its `replace_region`.
// The merge: values a draw at 0.5 under `Less`, writing its depth, passes against where
// their magnitude lies above 0.5 under Metal's test. Metal stores the draw's depth there
// and every other texel without its sign (probe `depthstore`); a pass that sets a state
// with depth writes and draws nothing stores every texel so, and one whose state has none
// keeps every bit.
let held = || {
let depth = lane.texture(PixelFormat::Depth32Float);
let bytes: Vec<u8> = MERGED.iter().flat_map(|w| w.to_le_bytes()).collect();
@@ -1032,8 +986,8 @@ fn a_stored_depth_tests_reads_samples_and_compares_as_metal_s() {
let color = lane.pass(&merged, None, Some((0.5, CompareFunction::Less, true)));
// A state with depth writes and no draw, one with a draw of no instances, and one replaced
// by a state without depth writes before its draw: Metal strips each (probe
// `depthstore`), which a device whose pass is Metal's own leaves to the runtime's strip.
let stripped: Vec<(&str, Texture)> = [
// `depthstore`); a device whose pass is Metal's own is handed no state with depth writes.
let unstored: Vec<(&str, Texture)> = [
("no draw", Then::Nothing),
("no instances", Then::NoInstances),
("replaced", Then::WritesOffDraw),
@@ -1047,14 +1001,7 @@ fn a_stored_depth_tests_reads_samples_and_compares_as_metal_s() {
.collect();
let kept = held();
lane.state_pass(&kept, false, Then::Nothing);
// The five passes over a stand-in, four of them written back; three strips where the
// device's pass is Metal's own.
let (merges, writes, strips): (u64, u64, u64) = (5, 4, 3);
if keeps {
switched += merges;
}
let drawn = 0.5f32.to_bits();
let unsigned: Vec<u32> = MERGED.iter().map(|&w| w & 0x7fff_ffff).collect();
let want: Vec<u32> = MERGED
.iter()
.map(|&w| match metal_passes(0.5, CompareFunction::Less, w) {
@@ -1065,208 +1012,64 @@ fn a_stored_depth_tests_reads_samples_and_compares_as_metal_s() {
let read = lane.words(&merged);
let read_kept = lane.words(&kept);
println!("PROBED-DEPTH {name} no depth writes: read {read_kept:08x?}");
let read_stripped: Vec<(&str, Vec<u32>)> = stripped
.iter()
.map(|(case, depth)| {
let read = lane.words(depth);
println!("PROBED-DEPTH {name} depth writes, {case}: read {read:08x?}");
(*case, read)
})
.collect();
for (case, depth) in &unstored {
let read = lane.words(depth);
println!("PROBED-DEPTH {name} depth writes, {case}: read {read:08x?}");
if keeps {
let either = (read.iter().zip(MERGED))
.all(|(&w, m)| same_read(w, m) || same_read(w, m & 0x7fff_ffff));
assert!(either, "{name}: {case}: each word with or without its sign");
}
}
// The texels Metal's test passes: not those whose stored value equals the draw's (0.5).
let wins = MERGED
.iter()
.filter(|&&w| metal_passes(0.5, CompareFunction::Less, w))
.count();
println!(
"PROBED-DEPTH {name} written back: {} of 16 drawn (Metal's {wins}), read {read:08x?}",
"PROBED-DEPTH {name} merged: {} of 16 drawn (Metal's {wins}), read {read:08x?}",
passed(&color)
);
let counts = lane.device.work_counts();
let (switch_ons, passes, written_back, sign_strips) = (
counts.signed_depth_switch_ons - before.signed_depth_switch_ons,
counts.magnitude_stand_in_passes - before.magnitude_stand_in_passes,
counts.magnitude_write_backs - before.magnitude_write_backs,
counts.sign_strips - before.sign_strips,
);
println!(
"PROBED-DEPTH {name}: {metals} of {asked} answers Metal's; keeps {keeps}; takes the \
stand-in {takes}; switched on {switch_ons}, passes over the stand-in {passes}, \
written back {written_back}, sign strips {sign_strips}"
"PROBED-DEPTH {name}: {metals} of {asked} answers Metal's; keeps {keeps}; the \
device's test is Metal's {magnitudes}"
);
if keeps {
if magnitudes {
assert_eq!(passed(&color), wins, "{name}: the merge pass drew");
assert_eq!(
read, want,
"{name}: the merge stored the draw's depth and the others without their signs"
);
for (case, read) in &read_stripped {
assert_eq!(
read, &unsigned,
"{name}: a pass with depth writes, {case}, stored every texel without its sign"
);
}
assert_eq!(
read_kept, MERGED,
"{name}: a pass without depth writes kept every bit"
);
}
// Each switched texture's 15 tests and the three passes load it over its stand-in.
let tests = PROBE_TESTS.len() * FRAGMENTS.len();
assert_eq!(switch_ons, switched, "{name}: switch-ons");
assert_eq!(
passes,
match takes {
true => (switched - merges) * tests as u64 + merges,
false => 0,
},
"{name}: passes over the stand-in"
);
assert_eq!(
written_back,
writes * u64::from(takes),
"{name}: written back"
);
// The device keeps the value and its pass is Metal's own: its single-sample depth is
// stripped after each pass with depth writes that drew under none.
let strips_signs = keeps && !takes;
assert_eq!(
sign_strips,
strips * u64::from(strips_signs),
"{name}: sign strips"
);
if keeps {
let same = read_kept.iter().zip(MERGED).all(|(&a, b)| same_read(a, b));
assert!(same, "{name}: a pass without depth writes kept every value");
}
let taken = messages.taken_kinds();
let expected: Vec<Degradation> = first.difference(&taken).copied().collect();
let counts = assert_once_allowing(&messages.take_notices(), &expected, &allowed);
assert_eq!(
counts.contains_key(&Degradation::SignedDepthTest),
takes,
"{name}: signed-depth-test for the merge where the target takes the stand-in"
);
assert_once_allowing(&messages.take_notices(), &expected, &allowed);
}
layer_reported_nothing_at_all(&messages);
}
/// A target that takes no magnitude stand-in, or whose pass renders it through another image,
/// stores the words it did not write without their signs after a pass with depth writes, as
/// Metal's (probe `depthstore`: single-sample `Depth32Float` and `Depth32Float_Stencil8`, and a 4x
/// multisampled `Depth32Float` a blit from a buffer wrote, each sample): a `Depth32Float_Stencil8`,
/// a `Depth32Float` beside a separate `Stencil8` texture (the pass renders the scratch image of
/// both), and a 4x multisampled `Depth32Float` and `Depth32Float_Stencil8`, each holding the
/// merge's values, each loaded and stored by a pass that sets a state with depth writes and draws
/// nothing: every word read back is the one read before without its sign, each pass stripped once
/// (`WorkCounts::sign_strips`), and then a pass whose state has no depth writes keeps every bit.
/// A device's blit into a multisampled depth may change some values first (`drawn-depth-copy`);
/// the strip keeps what it stored but the sign. A device that may clamp such a value strips
/// nothing; `signed-depth-test` names the tests of a target that takes no stand-in on a device
/// whose test is not Metal's. Each case prints a `STRIPPED-DEPTH` line.
/// A NaN clear depth stores as Metal's (our probe `nanclear`, the M3 Max under macOS 27.0.1): a
/// `Depth32Float` or `Depth32Float_Stencil8` attachment, 1x and 4x, cleared to a NaN of either sign
/// and stored, holds `0x7fc00000` in every texel and sample; a `Depth16Unorm` one holds 0. Where
/// the device makes no write of the word (a multisampled depth with neither maintenance8's colour
/// copies nor an exact `FragDepth`, a device that may clamp a depth), the pass clears to 1.0,
/// announced. A draw at 0.5 in the clearing pass passes `Less` and fails `Greater`, as Metal's
/// test orders a NaN above every value, where the device's test is Metal's own or the pass clears
/// to 1.0; elsewhere the device compares the NaN as it is, announced (`signed-depth-test`). Each
/// case prints a `NAN-CLEAR-DEPTH` line.
#[test]
fn a_target_without_a_stand_in_stores_its_words_without_their_signs() {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
{
let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap();
let name = device.name().to_owned();
let keeps = !clamps_depth_uploads(&device);
let lane = Lane::new(device);
let before = lane.device.work_counts();
let words = |samples: u64| -> Vec<u32> {
(0..SIDE * SIDE * samples)
.map(|i| MERGED[((i + i / 16) % 16) as usize])
.collect()
};
let (depth, combined) = (BlitOption::None, BlitOption::DepthFromDepthStencil);
let mut stripped = 0u64;
// The separate textures: the depth by `replace_region`, the stencil the pass loads too.
{
let depth = lane.texture(PixelFormat::Depth32Float);
let bytes: Vec<u8> = MERGED.iter().flat_map(|w| w.to_le_bytes()).collect();
depth
.replace_region(Region::new_2d(0, 0, SIDE, SIDE), 0, 0, &bytes, SIDE * 4, 0)
.unwrap();
let mut d = TextureDescriptor::texture_2d(PixelFormat::Stencil8, SIDE, SIDE, false);
d.usage = TextureUsage::RENDER_TARGET;
d.resource_options = ResourceOptions::private();
let stencil = lane.device.new_texture(&d).unwrap();
let held = lane.words(&depth);
lane.bare_state_pass(&depth, Some(&stencil), true);
let read = lane.words(&depth);
lane.bare_state_pass(&depth, Some(&stencil), false);
let kept = lane.words(&depth);
println!("STRIPPED-DEPTH {name} separate: held {held:08x?}, read {read:08x?}");
if keeps {
let unsigned: Vec<u32> = held.iter().map(|&w| w & 0x7fff_ffff).collect();
assert_eq!(read, unsigned, "{name}: separate textures' depth, stripped");
stripped += 1;
}
assert_eq!(kept, read, "{name}: separate textures' depth, kept");
}
for (case, pf, samples, option) in [
("combined", PixelFormat::Depth32FloatStencil8, 1, combined),
("multisampled", PixelFormat::Depth32Float, 4, depth),
(
"multisampled combined",
PixelFormat::Depth32FloatStencil8,
4,
combined,
),
] {
let texture = match lane.blitted(pf, samples, &words(samples), option) {
Ok(texture) => texture,
Err(error) => {
println!("STRIPPED-DEPTH {name} {case}: the blit in refused: {error}");
continue;
}
};
let held = lane.blitted_words(&texture, samples, option);
lane.bare_state_pass(&texture, None, true);
let read = lane.blitted_words(&texture, samples, option);
lane.bare_state_pass(&texture, None, false);
let kept = lane.blitted_words(&texture, samples, option);
println!(
"STRIPPED-DEPTH {name} {case}: held {:08x?}, read {:08x?}",
&held[..16],
&read[..16]
);
if keeps {
let unsigned: Vec<u32> = held.iter().map(|&w| w & 0x7fff_ffff).collect();
assert_eq!(read, unsigned, "{name}: {case}, stripped");
stripped += 1;
}
assert_eq!(kept, read, "{name}: {case}, kept");
}
let strips = lane.device.work_counts().sign_strips - before.sign_strips;
println!("STRIPPED-DEPTH {name}: keeps {keeps}; sign strips {strips}");
assert_eq!(strips, stripped, "{name}: sign strips");
let signed = messages
.take_notices()
.iter()
.filter_map(|m| m.degradation.as_ref())
.any(|notice| notice.degradation == Degradation::SignedDepthTest);
assert_eq!(
signed,
signs_depth_tests(&lane.device),
"{name}: signed-depth-test for the tests of the targets without a stand-in"
);
}
layer_reported_nothing_at_all(&messages);
}
/// A NaN clear depth stores and tests as Metal's (our probe `nanclear`, the M3 Max under macOS
/// 27.0.1): a `Depth32Float` or `Depth32Float_Stencil8` attachment, 1x and 4x, cleared to a NaN of
/// either sign and stored, holds `0x7fc00000` in every texel and sample, and a draw at 0.5 in the
/// clearing pass passes `Less` and fails `Greater` (Metal's test orders a NaN above every value); a
/// `Depth16Unorm` one holds 0. Where the device makes no write of the word (a multisampled depth
/// with neither maintenance8's colour copies nor an exact `FragDepth`, a device that may clamp a
/// depth), the pass clears to 1.0, announced. Each case prints a `NAN-CLEAR-DEPTH` line.
#[test]
fn a_nan_clear_depth_stores_and_tests_as_metal_s() {
fn a_nan_clear_depth_stores_as_metal_s() {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
{
let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap();
let name = device.name().to_owned();
let keeps = !clamps_depth_uploads(&device);
let signs = signs_depth_tests(&device);
let colour = device.enabled().features.contains(&VkFeature::Maintenance8)
&& !device
.properties()
@@ -1327,7 +1130,8 @@ fn a_nan_clear_depth_stores_and_tests_as_metal_s() {
codes.iter().all(|&b| b == 0),
"{name}: Depth16Unorm's NaN clear stores 0"
);
// In the clearing pass, a draw at 0.5 passes `Less` and fails `Greater` against the NaN.
// In the clearing pass, a draw at 0.5 passes `Less` and fails `Greater` against the NaN,
// where the device's test is Metal's own or the pass cleared to 1.0.
for (compare, want) in [(CompareFunction::Less, 16), (CompareFunction::Greater, 0)] {
let depth = lane.texture(PixelFormat::Depth32Float);
let color = lane.pass(&depth, Some(f64::NAN), Some((0.5, compare, false)));
@@ -1335,11 +1139,13 @@ fn a_nan_clear_depth_stores_and_tests_as_metal_s() {
"NAN-CLEAR-DEPTH {name} draw at 0.5 under {compare:?}: {} of 16 drawn",
passed(&color)
);
assert_eq!(
passed(&color),
want,
"{name}: {compare:?} against a NaN clear"
);
if !signs {
assert_eq!(
passed(&color),
want,
"{name}: {compare:?} against a NaN clear"
);
}
}
messages.take_notices();
}
@@ -1436,7 +1242,7 @@ fn fresh_words(lane: &Lane, depth: &Texture, option: BlitOption) -> Vec<u32> {
.collect()
}
/// The kinds [`a_new_target_s_pattern_loaded_unwritten_tests_and_stores_as_metal_s`]'s device
/// The kinds [`a_new_target_s_pattern_loaded_unwritten_draws_as_the_device_tests_it`]'s device
/// announces at each occurrence, so that each format's targets announce their own.
const FRESH_SIGNED_EACH: [Degradation; 2] = [
Degradation::SignedDepthTest,
@@ -1444,15 +1250,14 @@ const FRESH_SIGNED_EACH: [Degradation; 2] = [
];
/// A new target's pattern, a NaN with the sign set, loaded by a pass before anything wrote it,
/// tests and stores as Metal's (the module docs): each target switched on once as its pass is
/// planned, a `Depth32Float` tested over its magnitude stand-in where the device's test is not
/// Metal's own, each such pass announcing the merge's corner, a `Depth32Float_Stencil8`'s test
/// announced at each pass that switches it on there; on a device that may clamp the pattern, each
/// target reads and stores zero, announced at its first load; a target cleared first is not
/// switched on. The device announces [`FRESH_SIGNED_EACH`] at each occurrence, so each format's
/// targets announce their own.
/// draws and stores as the device's test and pass take it (the module docs): as Metal's where the
/// device's test is Metal's own; elsewhere each pass that loads it announces `signed-depth-test`
/// and each texel no fragment wrote keeps the pattern, with or without its sign; on a device that
/// may clamp the pattern, each target reads and stores zero, announced at its first load; a
/// target cleared first announces neither. The device announces [`FRESH_SIGNED_EACH`] at each
/// occurrence, so each format's targets announce their own.
#[test]
fn a_new_target_s_pattern_loaded_unwritten_tests_and_stores_as_metal_s() {
fn a_new_target_s_pattern_loaded_unwritten_draws_as_the_device_tests_it() {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
{
@@ -1462,13 +1267,8 @@ fn a_new_target_s_pattern_loaded_unwritten_tests_and_stores_as_metal_s() {
let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), each).unwrap();
let name = device.name().to_owned();
let keeps = !clamps_depth_uploads(&device);
let native = device
.properties()
.driver_facts
.contains(&DriverFact::DepthTestComparesMagnitudes);
// The device keeps the pattern and its test is not Metal's: a `Depth32Float` takes the
// magnitude stand-in.
let takes = signs_depth_tests(&device);
// The device keeps the pattern and its test is not Metal's own.
let signs = signs_depth_tests(&device);
let lane = Lane::new(device);
let white = |pf: PixelFormat| {
let mut d = white_descriptor(&lane.library);
@@ -1479,7 +1279,6 @@ fn a_new_target_s_pattern_loaded_unwritten_tests_and_stores_as_metal_s() {
let options = PipelineOptions::default();
lane.device.new_render_pipeline_state(&d, &options).unwrap()
};
let before = lane.device.work_counts();
let all = (FRESH_SIDE * FRESH_SIDE) as usize;
// Each function, whether a draw at 0.5 passes over Metal's pattern and over a zero depth.
let compares = [
@@ -1499,8 +1298,6 @@ fn a_new_target_s_pattern_loaded_unwritten_tests_and_stores_as_metal_s() {
),
] {
let white = white(pf);
let tested = pf == PixelFormat::Depth32Float || native;
let case_before = lane.device.work_counts();
let mut notices = Vec::new();
for (compare, over_pattern, over_zero) in compares {
let target = fresh_target(&lane, pf);
@@ -1512,65 +1309,53 @@ fn a_new_target_s_pattern_loaded_unwritten_tests_and_stores_as_metal_s() {
stored {:08x?}",
&words[..2]
);
// Where the device keeps the pattern, each texel a fragment wrote holds 0.5 and
// every other the pattern without its sign, as Metal's; elsewhere the target reads
// zero, announced, and draws and stores as over a zero depth.
// Where the device keeps the pattern and its test is Metal's own, each texel a
// fragment wrote holds 0.5 and every other the pattern without its sign, as
// Metal's; where its test is not, every other the pattern, with or without its
// sign; elsewhere the target reads zero, announced, and draws and stores as over a
// zero depth.
let (draws, unwritten) = match keeps {
true => (over_pattern, 0x7fff_ffff),
false => (over_zero, 0),
};
if tested || !keeps {
if !signs {
let want = if draws { all } else { 0 };
assert_eq!(drawn, want, "{name}: {case} under {compare:?}");
}
let want = if drawn == all { 0x3f00_0000 } else { unwritten };
let stored = |w: u32| match drawn == all {
true => w == 0x3f00_0000,
false => w == unwritten || (signs && w == 0xffff_ffff),
};
assert!(
words.iter().all(|&w| w == want),
"{name}: {case} under {compare:?} stores {want:08x}: {:08x?}",
words.iter().all(|&w| stored(w)),
"{name}: {case} under {compare:?} stores {unwritten:08x}: {:08x?}",
&words[..4]
);
}
let written_back =
lane.device.work_counts().magnitude_write_backs - case_before.magnitude_write_backs;
let announced = counts(&notices);
let of = |kind: Degradation| announced.get(&kind).copied().unwrap_or(0);
println!(
"FRESH-SIGNED-DEPTH {name} {case}: signed-depth-test {}, fresh-pattern-zeroed {}, \
written back {written_back}",
"FRESH-SIGNED-DEPTH {name} {case}: signed-depth-test {}, fresh-pattern-zeroed {}",
of(Degradation::SignedDepthTest),
of(Degradation::FreshPatternZeroed),
);
// Over the stand-in, each pass stores the depth after a draw with depth writes: its
// words are merged back, which announces the merge's corner (a draw writing exactly
// +inf over the stored NaN). A target without a stand-in on a device whose test is not
// Metal's announces its test at the pass that loads its pattern and switches it on.
let stands_in = pf == PixelFormat::Depth32Float && takes;
assert_eq!(
written_back,
if stands_in { targets as u64 } else { 0 },
"{name}: {case}: passes merged back"
);
let signed = match (keeps, tested) {
(false, _) => 0,
(true, true) => written_back as usize,
(true, false) => targets,
};
// A device whose test is not Metal's announces its test at each pass that loads a
// target's pattern.
let signed = if signs { targets } else { 0 };
assert_eq!(
of(Degradation::SignedDepthTest),
signed,
"{name}: {case}: signed-depth-test"
);
if keeps && !tested {
let at_load = notices
.iter()
.filter_map(|m| m.degradation.as_ref())
.filter(|n| n.degradation == Degradation::SignedDepthTest)
.all(|n| n.reason.starts_with("new_texture "));
assert!(
at_load,
"{name}: {case}: its test, at the pass that loads it"
);
}
let at_load = notices
.iter()
.filter_map(|m| m.degradation.as_ref())
.filter(|n| n.degradation == Degradation::SignedDepthTest)
.all(|n| n.reason.starts_with("new_texture "));
assert!(
at_load,
"{name}: {case}: its test, at the pass that loads it"
);
// A device that may clamp the pattern writes none: zero, announced where each target's
// pass first loads it.
let zeroed = if keeps { 0 } else { targets };
@@ -1580,33 +1365,17 @@ fn a_new_target_s_pattern_loaded_unwritten_tests_and_stores_as_metal_s() {
"{name}: {case}: fresh-pattern-zeroed"
);
}
let after = lane.device.work_counts();
let moved = |of: fn(&WorkCounts) -> u64| of(&after) - of(&before);
println!(
"FRESH-SIGNED-DEPTH {name}: switched on {}, passes over a stand-in {}",
moved(|c| c.signed_depth_switch_ons),
moved(|c| c.magnitude_stand_in_passes),
);
// Each new target switched on once where the device keeps its pattern; none elsewhere.
let switched = if keeps { 2 * targets as u64 } else { 0 };
assert_eq!(moved(|c| c.signed_depth_switch_ons), switched, "{name}");
let stand_ins = if takes { targets as u64 } else { 0 };
assert_eq!(moved(|c| c.magnitude_stand_in_passes), stand_ins, "{name}");
// A new target cleared first loads its clear in place.
// A new target cleared first loads its clear.
let white = white(PixelFormat::Depth32Float);
let target = fresh_target(&lane, PixelFormat::Depth32Float);
lane.clearing_pass(&target, 0.75);
let before = lane.device.work_counts();
let pair = (&target, PixelFormat::Depth32Float);
let drawn = fresh_pass(&lane, &white, pair, CompareFunction::Less);
let switched =
lane.device.work_counts().signed_depth_switch_ons - before.signed_depth_switch_ons;
println!("FRESH-SIGNED-DEPTH {name} cleared first: drawn {drawn}, switched on {switched}");
println!("FRESH-SIGNED-DEPTH {name} cleared first: drawn {drawn}");
assert_eq!(
drawn, all,
"{name}: a draw at 0.5 under Less over a clear of 0.75"
);
assert_eq!(switched, 0, "{name}: a cleared target is not switched on");
let announced = counts(&messages.take_notices());
assert!(
FRESH_SIGNED_EACH
@@ -1618,10 +1387,9 @@ fn a_new_target_s_pattern_loaded_unwritten_tests_and_stores_as_metal_s() {
layer_reported_nothing_at_all(&messages);
}
/// The depth of an ordinary pass, which never stores a value whose stand-in is not itself, loads
/// in place: no switch-on, no pass over a stand-in, no merge, no kept image or stand-in made, and
/// the command buffers each pass begins and submits are printed (`WorkCounts`), the batch's to
/// compare with the base's.
/// The depth of an ordinary pass loads in place: no kept image or stand-in made, and the command
/// buffers each pass begins and submits are printed (`WorkCounts`), the batch's to compare with
/// the base's.
#[test]
fn an_ordinary_depth_loads_in_place() {
let cache = ScratchCache::new().unwrap();
@@ -1648,18 +1416,10 @@ fn an_ordinary_depth_loads_in_place() {
moved(|c| c.kept_backings_made),
moved(|c| c.stand_ins_made),
);
assert_eq!(moved(|c| c.signed_depth_switch_ons), 0, "{name}");
assert_eq!(moved(|c| c.magnitude_stand_in_passes), 0, "{name}");
assert_eq!(moved(|c| c.magnitude_write_backs), 0, "{name}");
assert_eq!(moved(|c| c.kept_backings_made), 0, "{name}");
assert_eq!(moved(|c| c.stand_ins_made), 0, "{name}");
// 0.5, then each pass's 0.25.
assert_eq!(texels(&depth)[..4], 0.25f32.to_le_bytes(), "{name}");
// A pass with depth writes that draws under none strips no depth never switched on.
lane.state_pass(&depth, true, Then::Nothing);
let strips = lane.device.work_counts().sign_strips - before.sign_strips;
println!("ORDINARY-DEPTH {name}: sign strips {strips}");
assert_eq!(strips, 0, "{name}: sign strips");
messages.take_notices();
}
layer_reported_nothing_at_all(&messages);
@@ -166,11 +166,9 @@ fn made(
for &(colors, attachments, samples) in pipelines {
first.extend(lane.made(colors, attachments, samples));
}
first.extend(
resolves
.iter()
.filter_map(|&pf| resolve_kind(&lane.device, pf, MSAA.samples as u32)),
);
if !resolves.is_empty() {
first.extend(resolve_kind(&lane.device, MSAA.samples as u32));
}
first
}
@@ -596,7 +594,7 @@ fn a_clear_resolved_into_the_srgb_twin_without_a_draw_keeps_the_samples() {
lane.run(&descriptor, Draw::None, None);
// The pass resolves the 4x attachment: no draw, no buffer. The resolve is into the
// attachment's format's sRGB twin, which the crate-owned resolve draws on every device
// and under either policy (`color_resolve.rs`), announced `shader-resolve`.
// (`color_resolve.rs`), announced `shader-resolve`.
let mut first = made(&lane, &[], &[], false);
first.insert(Degradation::ShaderResolve);
announces(&messages, &case, false, &first);
@@ -32,8 +32,12 @@ use metal2vulkan_runtime::{
TextureDescriptor,
};
/// The kinds this lane's resolves announce, for `degrade_notices`' census.
pub(super) const XR_RESOLVE: [Degradation; 1] = [Degradation::ExtendedRangeResolve];
/// The kinds this lane's resolves announce, for `degrade_notices`' census: the crate-owned
/// resolve after the pass, which no device's average replaces for an extended-range attachment.
pub(super) const XR_RESOLVE: [Degradation; 2] = [
Degradation::ExtendedRangeResolve,
Degradation::ShaderResolve,
];
/// The target's width and height.
const WIDTH: u64 = 8;
@@ -418,7 +422,7 @@ fn extended_range_resolves_are_metals_or_within_a_code() {
);
// The `Shared` textures and buffers the draws read and write announce their memory on a
// device without unified memory.
let mut kinds = vec![XR_RESOLVE[0], Degradation::ShaderResolve];
let mut kinds = XR_RESOLVE.to_vec();
kinds.extend(forced(&[(
Degradation::SharedInSystemMemory,
shared_in_system_memory(&lane.device),
@@ -182,8 +182,7 @@ fn copy(
}
/// Probes 8 and 8b: depth and stencil formats copy their bytes to and from colour formats of
/// their unit, in a depth image or (for a read-only `Depth32Float` on a device whose depth images
/// may not keep a `float`) a depth twin.
/// their unit, in a depth image.
#[test]
fn depth_and_stencil_copy_their_bytes_with_colour_formats_of_their_unit() {
let messages = Messages::default();
@@ -257,11 +257,12 @@ fn scratched(messages: &Messages) -> bool {
}
/// The kind a resolve of a 4x attachment of `pf` that a pass fetched announces on `lane`'s
/// device: where it reads sample planes, the exact resolve reads them for a format of Metal's
/// rules and the device's average resolves any other; else as `degrade_notices::resolve_kind`.
/// device: where it reads sample planes, the crate-owned resolve reads them for a format of
/// Metal's rules and the device's average resolves any other; else as
/// `degrade_notices::resolve_kind`.
fn fetched_resolve(lane: &Lane, pf: PixelFormat) -> Option<Degradation> {
if !reads_planes(lane) {
return resolve_kind(&lane.device, pf, 4);
return resolve_kind(&lane.device, 4);
}
let rules = metal2vulkan::metal::format::direct_format(pf)
.and_then(metal2vulkan::bind::ColorResolveFormat::of)
@@ -270,7 +271,7 @@ fn fetched_resolve(lane: &Lane, pf: PixelFormat) -> Option<Degradation> {
// `resolve_kind` says.
match rules {
true => Some(Degradation::ShaderResolve),
false => resolve_kind(&lane.device, pf, 4),
false => resolve_kind(&lane.device, 4),
}
}
@@ -1642,12 +1643,10 @@ fn a_plain_draw_before_a_fetch_takes_the_devices_faster_form() {
/// that clears it to 0.75 and stores it renders into it. A pass that loads it, halves it by a
/// fetch, stores it and resolves it renders into a 4x scratch image that has the usage, copied in
/// before the pass and back after it: the resolve holds 0.375. A pass that loads it and only
/// resolves it then resolves what the scratch copied back, 0.375 again (by the exact resolve,
/// from a copy of its samples, where the device resolves `R32Float` so). Each holds Metal's
/// texels on every venue, and the scratch is announced once, naming the missing usage and the
/// caller. Through the attachment's multisampled storage image the fetching pass splits for the
/// device's resolve, announced as the interlock's splits are, where the exact resolve does not
/// resolve it.
/// resolves it then resolves what the scratch copied back, 0.375 again, by the device's average.
/// Each holds Metal's texels on every venue, and the scratch is announced once, naming the
/// missing usage and the caller. Through the attachment's multisampled storage image the fetching
/// pass splits for the device's resolve, announced as the interlock's splits are.
#[test]
fn a_callers_multisampled_image_without_the_fetch_usage_fetches_through_a_scratch() {
let (messages, cache, lane) = lane();
@@ -1720,13 +1719,11 @@ fn a_callers_multisampled_image_without_the_fetch_usage_fetches_through_a_scratc
);
let notices = messages.take_notices();
messages.restore_notices(notices.clone());
// The caller's image rests out of `GENERAL`; it takes no input attachment usage but transfer
// reads, so where the device's average is not measured to be Metal's the exact resolve reads
// the fetch's scratch, which has the usage, and in the pass that only resolves a copy of the
// image's samples (`shader-resolve`); and where the device reads sample planes, the fetch's
// pass reads them and resolves from them by the exact resolve.
// The caller's image rests out of `GENERAL`. The device's average resolves it, announced
// where it is not measured to be Metal's; where the device reads sample planes, the fetch's
// pass reads them and resolves from them by the crate-owned resolve (`shader-resolve`).
let planes = reads_planes(&lane);
let exact = resolve_kind(&lane.device, pf, 4).is_some();
let rounded = resolve_kind(&lane.device, 4).is_some();
let mut first = made(
&lane,
&[pipeline_descriptor(
@@ -1739,13 +1736,14 @@ fn a_callers_multisampled_image_without_the_fetch_usage_fetches_through_a_scratc
// Through the attachment's own multisampled storage image the fetching draw's instance
// leaves the attachment out of its subpass, and the device's resolve needs it in one: the
// pass splits there (the RTX 3080's two instances), announced where the
// device announces the interlock's splits; the exact resolve, drawn after the pass, needs
// none, and through sample planes it reads them: one instance either way.
let split = !planes && !exact && announces_interlock_splits(&lane);
// device announces the interlock's splits; through sample planes the resolve reads them: one
// instance.
let split = !planes && announces_interlock_splits(&lane);
first.extend(forced(&[
(Degradation::WrappedImageLayoutTransitions, true),
(Degradation::SamplePlanes, planes),
(Degradation::ShaderResolve, exact || planes),
(Degradation::ShaderResolve, planes),
(Degradation::DeviceRoundedResolve, rounded),
(Degradation::RenderPassSplit, split),
]));
let counts = assert_made_once(&messages, &[Degradation::FetchThroughScratch], &first);
@@ -1746,12 +1746,11 @@ fn a_heap_texture_buffer_is_the_heap_s_bytes() {
/// Two `Depth32Float` textures a shader reads, side by side in a placement heap, keep their texels
/// (a Metal heap probe, an M3 Max and an M4 alike: each read back as uploaded, then a buffer filled
/// over the first one's answered bytes changed every texel of it and none of the second's). Where
/// the device holds such a texture with a depth twin (RADV, ANV and unmeasured drivers) the
/// answered size takes the twin's bytes too, so the second texture, uploaded before the first,
/// keeps its texels when the first's upload writes its twin; the comparisons of both compare as a
/// texture's outside a heap does; in a `Shared` and a `Private` heap. `HEAPTEX depth` lines print
/// the answer and the device's twin notices.
/// over the first one's answered bytes changed every texel of it and none of the second's). Each
/// reads back what a texture outside a heap of the same upload reads (the device's depth image may
/// store a value outside `[0, 1]` clamped or a denormal as zero, announced), and the comparisons
/// of both compare as a texture's outside a heap does; in a `Shared` and a `Private` heap.
/// `HEAPTEX depth` lines print the answer and the device's notices.
///
/// Where the device's driver lays depth and stencil images apart from their memory
/// (`DriverFact::DepthStencilImagesLieApart`: MoltenVK, which makes such an image's Metal texture
@@ -1797,9 +1796,11 @@ fn heap_depth_textures_keep_their_bytes_with_their_twins() {
descriptor.resource_options = ResourceOptions::private();
let texture = device.new_texture(&descriptor).unwrap();
upload(&queue, &[(&texture, bytes)], side);
compare(device, (&texture, None), &state, &jobs, 1)
let compares = compare(device, (&texture, None), &state, &jobs, 1);
(texels(&queue, &texture, side), compares)
};
let (first_compares, second_compares) = (plain(&first), plain(&second));
let ((first_kept, first_compares), (second_kept, second_compares)) =
(plain(&first), plain(&second));
for storage in [StorageMode::Shared, StorageMode::Private] {
let options = tracked(storage);
let mut descriptor =
@@ -1821,10 +1822,10 @@ fn heap_depth_textures_keep_their_bytes_with_their_twins() {
let a = placement.new_texture_at_offset(&descriptor, 0).unwrap();
let b = placement.new_texture_at_offset(&descriptor, next).unwrap();
made = true;
// The second first: the first's upload writes its twin, if it has one, after.
// The second first: the first's upload lands after it.
upload(&queue, &[(&b, &second), (&a, &first)], side);
assert_eq!(texels(&queue, &a, side), first, "{what}: the first");
assert_eq!(texels(&queue, &b, side), second, "{what}: the second");
assert_eq!(texels(&queue, &a, side), first_kept, "{what}: the first");
assert_eq!(texels(&queue, &b, side), second_kept, "{what}: the second");
let compared = compare(device, (&a, None), &state, &jobs, 1);
assert_eq!(bits(&compared), bits(&first_compares), "{what}: the first");
let compared = compare(device, (&b, None), &state, &jobs, 1);
@@ -1836,7 +1837,11 @@ fn heap_depth_textures_keep_their_bytes_with_their_twins() {
// A buffer over the first's bytes, filled: the second keeps its texels.
let over = placement.new_buffer_at_offset(size, options, 0).unwrap();
gpu_fill(&queue, &over, 0..size, 0x3e);
assert_eq!(texels(&queue, &b, side), second, "{what}: after the fill");
assert_eq!(
texels(&queue, &b, side),
second_kept,
"{what}: after the fill"
);
let compared = compare(device, (&b, None), &state, &jobs, 1);
assert_eq!(
bits(&compared),
@@ -1847,7 +1852,7 @@ fn heap_depth_textures_keep_their_bytes_with_their_twins() {
.as_chunks::<4>()
.0
.iter()
.zip(first.as_chunks::<4>().0.iter())
.zip(first_kept.as_chunks::<4>().0.iter())
.filter(|(after, before)| after != before)
.count();
eprintln!(
@@ -1873,13 +1878,9 @@ fn heap_depth_textures_keep_their_bytes_with_their_twins() {
};
let notices = counts(&messages.take_notices());
let count = |kind| notices.get(&kind).copied().unwrap_or(0);
let twins = count(Degradation::DepthTwin);
let aparts = count(APART[0]);
let shadowed = count(Degradation::ShadowedTexture);
eprintln!(
"HEAPTEX depth: {twins} depth-twin notices, {aparts} heap-depth-stencil-apart, \
{shadowed} shadowed-texture"
);
eprintln!("HEAPTEX depth: {aparts} heap-depth-stencil-apart, {shadowed} shadowed-texture");
assert_eq!(aparts, 0);
// A shadow of a `Shared` heap's bytes where its memory takes no optimal depth image: every
// texel the fill covered changed, as in a shadow where the driver lays the image apart.
@@ -1645,7 +1645,7 @@ fn passes_and_draws_are_refused_as_metal_refuses_them() {
// A NaN clear depth of a format whose store of one is not measured, where the device makes
// it (a value outside [0, 1] clears to the nearer end:
// `clears_store_the_bytes_metal_stores`; a NaN of a measured format clears as Metal's:
// `depth_denormals::a_nan_clear_depth_stores_and_tests_as_metal_s`).
// `depth_denormals::a_nan_clear_depth_stores_as_metal_s`).
match attachment(
&device,
PixelFormat::Depth24UnormStencil8,
@@ -38,33 +38,27 @@
//! a pass of no draws that loads it, and compares every channel of the resolve texture with the
//! rule applied to the samples read back: every pair of codes of an 8-bit channel at 2 samples,
//! every pair as `(a, a, b, b)` and random texels at 4, and random texels with the edge values of
//! a wider channel. Under the lanes' policy (`DevicePolicy::exact_answers`, so
//! `ResolvePolicy::Exact`) the runtime resolves every one of these formats by Metal's rules on
//! every device (its exact resolve, or a driver measured to average as Metal does), so every
//! channel must match; under the default, `ResolvePolicy::Device`, the device's average resolves
//! them in the pass, announced, and [`the_device_resolve_rounds_as_announced`] measures it against
//! the rules. Metal has no texture of more than 4 samples on Apple silicon, so a resolve of 8 is
//! compared with the same rules and printed as unmeasured, never as Metal's. A device without
//! `imageViewFormatReinterpretation` (MoltenVK) views no texel as an unsigned format of other
//! components, so the formats only such a view reads back are printed as unread there. The runs
//! before the runtime resolved so (at 2b41d71d) measured each driver's own
//! average, which `DriverFact::ColorResolveAverageIsMetals` records.
//! a wider channel. The device's average resolves every one of these formats in the pass,
//! announced where it is not measured to be Metal's, and [`the_device_resolve_rounds_as_announced`]
//! measures it against the rules. Metal has no texture of more than 4 samples on Apple silicon, so
//! a resolve of 8 is compared with the same rules and printed as unmeasured, never as Metal's. A
//! device without `imageViewFormatReinterpretation` (MoltenVK) views no texel as an unsigned format
//! of other components, so the formats only such a view reads back are printed as unread there. The
//! runs before the runtime resolved so (at 2b41d71d) measured each driver's own average, which
//! `DriverFact::ColorResolveAverageIsMetals` records.
use super::presenting::{image_info, made_image, shared_among};
use super::resolves::{lane, lane_with, quiet, Lane, FULL, WHITE};
use crate::air_library::AirLibrary;
use super::resolves::{lane, quiet, Lane};
use crate::candidate::runtime_samples::{encode_through, library, shape};
use crate::executor_contract::multisample::{ReadbackView, SampleRead};
use crate::runtime_lane::buffer_with;
use metal2vulkan::bind::{SRGB_RESOLVE_LINEAR, SRGB_RESOLVE_THRESHOLDS};
use metal2vulkan::device::{DriverFact, ResolvePolicy};
use metal2vulkan::device::DriverFact;
use metal2vulkan::metal::state::DepthStencilDescriptor;
use metal2vulkan::metal::{CompareFunction, PixelFormat, PrimitiveType, TextureType, TextureUsage};
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
use metal2vulkan_runtime::{
BlitOption, ClearColor, Degradation, LoadAction, PipelineOptions, RenderPassDescriptor,
ResourceOptions, StoreAction, Texture, TextureDescriptor, VkImageLayouts,
ResourceOptions, StoreAction, Texture, TextureDescriptor,
};
/// How a channel's bits encode its value.
@@ -730,17 +724,6 @@ fn case_extent(n: u32) -> [u32; 2] {
/// Draw a texture of `case` at `n` samples ([`case_extent`]), read its samples back, resolve it,
/// and compare.
fn resolve_case(lane: &Lane, case: &Case, n: u32) -> Result<Outcome, String> {
resolve_case_through(lane, case, n, None)
}
/// [`resolve_case`], where `through` names a texture of the case's format, samples and extent:
/// the drawn samples copied into it after the readback (`copy_texture`), and it resolved instead.
fn resolve_case_through(
lane: &Lane,
case: &Case,
n: u32,
through: Option<&Texture>,
) -> Result<Outcome, String> {
let [width, height] = case_extent(n);
let mut r = SplitMix(0x5250_4c00 ^ (u64::from(n) << 32) ^ case.pf as u64);
let pixels = (width * height) as usize;
@@ -845,21 +828,9 @@ fn resolve_case_through(
n,
)
.map_err(|e| format!("the readback: {e}"))?;
let source = match through {
Some(texture) => {
let mut blit = command_buffer
.blit_command_encoder()
.map_err(|e| format!("the copy's encoder: {e}"))?;
blit.copy_texture(&msaa, texture)
.map_err(|e| format!("the copy into the resolved texture: {e}"))?;
blit.end_encoding().map_err(|e| e.to_string())?;
texture.clone()
}
None => msaa.clone(),
};
let mut pass = RenderPassDescriptor::new();
let target = &mut pass.color_attachments[0];
target.texture = Some(source);
target.texture = Some(msaa.clone());
target.load_action = LoadAction::Load;
target.store_action = StoreAction::MultisampleResolve;
target.resolve_texture = Some(resolved.clone());
@@ -971,77 +942,8 @@ fn compare_shared(
}
}
/// Every closed format at every sample count the device takes, printed against Metal's rules
/// and held to them (the module docs).
#[test]
fn color_resolves_against_metals_rules() {
let (messages, _cache, lane) = lane();
let name = lane.device.name().to_owned();
let description = &lane.device.properties().description;
eprintln!(
"resolve rounding on {name}: driver {:?}, driverVersion {:#x}, vendor {:#x}",
description.driver_id, description.driver_version, description.vendor_id
);
let mut differ = Vec::new();
for n in [2u32, 4, 8] {
let supported = lane
.device
.properties()
.supports_texture_sample_count(n.into())
.unwrap();
if !supported {
eprintln!("resolve rounding on {name}: no texture of {n} samples");
continue;
}
for case in CASES {
let pf = case.pf;
if !case.resolves(n) {
eprintln!(
"resolve rounding {pf:?} x{n} on {name}: skipped, Metal's rule of the format \
holds at 2 and 4 samples (the device's average resolves it, announced)"
);
continue;
}
match resolve_case(&lane, case, n) {
Err(why) => eprintln!("resolve rounding {pf:?} x{n} on {name}: {why}"),
Ok(outcome) => {
if outcome.differ != 0 {
differ.push(format!("{pf:?} x{n}: {} channels", outcome.differ));
}
let verdict = match (n, outcome.differ) {
(2 | 4, 0) => "Metal's".to_owned(),
(2 | 4, _) => "not Metal's".to_owned(),
(_, 0) => {
"unmeasured (no Metal answer at this count), Metal's rules".to_owned()
}
_ => "unmeasured (no Metal answer at this count), not Metal's rules"
.to_owned(),
};
eprintln!(
"resolve rounding {pf:?} x{n} on {name}: {verdict}, {} of {} channels \
differ ({} samples stored otherwise than drawn){}",
outcome.differ,
outcome.channels,
outcome.changed,
if outcome.examples.is_empty() {
String::new()
} else {
format!(": {}", outcome.examples.join("; "))
}
);
}
}
}
}
assert!(
differ.is_empty(),
"resolves not by Metal's rules on {name}: {differ:#?}"
);
quiet(lane, &messages);
}
/// Under `ResolvePolicy::Device`, the default, every closed format at every sample count the
/// device takes resolves by the device's `AVERAGE` in the pass: nothing announces
/// Every closed format at every sample count the device takes resolves by the device's
/// `AVERAGE` in the pass: nothing announces
/// `shader-resolve`, and `device-rounded-resolve` is announced exactly where the device's average
/// is not measured to be Metal's (`DriverFact::ColorResolveAverageIsMetals`, at 2 and 4 samples),
/// where every channel is Metal's. Elsewhere what the device's average gives against Metal's rule
@@ -1051,9 +953,7 @@ fn color_resolves_against_metals_rules() {
/// counted, not bounded).
#[test]
fn the_device_resolve_rounds_as_announced() {
let (messages, _cache, lane) = lane_with(|options| {
options.policy.resolve = ResolvePolicy::Device;
});
let (messages, _cache, lane) = lane();
let name = lane.device.name().to_owned();
let description = &lane.device.properties().description;
eprintln!(
@@ -1121,7 +1021,7 @@ fn the_device_resolve_rounds_as_announced() {
assert_eq!(
counts.get(&Degradation::ShaderResolve),
None,
"shader-resolve on {name} under the device's resolve"
"shader-resolve on {name}"
);
// At more than 4 samples no device's average is measured to be Metal's.
let rounded = !metals || resolved_past_metal;
@@ -1144,179 +1044,7 @@ fn the_device_resolve_rounds_as_announced() {
quiet(lane, &messages);
}
/// A caller's multisampled image of `pf`, `n` samples and `extent`, made with `usage` alone
/// (`new_texture_with_vk_image`, as a `RenderTarget` texture), and its image and memory, which
/// the caller destroys after the texture and every command buffer that used it.
fn callers_image(
lane: &Lane,
pf: PixelFormat,
n: u32,
[width, height]: [u32; 2],
usage: ash::vk::ImageUsageFlags,
) -> (Texture, ash::vk::Image, ash::vk::DeviceMemory) {
let format = metal2vulkan::metal::format::direct_format(pf).expect("a direct format");
// SAFETY: used only while the device lives.
let raw = unsafe { lane.device.raw() };
// SAFETY: a physical device of the instance.
let memory = unsafe {
raw.instance
.get_physical_device_memory_properties(raw.physical_device)
};
let info = image_info(format.into(), usage)
.extent(ash::vk::Extent3D {
width,
height,
depth: 1,
})
.samples(ash::vk::SampleCountFlags::from_raw(n));
let info = shared_among(info, raw.queue_families);
// SAFETY: the device is live.
let (image, image_memory) = unsafe { made_image(raw.device, &memory, &info) };
let mut descriptor = TextureDescriptor::texture_2d(pf, width.into(), height.into(), false);
if n > 1 {
descriptor.texture_type = TextureType::Type2DMultisample;
descriptor.sample_count = n.into();
}
descriptor.usage = TextureUsage::RENDER_TARGET;
descriptor.resource_options = ResourceOptions::private();
// SAFETY: the image is the device's, made with `info`, and nothing else uses it.
let texture = unsafe {
lane.device.new_texture_with_vk_image(
&descriptor,
image,
&info,
VkImageLayouts::new(
ash::vk::ImageLayout::UNDEFINED.into(),
ash::vk::ImageLayout::TRANSFER_DST_OPTIMAL.into(),
),
)
}
.unwrap();
(texture, image, image_memory)
}
/// Destroy a caller's image of [`callers_image`] and free its memory.
///
/// # Safety
///
/// Nothing uses them: their texture is gone and every command buffer that used it completed.
unsafe fn destroy_callers(lane: &Lane, image: ash::vk::Image, memory: ash::vk::DeviceMemory) {
// SAFETY: the caller's contract; the device is live.
unsafe {
let raw = lane.device.raw();
raw.device.destroy_image(image, None);
raw.device.free_memory(memory, None);
}
}
/// The formats [`a_callers_image_without_input_usage_resolves_by_metals_rules`] resolves: 8-bit
/// unorm, sRGB, 16-bit snorm and 32-bit float channels.
const COPIED: [PixelFormat; 4] = [
PixelFormat::RGBA8Unorm,
PixelFormat::RGBA8UnormSRGB,
PixelFormat::RGBA16Snorm,
PixelFormat::R32Float,
];
/// A caller's multisampled image made with color attachment and transfer usage alone, so without
/// the input attachment usage the exact resolve reads an attachment through: where the device
/// resolves its format by the exact resolve, the runtime copies its samples into a scratch image
/// that has the usage and resolves that (`color_resolve.rs`). For each of [`COPIED`] at 2 and 4
/// samples, those the device takes (the others printed as skipped), the drawn samples (read back
/// from the runtime's own texture, [`resolve_case`]) are copied into such an image, which a pass of
/// no draws loads and resolves: every channel of the resolve must be Metal's rule over the
/// samples, and no pass announces `device-rounded-resolve`.
/// Where the device resolves so (`degrade_notices::resolve_kind`), `shader-resolve`'s reason, the
/// first pass's, names the copy: the path ran.
#[test]
fn a_callers_image_without_input_usage_resolves_by_metals_rules() {
let (messages, _cache, lane) = lane();
let name = lane.device.name().to_owned();
messages.take_notices();
let usage = ash::vk::ImageUsageFlags::COLOR_ATTACHMENT
| ash::vk::ImageUsageFlags::TRANSFER_SRC
| ash::vk::ImageUsageFlags::TRANSFER_DST;
let mut exact = false;
let mut differ = Vec::new();
for n in [2u32, 4] {
let supported = lane
.device
.properties()
.supports_texture_sample_count(n.into())
.unwrap();
if !supported {
eprintln!(
"resolve rounding through a caller's image on {name}: no texture of {n} samples"
);
continue;
}
for pf in COPIED {
let case = CASES.iter().find(|c| c.pf == pf).expect("a closed format");
let kind = super::degrade_notices::resolve_kind(&lane.device, pf, n);
exact |= kind == Some(Degradation::ShaderResolve);
let (callers, image, memory) = callers_image(&lane, pf, n, case_extent(n), usage);
let what = format!("{pf:?} x{n} through a caller's image on {name}");
let outcome = match resolve_case_through(&lane, case, n, Some(&callers)) {
Ok(outcome) => outcome,
// Refused before the command buffer was committed: nothing used the image.
Err(why) if why.starts_with("unread") => {
eprintln!("resolve rounding {what}: {why}");
drop(callers);
// SAFETY: the texture is gone and no command buffer that used it was
// committed.
unsafe { destroy_callers(&lane, image, memory) };
continue;
}
Err(why) => panic!("{what}: {why}"),
};
drop(callers);
// SAFETY: the texture is gone and its command buffer completed.
unsafe { destroy_callers(&lane, image, memory) };
eprintln!(
"resolve rounding {what}: {} of {} channels differ from Metal's rule ({} samples \
stored otherwise than drawn){}",
outcome.differ,
outcome.channels,
outcome.changed,
if outcome.examples.is_empty() {
String::new()
} else {
format!(": {}", outcome.examples.join("; "))
}
);
if outcome.differ != 0 {
differ.push(format!("{pf:?} x{n}: {} channels", outcome.differ));
}
}
}
let notices = messages.take_notices();
let counts = super::degrade_notices::counts(&notices);
eprintln!("resolve rounding through a caller's image on {name}: announced {counts:?}");
assert!(
differ.is_empty(),
"resolves through a caller's image not by Metal's rules on {name}: {differ:#?}"
);
assert_eq!(
counts.get(&Degradation::DeviceRoundedResolve),
None,
"device-rounded-resolve on {name}"
);
if exact {
let reason = notices
.iter()
.filter_map(|message| message.degradation.as_ref())
.find(|notice| notice.degradation == Degradation::ShaderResolve)
.map(|notice| notice.reason.clone())
.unwrap_or_default();
assert!(
reason.contains("copied into a scratch image"),
"shader-resolve's reason on {name} names no copy: {reason:?}"
);
}
quiet(lane, &messages);
}
/// The side of [`a_maps_form_pass_resolves_bgra8_by_metals_rule`]'s targets.
/// The side of [`a_maps_form_pass_resolves_bgra8_as_announced`]'s targets.
const MAPS_SIDE: u32 = 64;
/// One pass of `pf` at 4 samples beside Maps' depth form (a 4x `Depth32Float_Stencil8` of
@@ -1496,15 +1224,21 @@ fn maps_form_pass(
}
/// Maps' color formats at 4 samples (`BGRA8Unorm_sRGB`, `BGRA8Unorm`), each in a pass beside its
/// depth form, resolved in the pass: on a cleared and on a randomly filled target, three runs
/// each, every channel of the resolve is the rule over the samples read back (half-covered diagonal
/// pixels and per-sample colors among them), and no pass announces `device-rounded-resolve`. The
/// coordinator's ask of 2026-10-09 for the consumer, who relays that kind only for the half-float
/// formats measured on the M3.
/// depth form, resolved in the pass by the device's average: on a cleared and on a randomly filled
/// target, three runs each, the channels of the resolve that differ from the rule over the samples
/// read back (half-covered diagonal pixels and per-sample colors among them) are printed. Where
/// the device's average is measured to be Metal's (`DriverFact::ColorResolveAverageIsMetals`)
/// every channel is the rule and no pass announces `device-rounded-resolve`; elsewhere a pass
/// announces it.
#[test]
fn a_maps_form_pass_resolves_bgra8_by_metals_rule() {
fn a_maps_form_pass_resolves_bgra8_as_announced() {
let (messages, _cache, lane) = lane();
let name = lane.device.name().to_owned();
let metals = lane
.device
.properties()
.driver_facts
.contains(&DriverFact::ColorResolveAverageIsMetals);
messages.take_notices();
for pf in [PixelFormat::BGRA8UnormSRGB, PixelFormat::BGRA8Unorm] {
let case = CASES.iter().find(|c| c.pf == pf).expect("a closed format");
@@ -1524,7 +1258,9 @@ fn a_maps_form_pass_resolves_bgra8_by_metals_rule() {
"Maps' form resolve {what}: {differ} channels differ from Metal's \
rule ({mixed} channels over samples that differ)"
);
assert_eq!(differ, 0, "{what}");
if metals {
assert_eq!(differ, 0, "{what}");
}
assert!(mixed > 0, "{what}: no pixel's samples differ");
}
}
@@ -1534,8 +1270,8 @@ fn a_maps_form_pass_resolves_bgra8_by_metals_rule() {
let notices = super::degrade_notices::counts(&messages.take_notices());
eprintln!("Maps' form resolve on {name}: announced {notices:?}");
assert_eq!(
notices.get(&Degradation::DeviceRoundedResolve),
None,
notices.contains_key(&Degradation::DeviceRoundedResolve),
!metals,
"device-rounded-resolve on {name}"
);
quiet(lane, &messages);
@@ -1543,9 +1279,8 @@ fn a_maps_form_pass_resolves_bgra8_by_metals_rule() {
/// A 4x sRGB texture of `RenderTarget` usage alone, cleared in a pass of no draws that resolves
/// it, resolves to the clear's codes, the bytes Metal stores for that clear (`renders.rs`'
/// `COLOR_CLEARS`): every sample holds the clear, which Metal's rule gives back. The exact resolve
/// reads such an attachment through its UNORM twin's view (`color_resolve.rs`), whatever form the
/// device keeps the clear in.
/// `COLOR_CLEARS`): every sample holds the clear, which Metal's rule and the device's average
/// give back, whatever form the device keeps the clear in.
#[test]
fn cleared_srgb_attachments_resolve_to_the_clear_s_codes() {
let (messages, _cache, lane) = lane();
@@ -1596,204 +1331,3 @@ fn cleared_srgb_attachments_resolve_to_the_clear_s_codes() {
}
quiet(lane, &messages);
}
/// The width and height of the cost test's target: a 1080p frame.
const FRAME: [u32; 2] = [1920, 1080];
/// Command buffers per variant of the cost test, of which the median GPU time is printed.
const TIMED: usize = 15;
/// The formats [`the_exact_resolve_costs_against_a_plain_store`] times: one of the 8-bit unorm rule,
/// one of the sRGB rule (Maps' `BGRA8Unorm_sRGB`), one of the `half` rule, one of the packed 16-bit
/// unorm rule, and `RG32Float`, whose 8 bytes a sample are `RGBA16Float`'s under the 32-bit float
/// rule, so that the two's difference is the `half` rule's arithmetic.
const TIMED_FORMATS: [PixelFormat; 5] = [
PixelFormat::RGBA8Unorm,
PixelFormat::BGRA8UnormSRGB,
PixelFormat::RGBA16Float,
PixelFormat::B5G6R5Unorm,
PixelFormat::RG32Float,
];
/// The side of the cost test's edge-dense draw's squares, in pixels: each square holds the
/// triangle of its lower-left half, whose diagonal splits one pixel in `CELL` of the frame between
/// the triangle and the clear color (6.25%), every other pixel's samples alike.
const CELL: u32 = 16;
/// The clip-space corners (`float4`s) of the cost test's edge-dense draw: over `FRAME` in squares
/// of [`CELL`], each square's lower-left triangle.
fn cells() -> Vec<u8> {
let [width, height] = FRAME;
let clip = |x: u32, y: u32| {
[
x as f32 / width as f32 * 2.0 - 1.0,
y as f32 / height as f32 * 2.0 - 1.0,
0.5,
1.0,
]
};
let mut corners = Vec::new();
for y in (0..height).step_by(CELL as usize) {
for x in (0..width).step_by(CELL as usize) {
for corner in [clip(x, y), clip(x + CELL, y), clip(x, y + CELL)] {
corners.extend(corner.iter().flat_map(|v| v.to_le_bytes()));
}
}
}
corners
}
/// What a timed pass of the cost test draws.
#[derive(Clone, Copy)]
enum Geometry {
/// The fullscreen triangle: no pixel holds unlike samples.
Full,
/// The triangles of [`cells`].
Cells,
}
/// The resolve's cost against a plain store: for each of [`TIMED_FORMATS`], a 1920x1080 target of
/// 4 samples, cleared and drawn once white, then resolved into a single-sampled texture as the
/// runtime resolves the runtime's own texture of it on the device (printed: `shader-resolve`, the
/// exact resolve after the pass; `device-rounded-resolve`, the device's average in the pass; none,
/// the device's average, measured to be Metal's), resolved the same way from a caller's image
/// without input attachment usage (the exact resolve reads a copy of its samples,
/// `color_resolve.rs`), or stored without a resolve; and the runtime's own texture drawn instead
/// with the edge-dense triangles of [`cells`] (the owned fixture `cfb_sample_depth`'s placed
/// vertices and white), resolved and stored, as a frame whose edge pixels take the exact rule's
/// average where the fullscreen triangle's take none. Each the median GPU time of its command
/// buffers, printed (skipped, and so printed, where the device takes no texture of 4 samples or
/// none of the format). Nothing about the times is asserted. No texture of these formats reaches
/// the device's own resolve where the exact resolve applies: a caller's image has the transfer
/// usage the runtime's texture has (`Device::new_texture_with_vk_image`), so it resolves from a
/// copy.
#[test]
fn the_exact_resolve_costs_against_a_plain_store() {
let (messages, _cache, lane) = lane();
let name = lane.device.name().to_owned();
let supported = lane
.device
.properties()
.supports_texture_sample_count(4u32.into())
.unwrap();
if !supported {
eprintln!("resolve cost on {name}: skipped, no texture of 4 samples");
quiet(lane, &messages);
return;
}
let [width, height] = FRAME;
let placed = {
let bitcode = llvm_assemble(&engine_dir().join("cfb_sample_depth.ll")).unwrap();
lane.device.new_library_with_air(&bitcode).unwrap()
};
let corners = cells();
let vertices = (corners.len() / 16) as u32;
let corners = buffer_with(&lane.device, &corners).unwrap();
for pf in TIMED_FORMATS {
let descriptor = |samples: u64| {
let mut d = TextureDescriptor::texture_2d(pf, width.into(), height.into(), false);
if samples > 1 {
d.texture_type = TextureType::Type2DMultisample;
d.sample_count = samples;
}
d.usage = TextureUsage::RENDER_TARGET;
d.resource_options = ResourceOptions::private();
d
};
let (own, resolved) = match (
lane.device.new_texture(&descriptor(4)),
lane.device.new_texture(&descriptor(1)),
) {
(Ok(own), Ok(resolved)) => (own, resolved),
(Err(e), _) | (_, Err(e)) => {
eprintln!("resolve cost {pf:?} on {name}: skipped, {e}");
continue;
}
};
let (copied, copied_image, copied_memory) = callers_image(
&lane,
pf,
4,
FRAME,
ash::vk::ImageUsageFlags::COLOR_ATTACHMENT
| ash::vk::ImageUsageFlags::TRANSFER_SRC
| ash::vk::ImageUsageFlags::TRANSFER_DST,
);
let pipeline = lane.pipeline((FULL, WHITE), &[pf], (None, None), 4);
let cells_pipeline = {
let function = |name| {
StageSource::Function(
placed
.new_function_with_name(name)
.unwrap()
.function_descriptor(),
)
};
let mut descriptor = RenderPipelineDescriptor::new(function("cfb_depth_vertex"));
descriptor.fragment = Some(function("cfb_depth_white"));
descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(pf));
descriptor.raster_sample_count = 4;
lane.device
.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap()
};
let time = |msaa: &Texture, resolve: bool, geometry: Geometry| {
let mut times = Vec::with_capacity(TIMED);
for _ in 0..TIMED {
let mut pass = RenderPassDescriptor::new();
let target = &mut pass.color_attachments[0];
target.texture = Some(msaa.clone());
target.load_action = LoadAction::Clear;
if resolve {
target.store_action = StoreAction::MultisampleResolve;
target.resolve_texture = Some(resolved.clone());
} else {
target.store_action = StoreAction::Store;
}
let command_buffer = lane.queue.command_buffer().unwrap();
let mut encoder = command_buffer.render_command_encoder(&pass).unwrap();
let mut held = Vec::new();
match geometry {
Geometry::Full => lane.draw(&mut encoder, &mut held, &pipeline, 0.5),
Geometry::Cells => {
encoder.set_render_pipeline_state(&cells_pipeline).unwrap();
encoder.set_vertex_buffer(Some(&corners), 0, 0).unwrap();
encoder
.draw_primitives(PrimitiveType::Triangle, 0, vertices, 1, 0)
.unwrap();
}
}
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer
.wait_until_completed_for(super::WAIT)
.unwrap();
let (start, end) = (
command_buffer.gpu_start_time().unwrap(),
command_buffer.gpu_end_time().unwrap(),
);
times.push((end - start) * 1e6);
}
times.sort_by(f64::total_cmp);
times[TIMED / 2]
};
let own_resolve = time(&own, true, Geometry::Full);
let through_copy = time(&copied, true, Geometry::Full);
let stored = time(&own, false, Geometry::Full);
let cells_resolve = time(&own, true, Geometry::Cells);
let cells_stored = time(&own, false, Geometry::Cells);
let kind = super::degrade_notices::resolve_kind(&lane.device, pf, 4)
.map_or("none", Degradation::code);
eprintln!(
"resolve cost on {name}: {width}x{height} {pf:?} x4 (announced kind {kind}), median \
GPU time of {TIMED}: the runtime's own texture's resolve {own_resolve:.0} us, a \
caller's image's resolve {through_copy:.0} us, stored without a resolve {stored:.0} us; \
edge-dense ({CELL}-pixel triangles): resolve {cells_resolve:.0} us, stored \
{cells_stored:.0} us"
);
drop(copied);
// SAFETY: nothing uses them: the texture is gone and every command buffer completed.
unsafe { destroy_callers(&lane, copied_image, copied_memory) };
}
quiet(lane, &messages);
}
@@ -9,15 +9,17 @@
//! the depth from the vertex and the stencil from the reference.
//!
//! A color resolve averages: Vulkan leaves the average's rounding (and an sRGB average's space)
//! to the device, and Metal rounds a unorm tie up (127.5 to 128). The runtime resolves a unorm,
//! sRGB or float attachment by Metal's rules (its exact resolve, or a driver measured to resolve
//! as Metal does), so each such resolve asserts Metal's texels; a half-float one is the device's
//! average, asserted within one unit of Metal's (one half ulp) and printed as a near-equivalent
//! where it differs. Depth and stencil resolves pick one sample, which Vulkan states exactly. What
//! Metal's validation stops, the runtime refuses typed, apart from a color attachment's resolve
//! that names no texture or a texture under a store action that does not resolve, which resolves
//! nothing and leaves that texture untouched, and a multisampled color attachment's resolve into
//! its format's sRGB twin, which resolves in the resolve texture's encoding, as plain Metal's.
//! to the device, and Metal rounds a unorm tie up (127.5 to 128). The runtime resolves a color
//! attachment by the device's average, so each resolve asserts Metal's texels on a driver measured
//! to resolve as Metal does (`DriverFact::ColorResolveAverageIsMetals`), and elsewhere within the
//! bound `device-rounded-resolve` states: a unorm channel within one code (an 8-bit one within
//! two, an sRGB channel's bound), a half within one unit (one half ulp), a 32-bit float's
//! difference printed and not bounded. A resolve that differs is printed as a near-equivalent.
//! Depth and stencil resolves pick one sample, which Vulkan states exactly. What Metal's validation
//! stops, the runtime refuses typed, apart from a color attachment's resolve that names no texture
//! or a texture under a store action that does not resolve, which resolves nothing and leaves that
//! texture untouched, and a multisampled color attachment's resolve into its format's sRGB twin,
//! which resolves in the resolve texture's encoding, as plain Metal's.
use super::degrade_notices::assert_once;
use super::{
@@ -325,9 +327,10 @@ impl Channels {
}
}
/// Print the device's resolved texels beside Metal's, and assert them Metal's, or for half
/// floats (`channels`), whose resolve is the device's average, each channel within one unit; the
/// differing cases are named in `differ`. A resolve that is not Metal's is printed as a
/// Print the device's resolved texels beside Metal's, and assert them Metal's on a driver whose
/// average is measured to be Metal's, else within the bound `device-rounded-resolve` states for
/// `channels` (the module docs), for half floats each channel within one unit on every driver;
/// the differing cases are named in `differ`. A resolve that is not Metal's is printed as a
/// near-equivalent, never as Metal's answer.
pub(super) fn near(
lane: &Lane,
@@ -338,6 +341,11 @@ pub(super) fn near(
differ: &RefCell<Vec<String>>,
) {
let device = lane.device.name();
let metals = lane
.device
.properties()
.driver_facts
.contains(&DriverFact::ColorResolveAverageIsMetals);
let exact = resolved == metal;
eprintln!(
"resolve {name} on {device}: {} ({})",
@@ -349,9 +357,16 @@ pub(super) fn near(
}
);
let (got, want) = (channels.values(resolved), channels.values(metal));
let within = got.len() == want.len() && got.iter().zip(&want).all(|(a, b)| (a - b).abs() <= 1);
let averaged = matches!(channels, Channels::Half);
if !(exact || (averaged && within)) {
let bound = match (channels, metals) {
(Channels::Half, _) => Some(1),
(_, true) => Some(0),
(Channels::Unorm8, false) => Some(2),
(Channels::Unorm16, false) => Some(1),
(Channels::Float, false) => None,
};
let within = got.len() == want.len()
&& bound.is_none_or(|bound| got.iter().zip(&want).all(|(a, b)| (a - b).abs() <= bound));
if !(exact || within) {
differ.borrow_mut().push(format!(
"{name}: {} where Metal resolved {}",
hex(resolved),
@@ -360,8 +375,8 @@ pub(super) fn near(
}
}
/// Probe 6's per-sample resolves of each color format: Metal's, a half one within one unit of
/// Metal's (the module docs).
/// Probe 6's per-sample resolves of each color format: Metal's, or within the device's announced
/// bound of Metal's (the module docs).
#[test]
fn color_resolves_are_metals() {
let (messages, _cache, lane) = lane();
@@ -1916,14 +1931,11 @@ enum DepthTexel {
/// `DontCare`. Stored, it holds the clear or its texels where nothing is drawn, and the draw's
/// depth 0.25 (`Less`, written) and stencil 0x5a (`Always`, `Replace`) where the draw passes, as
/// the probe's drawn pixel holds them (here every pixel: the fullscreen triangle); under
/// `DontCare`, its texels before the pass. A `Depth32Float` texture held in a color image beside
/// its depth twin (a device whose depth images may not keep every `float`) is
/// `NotImplemented(Render)` (printed).
/// `DontCare`, its texels before the pass.
#[test]
fn a_depth_or_stencil_texture_without_render_target_usage_renders_as_metal() {
let (messages, _cache, lane) = lane();
let name = lane.device.name().to_owned();
let (_, _, keeps_floats) = super::texture_blits::depth_images(&lane.device);
let rgba8 = PixelFormat::RGBA8Unorm;
let (load, clear) = (LoadAction::Load, LoadAction::Clear);
let (store, dontcare) = (StoreAction::Store, StoreAction::DontCare);
@@ -2028,17 +2040,6 @@ fn a_depth_or_stencil_texture_without_render_target_usage_renders_as_metal() {
l.draw(e, h, &pipeline, 0.25);
}
});
if pf == PixelFormat::Depth32Float && !keeps_floats {
assert_eq!(
ran,
Err(Error::NotImplemented(RuntimeGap::Render)),
"{case}"
);
eprintln!(
"refused: {case} on {name}, a depth twin's texture (Metal renders it)"
);
continue;
}
ran.unwrap_or_else(|e| panic!("{case} on {name}: {e}"));
// What each aspect holds: the draw's where it ran and the pass stored, else the
// clear where it cleared and stored, else the texels before the pass.
@@ -9,17 +9,15 @@
//! under an exponent above 0 is stored normalized (its mantissas shifted up as its exponent steps
//! down; measured there too).
//!
//! Under `TileStorePolicy::Device`, the default, the runtime keeps the device's load and store
//! (docs/FAST-PATHS.md), so the texels keep their codes and words, and a draw in such a pass
//! announces `snorm-minimum-kept` or `shared-exponent-kept`, naming the attachment. Under
//! `TileStorePolicy::Exact` the load pass (`render/unused_bits_load.rs`) rewrites them as Metal's
//! store leaves them before the pass, and nothing is announced. On a driver whose pass stores them
//! as Metal's (`DriverFact::TileStoreIsMetals`: MoltenVK, whose pass is a Metal pass) the texels
//! take Metal's codes and words under either value, with no load pass and nothing announced.
//! The runtime keeps the device's load and store, so the texels keep their codes and words, and
//! a draw in such a pass announces `snorm-minimum-kept` or `shared-exponent-kept`, naming the
//! attachment, with no load pass. On a driver whose pass stores them as Metal's
//! (`DriverFact::TileStoreIsMetals`: MoltenVK, whose pass is a Metal pass) the texels take Metal's
//! codes and words, and nothing is announced.
use super::degrade_notices::counts;
use super::resolves::{lane_with, quiet, Lane, Shape, FULL, SIZE, WHITE};
use metal2vulkan::device::{DriverFact, TileStorePolicy};
use metal2vulkan::device::DriverFact;
use metal2vulkan::metal::{ColorWriteMask, PixelFormat, TextureUsage};
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
use metal2vulkan_runtime::{
@@ -107,15 +105,12 @@ fn pass(t: &Texture, load: LoadAction) -> RenderPassDescriptor {
descriptor
}
/// What a drawing pass of the lane's device leaves under `tile_store`: whether the device's store
/// is Metal's (`DriverFact::TileStoreIsMetals`), and whether the load pass rewrites the texels.
fn expected(lane: &Lane, tile_store: TileStorePolicy) -> (bool, bool) {
let metals = lane
.device
/// Whether the lane's device's store is Metal's (`DriverFact::TileStoreIsMetals`).
fn metals_store(lane: &Lane) -> bool {
lane.device
.properties()
.driver_facts
.contains(&DriverFact::TileStoreIsMetals);
(metals, tile_store == TileStorePolicy::Exact && !metals)
.contains(&DriverFact::TileStoreIsMetals)
}
/// The load passes the lane's device recorded so far.
@@ -124,19 +119,19 @@ fn load_passes(lane: &Lane) -> u64 {
}
/// A pass that loads a 4² target of each signed normalized format holding the minimum code in
/// every channel and draws under a write mask of none of its channels, under `tile_store`: where
/// the device's store is Metal's or the load pass rewrites the codes (one load pass), every
/// texel takes the code above and nothing is announced; else every code stays and
/// `snorm-minimum-kept` is announced once (the device asks for it at each occurrence), naming
/// color 0 and its format. A pass that loads the minimum codes again and draws nothing keeps
/// every one, records no load pass and announces nothing, as Metal's keeps every texel.
fn snorm_minimum_codes(tile_store: TileStorePolicy) {
/// every channel and draws under a write mask of none of its channels, recording no load pass:
/// where the device's store is Metal's, every texel takes the code above and nothing is
/// announced; else every code stays and `snorm-minimum-kept` is announced once (the device asks
/// for it at each occurrence), naming color 0 and its format. A pass that loads the minimum codes
/// again and draws nothing keeps every one, records no load pass and announces nothing, as
/// Metal's keeps every texel.
#[test]
fn a_drawing_pass_keeps_a_snorm_minimum_code_and_says_so() {
let (messages, _cache, lane) = lane_with(|options| {
options.announce_each = SNORM_MINIMUM.into_iter().collect();
options.policy.tile_store = tile_store;
});
let (metals, rewritten) = expected(&lane, tile_store);
eprintln!("{tile_store:?}: Metal's store {metals}, rewritten {rewritten}");
let metals = metals_store(&lane);
eprintln!("Metal's store {metals}");
for (pf, texel, code, above) in FORMATS {
let pipeline = lane
.device
@@ -151,20 +146,13 @@ fn snorm_minimum_codes(tile_store: TileStorePolicy) {
let loads = load_passes(&lane) - before;
let got = lane.read(&t, (0, 0), texel, BlitOption::None);
let notices = messages.take_notices();
assert_eq!(
loads,
u64::from(rewritten),
"{pf:?} {tile_store:?}: load passes"
);
if metals || rewritten {
assert_eq!(loads, 0, "{pf:?}: load passes");
if metals {
let raised = filled(texel, above);
assert!(
got == raised,
"{pf:?} {tile_store:?}: not Metal's codes: {got:02x?}"
);
assert!(got == raised, "{pf:?}: not Metal's codes: {got:02x?}");
assert!(
!counts(&notices).contains_key(&SNORM_MINIMUM[0]),
"{pf:?} {tile_store:?}: announced where the codes are Metal's"
"{pf:?}: announced where the codes are Metal's"
);
} else {
assert!(got == bytes, "{pf:?}: the codes moved: {got:02x?}");
@@ -199,34 +187,22 @@ fn snorm_minimum_codes(tile_store: TileStorePolicy) {
quiet(lane, &messages);
}
/// [`snorm_minimum_codes`] under the default, the device's load and store.
#[test]
fn a_drawing_pass_keeps_a_snorm_minimum_code_and_says_so() {
snorm_minimum_codes(TileStorePolicy::Device);
}
/// [`snorm_minimum_codes`] under the exact tile store, the load pass's rewrite.
#[test]
fn the_exact_tile_store_raises_a_snorm_minimum_code() {
snorm_minimum_codes(TileStorePolicy::Exact);
}
/// A pass that loads a 4² `RGB9E5Float` target whose every word is unnormalized (mantissas 1, 2
/// and 3 under the exponent 20: its largest mantissa below 256) and draws under a write mask of
/// none of its channels, under `tile_store`: where the device's store is Metal's or the load pass
/// rewrites the words (one load pass), every word takes Metal's (mantissas 128, 256 and 384 under
/// the exponent 13) and nothing is announced; else every word stays and `shared-exponent-kept` is
/// announced once (the device asks for it at each occurrence), naming color 0 and its format. A
/// pass that loads it and draws nothing announces nothing. A device that renders no
/// `RGB9E5Float` (refusing its texture or pipeline state) takes neither, and says so.
fn shared_exponent_words(tile_store: TileStorePolicy) {
/// none of its channels, recording no load pass: where the device's store is Metal's, every word
/// takes Metal's (mantissas 128, 256 and 384 under the exponent 13) and nothing is announced;
/// else every word stays and `shared-exponent-kept` is announced once (the device asks for it at
/// each occurrence), naming color 0 and its format. A pass that loads it and draws nothing
/// announces nothing. A device that renders no `RGB9E5Float` (refusing its texture or pipeline
/// state) takes neither, and says so.
#[test]
fn a_drawing_pass_keeps_an_unnormalized_shared_exponent_word_and_says_so() {
let pf = PixelFormat::RGB9E5Float;
let (messages, _cache, lane) = lane_with(|options| {
options.announce_each = SHARED_EXPONENT.into_iter().collect();
options.policy.tile_store = tile_store;
});
let name = lane.device.name();
let (metals, rewritten) = expected(&lane, tile_store);
let metals = metals_store(&lane);
let mut descriptor = TextureDescriptor::texture_2d(pf, SIZE, SIZE, false);
descriptor.usage = TextureUsage::RENDER_TARGET;
descriptor.resource_options = ResourceOptions::shared();
@@ -264,20 +240,16 @@ fn shared_exponent_words(tile_store: TileStorePolicy) {
let loads = load_passes(&lane) - before;
let got = lane.read(&t, (0, 0), 4, BlitOption::None);
let notices = messages.take_notices();
assert_eq!(
loads,
u64::from(rewritten),
"{pf:?} {tile_store:?} on {name}: load passes"
);
if metals || rewritten {
assert_eq!(loads, 0, "{pf:?} on {name}: load passes");
if metals {
let normalized = metal.to_le_bytes().repeat((SIZE * SIZE) as usize);
assert!(
got == normalized,
"{pf:?} {tile_store:?} on {name}: not Metal's words: {got:02x?}"
"{pf:?} on {name}: not Metal's words: {got:02x?}"
);
assert!(
!counts(&notices).contains_key(&SHARED_EXPONENT[0]),
"{pf:?} {tile_store:?} on {name}: announced where the words are Metal's"
"{pf:?} on {name}: announced where the words are Metal's"
);
} else {
assert!(
@@ -305,15 +277,3 @@ fn shared_exponent_words(tile_store: TileStorePolicy) {
);
quiet(lane, &messages);
}
/// [`shared_exponent_words`] under the default, the device's load and store.
#[test]
fn a_drawing_pass_keeps_an_unnormalized_shared_exponent_word_and_says_so() {
shared_exponent_words(TileStorePolicy::Device);
}
/// [`shared_exponent_words`] under the exact tile store, the load pass's rewrite.
#[test]
fn the_exact_tile_store_normalizes_a_shared_exponent_word() {
shared_exponent_words(TileStorePolicy::Exact);
}
@@ -1,14 +1,14 @@
//! Device tests of the blit encoder's texture commands on the device the cfg selects, under the
//! validation layer: copies between buffers and textures (on the layouts Vulkan states and on the
//! ones that go through a scratch buffer) and between textures, Metal's refusals, 32-bit float
//! depth outside `[0, 1]` uploaded as Metal holds it with the form each device stores it in printed
//! (a texture with a depth twin keeping it), what each driver's depth images keep of the `float`s
//! Metal's hold, against its driver facts, and `generate_mipmaps` with each format's verdict
//! printed.
//! depth outside `[0, 1]` uploaded as Metal holds it with the form each device stores it in
//! printed, what each driver's depth images keep of the `float`s Metal's hold, against its driver
//! facts, and `generate_mipmaps` with each format's verdict printed.
use super::degrade_notices::signs_depth_tests;
use super::degrade_notices::{assert_made_once, assert_once, forced, loses_depth_denormals};
use super::degrade_notices::{decodes_blocks_its_way, shared_in_system_memory};
use super::degrade_notices::{twins_blocks, twins_carried, twins_depth};
use super::degrade_notices::{twins_blocks, twins_carried};
use super::{layer_reported_nothing_at_all, validated_device, Messages, ScratchCache};
use crate::gpu::TEST_DEVICE;
use metal2vulkan::bind::{MipmapFilterChain, MipmapRule};
@@ -1143,11 +1143,6 @@ fn mipmaps_leave_single_levels_and_depth_as_they_are() {
layer_reported_nothing_at_all(&messages);
}
/// The kind [`depth_outside_the_unit_range_uploads_as_metal_holds_it`] takes when it makes a
/// texture with a depth twin, on a device whose depth images its driver is not measured to keep
/// every `float` in ([`depth_images`]), and expects absent elsewhere.
pub(super) const TWINS: [Degradation; 1] = [Degradation::DepthTwin];
/// The kind [`mipmaps_of_every_format_run_or_are_refused_typed`] takes where a device's blit
/// chain of some format ran, and expects absent where none did.
pub(super) const MIPMAPS: [Degradation; 1] = [Degradation::MipmapsWithinSpread];
@@ -1199,26 +1194,22 @@ fn picked(pf: PixelFormat) -> bool {
}
/// The kind [`depth_outside_the_unit_range_uploads_as_metal_holds_it`] takes when it uploads into
/// a render target's depth image, which has no twin, on a device whose depth image may clamp
/// ([`depth_images`]).
/// a depth image on a device whose depth image may clamp ([`depth_images`]).
pub(super) const UPLOADS: [Degradation; 1] = [Degradation::RestrictedDepthUpload];
/// 32-bit float depth outside `[0, 1]` uploads as Metal holds it, through `replace_region` and
/// 32-bit float depth outside `[0, 1]` uploads into a depth image, through `replace_region` and
/// through a blit from a buffer, on every device.
///
/// A texture the program only reads or samples keeps each value on every venue here: where the
/// device's depth images keep every `float` ([`depth_images`]), in its depth image; elsewhere in
/// the `R32_SFLOAT` image of a depth twin, announced once ([`TWINS`]), as every venue here samples
/// and copies both formats. A render target's depth image keeps each value where the device
/// enabled `VK_EXT_depth_range_unrestricted` or its driver is measured to keep one without it;
/// elsewhere Vulkan leaves such a value undefined (`VUID-vkCmdCopyBufferToImage-pRegions-07931`)
/// and a device keeps it or stores it clamped to `[0, 1]`, which its upload announces once
/// ([`UPLOADS`]): each value reads back as one of the two, and the form the device took is
/// printed; where it keeps them, the upload of a negative value into a render target, and a copy
/// out of a twin into one, switch its depth on to render a pass that loads it over its magnitude
/// stand-in (`texture/signed_depth.rs`), unannounced.
/// Copies between two textures with twins, and from a render target into one, land in both its
/// images.
/// A depth image, a read-only texture's and a render target's alike, keeps each value where the
/// device enabled `VK_EXT_depth_range_unrestricted` or its driver is measured to keep one without
/// it; elsewhere Vulkan leaves such a value undefined
/// (`VUID-vkCmdCopyBufferToImage-pRegions-07931`) and a device keeps it or stores it clamped to
/// `[0, 1]`, which its first upload announces once ([`UPLOADS`]): each value reads back as one of
/// the two, and the form the device took is printed; where it keeps them, the upload of a negative
/// value into a render target, whose depth a test reads, announces `signed-depth-test` where the
/// device's depth test compares the value as it is (`degrade_notices::signs_depth_tests`). A copy
/// between two depth images moves the source's words, and a copy into a render target announces the
/// same.
#[test]
fn depth_outside_the_unit_range_uploads_as_metal_holds_it() {
const VALUES: [f32; 4] = [-0.5, 2.0, 1000.0, 0.25];
@@ -1228,9 +1219,7 @@ fn depth_outside_the_unit_range_uploads_as_metal_holds_it() {
{
let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap();
let name = device.name();
let (unrestricted, clamps, keeps_floats) = depth_images(&device);
// Whether a read-only texture takes a twin.
let twinned = !keeps_floats;
let (unrestricted, clamps, _) = depth_images(&device);
let queue = device.new_command_queue().unwrap();
let made = |usage: TextureUsage| {
let mut d = TextureDescriptor::texture_2d(PixelFormat::Depth32Float, 2, 2, false);
@@ -1268,27 +1257,11 @@ fn depth_outside_the_unit_range_uploads_as_metal_holds_it() {
// What the device announced before its first texture.
messages.take_notices();
let replaced = made(read_only);
let twin = forced(&[(Degradation::DepthTwin, twinned)]);
let announced = assert_made_once(&messages, &[], &twin);
for kind in TWINS {
assert_eq!(
announced.contains_key(&kind),
twinned,
"{kind:?} on {name} exactly where the device's depth image may not hold a \
texel: {announced:?}"
);
}
replaced
.replace_region(Region::new_2d(0, 0, 2, 2), 0, 0, &words, 8, 0)
.unwrap();
let blitted = made(read_only);
let held = made(target);
let quiet = assert_once(&messages.take_notices(), &[]);
assert!(
!quiet.contains_key(&Degradation::RestrictedDepthUpload),
"an upload into a depth twin's texture announced on {name}: {quiet:?}"
);
held.replace_region(Region::new_2d(0, 0, 2, 2), 0, 0, &words, 8, 0)
assert_once(&messages.take_notices(), &[]);
replaced
.replace_region(Region::new_2d(0, 0, 2, 2), 0, 0, &words, 8, 0)
.unwrap();
let clamped = forced(&[(Degradation::RestrictedDepthUpload, clamps)]);
let uploaded = assert_made_once(&messages, &[], &clamped);
@@ -1299,6 +1272,10 @@ fn depth_outside_the_unit_range_uploads_as_metal_holds_it() {
"{kind:?} on {name} exactly where the device may clamp: {uploaded:?}"
);
}
held.replace_region(Region::new_2d(0, 0, 2, 2), 0, 0, &words, 8, 0)
.unwrap();
let signed = forced(&[(Degradation::SignedDepthTest, signs_depth_tests(&device))]);
assert_made_once(&messages, &[], &signed);
let source = device.new_buffer(16, ResourceOptions::shared()).unwrap();
with_bytes(&source, |bytes| bytes.copy_from_slice(&words));
let command_buffer = queue.command_buffer().unwrap();
@@ -1318,38 +1295,42 @@ fn depth_outside_the_unit_range_uploads_as_metal_holds_it() {
.unwrap();
blit.end_encoding().unwrap();
run(&command_buffer);
for (how, texture) in [("replace_region", &replaced), ("a blit", &blitted)] {
assert_eq!(floats(texture), VALUES, "{how} on {name}");
}
form("replace_region", &floats(&replaced));
form("a blit", &floats(&blitted));
form("replace_region into a render target", &floats(&held));
// A copy of a texture with a twin into another (both images), into a render target (its
// twin), and of a render target into a texture with a twin (its image through a scratch
// buffer, its twin directly), whose twin a last copy reads back.
let (copied, out_of_twin, into_twin, back) =
(made(read_only), made(target), made(read_only), made(target));
// A copy between two read-only textures, out of one into a render target, and back.
let (copied, into_target, back) = (made(read_only), made(target), made(read_only));
let command_buffer = queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.copy_texture(&replaced, &copied).unwrap();
blit.copy_texture(&replaced, &out_of_twin).unwrap();
blit.copy_texture(&held, &into_twin).unwrap();
blit.copy_texture(&into_twin, &back).unwrap();
blit.copy_texture(&replaced, &into_target).unwrap();
blit.copy_texture(&held, &back).unwrap();
blit.end_encoding().unwrap();
run(&command_buffer);
assert_eq!(floats(&copied), VALUES, "a copy between twins on {name}");
form("a copy out of a twin", &floats(&out_of_twin));
let held = floats(&held);
assert_eq!(floats(&into_twin), held, "a copy into a twin on {name}");
// The last copy writes a render target's depth image on the GPU, which may clamp where
// the device's depth images may (ANV: the twin's copy into it stores the clamp).
form("a copy into a twin, read back", &floats(&back));
// The blit from the `Shared` buffer writes a depth image on the GPU where the texture
// takes no twin, which announces what a float depth's may store; every other copy into
// a depth image copies one depth image's bits into another.
let replaced = floats(&replaced);
assert_eq!(
floats(&copied),
replaced,
"a copy between depth images on {name}"
);
assert_eq!(
floats(&into_target),
replaced,
"a copy into a render target on {name}"
);
assert_eq!(
floats(&back),
floats(&held),
"a copy out of a render target on {name}"
);
// The blit from the `Shared` buffer writes a depth image on the GPU, which announces what
// a float depth's may store; every other copy into a depth image copies one depth
// image's bits into another.
let first = forced(&[
(
Degradation::DepthDenormals,
!twinned && loses_depth_denormals(&device, false),
loses_depth_denormals(&device, false),
),
(
Degradation::SharedInSystemMemory,
@@ -1357,7 +1338,7 @@ fn depth_outside_the_unit_range_uploads_as_metal_holds_it() {
),
]);
let later = assert_made_once(&messages, &[], &first);
for kind in TWINS.iter().chain(&UPLOADS) {
for kind in &UPLOADS {
assert!(
!later.contains_key(kind),
"{kind:?} announced again on {name}: {later:?}"
@@ -1515,13 +1496,8 @@ fn mipmaps_of_every_format_run_or_are_refused_typed() {
outcome.push("no texture");
continue;
};
// A read-only `Depth32Float` texture's depth twin, a BC texture's decoded twin,
// and a BC6H or BC7 texture's device decode.
// A BC texture's decoded twin, and a BC6H or BC7 texture's device decode.
first.extend(forced(&[
(
Degradation::DepthTwin,
pf == PixelFormat::Depth32Float && twins_depth(&device),
),
(Degradation::DecodedBlockTwin, twins_blocks(&device, pf)),
(
Degradation::CarriedDecodedTwin,
@@ -15,12 +15,12 @@
//! or `two-plane-heap-fills` for a heap's two-plane texture of more than one level or slice, whose
//! fill writes the heap's bytes at level 0's rows, as Metal's does, which `two_plane_heap_fills.rs`
//! checks byte for byte against the M3 Max's. A format the device holds no texture of is
//! skipped, with an `XR-TEXTURE-FILLS-SKIPPED` line, and so is `Depth32Float_Stencil8` where its
//! uploads announce that the device may store depth outside `[0, 1]` clamped
//! (`restricted-depth-upload`, checked to fire exactly where the runtime plans a depth image that
//! may clamp); a differing format prints its cases on one `XR-TEXTURE-FILLS-DIFFERS` line. The
//! two-plane formats in private textures of their own memory replay `tfl4.swift` the same way, 8
//! texels wide (`OWN_TWO_PLANES`).
//! skipped, with an `XR-TEXTURE-FILLS-SKIPPED` line, and so are `Depth32Float` and
//! `Depth32Float_Stencil8` where their uploads announce that the device may store depth outside
//! `[0, 1]` clamped (`restricted-depth-upload`, checked to fire once, at the first of them, where a
//! depth image may clamp); a differing format prints its cases on one `XR-TEXTURE-FILLS-DIFFERS`
//! line. The two-plane formats in private textures of their own memory replay `tfl4.swift` the same
//! way, 8 texels wide (`OWN_TWO_PLANES`).
//!
//! A heap case's digest holds each changed run's first 64 bytes and its length, which is what the
//! probes printed. Exactly two cases of the whole table have a longer run -- `b5` of 550 and of
@@ -29,11 +29,11 @@
//! (`WHOLE_RUNS`); a longer run the table does not hold fails rather than passing on its first 64
//! bytes.
use super::degrade_notices::UNPACKED_FILL;
use super::degrade_notices::{assert_made_once, forced, loses_depth_denormals, on_device};
use super::degrade_notices::{
decodes_blocks_its_way, shared_in_system_memory, twins_blocks, twins_carried,
};
use super::degrade_notices::{twins_depth, UNPACKED_FILL};
use super::extended_range_two_planes::{get, put};
use super::texture_blits::depth_images;
use super::{buffer_with, read_buffer};
@@ -640,23 +640,22 @@ fn texture_fills_write_metal_s_bytes() {
None => continue 'formats,
}
}
// `Depth32Float_Stencil8`'s patterns are depth outside [0, 1]: where its uploads
// announce that the device may store such a value clamped (`restricted-depth-upload`),
// exactly where the runtime plans a depth image that may clamp (`texture_blits.rs`),
// the format's bytes are not Metal's to match.
// A 32-bit float depth's patterns may be depth outside [0, 1]: where its uploads
// announce that the device may store such a value clamped (`restricted-depth-upload`,
// where a depth image may clamp, `texture_blits.rs`), the format's bytes are not
// Metal's to match.
let first_unpacked = unpacked_here && !unpacked_announced;
unpacked_announced |= first_unpacked;
let kinds: &[Degradation] = if first_unpacked { &UNPACKED_FILL } else { &[] };
// A read-only `Depth32Float` texture's depth twin and a BC texture's decoded twin; the
// uploads into a depth image (the twin's texture holds its texels in colour), what
// a float depth's may store, and the combined format's clamp; the `Shared` buffers.
// A BC texture's decoded twin; the uploads into a 32-bit float depth image, what such
// a depth may store and where it may clamp; the `Shared` buffers.
let pf = format(raw);
let mipmapped = CASES.iter().any(|name| case(raw, name, false).levels > 1);
let twin = pf == PixelFormat::Depth32Float && twins_depth(device);
let combined = pf == PixelFormat::Depth32FloatStencil8;
let depth_image = combined || (pf == PixelFormat::Depth32Float && !twin);
let depth_image = matches!(
pf,
PixelFormat::Depth32Float | PixelFormat::Depth32FloatStencil8
);
let first = forced(&[
(Degradation::DepthTwin, twin),
(Degradation::DecodedBlockTwin, twins_blocks(device, pf)),
(
Degradation::CarriedDecodedTwin,
@@ -676,7 +675,7 @@ fn texture_fills_write_metal_s_bytes() {
),
(
Degradation::RestrictedDepthUpload,
combined && depth_images(device).1,
depth_image && depth_images(device).1,
),
(
Degradation::SharedInSystemMemory,
@@ -687,18 +686,10 @@ fn texture_fills_write_metal_s_bytes() {
(Degradation::ShadowedTexture, heap > 0),
(Degradation::HeapTwoPlaneLayout, heap > 0 && mipmapped),
]);
let announced = assert_made_once(messages, kinds, &first);
let clamped = announced.contains_key(&Degradation::RestrictedDepthUpload);
if raw == 260 {
assert_eq!(
clamped,
depth_images(device).1,
"restricted-depth-upload announced exactly where a depth image may clamp"
);
if clamped {
println!("XR-TEXTURE-FILLS-SKIPPED 260: restricted-depth-upload announced");
continue;
}
assert_made_once(messages, kinds, &first);
if depth_image && depth_images(device).1 {
println!("XR-TEXTURE-FILLS-SKIPPED {raw}: restricted-depth-upload announced");
continue;
}
let ours = digest(&answers.join("\n"));
if ours != metal {
@@ -1590,7 +1590,7 @@ fn written_depths_store_metals_bits_in_every_sample() {
.properties()
.driver_facts
.contains(&DriverFact::DontCareStoreIsMetals);
first.extend(resolve_kind(&probe.device, PixelFormat::RGBA32Float, 4));
first.extend(resolve_kind(&probe.device, 4));
first.extend(forced(&[(Degradation::DontCareStore, !dont_care_metals)]));
let read = read_function(&probe.device, PixelFormat::Depth32Float, SampleRead::Depth).unwrap();
first.extend(made_compute_kinds(&probe.device, read));
@@ -1,508 +0,0 @@
//! A 32-bit float depth's magnitude stand-in, and the merge back of a pass rendered over it.
//!
//! Metal's depth test compares a fragment's depth with the stored value's magnitude, as the
//! integers of their low 31 bits: a stored -0.5 passes `Equal` for a fragment at 0.5, and a stored
//! NaN orders above +inf. Vulkan's compares the stored value as it is. A consumer whose depth image
//! holds such a value renders a pass that loads it over a stand-in image instead: before the pass
//! it copies the depth's words into the *exact* buffer, one dispatch of
//! [`depth_magnitude_module`] writes each word's stand-in into the *stand-in* buffer, and it copies
//! that into the stand-in image, which the pass loads, tests and writes. After a pass that may have
//! written the depth, it copies the stand-in image into the stand-in buffer, one dispatch merges it
//! into the exact buffer, and it copies that back into the depth.
//!
//! **The stand-in** of a word `w`, the bits of a `float`: its magnitude `w & 0x7fffffff`; a NaN's
//! is +inf's, `0x7f800000`; and where the push's `flush` word is not 0, a nonzero denormal's is the
//! smallest normal's, `0x00800000`, for a device whose depth test compares a stored denormal as
//! zero. A fragment's depth is never negative or NaN, so Vulkan's test against the stand-in gives
//! Metal's answer against the word, but where the fragment lies at exactly 2^-126 against a
//! denormal's stand-in.
//!
//! **The merge**: Metal stores each texel of a pass that sets a depth/stencil state with depth
//! writes without its sign, `w & 0x7fffffff` (a NaN's payload and a denormal kept), where no
//! fragment wrote it, and the fragment's depth where one did (our probe `depthstore`, the M3 Max
//! under macOS 27.0.1). Where the stand-in buffer's word (the pass's) equals the stand-in of the
//! exact buffer's, the pass left the texel as it loaded it, and the exact word without its sign
//! replaces it; elsewhere the pass's word does. A pass that writes exactly a word's stand-in over a
//! word whose stand-in is not that word without its sign (+inf over a NaN, the smallest normal
//! over a denormal) leaves the word without its sign, where Metal stores the pass's.
//!
//! **The strip**: after a pass with depth writes that renders the depth in place on a device
//! whose depth test is Metal's own but which leaves the stored words as they are where no draw ran
//! under such a state, every word without its sign, as Metal stores them.
//!
//! **The module** (one per device). One `GLCompute` entry `main` with local size
//! ([`DepthMagnitudeModule::LOCAL_SIZE`], 1, 1), [`DepthMagnitudeModule::PUSH_BYTES`] of `COMPUTE`
//! push constants at offset 0 ([`DepthMagnitudeModule::shape`]), and two storage buffers in set 0,
//! each a whole number of 4-byte words:
//!
//! | Binding | Buffer |
//! |---|---|
//! | [`DepthMagnitudeModule::EXACT_BINDING`] | the depth's words; a merge writes them |
//! | [`DepthMagnitudeModule::STAND_IN_BINDING`] | their stand-ins; in a merge, the pass's |
//!
//! The shape's words, in order: `count`, the words; `flush`, whether a denormal's stand-in is the
//! smallest normal; `merge`, 0 for a stand-in and 1 for a merge; and `strip`, in a merge 1 for a
//! strip ([`DepthMagnitudeModule::strip`]), which stores every exact word without its sign and
//! reads no stand-in. Invocation
//! `i` below `count` takes word `i` of both buffers; one past `count` does nothing. A consumer
//! whose words exceed `maxStorageBufferRange` or `maxComputeWorkGroupCount[0]` workgroups binds
//! them in windows, one dispatch each: no word's result reads another word.
//!
//! **Synchronization** (consumer): the copies' `TRANSFER_WRITE` → `SHADER_STORAGE_READ` and
//! `SHADER_STORAGE_WRITE` in `COMPUTE_SHADER` before the dispatch; its writes → `TRANSFER_READ`
//! before a buffer is copied into an image.
use std::sync::Arc;
use crate::budget::{Budget, Meter};
use crate::device::requirements::Requirements;
use crate::device::Device;
use crate::error::{Error, InternalError, InternalKind};
use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage, Symbol};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{GlobalId, TypeId, Value};
use crate::spirv::ir::{
natural_layout, BinOp, ExecMode, ExecModel, IoDir, LayoutRule, MemAccess, StorageClass, Type,
TypedModule,
};
/// The crate-owned depth magnitude module of one device, validated like any output.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DepthMagnitudeModule {
/// SPIR-V 1.5 words, entry point `main`, bindings numbered as below in set 0.
pub spirv: Arc<[u32]>,
/// What the module needs from the device (within every Vulkan 1.2 device).
pub requirements: Requirements,
}
impl DepthMagnitudeModule {
/// Descriptor set of every binding.
pub const SET: u32 = 0;
/// The depth's words, a storage buffer a merge writes.
pub const EXACT_BINDING: u32 = 0;
/// Their stand-ins, a storage buffer a stand-in writes; the pass's words in a merge.
pub const STAND_IN_BINDING: u32 = 1;
/// Invocations of one workgroup, along x: one 4-byte word each.
pub const LOCAL_SIZE: u32 = 64;
/// Bytes of the `COMPUTE` push-constant range at offset 0: the shape.
pub const PUSH_BYTES: u32 = 16;
/// The push bytes of a dispatch over `count` words: a merge where `merge`, else a stand-in,
/// with a denormal's stand-in the smallest normal where `flush` (the module docs).
pub fn shape(count: u32, merge: bool, flush: bool) -> [u8; 16] {
Self::words(count, u32::from(flush), u32::from(merge), 0)
}
/// The push bytes of a strip over `count` words: each exact word stored without its sign,
/// the stand-in buffer unread (the module docs).
pub fn strip(count: u32) -> [u8; 16] {
Self::words(count, 0, 1, 1)
}
/// The shape's words as push bytes.
fn words(count: u32, flush: u32, merge: u32, strip: u32) -> [u8; 16] {
let words = [count, flush, merge, strip];
let mut bytes = [0; 16];
for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) {
chunk.copy_from_slice(&word.to_le_bytes());
}
bytes
}
/// The stand-in of the word `bits` (the module docs), as the module computes it: its
/// magnitude, a NaN's +inf's, and where `flush` a nonzero denormal's the smallest normal's.
pub fn stand_in(bits: u32, flush: bool) -> u32 {
let magnitude = bits & 0x7fff_ffff;
if magnitude > 0x7f80_0000 {
return 0x7f80_0000;
}
if flush && magnitude != 0 && magnitude < 0x0080_0000 {
return 0x0080_0000;
}
magnitude
}
}
/// The binding symbol of the exact buffer in the typed module.
const EXACT: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Buffer,
index: 0,
};
/// The binding symbol of the stand-in buffer in the typed module.
const STAND_IN: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Buffer,
index: 1,
};
/// A `Block { u32 words[]; }` storage buffer bound at `sym`.
fn words_buffer(b: &mut ModuleBuilder, sym: ResourceSlot, u32_: TypeId) -> BResult<GlobalId> {
let rta = b.ty(Type::RuntimeArray {
elem: u32_,
stride: Some(4),
})?;
let layout = natural_layout(b.types(), LayoutRule::Std430, true, &[rta])?;
let block = b.ty(Type::Struct {
members: [rta].into(),
layout: Some(layout),
})?;
b.resource(sym, StorageClass::StorageBuffer, block)
}
fn u32_value(f: &mut FunctionBuilder<'_>, v: u32) -> BResult<Value> {
let c = f.u32_const(v)?;
f.module().const_value(c)
}
/// The push field the shape is declared under: a crate-owned module's own words, which no
/// selection places.
const SHAPE: PushField = PushField::DispatchRegion;
/// The module as a typed module, before serialization: the module [`depth_magnitude_module`]
/// serializes, which the CPU interpreter runs. Its bindings are the symbols `EXACT` and
/// `STAND_IN`, and its push field the shape, a `uvec4` (the module docs).
fn typed_module() -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let u32_ = b.ty(Type::Int {
width: 32,
signed: false,
})?;
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
let uvec4 = b.ty(Type::Vector { elem: u32_, len: 4 })?;
let m_shape = b.push_member(SHAPE, uvec4, 0)?;
let push = b.push_global()?;
let exact = words_buffer(&mut b, EXACT, u32_)?;
let stand_in = words_buffer(&mut b, STAND_IN, u32_)?;
let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let zero = u32_value(&mut f, 0)?;
let sign_off = u32_value(&mut f, 0x7fff_ffff)?;
let infinity = u32_value(&mut f, 0x7f80_0000)?;
let smallest = u32_value(&mut f, 0x0080_0000)?;
let invocation = f.module().global_value(invocation)?;
let invocation = f.load(invocation, MemAccess::default())?;
let i = f.composite_extract(invocation, &[0])?;
let exact = f.module().global_value(exact)?;
let stand_in = f.module().global_value(stand_in)?;
let push = f.module().global_value(push)?;
let member = u32_value(&mut f, m_shape.index)?;
let shape = f.access_chain(push, &[member])?;
let shape = f.load(shape, MemAccess::default())?;
let count = f.composite_extract(shape, &[0])?;
let flush = f.composite_extract(shape, &[1])?;
let merge = f.composite_extract(shape, &[2])?;
let strip = f.composite_extract(shape, &[3])?;
let merging = f.binary(BinOp::INotEqual, merge, zero)?;
let stripping = f.binary(BinOp::INotEqual, strip, zero)?;
let flushing = f.binary(BinOp::INotEqual, flush, zero)?;
let inside = f.binary(BinOp::ULessThan, i, count)?;
let word: ArmFn<'_, ()> = Box::new(move |f, _| {
let at_exact = f.access_chain(exact, &[zero, i])?;
let held = f.load(at_exact, MemAccess::default())?;
// The stand-in of the word (`DepthMagnitudeModule::stand_in`).
let unsigned = f.binary(BinOp::BitwiseAnd, held, sign_off)?;
let nan = f.binary(BinOp::UGreaterThan, unsigned, infinity)?;
let magnitude = f.select(nan, infinity, unsigned)?;
let nonzero = f.binary(BinOp::INotEqual, magnitude, zero)?;
let below = f.binary(BinOp::ULessThan, magnitude, smallest)?;
let denormal = f.binary(BinOp::LogicalAnd, nonzero, below)?;
let raised = f.binary(BinOp::LogicalAnd, denormal, flushing)?;
let standing = f.select(raised, smallest, magnitude)?;
let at_stand_in = f.access_chain(stand_in, &[zero, i])?;
let into: ArmFn<'_, ()> = Box::new(move |f, _| {
// A strip: every word without its sign; the stand-in buffer is not read.
let bare: ArmFn<'_, ()> = Box::new(move |f, _| {
f.store(at_exact, unsigned, MemAccess::default())?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
let merged: ArmFn<'_, ()> = Box::new(move |f, _| {
let drawn = f.load(at_stand_in, MemAccess::default())?;
// A word the pass left as it loaded it is the exact word without its sign, as
// Metal stores it after a pass with depth writes; any other is the pass's.
let changed = f.binary(BinOp::INotEqual, drawn, standing)?;
let merged = f.select(changed, drawn, unsigned)?;
f.store(at_exact, merged, MemAccess::default())?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), stripping, bare, Some(merged))?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
let out: ArmFn<'_, ()> = Box::new(move |f, _| {
f.store(at_stand_in, standing, MemAccess::default())?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), merging, into, Some(out))?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), inside, word, None)?;
f.ret(None)?;
let id = f.finish()?;
b.entry(
ExecModel::GLCompute,
id,
vec![ExecMode::LocalSize {
x: DepthMagnitudeModule::LOCAL_SIZE,
y: 1,
z: 1,
}],
)?;
b.finalize()
}
/// The fixed binding numbers of the module's symbols.
fn binding_of(sym: &Symbol) -> Option<u32> {
match sym {
Symbol::DescriptorSet(_) => Some(DepthMagnitudeModule::SET),
Symbol::Binding(s) if *s == EXACT => Some(DepthMagnitudeModule::EXACT_BINDING),
Symbol::Binding(s) if *s == STAND_IN => Some(DepthMagnitudeModule::STAND_IN_BINDING),
_ => None,
}
}
/// The depth magnitude module of `device`: built with the typed builder, checked by the owned
/// verifier against the device's profile (requirements included), serialized, and numbered with
/// the fixed bindings of [`DepthMagnitudeModule`].
pub fn depth_magnitude_module(device: &Device) -> Result<DepthMagnitudeModule, Error> {
let profile = device.profile();
let m = typed_module()?;
let mut meter = Meter::new(&Budget::default());
crate::spirv::verify::verify(&m, profile, &mut meter)?;
let r = crate::spirv::serialize::serialize(m)?;
profile.check(&r.requirements).map_err(|c| {
Error::Internal(InternalError::new(
InternalKind::RequirementsExceedProfile,
format!("the depth magnitude module needs {c:?}"),
))
})?;
let words = crate::spirv::serialize::relocate(&r, &binding_of)?;
Ok(DepthMagnitudeModule {
spirv: words.into(),
requirements: r.requirements,
})
}
#[cfg(test)]
mod tests {
use super::{typed_module, DepthMagnitudeModule, EXACT, STAND_IN};
use crate::spirv::interp::{run, Buffer, Config, Order, Resources};
use crate::spirv::testing::{assert_valid, committed_profiles};
/// The 18 stored values of the `depthkeep` probe (the M3 Max under macOS 27.0.1): ±2, ±0.5,
/// the smallest and largest denormal of each sign, ±0, the smallest normal, 0.25, 0.5, 1, the
/// `float` after 1, 1.5, ±inf, and the quiet NaN.
const PROBED: [u32; 18] = [
0x4000_0000,
0xc000_0000,
0x3f00_0000,
0xbf00_0000,
0x0000_0001,
0x8000_0001,
0x007f_ffff,
0x807f_ffff,
0x0000_0000,
0x8000_0000,
0x0080_0000,
0x3e80_0000,
0x3f80_0000,
0x3f80_0001,
0x3fc0_0000,
0x7f80_0000,
0xff80_0000,
0x7fc0_0000,
];
#[test]
fn the_magnitude_kernel_is_valid_on_every_committed_profile() {
for (_, p) in committed_profiles().expect("profiles") {
assert_valid(typed_module().expect("module"), &p);
}
}
fn bytes(words: &[u32]) -> Vec<u8> {
words.iter().flat_map(|w| w.to_le_bytes()).collect()
}
fn words(bytes: &[u8]) -> Vec<u32> {
bytes
.as_chunks::<4>()
.0
.iter()
.map(|w| u32::from_le_bytes(*w))
.collect()
}
/// Run the kernel over `exact` and `stand_in`, in `groups` workgroups of the shape of
/// `count` words, both invocation orders: both buffers after it.
fn ran(
exact: &[u32],
stand_in: &[u32],
count: u32,
merge: bool,
flush: bool,
groups: u32,
) -> (Vec<u32>, Vec<u32>) {
let push = DepthMagnitudeModule::shape(count, merge, flush);
ran_with(exact, stand_in, push, groups)
}
/// Run the kernel over `exact` and `stand_in` with the push bytes `push`, as [`ran`] does.
fn ran_with(
exact: &[u32],
stand_in: &[u32],
push: [u8; 16],
groups: u32,
) -> (Vec<u32>, Vec<u32>) {
let m = typed_module().expect("module");
let mut out = Vec::new();
for order in [Order::Forward, Order::Reverse] {
let part = |slot, words: &[u32]| Buffer {
slot: Some(slot),
address: None,
bytes: bytes(words),
};
let res = Resources {
buffers: vec![part(EXACT, exact), part(STAND_IN, stand_in)],
push: push.to_vec(),
spec: Default::default(),
};
let cfg = Config {
order,
workgroups: [groups, 1, 1],
..Config::default()
};
let buffers = run(&m, &cfg, res).expect("run").buffers;
out.push((words(&buffers[0]), words(&buffers[1])));
}
assert_eq!(out[0], out[1], "order independent");
out.swap_remove(0)
}
/// Each probed value's stand-in is its magnitude, a NaN's +inf, and, flushing, a denormal's
/// the smallest normal: the kernel's, as the host computes it; the exact buffer is only read.
#[test]
fn each_probed_value_stands_in_as_its_magnitude() {
for flush in [false, true] {
let want: Vec<u32> = PROBED
.iter()
.map(|&w| DepthMagnitudeModule::stand_in(w, flush))
.collect();
let (exact, stand_in) = ran(&PROBED, &[0; 18], 18, false, flush, 1);
assert_eq!(exact, PROBED, "the exact words are only read");
assert_eq!(stand_in, want, "flush {flush}");
for (&held, &standing) in PROBED.iter().zip(&want) {
let magnitude = held & 0x7fff_ffff;
let expected = match magnitude {
m if m > 0x7f80_0000 => 0x7f80_0000,
m if flush && m != 0 && m < 0x0080_0000 => 0x0080_0000,
m => m,
};
assert_eq!(standing, expected, "{held:08x} flush {flush}");
}
}
}
/// A merge stores each exact word whose stand-in the pass left without its sign, as Metal
/// stores it (a NaN's payload and a denormal kept), and the pass's word wherever it differs; a
/// word the pass wrote with its stand-in's value is the exact word without its sign, which
/// for a negative one is the pass's (|D| over -D), and for a NaN not (the module docs' corner).
#[test]
fn a_merge_stores_the_words_the_pass_left_without_their_signs() {
let exact = [
0xbf00_0000,
0xffc0_0001,
0x3e80_0000,
0x8000_0001,
0xc000_0000,
0x8000_0000,
0x7fc0_0001,
0x8000_0002,
];
// The pass left the first, second, sixth and eighth, wrote 0.75 over the third, 0 over the
// fourth and +inf over the NaN, and wrote 2's stand-in, 2, over -2.
let drawn = [
0x3f00_0000,
0x7f80_0000,
0x3f40_0000,
0x0000_0000,
0x4000_0000,
0x0000_0000,
0x7f80_0000,
0x0080_0000,
];
let (merged, stand_in) = ran(&exact, &drawn, 8, true, true, 1);
assert_eq!(stand_in, drawn, "the pass's words are only read");
assert_eq!(
merged,
[
0x3f00_0000,
0x7fc0_0001,
0x3f40_0000,
0x0000_0000,
0x4000_0000,
0x0000_0000,
0x7fc0_0001,
0x0000_0002
]
);
// Not flushing, a denormal's stand-in is its magnitude, so 0 and 2^-126 there are writes.
let (merged, _) = ran(&exact, &drawn, 8, true, false, 1);
assert_eq!(merged[3], 0x0000_0000);
assert_eq!(merged[7], 0x0080_0000);
}
/// A strip stores every exact word without its sign, a NaN's payload and a denormal kept, and
/// leaves the stand-in buffer as it was; a word past the count stays.
#[test]
fn a_strip_stores_every_word_without_its_sign() {
let exact = [
0xbf00_0000,
0xffc0_0001,
0x8000_0001,
0x8000_0000,
0x3e80_0000,
0xff80_0000,
0xbf80_0000,
];
let junk = [0xeeee_eeee; 7];
let (stripped, stand_in) = ran_with(&exact, &junk, DepthMagnitudeModule::strip(6), 1);
assert_eq!(stand_in, junk, "the stand-in buffer is not written");
assert_eq!(
stripped,
[
0x3f00_0000,
0x7fc0_0001,
0x0000_0001,
0x0000_0000,
0x3e80_0000,
0x7f80_0000,
0xbf80_0000
]
);
}
/// Invocations past the words write nothing, and every word of several workgroups is taken.
#[test]
fn every_word_stands_in_across_workgroups_and_none_past_them() {
let count = 64 * 3 + 5;
let exact: Vec<u32> = (0..count + 7).map(|i| 0x8000_0000 | (i * 0x0101)).collect();
let (_, stand_in) = ran(
&exact,
&vec![0xeeee_eeee; exact.len()],
count,
false,
false,
4,
);
for (i, &w) in stand_in.iter().enumerate() {
match (i as u32) < count {
true => assert_eq!(w, exact[i] & 0x7fff_ffff, "word {i}"),
false => assert_eq!(w, 0xeeee_eeee, "word {i} past the count"),
}
}
}
}
@@ -29,12 +29,6 @@
//! output at `Location` 0, into a multisampled unsigned colour attachment (`R32_UINT`,
//! `R8_UINT`) with no depth/stencil attachment: the other way, a depth or stencil aspect's
//! samples into colour.
//! - [`DepthStencilCopy::DepthMagnitude`] and [`DepthStencilCopy::MagnitudeBits`]: a 32-bit
//! float depth's bits without the sign bit (`bits & 0x7fffffff`, integer operations, so a
//! NaN's payload and a denormal are kept), the first from a depth aspect, written as
//! `FragDepth` as [`DepthStencilCopy::Depth`] writes it, the second from an unsigned colour
//! image of such bits (`R32_UINT`), written as [`DepthStencilCopy::DepthBits`] writes them:
//! a multisampled depth stored without its signs.
//! - [`DepthStencilCopy::Depth16Code`] and [`DepthStencilCopy::Depth16Bits`]: a 16-bit unsigned
//! normalized depth, carried as its **code** rather than as a float, in an unsigned colour
//! image of the code's bits (`R16_UINT`). `Depth16Code` reads a code `c` there and writes
@@ -141,13 +135,6 @@ pub enum DepthStencilCopy {
/// The stencil's value as the first component of the unsigned colour output at `Location` 0,
/// from a sampled view of a stencil aspect.
StencilBits,
/// The depth without its sign, its `f32` bits with the sign bit cleared, as `FragDepth`,
/// from a sampled view of a depth aspect.
DepthMagnitude,
/// The bits without the sign bit, `bits & 0x7fffffff`, as the first component of the
/// unsigned colour output at `Location` 0, from a sampled view of an unsigned colour image
/// of a 32-bit float depth's bits.
MagnitudeBits,
/// The depth a 16-bit unsigned normalized code stands for, `code / 65535`, as `FragDepth`,
/// from a sampled view of an unsigned colour image of such codes (`R16_UINT`): a 16-bit
/// depth's copy in, exact by construction (the module docs).
@@ -337,8 +324,6 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult<TypedModule> {
DepthStencilCopy::Depth
| DepthStencilCopy::DepthBits
| DepthStencilCopy::StencilBits
| DepthStencilCopy::DepthMagnitude
| DepthStencilCopy::MagnitudeBits
| DepthStencilCopy::Depth16Code
| DepthStencilCopy::Depth16Bits
| DepthStencilCopy::DepthFromStandIn { .. } => CopySource::Aspect,
@@ -350,10 +335,7 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult<TypedModule> {
let source_ty = match (copy, source) {
(DepthStencilCopy::DepthFromStandIn { form }, _) => stand_in_image(&mut b, f32_, form)?,
(
DepthStencilCopy::Depth
| DepthStencilCopy::DepthBits
| DepthStencilCopy::DepthMagnitude
| DepthStencilCopy::Depth16Bits,
DepthStencilCopy::Depth | DepthStencilCopy::DepthBits | DepthStencilCopy::Depth16Bits,
_,
) => multisampled_image(
&mut b,
@@ -437,17 +419,6 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult<TypedModule> {
let output = f.module().global_value(output)?;
f.store(output, value, MemAccess::default())?;
}
DepthStencilCopy::DepthMagnitude => {
let bits = f.convert(ConvOp::Bitcast, value, u32_)?;
let mask = uint(&mut f, 0x7fff_ffff)?;
let bits = f.binary(BinOp::BitwiseAnd, bits, mask)?;
let magnitude = f.convert(ConvOp::Bitcast, bits, f32_)?;
let output = f
.module()
.builtin(crate::spv::BuiltIn::FragDepth, IoDir::Output, f32_)?;
let output = f.module().global_value(output)?;
f.store(output, magnitude, MemAccess::default())?;
}
DepthStencilCopy::Depth16Code => {
// The code's depth: one correctly rounded division, so the `float` nearest
// `code / 65535` (the module docs).
@@ -462,17 +433,12 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult<TypedModule> {
}
DepthStencilCopy::DepthBits
| DepthStencilCopy::StencilBits
| DepthStencilCopy::MagnitudeBits
| DepthStencilCopy::Depth16Bits => {
// The colour output, at `Location` 0.
let uvec4 = f.module().ty(Type::Vector { elem: u32_, len: 4 })?;
let output = f.module().fixed_io(0, IoDir::Output, uvec4, false)?;
let bits = match copy {
DepthStencilCopy::DepthBits => f.convert(ConvOp::Bitcast, value, u32_)?,
DepthStencilCopy::MagnitudeBits => {
let mask = uint(&mut f, 0x7fff_ffff)?;
f.binary(BinOp::BitwiseAnd, value, mask)?
}
// `round(depth * 65535)`: the conversion to unsigned truncates, so the half is
// added first. Exact for every code (the module docs).
DepthStencilCopy::Depth16Bits => {
@@ -497,12 +463,10 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult<TypedModule> {
DepthStencilCopy::StencilPlane { .. } => {}
DepthStencilCopy::StencilExport { .. } => modes.push(ExecMode::StencilRefReplacing),
DepthStencilCopy::Depth
| DepthStencilCopy::DepthMagnitude
| DepthStencilCopy::Depth16Code
| DepthStencilCopy::DepthFromStandIn { .. } => modes.push(ExecMode::DepthReplacing),
DepthStencilCopy::DepthBits
| DepthStencilCopy::StencilBits
| DepthStencilCopy::MagnitudeBits
| DepthStencilCopy::Depth16Bits => {}
}
b.entry(ExecModel::Fragment, id, modes)?;
@@ -21,8 +21,6 @@ fn every_copy() -> Vec<DepthStencilCopy> {
copies.push(DepthStencilCopy::Depth);
copies.push(DepthStencilCopy::DepthBits);
copies.push(DepthStencilCopy::StencilBits);
copies.push(DepthStencilCopy::DepthMagnitude);
copies.push(DepthStencilCopy::MagnitudeBits);
copies.push(DepthStencilCopy::Depth16Code);
copies.push(DepthStencilCopy::Depth16Bits);
for form in FORMS {
+2 -9
View File
@@ -400,12 +400,7 @@ fn member_view(
class: &ImageHandleClass,
layout: vk::ImageLayout,
) -> Result<ImageViewDesc, BindError> {
let TextureShape::Texture {
pixel_format,
depth_twin,
..
} = *shape
else {
let TextureShape::Texture { pixel_format, .. } = *shape else {
return Err(internal("a texture-buffer heap member"));
};
let raw = raw_held(shape)
@@ -431,7 +426,6 @@ fn member_view(
layout,
components: vk::ComponentMapping::IDENTITY,
level: None,
twin: false,
shader_swizzle: false,
});
}
@@ -494,11 +488,10 @@ fn member_view(
layout,
components: vk::ComponentMapping::IDENTITY,
level: None,
twin: false,
shader_swizzle: false,
});
}
let mut view = sampled_view(profile, pixel_format, class, depth_twin)?;
let mut view = sampled_view(profile, pixel_format, class)?;
view.layout = layout;
Ok(view)
}
+1 -3
View File
@@ -41,7 +41,6 @@ fn shape(ty: TextureType, pf: PixelFormat, samples: u32, usage: TextureUsage) ->
usage,
mipmap_level_count: 1,
sparse: false,
depth_twin: false,
swizzle: crate::metal::TextureSwizzleChannels::DEFAULT,
}
}
@@ -732,7 +731,6 @@ fn a_storage_write_makes_every_write_of_its_slot_general() {
layout,
components: vk::ComponentMapping::IDENTITY,
level: None,
twin: false,
shader_swizzle: false,
};
let sampled = HandleClass::Image(class(
@@ -1258,7 +1256,7 @@ fn a_form_a_heap_reads_is_held_raw_in_the_unsigned_class() {
assert_eq!(fit(&s, &u2d), Fit::Holds, "{pf:?}");
assert_eq!(fit(&s, &i2d), Fit::NumericType, "{pf:?}");
let facts = TextureFacts::new(TextureType::Type2D, pf);
let mut slot = crate::bind::plan::resources::sampled_view(p, pf, &u2d, false)
let mut slot = crate::bind::plan::resources::sampled_view(p, pf, &u2d)
.unwrap_or_else(|e| panic!("{stem} {pf:?}: {e}"));
slot.layout = layout;
assert_eq!(
+2 -8
View File
@@ -86,10 +86,7 @@
//! [`shadow_copy_in_module`] copies a merged texture's texels in and keeps them with one dispatch.
//! A copy of many
//! equal rows between two buffers is one dispatch of [`rows_copy_module`] where a copy's region
//! per row costs more. A render pass that loads a
//! 32-bit float depth holding a value Vulkan's depth test compares otherwise than Metal's (a
//! negative value or a NaN, whose magnitude Metal compares) renders over its stand-in, written
//! before the pass and merged back after it by [`depth_magnitude_module`]. A blit between a buffer
//! per row costs more. A blit between a buffer
//! and a two-plane extended-range texture moves its color words through [`plane_words_module`],
//! and a blit between two such textures moves both planes as Metal's blit does through
//! [`plane_copy_module`]. A rotated texture's texels move between its
@@ -101,8 +98,7 @@
//! through [`tiled_texels_module`]. A render pass that loads an extended-range, padded 10-bit or
//! bfloat color attachment and draws first rewrites the bits its codes leave unused through
//! [`unused_bits_module`] of its format, in the 32 x 32 tiles a mask names, as Metal's tile store
//! does; under the exact tile store it also raises a signed normalized attachment's minimum codes
//! and normalizes an `RGB9E5Float` attachment's words there. The tiles a pass's draws reach, which Metal's tile store writes back, are the mask one
//! does. The tiles a pass's draws reach, which Metal's tile store writes back, are the mask one
//! dispatch of [`tile_reach_module`] bins its captured primitives into: [`capture_assembly_module`]
//! assembles them from a pass's capture draws' records, and [`capture_settle_module`] widens the
//! mask to every tile where the binning counted a primitive it cannot answer. A GPU blit that reads
@@ -144,7 +140,6 @@ pub(crate) mod capture_assembly;
pub(crate) mod chroma_decode;
pub(crate) mod color_resolve;
pub(crate) mod compressed_blit;
pub(crate) mod depth_magnitude;
pub(crate) mod depth_stencil_copy;
pub(crate) mod depth_stencil_resolve;
pub(crate) mod dispatch;
@@ -216,7 +211,6 @@ pub use compressed_blit::{compressed_blit_module, CompressedBlit, CompressedBlit
pub use etc_decode::{etc_decode_module, EtcDecode, EtcTexels};
// The bytes of `WriteSource::ColorWriteTable`'s buffer.
pub use crate::lower::arith::srgb::color_write_table;
pub use depth_magnitude::{depth_magnitude_module, DepthMagnitudeModule};
pub use depth_stencil_copy::{
depth_split_module, depth_stencil_copy_modules, stencil_split_module, CopySource,
DepthSplitModule, DepthStandInForm, DepthStencilCopy, DepthStencilCopyModules, StencilBit,
-7
View File
@@ -889,12 +889,6 @@ pub struct ImageViewDesc {
/// first level is its parent's level `b` is the parent's level `b + i`. Every layer either way.
#[cfg_attr(feature = "serde", serde(default))]
pub level: Option<u32>,
/// The view is of the texture's depth twin: the `D32_SFLOAT` image a texture held in
/// `R32_SFLOAT` ([`TextureFacts::depth_twin`](crate::bind::TextureFacts)) keeps for the
/// comparisons the device makes of it (the shader makes the others). `false` for every other
/// view, which is of the texture's own image.
#[cfg_attr(feature = "serde", serde(default))]
pub twin: bool,
/// The function applies the bound texture's swizzle (`MTLTexture.swizzle`) to the texels it
/// reads and writes through the view, so the view takes none: its component mapping is
/// `components` alone. Set for a storage view of a swizzled texture at a slot of
@@ -926,7 +920,6 @@ impl ImageViewDesc {
layout,
components,
level: None,
twin: false,
shader_swizzle: false,
}
}
+9 -48
View File
@@ -489,45 +489,13 @@ fn sampled_components(
/// The view of a sampled image of `pf` declared as `class` on `profile`: `vk_format` for
/// `SampledImage` with the emulation's component mapping, the depth (or stencil-only) aspect, in
/// `SHADER_READ_ONLY_OPTIMAL`. A texture held with a depth twin (`twin`) is read through an
/// `R32_SFLOAT` view of its image, and a comparison reads a `D32_SFLOAT` view of its twin. A depth
/// that no comparison reads, its twin's included, reads as Metal's `(d, d, d, 1)`
/// `SHADER_READ_ONLY_OPTIMAL`. A depth that no comparison reads reads as Metal's `(d, d, d, 1)`
/// ([`DEPTH_AS_COLOR`]).
pub(crate) fn sampled_view(
profile: &DeviceProfile,
pf: PixelFormat,
class: &ImageHandleClass,
twin: bool,
) -> Result<ImageViewDesc, BindError> {
if twin {
if pf != PixelFormat::Depth32Float {
return Err(internal(format!(
"a depth twin of a {pf:?} texture: only a Depth32Float texture has one"
)));
}
let (format, aspect, components) = match class.depth_compare {
true => (
vk::Format::D32_SFLOAT,
vk::ImageAspectFlags::DEPTH,
vk::ComponentMapping::IDENTITY,
),
false => (
vk::Format::R32_SFLOAT,
vk::ImageAspectFlags::COLOR,
DEPTH_AS_COLOR,
),
};
return Ok(ImageViewDesc {
view_type: view_type(class)?,
format,
aspect,
layout: vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
components,
level: None,
twin: class.depth_compare,
shader_swizzle: false,
});
}
let usages = [FormatUsage::SampledImage].into();
let m = vk_format(pf, &usages, profile).map_err(bind_error)?;
let aspect = view_aspect(pf);
@@ -538,7 +506,6 @@ pub(crate) fn sampled_view(
layout: vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
components: sampled_components(aspect, m.components, class.depth_compare),
level: None,
twin: false,
shader_swizzle: false,
})
}
@@ -1216,7 +1183,6 @@ impl ResourcePlanner<'_> {
}
TextureShape::Texture {
pixel_format,
depth_twin,
swizzle,
..
} => {
@@ -1279,11 +1245,10 @@ impl ResourcePlanner<'_> {
layout: vk::ImageLayout::GENERAL,
components: vk::ComponentMapping::IDENTITY,
level: None,
twin: false,
shader_swizzle,
}
} else {
match self.texel_view(pixel_format, &class, depth_twin, raw)? {
match self.texel_view(pixel_format, &class, raw)? {
Some((view, _)) => ImageViewDesc {
shader_swizzle,
..view
@@ -1296,19 +1261,17 @@ impl ResourcePlanner<'_> {
}
}
/// The view of a sampled image of `pf` declared as `class`, of a texture held with a depth
/// twin when `twin`.
/// The view of a sampled image of `pf` declared as `class`.
fn sampled_view(
&self,
pf: PixelFormat,
class: &ImageHandleClass,
twin: bool,
) -> Result<ImageViewDesc, BindError> {
sampled_view(self.profile, pf, class, twin)
sampled_view(self.profile, pf, class)
}
/// The view a binding of a texture slot reads a texture of `pf` through (declared `class`,
/// `twin` for a depth twin's): its sampled view, or for a binding of the raw view (`raw`) that
/// The view a binding of a texture slot reads a texture of `pf` through (declared `class`):
/// its sampled view, or for a binding of the raw view (`raw`) that
/// view, `None` for a format without one. Where the device cannot sample an 8-bit sRGB format,
/// whose sampled texture it holds as the format's UNORM twin (`metal::format::srgb_raw_twin`),
/// the twin's sampled view serves both bindings: the raw codes are the twin's texels, and the
@@ -1320,17 +1283,16 @@ impl ResourcePlanner<'_> {
&self,
pf: PixelFormat,
class: &ImageHandleClass,
twin: bool,
raw: bool,
) -> Result<Option<(ImageViewDesc, PixelFormat)>, BindError> {
let missing = match self.sampled_view(pf, class, twin) {
let missing = match self.sampled_view(pf, class) {
Ok(own) if raw => return Ok(raw_view(own).map(|view| (view, pf))),
Ok(own) => return Ok(Some((own, pf))),
Err(missing) => missing,
};
match srgb_raw_twin(pf) {
Some(linear) => self
.sampled_view(linear, class, false)
.sampled_view(linear, class)
.map(|view| Some((view, linear)))
.map_err(|_| missing),
None => Err(missing),
@@ -1733,10 +1695,9 @@ impl ResourcePlanner<'_> {
}
Some(TextureShape::Texture {
pixel_format,
depth_twin,
swizzle,
..
}) => match self.texel_view(pixel_format, &class, depth_twin, sampler.raw)? {
}) => match self.texel_view(pixel_format, &class, sampler.raw)? {
Some((view, viewed)) => {
self.texture_use(texture, &t, false);
// A swizzled packed normalized texture's sampled view takes no swizzle where
@@ -99,7 +99,6 @@ fn compatibility_is_type_samples_numeric_type_and_depth() {
usage: crate::metal::TextureUsage::SHADER_READ,
mipmap_level_count: 1,
sparse: false,
depth_twin: false,
swizzle: crate::metal::TextureSwizzleChannels::DEFAULT,
};
assert!(compatible(
@@ -171,7 +170,6 @@ fn a_ulong_slot_binds_only_rg32uint_textures() {
usage: crate::metal::TextureUsage::SHADER_READ,
mipmap_level_count: 1,
sparse: false,
depth_twin: false,
swizzle: crate::metal::TextureSwizzleChannels::DEFAULT,
};
let t = slot_iface(TextureType::Type2D, SampledType::Uint64);
@@ -266,7 +264,6 @@ fn a_numeric_slot_binds_either_integer_type() {
usage: crate::metal::TextureUsage::SHADER_WRITE,
mipmap_level_count: 1,
sparse: false,
depth_twin: false,
swizzle: crate::metal::TextureSwizzleChannels::DEFAULT,
},
);
@@ -431,7 +428,7 @@ fn a_depth_read_as_colour_replicates_its_depth_as_metal_does() {
let mut seen = 0;
for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") {
for pf in depths {
let Ok(read) = sampled_view(&p, pf, &class(false), false) else {
let Ok(read) = sampled_view(&p, pf, &class(false)) else {
continue;
};
seen += 1;
@@ -440,7 +437,7 @@ fn a_depth_read_as_colour_replicates_its_depth_as_metal_does() {
(vk::ImageAspectFlags::DEPTH, DEPTH_AS_COLOR),
"{stem} {pf:?}"
);
let compare = sampled_view(&p, pf, &class(true), false).unwrap();
let compare = sampled_view(&p, pf, &class(true)).unwrap();
assert_eq!(
compare.components,
vk::ComponentMapping::IDENTITY,
@@ -448,7 +445,7 @@ fn a_depth_read_as_colour_replicates_its_depth_as_metal_does() {
);
}
for pf in stencils {
let Ok(read) = sampled_view(&p, pf, &uint, false) else {
let Ok(read) = sampled_view(&p, pf, &uint) else {
continue;
};
assert_eq!(
@@ -464,72 +461,6 @@ fn a_depth_read_as_colour_replicates_its_depth_as_metal_does() {
assert!(seen > 0, "no profile samples a depth format");
}
/// A `Depth32Float` texture held with a depth twin is read through an `R32_SFLOAT` colour view of
/// its image and compared through a `D32_SFLOAT` depth view of its twin, on every committed
/// profile; a texture without one keeps its depth view of its own image, and only a `Depth32Float`
/// texture takes a twin.
#[test]
fn a_depth_twin_is_read_through_its_colour_image_and_compared_through_its_twin() {
let t = TextureSlot {
depth_compare: true,
..slot_iface(TextureType::Type2D, SampledType::Float)
};
let class = |compare| {
declared(
&t,
vk::DescriptorType::SAMPLED_IMAGE,
false,
compare,
StorageFormatClass::NotStorage,
)
.unwrap()
};
for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") {
let d32 = PixelFormat::Depth32Float;
let read = sampled_view(&p, d32, &class(false), true).unwrap();
assert_eq!(
(read.format, read.aspect, read.twin, read.components),
(
vk::Format::R32_SFLOAT,
vk::ImageAspectFlags::COLOR,
false,
DEPTH_AS_COLOR
),
"{stem}"
);
let compare = sampled_view(&p, d32, &class(true), true).unwrap();
assert_eq!(
(
compare.format,
compare.aspect,
compare.twin,
compare.components
),
(
vk::Format::D32_SFLOAT,
vk::ImageAspectFlags::DEPTH,
true,
vk::ComponentMapping::IDENTITY
),
"{stem}"
);
for compare in [false, true] {
let Ok(own) = sampled_view(&p, d32, &class(compare), false) else {
continue;
};
assert_eq!(
(own.aspect, own.twin),
(vk::ImageAspectFlags::DEPTH, false),
"{stem}"
);
}
assert!(matches!(
sampled_view(&p, PixelFormat::Depth16Unorm, &class(false), true),
Err(BindError::Internal(_))
));
}
}
/// A bound runtime sampler's values are checked at plan time from its shape, with exactly the
/// verdict `vk_sampler` gives the descriptor for the binding's use: mirror-clamp needs
/// `samplerMirrorClampToEdge`, and NaN or inverted LOD clamps are invalid descriptors; anisotropy is
@@ -701,7 +632,6 @@ fn an_immutable_linear_sampler_needs_a_filterable_view() {
usage: crate::metal::TextureUsage::SHADER_READ,
mipmap_level_count: 1,
sparse: false,
depth_twin: false,
swizzle: crate::metal::TextureSwizzleChannels::DEFAULT,
},
);
@@ -729,7 +659,7 @@ fn an_immutable_linear_sampler_needs_a_filterable_view() {
StorageFormatClass::NotStorage,
)
.expect("declared");
let format = sampled_view(&p, pf, &class, false).expect("view").format;
let format = sampled_view(&p, pf, &class).expect("view").format;
let filterable = p.supports_format(format, FormatUsage::SampledImageFilterLinear);
if integer || filterable {
assert!(
@@ -803,7 +733,6 @@ fn a_linear_compare_sampler_needs_no_filterable_view() {
usage: crate::metal::TextureUsage::SHADER_READ,
mipmap_level_count: 1,
sparse: false,
depth_twin: false,
swizzle: crate::metal::TextureSwizzleChannels::DEFAULT,
},
);
@@ -833,7 +762,7 @@ fn a_linear_compare_sampler_needs_no_filterable_view() {
StorageFormatClass::NotStorage,
)
.expect("declared");
let format = sampled_view(&p, pf, &class, false).expect("view").format;
let format = sampled_view(&p, pf, &class).expect("view").format;
let filterable = p.supports_format(format, FormatUsage::SampledImageFilterLinear);
if compare || filterable {
assert!(
@@ -899,7 +828,6 @@ fn bicubic_texels_follow_the_bound_format() {
usage: crate::metal::TextureUsage::SHADER_READ,
mipmap_level_count: 1,
sparse: false,
depth_twin: false,
swizzle: crate::metal::TextureSwizzleChannels::DEFAULT,
},
);
@@ -995,7 +923,6 @@ fn an_explicit_cube_gradient_binding_takes_an_anisotropic_sampler_isotropically(
usage: crate::metal::TextureUsage::SHADER_READ,
mipmap_level_count: 1,
sparse: false,
depth_twin: false,
swizzle: crate::metal::TextureSwizzleChannels::DEFAULT,
},
);
@@ -1205,7 +1132,6 @@ fn texel_format_follows_the_bound_format() {
usage: crate::metal::TextureUsage::SHADER_READ,
mipmap_level_count: 1,
sparse: false,
depth_twin: false,
swizzle: crate::metal::TextureSwizzleChannels::DEFAULT,
})
};
@@ -1348,7 +1274,7 @@ fn a_separate_pair_takes_the_combined_pairs_checks() {
StorageFormatClass::NotStorage,
)
.expect("declared");
let view = sampled_view(&p, pf, &class, false).expect("view");
let view = sampled_view(&p, pf, &class).expect("view");
let filterable = p.supports_format(view.format, FormatUsage::SampledImageFilterLinear);
let refusal = Err(BindError::Unsupported(Unsupported::needs(
Feature::Format,
@@ -1390,7 +1316,6 @@ fn a_separate_pair_takes_the_combined_pairs_checks() {
usage: crate::metal::TextureUsage::SHADER_READ,
mipmap_level_count: 1,
sparse: false,
depth_twin: false,
swizzle: crate::metal::TextureSwizzleChannels::DEFAULT,
},
);
+3 -8
View File
@@ -351,8 +351,8 @@ pub(crate) fn srgb_twin_variant(
/// `SnapshotForm::of`): by the view the snapshot's copy fetches through, the bound texture's
/// sampled view or, at a slot whose raw codes the variant reads (`srgb`, `slots::srgb_variant`),
/// its raw view (`metal::texel_format::srgb_raw_view`), and the slot's declared sampled type.
/// [`SnapshotForm::Bits`] at a slot the variant reads in another class (`cross`), a depth twin's,
/// or one whose sampled view the device has no format for. The variant's compile reads the same
/// [`SnapshotForm::Bits`] at a slot the variant reads in another class (`cross`), or one whose
/// sampled view the device has no format for. The variant's compile reads the same
/// key, so its plan for the same shape states the same forms.
pub(crate) fn snapshot_forms(
profile: &DeviceProfile,
@@ -368,12 +368,7 @@ pub(crate) fn snapshot_forms(
let Some(SlotInterface::Texture(t)) = interface.get(&slot) else {
return SnapshotForm::Bits;
};
let Some(TextureShape::Texture {
pixel_format,
depth_twin: false,
..
}) = bound_texture(shape, slot)
else {
let Some(TextureShape::Texture { pixel_format, .. }) = bound_texture(shape, slot) else {
return SnapshotForm::Bits;
};
if cross.contains_key(&slot) {
+5 -23
View File
@@ -1168,11 +1168,11 @@ impl BoundTexture {
impl TextureFacts {
/// The facts of an image texture that can change a plan (its view facts): the type, the pixel
/// format, the sample count, the usage, whether it is sparse, its level count, which decides a
/// storage slot's level views and pushed level count, whether it is held with a depth twin, its
/// swizzle, its address-mode map, its [`offset_base_axes`](Self::offset_base_axes), and
/// whether its planes are read in place ([`ycbcr_in_place`](Self::ycbcr_in_place), whose
/// words the slot's push field carries, not the shape). Its array length only changes the
/// view's subresource range, which is every layer.
/// storage slot's level views and pushed level count, its swizzle, its address-mode map, its
/// [`offset_base_axes`](Self::offset_base_axes), and whether its planes are read in place
/// ([`ycbcr_in_place`](Self::ycbcr_in_place), whose words the slot's push field carries, not
/// the shape). Its array length only changes the view's subresource range, which is every
/// layer.
///
/// The level count is stated whatever the usage: plain Metal writes a texture made without
/// `ShaderWrite` at every level, through every write form, as one made with it.
@@ -1187,7 +1187,6 @@ impl TextureFacts {
usage: self.usage,
mipmap_level_count: self.mipmap_level_count,
sparse: self.sparse,
depth_twin: self.depth_twin,
swizzle: self.swizzle,
address_modes: self.address_modes,
offset_base_axes: self.offset_base_axes(),
@@ -1382,18 +1381,6 @@ pub struct TextureFacts {
/// (`shaderResourceResidency`); the plan refuses it elsewhere.
#[cfg_attr(feature = "serde", serde(default))]
pub sparse: bool,
/// The texture's texels are held in an `R32_SFLOAT` image, and a `D32_SFLOAT` twin holds them
/// for comparisons: a `Depth32Float` texture the program only reads or samples, made by a
/// consumer on a device without `VK_EXT_depth_range_unrestricted`, so that a texel outside [0,
/// 1] keeps its value, or on one whose driver is not measured to keep a denormal in a depth
/// image (the runtime's driver facts), so that a denormal does. A sampled view of it reads the
/// `R32_SFLOAT` image, and a view a comparison reads is of the twin
/// ([`ImageViewDesc::twin`](crate::bind::ImageViewDesc)).
/// Only a `Depth32Float` texture holds its texels there. A multisampled one does under
/// `MultisampleDepthTwinPolicy::Exact` and has no `D32_SFLOAT` twin beside it: Metal reads a
/// `depth2d_ms` and compares nothing, so no view of a twin is asked for.
#[cfg_attr(feature = "serde", serde(default))]
pub depth_twin: bool,
/// `MTLTexture.swizzle`: the source of each channel the texture's reads and samples return,
/// border texels included. A sample emulated by fetches reads its border taps through it, and
/// an opaque-black border the device replaces is checked against it.
@@ -1447,7 +1434,6 @@ impl TextureFacts {
array_length: 1,
mipmap_level_count: 1,
sparse: false,
depth_twin: false,
swizzle: metal::TextureSwizzleChannels::DEFAULT,
address_modes: metal::sampler::AddressModeMap::IDENTITY,
parent_relative_level: 0,
@@ -2045,10 +2031,6 @@ pub enum TextureShape {
/// where the module has none.
#[cfg_attr(feature = "serde", serde(default))]
sparse: bool,
/// The texture is held in an `R32_SFLOAT` image with a `D32_SFLOAT` twin
/// ([`TextureFacts::depth_twin`]): a sampled view reads the image, a compared one the twin.
#[cfg_attr(feature = "serde", serde(default))]
depth_twin: bool,
/// The texture's swizzle ([`TextureFacts::swizzle`]): the border taps of a sample emulated
/// by fetches read through it, and an opaque-black border the device replaces is checked
/// against it.
+4 -106
View File
@@ -22,17 +22,6 @@
//! (`ExtendedRange::load_code`; on an Apple M4 under macOS 27.0.1: 56,829 of the
//! 65,536 codes move, in every tile a draw reaches).
//!
//! The same store writes a single-sampled signed normalized or `RGB9E5Float` attachment's tiles
//! back through their values (an Apple M3 Max under macOS 27.0.1), which a consumer's exact tile
//! store takes (`TileStorePolicy::Exact`):
//!
//! - a signed normalized format's code (`R8Snorm`, `RG8Snorm`, `RGBA8Snorm`, `R16Snorm`,
//! `RG16Snorm`, `RGBA16Snorm`): a channel's minimum code (-128, or -32768), which reads as -1.0
//! as the code above it does, raised to that code (-127, -32767);
//! - an `RGB9E5Float` word whose largest mantissa is below 256 under an exponent above 0:
//! normalized, its three mantissas shifted up one bit as its exponent steps down one, until the
//! largest reaches 256 or the exponent 0 (the word Metal's encoding of its value gives).
//!
//! A consumer copies the region's texels, row after row, into a buffer of words, one dispatch of
//! [`unused_bits_module`] of the texture's form rewrites the words of the tiles a mask names, and
//! it copies them back before the pass: the pass's write masks, discards, tests and uncovered
@@ -121,18 +110,11 @@ impl UnusedBitsModule {
/// The bytes of one texel of `format` held as `words`: an extended-range, padded or bfloat
/// format's raw texel (`ExtendedRange::raw_format`) or a two-plane format's color word
/// alone, or a signed normalized or `RGB9E5Float` texel. `None` where `format` has no such
/// words: another format, or [`TexelWords::ColorPlane`] of a format but a two-plane one.
/// alone. `None` where `format` has no such words: another format, or
/// [`TexelWords::ColorPlane`] of a format but a two-plane one.
pub fn texel_bytes(format: PixelFormat, words: TexelWords) -> Option<u32> {
let rule = rule(format, words)?;
let Some(form) = ExtendedRange::of(format) else {
return match format {
PixelFormat::R8Snorm => Some(1),
PixelFormat::RG8Snorm | PixelFormat::R16Snorm => Some(2),
PixelFormat::RGBA16Snorm => Some(8),
_ => Some(4),
};
};
let form = ExtendedRange::of(format)?;
Some(match (rule, form) {
(Rule::Padded(_), ExtendedRange::R10X6 | ExtendedRange::R10X6Srgb) => 2,
(Rule::Bfloat, ExtendedRange::R16Bfloat) => 2,
@@ -178,29 +160,11 @@ enum Rule {
/// A bfloat form's two 16-bit codes: each one's value through `half` and back
/// (`ExtendedRange::load_code`, [`bfloat_load`]).
Bfloat,
/// A signed normalized format's codes, each byte (each 16-bit half where `wide`): one at the
/// minimum code (`0x80`, `0x8000`) raised to the code above it ([`snorm_minimum`]).
SnormMinimum { wide: bool },
/// An `RGB9E5Float` word, normalized ([`shared_exponent`]).
SharedExponent,
}
/// The rule of `format`'s texels held as `words`, or `None` where it has none.
fn rule(format: PixelFormat, words: TexelWords) -> Option<Rule> {
if let Some(form) = ExtendedRange::of(format) {
return extended_rule(form, words);
}
Some(match (format, words) {
(_, TexelWords::ColorPlane) => return None,
(PixelFormat::R8Snorm | PixelFormat::RG8Snorm | PixelFormat::RGBA8Snorm, _) => {
Rule::SnormMinimum { wide: false }
}
(PixelFormat::R16Snorm | PixelFormat::RG16Snorm | PixelFormat::RGBA16Snorm, _) => {
Rule::SnormMinimum { wide: true }
}
(PixelFormat::RGB9E5Float, _) => Rule::SharedExponent,
_ => return None,
})
extended_rule(ExtendedRange::of(format)?, words)
}
/// The rule of an extended-range, padded or bfloat `form`'s texels held as `words`, or `None`
@@ -376,75 +340,9 @@ fn rewritten(
let hi = f.binary(BinOp::ShiftLeftLogical, hi, k16)?;
f.binary(BinOp::BitwiseOr, lo, hi)?
}
Rule::SnormMinimum { wide } => snorm_minimum(f, word, *wide)?,
Rule::SharedExponent => shared_exponent(f, word)?,
})
}
/// `word`'s signed normalized codes, each byte (each 16-bit half where `wide`) at the minimum
/// code (`0x80`, `0x8000`) raised by one to the code above it: no carry leaves its lane.
fn snorm_minimum(f: &mut FunctionBuilder<'_>, word: Value, wide: bool) -> BResult<Value> {
let (bits, minimum) = match wide {
true => (16, 0x8000),
false => (8, 0x80),
};
let (zero, mask, minimum) = (
u32_value(f, 0)?,
u32_value(f, (1 << bits) - 1)?,
u32_value(f, minimum)?,
);
let mut out = word;
for shift in (0..32).step_by(bits) {
let k = u32_value(f, shift)?;
let lane = f.binary(BinOp::ShiftRightLogical, word, k)?;
let lane = f.binary(BinOp::BitwiseAnd, lane, mask)?;
let least = f.binary(BinOp::IEqual, lane, minimum)?;
let one = u32_value(f, 1 << shift)?;
let raise = f.select(least, one, zero)?;
out = f.binary(BinOp::IAdd, out, raise)?;
}
Ok(out)
}
/// The `RGB9E5Float` word `word` normalized: its three 9-bit mantissas (red at bit 0, green at
/// 9, blue at 18) shifted up by `s` and its exponent (bits 27 to 31) lowered by `s`, `s` the
/// fewest shifts that bring the largest mantissa to 256 or more, at most the exponent (all of it
/// for three zero mantissas). A word whose largest mantissa is 256 or more, or whose exponent is
/// 0, stays.
fn shared_exponent(f: &mut FunctionBuilder<'_>, word: Value) -> BResult<Value> {
let c = |f: &mut FunctionBuilder<'_>, v: u32| u32_value(f, v);
let mantissa = c(f, 0x1ff)?;
let (k9, k18, k27) = (c(f, 9)?, c(f, 18)?, c(f, 27)?);
let r = f.binary(BinOp::BitwiseAnd, word, mantissa)?;
let g = f.binary(BinOp::ShiftRightLogical, word, k9)?;
let g = f.binary(BinOp::BitwiseAnd, g, mantissa)?;
let b = f.binary(BinOp::ShiftRightLogical, word, k18)?;
let b = f.binary(BinOp::BitwiseAnd, b, mantissa)?;
let e = f.binary(BinOp::ShiftRightLogical, word, k27)?;
let largest = f.glsl(GlslOp::UMax, &[g, b])?;
let largest = f.glsl(GlslOp::UMax, &[r, largest])?;
// The shifts that bring the largest to 256: `8 - msb` below it, none at or above it, and the
// whole exponent for a zero.
let msb = f.glsl(GlslOp::FindUMsb, &[largest])?;
let (zero, k8, k31, k256) = (c(f, 0)?, c(f, 8)?, c(f, 31)?, c(f, 256)?);
let need = f.binary(BinOp::ISub, k8, msb)?;
let full = f.binary(BinOp::UGreaterThanEqual, largest, k256)?;
let need = f.select(full, zero, need)?;
let none = f.binary(BinOp::IEqual, largest, zero)?;
let need = f.select(none, k31, need)?;
let shift = f.glsl(GlslOp::UMin, &[need, e])?;
let r = f.binary(BinOp::ShiftLeftLogical, r, shift)?;
let g = f.binary(BinOp::ShiftLeftLogical, g, shift)?;
let b = f.binary(BinOp::ShiftLeftLogical, b, shift)?;
let e = f.binary(BinOp::ISub, e, shift)?;
let g = f.binary(BinOp::ShiftLeftLogical, g, k9)?;
let b = f.binary(BinOp::ShiftLeftLogical, b, k18)?;
let e = f.binary(BinOp::ShiftLeftLogical, e, k27)?;
let out = f.binary(BinOp::BitwiseOr, r, g)?;
let out = f.binary(BinOp::BitwiseOr, out, b)?;
f.binary(BinOp::BitwiseOr, out, e)
}
/// `x >> k` rounded to nearest, ties to even (`k` at most 31, `x` below `2^30`).
fn shift_nearest_even(f: &mut FunctionBuilder<'_>, x: Value, k: Value) -> BResult<Value> {
let (zero, one) = (u32_value(f, 0)?, u32_value(f, 1)?);
@@ -4,16 +4,6 @@ use crate::metal::PixelFormat;
use crate::spirv::interp::{run, Buffer, Config, Order, Resources};
use crate::spirv::testing::{assert_valid, committed_profiles};
/// The signed normalized formats Metal's tile store rewrites.
const SNORM: [PixelFormat; 6] = [
PixelFormat::R8Snorm,
PixelFormat::RG8Snorm,
PixelFormat::RGBA8Snorm,
PixelFormat::R16Snorm,
PixelFormat::RG16Snorm,
PixelFormat::RGBA16Snorm,
];
/// Every format and the words it is held in.
fn formats() -> Vec<(PixelFormat, TexelWords)> {
let mut all = Vec::new();
@@ -36,11 +26,7 @@ fn formats() -> Vec<(PixelFormat, TexelWords)> {
PixelFormat::R16Bfloat,
PixelFormat::RG16Bfloat,
PixelFormat::RGBA16Bfloat,
PixelFormat::RGB9E5Float,
]
.into_iter()
.chain(SNORM)
{
] {
all.push((format, TexelWords::Raw));
}
all
@@ -79,49 +65,19 @@ fn only_a_two_plane_format_has_color_plane_words() {
PixelFormat::RGBA8Unorm,
PixelFormat::RGBA16Float,
PixelFormat::RG11B10Float,
PixelFormat::RGBA8Snorm,
PixelFormat::RGB9E5Float,
] {
assert!(rule(format, TexelWords::Raw).is_none(), "{format:?}");
assert!(UnusedBitsModule::texel_bytes(format, TexelWords::Raw).is_none());
}
}
/// Metal's store of an `RGB9E5Float` word (the module docs), computed here apart from the
/// kernel: its value's own encoding, the exponent the least that holds the largest mantissa
/// below 512, at least 0.
fn shared_exponent(word: u32) -> u32 {
let m = [word & 0x1ff, (word >> 9) & 0x1ff, (word >> 18) & 0x1ff];
let mut e = word >> 27;
let mut m = m;
while e > 0 && m.iter().all(|&x| x < 256) {
m = m.map(|x| x << 1);
e -= 1;
}
m[0] | m[1] << 9 | m[2] << 18 | e << 27
}
/// Metal's store of `word`, the `odd` word of its texel, of `format` held as `words` (the module
/// docs), computed here apart from the kernel.
fn stored(format: PixelFormat, words: TexelWords, word: u32, odd: bool) -> u32 {
let codes = 0x3fff_ffff;
let Some(form) = ExtendedRange::of(format) else {
if format == PixelFormat::RGB9E5Float {
return shared_exponent(word);
}
let lane = match format {
PixelFormat::R16Snorm | PixelFormat::RG16Snorm | PixelFormat::RGBA16Snorm => 16,
_ => 8,
};
let mask = (1u32 << lane) - 1;
return (0..32).step_by(lane).fold(0, |out, shift| {
let code = (word >> shift) & mask;
let code = if code == 1 << (lane - 1) {
code + 1
} else {
code
};
out | code << shift
});
};
let form = ExtendedRange::of(format).expect("an extended-range, padded or bfloat form");
match (form, words) {
(ExtendedRange::Bgr10 { .. }, _) => word | !codes,
(ExtendedRange::Planes { .. }, TexelWords::Raw) if odd => word,
@@ -218,16 +174,7 @@ fn each_word_of_a_masked_tile_takes_metals_store_and_no_other_changes() {
let row_words = (columns * texel).div_ceil(4);
let rows = layers * layer_rows - first_row;
let mut rng = Rng(u64::from(texel) << 32 | u64::from(row_words));
// Random words, a few holding a signed normalized minimum code in a lane, which random
// bits rarely give a 16-bit lane.
let before: Vec<u32> = (0..rows * row_words)
.map(|i| match (i % 7, rng.next()) {
(0, w) => w & 0xffff_0000 | 0x8000,
(1, w) => w & 0x0000_ffff | 0x8000_0000,
(2, w) => w & 0xffff_ff00 | 0x80,
(_, w) => w,
})
.collect();
let before: Vec<u32> = (0..rows * row_words).map(|_| rng.next()).collect();
let bytes: Vec<u8> = before.iter().flat_map(|w| w.to_le_bytes()).collect();
let groups = (before.len() as u32).div_ceil(UnusedBitsModule::LOCAL_SIZE) + 1;
let shape = UnusedBitsModule::shape(row_words, first_row, layer_rows, tiles_per_row);
@@ -352,97 +299,6 @@ fn every_bfloat_code_takes_its_load_code() {
}
}
/// Every 16-bit value of a signed normalized format's word takes Metal's store under a mask of
/// every tile: a lane at the minimum code (`0x80` of an 8-bit format's byte, `0x8000` of a 16-bit
/// one's half) becomes the code above it, every other lane stays (an 8-bit format's 256 minimum
/// pairs of bytes move, a 16-bit one's one value).
#[test]
fn every_signed_normalized_minimum_code_is_raised_to_the_code_above_it() {
let halves: Vec<u16> = (0..=u16::MAX).collect();
let bytes: Vec<u8> = halves.iter().flat_map(|h| h.to_le_bytes()).collect();
let words = (bytes.len() / 4) as u32;
let groups = words.div_ceil(UnusedBitsModule::LOCAL_SIZE) + 1;
for format in SNORM {
let wide = matches!(
format,
PixelFormat::R16Snorm | PixelFormat::RG16Snorm | PixelFormat::RGBA16Snorm
);
let want: Vec<u8> = halves
.iter()
.flat_map(|&h| {
let raised = match wide {
true if h == 0x8000 => 0x8001,
true => h,
false => u16::from_le_bytes(h.to_le_bytes().map(|b| match b {
0x80 => 0x81,
b => b,
})),
};
raised.to_le_bytes()
})
.collect();
let moved = halves
.iter()
.zip(want.chunks(2))
.filter(|(h, w)| h.to_le_bytes() != [w[0], w[1]])
.count();
assert_eq!(moved, if wide { 1 } else { 511 }, "{format:?}");
let texel = UnusedBitsModule::texel_bytes(format, TexelWords::Raw).unwrap();
let tiles_per_row = (4 * words / texel).div_ceil(32);
let mask = vec![u32::MAX; tiles_per_row.div_ceil(32) as usize];
let shape = UnusedBitsModule::shape(words, 0, 1, tiles_per_row);
assert_eq!(
rewritten((format, TexelWords::Raw), &bytes, &mask, shape, groups),
want,
"{format:?}"
);
}
}
/// Each `RGB9E5Float` word of every exponent and every largest mantissa (each mantissa's own
/// value, the others random below it) takes Metal's store under a mask of every tile: normalized
/// where its largest mantissa is below 256 under an exponent above 0, as the word Metal's pass left
/// for `1 | 2 << 9 | 3 << 18 | 20 << 27` (an Apple M3 Max under macOS 27.0.1), kept otherwise.
#[test]
fn every_unnormalized_shared_exponent_word_is_normalized() {
// The M3 Max's answer: the largest mantissa 3 shifted up seven times, the exponent 13.
let metal = 1 << 7 | 2 << 16 | 3 << 25 | 13 << 27;
assert_eq!(shared_exponent(1 | 2 << 9 | 3 << 18 | 20 << 27), metal);
let mut rng = Rng(0x9e5);
let mut words = Vec::new();
for e in 0..32u32 {
for largest in 0..512u32 {
let lane = rng.next() % 3;
let m: [u32; 3] = std::array::from_fn(|k| {
if k as u32 == lane {
largest
} else {
rng.next() % (largest + 1)
}
});
words.push(m[0] | m[1] << 9 | m[2] << 18 | e << 27);
}
}
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
let want: Vec<u8> = words
.iter()
.flat_map(|&w| shared_exponent(w).to_le_bytes())
.collect();
let moved = words.iter().filter(|&&w| shared_exponent(w) != w).count();
assert_eq!(
moved,
31 * 256,
"every word below 256 under an exponent above 0"
);
let n = words.len() as u32;
let groups = n.div_ceil(UnusedBitsModule::LOCAL_SIZE) + 1;
let tiles_per_row = n.div_ceil(32);
let mask = vec![u32::MAX; tiles_per_row.div_ceil(32) as usize];
let shape = UnusedBitsModule::shape(n, 0, 1, tiles_per_row);
let format = (PixelFormat::RGB9E5Float, TexelWords::Raw);
assert_eq!(rewritten(format, &bytes, &mask, shape, groups), want);
}
/// A mask of no word leaves every word, and a tile past the mask's words reads as unset.
#[test]
fn a_tile_past_the_mask_is_not_rewritten() {
+1 -1
View File
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 455;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 1653;
pub const RUNTIME_VERSION: u32 = 1656;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
+13 -21
View File
@@ -962,19 +962,16 @@ pub enum DriverFact {
/// A `D32_SFLOAT` image keeps each denormal value a copy writes into it, as Metal's
/// `Depth32Float` texel keeps any `float`. Vulkan states no such rule, and RADV's and ANV's
/// depth images answer a denormal as zero (RADV's of its sign), to a copy out of them and, on
/// RADV, to the shader's reads. On a driver without it `new_texture` holds a `Depth32Float`
/// texture the program only reads or samples in an `R32_SFLOAT` image with a `D32_SFLOAT` twin
/// for the comparisons the device makes (`image_plan::plan_depth_twin`). A clear to a denormal
/// and a copy from a buffer keep it too on such a driver; RADV and ANV store either as a zero,
/// and keep only a host copy's (`replace_region` on the host), so a write on the GPU that may
/// store a denormal there announces `depth-denormals`.
/// RADV, to the shader's reads. A clear to a denormal and a copy from a buffer keep it too on
/// such a driver; RADV and ANV store either as a zero, and keep only a host copy's
/// (`replace_region` on the host), so a write on the GPU that may store a denormal there
/// announces `depth-denormals`.
DepthImageKeepsDenormals,
/// Without `VK_EXT_depth_range_unrestricted` enabled, a `D32_SFLOAT` image keeps each value
/// outside `[0, 1]` a copy writes into it, where Vulkan leaves such a value undefined
/// (`VUID-vkCmdCopyBufferToImage-pRegions-07931`) and ANV stores it clamped. With the extension
/// Vulkan keeps it on every driver. On a driver without either, `new_texture` holds a
/// `Depth32Float` texture the program only reads or samples with a twin, as above, and an
/// upload into a depth image announces `restricted-depth-upload`.
/// Vulkan keeps it on every driver. On a driver without either, an upload into a depth image
/// announces `restricted-depth-upload`.
DepthImageKeepsValuesOutsideUnitRange,
/// A fragment shader's `FragDepth` is stored in a 32-bit float depth attachment unchanged:
/// each value in `[0, 1]` it is given, and, for the rest, the value it stored when given it
@@ -996,10 +993,8 @@ pub enum DriverFact {
/// ([`ColorResolveFormat`](crate::bind::ColorResolveFormat)): unorm's `(sum + n/2) / n`,
/// snorm's `floor((2·sum + n) / 2n)`, sRGB's mean of 12-bit linear values encoded by Metal's
/// thresholds, and `float`'s flushed sequential sum times `1/n`. Vulkan leaves the average's
/// rounding to the implementation. On a driver with it the runtime resolves such an attachment
/// in its pass under either [`ResolvePolicy`](crate::device::ResolvePolicy); elsewhere, and at
/// 8 samples or more, by that exact shader after the pass under `ResolvePolicy::Exact`, and in
/// its pass by the device's average, announced, under `ResolvePolicy::Device`
/// rounding to the implementation. The runtime resolves such an attachment in its pass by the
/// device's average on every driver; elsewhere, and at 8 samples or more, it announces it
/// (`color_resolve.rs`).
/// The fact holds for every colour format the driver resolves, those without a crate-owned
/// rule too (half floats, packed 16-bit, `RG11B10Float`, `RGB9E5Float`): MoltenVK 1.4.1
@@ -1186,12 +1181,10 @@ pub enum DriverFact {
/// own (MoltenVK) it holds by construction: the pass's depth test is Metal's test of a
/// `Depth32Float` texture on that GPU, which gives that GPU's Metal answer, and its pass
/// stores what Metal's stores (a pass with depth writes stores each texel it leaves without
/// its sign) wherever a draw hands it a state with depth writes. On a driver with it no render
/// target's depth renders over a magnitude stand-in, a single-sample `Depth32Float` one is
/// stripped of its signs after a pass that sets such a state but draws under none, and a write
/// that may store a negative value or a NaN announces nothing (`texture/signed_depth.rs`);
/// elsewhere a single-sample `Depth32Float` target renders over the stand-in, and a
/// multisampled or combined depth/stencil one announces `signed-depth-test`.
/// its sign) wherever a draw hands it a state with depth writes. On a driver with it a write
/// that may store a negative value or a NaN in a render target's depth announces nothing, and
/// a pass that sets such a state but draws under none, which keeps the signs, announces
/// `signed-depth-test`; elsewhere such a write announces it.
DepthTestComparesMagnitudes,
/// The device's first sparse resource's creation (`vkCreateImage` or `vkCreateBuffer` with
/// `SPARSE_BINDING`) waits for the work submitted before it on every queue: ANV through
@@ -1472,8 +1465,7 @@ pub enum DriverFact {
/// Metal's own load and store actions load and store
/// (`MVKAttachmentDescription::getMTLStoreAction` at 1.4.1), so the GPU's tile store is
/// Metal's by construction. On a driver with it the runtime announces no `snorm-minimum-kept`
/// or `shared-exponent-kept`, and its exact tile store (`TileStorePolicy::Exact`) adds no load
/// pass for such an attachment.
/// or `shared-exponent-kept`.
TileStoreIsMetals,
/// A buffer bound to memory the driver imported from a host pointer
/// (`VK_EXT_external_memory_host`) reads and writes, at each submission, the pages mapped at
+3 -4
View File
@@ -67,10 +67,9 @@ pub(crate) use mechanism::mechanism;
pub use metal::{MetalDeviceProperties, SimdSupport, StageSimd};
pub use policy::{
BatchOrderPolicy, CompletionPolicy, ContainmentPolicy, DecodedTexelsPolicy, DevicePolicy,
FloatMathsPolicy, HeapCompressionPolicy, HostPageTexturePolicy, MultisampleDepthTwinPolicy,
NanMinMaxPolicy, RenderLoweringPolicy, ResolvePolicy, RoundingOrderPolicy, SamplingPolicy,
TexelConversionPolicy, TileStorePolicy, Unorm8LinearFilterPolicy, VertexNormalizedPolicy,
YCbCrFilterPolicy,
FloatMathsPolicy, HeapCompressionPolicy, HostPageTexturePolicy, NanMinMaxPolicy,
RenderLoweringPolicy, RoundingOrderPolicy, SamplingPolicy, TexelConversionPolicy,
Unorm8LinearFilterPolicy, VertexNormalizedPolicy, YCbCrFilterPolicy,
};
pub(crate) use profile::whole_point_size;
pub use profile::{DeviceProfile, SpirvValidation};
+12 -130
View File
@@ -4,14 +4,12 @@
use crate::device::profile::{GuestIsolation, HandleDomain, PointerDomain};
/// Policy inputs of `Device::new`. Every field but `decoded_texels`, `heap_compression`,
/// `completion`, `tile_store`, `resolve`, `batch_order`, `render_lowering` and
/// `host_page_textures` can change emitted code, so the profile carries it (containment as the
/// encoding it selects) and its fingerprint covers it; those eight are the runtime's alone (the
/// texels of a carried texture's decoded twin, a heap's compressed texture's image, when the host
/// sees a command buffer complete, what a render pass's load leaves in the texels its draws do not
/// write, how a multisampled color attachment resolves, how a batch begins after the earlier ones
/// of its queue, where a render encoder's calls are lowered, and what holds a sampled texture over
/// host pages), and no profile carries them.
/// `completion`, `batch_order`, `render_lowering` and `host_page_textures` can change emitted
/// code, so the profile carries it (containment as the encoding it selects) and its fingerprint
/// covers it; those six are the runtime's alone (the texels of a carried texture's decoded twin, a
/// heap's compressed texture's image, when the host sees a command buffer complete, how a batch
/// begins after the earlier ones of its queue, where a render encoder's calls are lowered, and
/// what holds a sampled texture over host pages), and no profile carries them.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@@ -56,11 +54,6 @@ pub struct DevicePolicy {
/// instructions (the default).
pub rounding_order: RoundingOrderPolicy,
/// Whether a multisampled `Depth32Float` texture the program only reads is held in a depth
/// image (the default) or, where the device's depth images may not keep its texels, in a
/// colour image, as a single-sampled one of it already is. The runtime's choice alone: no
/// emitted code changes.
pub multisample_depth_twin: MultisampleDepthTwinPolicy,
/// Whether a texture whose format the device lacks, held in a carrier (an ASTC LDR texture,
/// or an EAC 11-bit one), samples a decoded twin of compact codes (the default) or of Metal's
/// values exactly. The runtime's choice alone: no emitted code changes.
@@ -76,16 +69,6 @@ pub struct DevicePolicy {
/// submission of its own, seen complete at its own end. The runtime's choice alone: no
/// emitted code changes.
pub completion: CompletionPolicy,
/// Whether a render pass that loads a signed normalized or `RGB9E5Float` color attachment and
/// draws keeps the texels its draws do not write as the device's load and store leave them
/// (the default), or as Metal's tile store writes them back in the tiles a draw reaches. The
/// runtime's choice alone: no emitted code changes.
pub tile_store: TileStorePolicy,
/// Whether a multisampled color attachment whose format has Metal's resolve rule resolves by
/// the device's own `AVERAGE` in the pass (the default), or by Metal's rule in one more render
/// pass instance after it, on a device whose average is not measured to be Metal's. The
/// runtime's choice alone: no emitted code changes.
pub resolve: ResolvePolicy,
/// Whether a batch of command buffers on one `VkQueue` begins after the batches before it
/// there by their ends (the default, on a driver measured to run no two kernel submissions of
/// one queue side by side), or by a barrier for each access that depends on theirs. The
@@ -107,14 +90,10 @@ impl DevicePolicy {
/// The untrusted-guest production policy: containment and isolation on, Metal's 8-bit linear
/// filter emulated exactly where the emulation runs, native device sampling (a two-plane YCbCr texture's samples among them),
/// native device maths, the device's own texel
/// conversions, the device's NaN and minimum and maximum, the device's
/// rounding order, a
/// multisampled `Depth32Float` texture's texels in a
/// depth image, compact codes in a carried texture's decoded twin, the driver's compressed image of a
/// heap's texture Metal keeps compressed, command buffers ready together in one kernel
/// submission, the device's load and store of a signed normalized or `RGB9E5Float` color
/// attachment, the device's resolve of a multisampled color attachment, batches of one
/// queue ordered by their ends where the driver runs them one after another, and a sampled
/// conversions, the device's NaN and minimum and maximum, the device's rounding order, compact
/// codes in a carried texture's decoded twin, the driver's compressed image of a heap's texture
/// Metal keeps compressed, command buffers ready together in one kernel submission, batches of
/// one queue ordered by their ends where the driver runs them one after another, and a sampled
/// texture over host pages in place where the device's check passed.
pub const UNTRUSTED: DevicePolicy = DevicePolicy {
pointer_domain: PointerDomain::ResidentTable,
@@ -129,12 +108,9 @@ impl DevicePolicy {
vertex_normalized: VertexNormalizedPolicy::Device,
nan_and_min_max: NanMinMaxPolicy::Native,
rounding_order: RoundingOrderPolicy::Native,
multisample_depth_twin: MultisampleDepthTwinPolicy::Device,
decoded_texels: DecodedTexelsPolicy::Compact,
heap_compression: HeapCompressionPolicy::Compressed,
completion: CompletionPolicy::Grouped,
tile_store: TileStorePolicy::Device,
resolve: ResolvePolicy::Device,
batch_order: BatchOrderPolicy::Ends,
render_lowering: RenderLoweringPolicy::AtCall,
host_page_textures: HostPageTexturePolicy::InPlace,
@@ -150,9 +126,8 @@ impl DevicePolicy {
/// ([`YCbCrFilterPolicy::Exact`]), its decode of a carried texture's texels
/// ([`DecodedTexelsPolicy::Exact`]), a heap's texture whose bytes alias the heap's
/// as written ([`HeapCompressionPolicy::Uncompressed`]), each command buffer seen complete
/// at its own end ([`CompletionPolicy::Exact`]), a loaded attachment's texels as its tile
/// store leaves them ([`TileStorePolicy::Exact`]), its multisample color resolve
/// ([`ResolvePolicy::Exact`]), each batch ordered after the earlier ones of its queue by
/// at its own end ([`CompletionPolicy::Exact`]), each batch ordered after the earlier ones of
/// its queue by
/// the accesses it depends on alone ([`BatchOrderPolicy::Exact`]), each render encoder
/// call lowered inside the call, which returns every refusal
/// ([`RenderLoweringPolicy::AtCall`]), and every texture over host pages a shadow, whose
@@ -166,12 +141,9 @@ impl DevicePolicy {
vertex_normalized: VertexNormalizedPolicy::Exact,
nan_and_min_max: NanMinMaxPolicy::Exact,
rounding_order: RoundingOrderPolicy::Exact,
multisample_depth_twin: MultisampleDepthTwinPolicy::Exact,
decoded_texels: DecodedTexelsPolicy::Exact,
heap_compression: HeapCompressionPolicy::Uncompressed,
completion: CompletionPolicy::Exact,
tile_store: TileStorePolicy::Exact,
resolve: ResolvePolicy::Exact,
batch_order: BatchOrderPolicy::Exact,
render_lowering: RenderLoweringPolicy::AtCall,
host_page_textures: HostPageTexturePolicy::Shadow,
@@ -423,38 +395,6 @@ pub enum RoundingOrderPolicy {
Exact,
}
/// Where the runtime holds the texels of a multisampled `Depth32Float` texture the program only
/// reads (shader-read usage, no render target, not memoryless) on a device whose depth images may
/// not keep them (`image_plan::ImageFacts::depth_loss`: without `VK_EXT_depth_range_unrestricted`
/// enabled or a driver measured to keep a value outside `[0, 1]` there, or without a driver
/// measured to keep a denormal). A single-sampled such texture is already held in an
/// `R32_SFLOAT` image, which keeps every `float` a copy writes
/// (`image_plan::plan_depth_twin`); a multisampled one was left out of that on the reading that
/// it has no writer, and `BlitCommandEncoder::fill_texture` is one. Metal's fill stores the
/// pattern's bytes as given, a denormal included, where RADV gives a denormal a GPU write puts
/// into a `D32_SFLOAT` image back as a zero and keeps only a CPU store's, which a multisampled
/// image takes none of (`sample-fills-d32-2`, `-d32-4`, `-d32s8-4` and
/// `runtime_lane::sample_fills::multisample_fills_write_metal_s_samples`, both RADV chips, exact
/// on MoltenVK, whose depth images keep denormals). Metal has no multisampled depth comparison
/// (`depth2d_ms` reads alone), so such a texture needs no depth twin beside the colour image.
/// The runtime's choice alone: no emitted code changes.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum MultisampleDepthTwinPolicy {
/// A depth image (the default): a write that may store a value the device's depth images do
/// not keep stores what they keep, announced `depth-denormals` or `restricted-depth-upload`
/// at the write.
#[default]
Device,
/// A colour image (`R32_SFLOAT`), which keeps every `float` the fills and the sample copies
/// write, where the device holds a multisampled image of it for the texture's uses; elsewhere
/// the depth image, announced as under [`MultisampleDepthTwinPolicy::Device`]. Costs the
/// texture its depth attachment usage, which such a texture does not ask for, and nothing
/// else: the image is of the same extent, samples and layers.
Exact,
}
/// What texels the runtime holds in the decoded twin of a texture whose blocks it holds in a
/// carrier on a device without the format (the runtime's `texture/decoded_twin.rs`), which the
/// texture's samples, reads and gathers read: an ASTC LDR texture's (`bind::AstcDecode`), and an
@@ -537,64 +477,6 @@ pub enum CompletionPolicy {
Exact,
}
/// What a render pass that loads a single-sampled color attachment of a signed normalized format
/// (`R8Snorm`, `RG8Snorm`, `RGBA8Snorm`, `R16Snorm`, `RG16Snorm`, `RGBA16Snorm`) or of
/// `RGB9E5Float`, stores it and draws leaves in the texels its draws do not write. An Apple GPU
/// writes each 32 x 32 tile a draw reaches back through its texels' values (an Apple M3 Max under
/// macOS 27.0.1): a channel's minimum code (-128, or -32768), which reads as -1.0 as the code above
/// it does, is stored as that code (-127, -32767), and an `RGB9E5Float` word whose largest
/// mantissa is below 256 under an exponent above 0 is stored normalized (its mantissas shifted up
/// as its exponent steps down, to 0 at most). No Metal write leaves such a code or word: only
/// uploaded or copied bytes hold one. The extended-range, padded 10-bit and bfloat attachments'
/// tile store, the runtime's load pass, runs under either value. The runtime's choice alone: no
/// emitted code changes.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TileStorePolicy {
/// The device's load and store (the default): such a texel keeps its code or word, announced
/// `snorm-minimum-kept` or `shared-exponent-kept` at each draw in such a pass.
#[default]
Device,
/// The runtime's load pass rewrites such an attachment's texels in the tiles the pass's draws
/// reach, as Metal's tile store leaves them, before the pass (as it does an extended-range
/// attachment's): a copy of the render area into a scratch buffer and back, with a dispatch.
/// An attachment the load pass cannot take (a texture held as a shadow, a sparse one, or one
/// whose image the device does not copy both ways) keeps the device's, announced as under
/// [`Device`](Self::Device).
Exact,
}
/// How a multisampled color attachment resolves into its resolve texture where its format has
/// Metal's resolve rule at its sample count (`bind::ColorResolveFormat`: unorm, snorm, sRGB,
/// 32-bit float and packed 16-bit unorm formats at every count, 16-bit float, `RG11B10Float` and
/// `RGB9E5Float` ones at 2 and 4 samples), on a device whose own `AVERAGE` resolve is not measured
/// to write Metal's (`DriverFact::ColorResolveAverageIsMetals`, which only MoltenVK on Apple's GPUs
/// holds: there the device's resolve is Metal's under either value, and nothing is announced).
/// Metal's resolve rounds each average by its format's rule; Vulkan's `AVERAGE` leaves the
/// rounding, an sRGB average's space and what a NaN or infinite sample makes of it to the device.
/// An attachment whose samples a fetching pass holds in its sample planes as it ends resolves from
/// them by Metal's rule under either value, which costs less than merging them back for the
/// device's resolve. The runtime's choice alone: no emitted code changes.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ResolvePolicy {
/// The device's `AVERAGE` resolve in the pass (the default), announced
/// `device-rounded-resolve`: a resolved channel can differ from Metal's by one code (an sRGB
/// channel by two) where the average lies near a rounding boundary, a float channel in its
/// last bits, and wholly where a sample is a NaN or an infinity. Measured at 2 and 4 samples
/// on RADV, ANV, NVIDIA and lavapipe; each rounds an 8-bit unorm tie down (RADV: 32512 of
/// `R8Unorm`'s 65536 pairs of samples one code below Metal's at 2 samples).
#[default]
Device,
/// Metal's rule, drawn after the pass: one more render pass instance per resolved attachment,
/// between barriers, reads its samples (as an input attachment, or from a copy of them where
/// its image takes no input attachment usage) and writes the resolve texture, announced
/// `shader-resolve` (a performance note).
Exact,
}
/// How a batch of command buffers on one `VkQueue` (the work the runtime submits for a command
/// buffer between its event waits and signals) begins after the earlier batches there. Metal
/// orders a command buffer after the earlier ones of its queue only where its work depends on
@@ -680,29 +680,6 @@ fn a_gpu_under_another_of_its_device_ids_takes_its_measured_rows() {
);
}
/// A driver measured to lay depth and stencil images apart from their memory is measured to keep
/// every `float` in a depth image too, so it holds no `Depth32Float`
/// texture with a depth twin and no heap texture's twin is kept apart on it. A driver measured
/// otherwise would reach the twin's `heap-depth-stencil-apart` route, which then needs a shadow of
/// its own.
#[test]
fn a_driver_that_lays_depth_images_apart_holds_no_depth_twin() {
let apart: Vec<_> = MEASURED.iter().filter(|row| row.fact == APART).collect();
assert!(
!apart.is_empty(),
"no driver is measured to lay depth images apart"
);
for row in apart {
let gpu = (row.vendor.unwrap_or(APPLE), row.device.unwrap_or(0));
let facts = among(MEASURED, Some(row.driver), gpu);
assert!(
facts.contains(&DENORMALS) && facts.contains(&OUTSIDE),
"{:?} lays depth images apart but may lose a depth texel: {facts:?}",
row.driver,
);
}
}
/// NVIDIA's driver stalls a submission about once in every thousand semaphore operations on the
/// two GPUs measured, the RTX 5080 Laptop GPU and the RTX 3090, which take the fact at every
/// release; another GPU of the driver (an RTX 5080 desktop GPU) does not, so it waits for
+9 -11
View File
@@ -372,10 +372,9 @@ pub struct HeapPlan {
pub compares_plain: bool,
/// The float class of its shape and its declaration, for a compared group whose comparisons
/// the shader makes ([`HeapPlan::compares_plain`]); set by [`finish`]. Its samples without
/// comparison read the members there: the binder holds a `Depth32Float` member with a depth
/// twin through its colour image in that class, and through the twin in the depth-comparison
/// class, whose depth view ANV clamps into `[0, 1]` and RADV holds a denormal in as zero
/// (runtime lane `depth_compares` through argument buffers).
/// comparison read the members there, and its comparisons the depth-comparison class, whose
/// depth view ANV clamps into `[0, 1]` and RADV holds a denormal in as zero (runtime lane
/// `depth_compares` through argument buffers).
pub plain: Option<(ImageHandleClass, ImageDecl)>,
/// Its float reads decode a member of a form a heap reads (`ExtendedRange::HEAP_READ`) where
/// the handle's class index names one; set by `select_read`.
@@ -1228,13 +1227,12 @@ fn tiled_shape(shape: ImageShape) -> bool {
/// outside `[0, 1]` where the consumer enabled `VK_EXT_depth_range_unrestricted`, or where its
/// driver is measured to keep them without it
/// (`VkProperty::DepthImageKeepsValuesOutsideUnitRange`, MoltenVK's), which the module then
/// requires; the device's comparison reads a depth image (the texture's own, or its depth twin):
/// on a device with neither the function records `PrecisionNote::RestrictedDepthRange`. Its reads,
/// samples and gathers, and the comparisons the shader makes of them, read the texels the consumer
/// holds them in, which a colour image keeps, so they record nothing: the interface's
/// `TextureSlot::access` states them, and the consumer announces an upload its own depth image may
/// clamp (`restricted-depth-upload`). No module requires the extension, since every value within
/// `[0, 1]` is exact without it.
/// requires; the device's comparison reads the texture's depth image: on a device with neither the
/// function records `PrecisionNote::RestrictedDepthRange`. Its reads, samples and gathers, and the
/// comparisons the shader makes of them, record nothing: the interface's `TextureSlot::access`
/// states them, and the consumer announces an upload its depth image may clamp
/// (`restricted-depth-upload`), which every read of it then reads. No module requires the
/// extension, since every value within `[0, 1]` is exact without it.
pub(crate) fn depth_comparison(cx: &mut SelectCx<'_>) {
let enabled = &cx.profile.fields().enabled;
if enabled
@@ -1156,7 +1156,6 @@ mod bind_serde_round_trips {
layout: vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
components: vk::ComponentMapping::IDENTITY,
level: None,
twin: false,
shader_swizzle: false,
},
},
+4 -5
View File
@@ -844,8 +844,8 @@ pub enum PrecisionNote {
/// shader does not make itself) on a device without `VK_EXT_depth_range_unrestricted` enabled
/// whose driver is not measured to keep depth values outside `[0, 1]` without it (narrowed to
/// comparisons, and to the device's). Metal's `Depth32Float` texels hold any
/// `float`, and the device's comparison reads them from a depth image: the texture's own, or
/// the depth twin of a texture the consumer holds in an `R32_SFLOAT` image. Vulkan leaves a
/// `float`, and the device's comparison reads them from the texture's depth image. Vulkan
/// leaves a
/// value outside `[0, 1]` uploaded there undefined without the extension
/// (`VUID-vkCmdCopyBufferToImage-pRegions-07931`), and a device may store it clamped (RADV on a
/// Radeon 780M and ANV read 1000.0 back as 1.0, measured) or keep it (MoltenVK and lavapipe
@@ -1159,9 +1159,8 @@ pub enum PrecisionNote {
/// - a heap texture;
/// - a runtime or argument buffer's sampler.
///
/// Not this note's: a depth image (a `Depth32Float` texture's own, or its twin) that a device's
/// comparison reads, which RADV holds a denormal in as zero
/// ([`PrecisionNote::DeviceDepthComparison`]).
/// Not this note's: a `Depth32Float` texture's depth image that a device's comparison reads,
/// which RADV holds a denormal in as zero ([`PrecisionNote::DeviceDepthComparison`]).
///
/// Validation derives no tolerance and no explanation from it, as for `DeviceDenormals`.
DeviceTexelDenormals,
+7 -71
View File
@@ -8,10 +8,9 @@
use crate::device::{
BatchOrderPolicy, CompletionPolicy, DecodedTexelsPolicy, DevicePolicy, FloatMathsPolicy,
HeapCompressionPolicy, HostPageTexturePolicy, MultisampleDepthTwinPolicy, NanMinMaxPolicy,
RenderLoweringPolicy, ResolvePolicy, RoundingOrderPolicy, SamplingPolicy,
TexelConversionPolicy, TileStorePolicy, Unorm8LinearFilterPolicy, VertexNormalizedPolicy,
YCbCrFilterPolicy,
HeapCompressionPolicy, HostPageTexturePolicy, NanMinMaxPolicy, RenderLoweringPolicy,
RoundingOrderPolicy, SamplingPolicy, TexelConversionPolicy, Unorm8LinearFilterPolicy,
VertexNormalizedPolicy, YCbCrFilterPolicy,
};
use crate::pipeline::PrecisionNote;
use std::collections::BTreeSet;
@@ -69,18 +68,13 @@ fn choices() -> Vec<Choice> {
vertex_normalized: _,
nan_and_min_max: _,
rounding_order: _,
// The runtime's: where a multisampled `Depth32Float` texture's texels are held, the
// texels of a carried texture's decoded twin, a heap's compressed
// texture's image, when the host sees a command buffer complete, a loaded attachment's
// tile store, a multisampled color attachment's resolve, how a batch begins after the
// earlier ones of its queue, where a render encoder's calls are lowered, and what holds a
// sampled texture over host pages.
multisample_depth_twin: _,
// The runtime's: the texels of a carried texture's decoded twin, a heap's compressed
// texture's image, when the host sees a command buffer complete, how a batch begins after
// the earlier ones of its queue, where a render encoder's calls are lowered, and what holds
// a sampled texture over host pages.
decoded_texels: _,
heap_compression: _,
completion: _,
tile_store: _,
resolve: _,
batch_order: _,
render_lowering: _,
host_page_textures: _,
@@ -94,12 +88,9 @@ fn choices() -> Vec<Choice> {
choice!(p.vertex_normalized: VertexNormalizedPolicy { Device, Exact }),
choice!(p.nan_and_min_max: NanMinMaxPolicy { Native, Exact }),
choice!(p.rounding_order: RoundingOrderPolicy { Native, Exact }),
choice!(p.multisample_depth_twin: MultisampleDepthTwinPolicy { Device, Exact }),
choice!(p.decoded_texels: DecodedTexelsPolicy { Compact, Exact }),
choice!(p.heap_compression: HeapCompressionPolicy { Compressed, Uncompressed }),
choice!(p.completion: CompletionPolicy { Grouped, Exact }),
choice!(p.tile_store: TileStorePolicy { Device, Exact }),
choice!(p.resolve: ResolvePolicy { Device, Exact }),
choice!(p.batch_order: BatchOrderPolicy { Ends, Exact }),
choice!(p.render_lowering: RenderLoweringPolicy { AtCall, Worker }),
choice!(p.host_page_textures: HostPageTexturePolicy { InPlace, Shadow }),
@@ -436,42 +427,6 @@ fn the_runtime_s_completion_choice_keys_no_profile() {
}
}
/// The runtime's choice of a loaded attachment's tile store (`tile_store`) moves no committed
/// profile's fingerprint: no profile carries it, so no translation follows it.
#[test]
fn the_runtime_s_tile_store_choice_keys_no_profile() {
use crate::spirv::testing::committed_profiles_with;
let device = committed_profiles_with(DevicePolicy::UNTRUSTED).expect("profiles");
let exact = committed_profiles_with(DevicePolicy {
tile_store: TileStorePolicy::Exact,
..DevicePolicy::UNTRUSTED
})
.expect("profiles");
assert_eq!(device.len(), exact.len());
for ((stem, d), (other, e)) in device.iter().zip(&exact) {
assert_eq!(stem, other);
assert_eq!(d.fingerprint(), e.fingerprint(), "{stem}");
}
}
/// The runtime's choice of a multisampled color attachment's resolve (`resolve`) moves no
/// committed profile's fingerprint: no profile carries it, so no translation follows it.
#[test]
fn the_runtime_s_resolve_choice_keys_no_profile() {
use crate::spirv::testing::committed_profiles_with;
let device = committed_profiles_with(DevicePolicy::UNTRUSTED).expect("profiles");
let exact = committed_profiles_with(DevicePolicy {
resolve: ResolvePolicy::Exact,
..DevicePolicy::UNTRUSTED
})
.expect("profiles");
assert_eq!(device.len(), exact.len());
for ((stem, d), (other, e)) in device.iter().zip(&exact) {
assert_eq!(stem, other);
assert_eq!(d.fingerprint(), e.fingerprint(), "{stem}");
}
}
/// The runtime's choice of how a batch begins after the earlier ones of its queue
/// (`batch_order`) moves no committed profile's fingerprint: no profile carries it, so no
/// translation follows it.
@@ -509,25 +464,6 @@ fn the_runtime_s_render_lowering_choice_keys_no_profile() {
}
}
/// The runtime's choice of where a multisampled `Depth32Float` texture's texels are held
/// (`multisample_depth_twin`) moves no committed profile's fingerprint: no profile carries it, so
/// no translation follows it.
#[test]
fn the_runtime_s_multisample_depth_twin_choice_keys_no_profile() {
use crate::spirv::testing::committed_profiles_with;
let device = committed_profiles_with(DevicePolicy::UNTRUSTED).expect("profiles");
let exact = committed_profiles_with(DevicePolicy {
multisample_depth_twin: MultisampleDepthTwinPolicy::Exact,
..DevicePolicy::UNTRUSTED
})
.expect("profiles");
assert_eq!(device.len(), exact.len());
for ((stem, d), (other, e)) in device.iter().zip(&exact) {
assert_eq!(stem, other);
assert_eq!(d.fingerprint(), e.fingerprint(), "{stem}");
}
}
/// The runtime's choice of a carried texture's decoded twin (`decoded_texels`) moves no committed
/// profile's fingerprint: no profile carries it, so no translation follows it.
#[test]
@@ -48,8 +48,8 @@ const EXTENDED: [ExtendedRange; 13] = [
];
/// Every format a render pass's load pass rewrites (`bind::unused_bits_module`): the
/// extended-range, padded and bfloat formats, the signed normalized formats and `RGB9E5Float`.
const UNUSED_BITS: [PixelFormat; 20] = [
/// extended-range, padded and bfloat formats.
const UNUSED_BITS: [PixelFormat; 13] = [
PixelFormat::BGR10XR,
PixelFormat::BGR10XRSRGB,
PixelFormat::BGRA10XR,
@@ -63,13 +63,6 @@ const UNUSED_BITS: [PixelFormat; 20] = [
PixelFormat::R16Bfloat,
PixelFormat::RG16Bfloat,
PixelFormat::RGBA16Bfloat,
PixelFormat::R8Snorm,
PixelFormat::RG8Snorm,
PixelFormat::RGBA8Snorm,
PixelFormat::R16Snorm,
PixelFormat::RG16Snorm,
PixelFormat::RGBA16Snorm,
PixelFormat::RGB9E5Float,
];
fn modules() -> Vec<Build> {
@@ -82,7 +75,6 @@ fn modules() -> Vec<Build> {
plain!(
capture_assembly_module,
capture_settle_module,
depth_magnitude_module,
flat_dispatch_module,
index_bounds_fill_module,
index_bounds_plan_module,
+1 -39
View File
@@ -90,11 +90,6 @@ assoc-const metal2vulkan::bind::ColorResolveModules::SOURCE_BINDING pub const SO
assoc-const metal2vulkan::bind::CompressedBlitModule::LOCAL_SIZE pub const LOCAL_SIZE: u32
assoc-const metal2vulkan::bind::CompressedBlitModule::SET pub const SET: u32
assoc-const metal2vulkan::bind::CompressedBlitModule::WORDS_BINDING pub const WORDS_BINDING: u32
assoc-const metal2vulkan::bind::DepthMagnitudeModule::EXACT_BINDING pub const EXACT_BINDING: u32
assoc-const metal2vulkan::bind::DepthMagnitudeModule::LOCAL_SIZE pub const LOCAL_SIZE: u32
assoc-const metal2vulkan::bind::DepthMagnitudeModule::PUSH_BYTES pub const PUSH_BYTES: u32
assoc-const metal2vulkan::bind::DepthMagnitudeModule::SET pub const SET: u32
assoc-const metal2vulkan::bind::DepthMagnitudeModule::STAND_IN_BINDING pub const STAND_IN_BINDING: u32
assoc-const metal2vulkan::bind::DepthSplitModule::DESTINATION_BINDING pub const DESTINATION_BINDING: u32
assoc-const metal2vulkan::bind::DepthSplitModule::LOCAL_SIZE pub const LOCAL_SIZE: u32
assoc-const metal2vulkan::bind::DepthSplitModule::SET pub const SET: u32
@@ -597,11 +592,6 @@ assoc-const-value metal2vulkan::bind::ColorResolveModules::SOURCE_BINDING 0
assoc-const-value metal2vulkan::bind::CompressedBlitModule::LOCAL_SIZE 64
assoc-const-value metal2vulkan::bind::CompressedBlitModule::SET 0
assoc-const-value metal2vulkan::bind::CompressedBlitModule::WORDS_BINDING 0
assoc-const-value metal2vulkan::bind::DepthMagnitudeModule::EXACT_BINDING 0
assoc-const-value metal2vulkan::bind::DepthMagnitudeModule::LOCAL_SIZE 64
assoc-const-value metal2vulkan::bind::DepthMagnitudeModule::PUSH_BYTES 16
assoc-const-value metal2vulkan::bind::DepthMagnitudeModule::SET 0
assoc-const-value metal2vulkan::bind::DepthMagnitudeModule::STAND_IN_BINDING 1
assoc-const-value metal2vulkan::bind::DepthSplitModule::DESTINATION_BINDING 1
assoc-const-value metal2vulkan::bind::DepthSplitModule::LOCAL_SIZE 8
assoc-const-value metal2vulkan::bind::DepthSplitModule::SET 0
@@ -1474,12 +1464,10 @@ enum metal2vulkan::device::HandleDomain #[cfg_attr(feature = "serde", derive(ser
enum metal2vulkan::device::HeapCompressionPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum HeapCompressionPolicy
enum metal2vulkan::device::HostPageTexturePolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum HostPageTexturePolicy
enum metal2vulkan::device::Independence #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Independence
enum metal2vulkan::device::MultisampleDepthTwinPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum MultisampleDepthTwinPolicy
enum metal2vulkan::device::NanMinMaxPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum NanMinMaxPolicy
enum metal2vulkan::device::PointerDomain #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum PointerDomain
enum metal2vulkan::device::RenderLoweringPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum RenderLoweringPolicy
enum metal2vulkan::device::ResolveMode #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ResolveMode
enum metal2vulkan::device::ResolvePolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ResolvePolicy
enum metal2vulkan::device::Robustness #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Robustness
enum metal2vulkan::device::RoundingOrderPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum RoundingOrderPolicy
enum metal2vulkan::device::SamplingPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum SamplingPolicy
@@ -1489,7 +1477,6 @@ enum metal2vulkan::device::StageCreateFlag #[derive(Clone, Copy, Debug, PartialE
enum metal2vulkan::device::SubgroupOp #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum SubgroupOp
enum metal2vulkan::device::TexelConversionPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum TexelConversionPolicy
enum metal2vulkan::device::Tier #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Tier
enum metal2vulkan::device::TileStorePolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum TileStorePolicy
enum metal2vulkan::device::Unorm8LinearFilterPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Unorm8LinearFilterPolicy
enum metal2vulkan::device::VertexNormalizedPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum VertexNormalizedPolicy
enum metal2vulkan::device::VkExtension #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum VkExtension
@@ -2748,8 +2735,6 @@ field metal2vulkan-runtime::WorkCounts.linear_passes_in_place pub linear_passes_
field metal2vulkan-runtime::WorkCounts.linear_passes_through_copies pub linear_passes_through_copies: u64
field metal2vulkan-runtime::WorkCounts.linked_use_questions_asked pub linked_use_questions_asked: u64
field metal2vulkan-runtime::WorkCounts.live_tables_uploaded pub live_tables_uploaded: u64
field metal2vulkan-runtime::WorkCounts.magnitude_stand_in_passes pub magnitude_stand_in_passes: u64
field metal2vulkan-runtime::WorkCounts.magnitude_write_backs pub magnitude_write_backs: u64
field metal2vulkan-runtime::WorkCounts.memory_blocks_live pub memory_blocks_live: u64
field metal2vulkan-runtime::WorkCounts.memory_frees pub memory_frees: MemoryFrees
field metal2vulkan-runtime::WorkCounts.merged_draw_commands pub merged_draw_commands: u64
@@ -2913,8 +2898,6 @@ field metal2vulkan-runtime::WorkCounts.shadows_over_fresh_pages pub shadows_over
field metal2vulkan-runtime::WorkCounts.shadows_sharing_truth pub shadows_sharing_truth: u64
field metal2vulkan-runtime::WorkCounts.shadows_zeroed pub shadows_zeroed: u64
field metal2vulkan-runtime::WorkCounts.shared_event_waits_held pub shared_event_waits_held: u64
field metal2vulkan-runtime::WorkCounts.sign_strips pub sign_strips: u64
field metal2vulkan-runtime::WorkCounts.signed_depth_switch_ons pub signed_depth_switch_ons: u64
field metal2vulkan-runtime::WorkCounts.slot_return_nanos pub slot_return_nanos: u64
field metal2vulkan-runtime::WorkCounts.slot_returns pub slot_returns: u64
field metal2vulkan-runtime::WorkCounts.slot_wait_nanos pub slot_wait_nanos: u64
@@ -3128,8 +3111,6 @@ field metal2vulkan::bind::ContinuedResult.count pub count: u32
field metal2vulkan::bind::ContinuedResult.first pub first: u32
field metal2vulkan::bind::ContinuedResult.offset pub offset: u64
field metal2vulkan::bind::ContinuedResult.sum pub sum: bool
field metal2vulkan::bind::DepthMagnitudeModule.requirements pub requirements: Requirements
field metal2vulkan::bind::DepthMagnitudeModule.spirv pub spirv: Arc<[u32]>
field metal2vulkan::bind::DepthSplitModule.requirements pub requirements: Requirements
field metal2vulkan::bind::DepthSplitModule.spirv pub spirv: Arc<[u32]>
field metal2vulkan::bind::DepthStencilCopyModules.fragment pub fragment: Arc<[u32]>
@@ -3260,7 +3241,6 @@ field metal2vulkan::bind::ImageViewDesc.format pub format: vk::Format
field metal2vulkan::bind::ImageViewDesc.layout pub layout: vk::ImageLayout
field metal2vulkan::bind::ImageViewDesc.level pub level: Option<u32>
field metal2vulkan::bind::ImageViewDesc.shader_swizzle pub shader_swizzle: bool
field metal2vulkan::bind::ImageViewDesc.twin pub twin: bool
field metal2vulkan::bind::ImageViewDesc.view_type pub view_type: vk::ImageViewType
field metal2vulkan::bind::ImageblockSize.height pub height: u32
field metal2vulkan::bind::ImageblockSize.width pub width: u32
@@ -3547,7 +3527,6 @@ field metal2vulkan::bind::TessellationScanModule.requirements pub requirements:
field metal2vulkan::bind::TessellationScanModule.spirv pub spirv: Arc<[u32]>
field metal2vulkan::bind::TextureFacts.address_modes pub address_modes: metal::sampler::AddressModeMap
field metal2vulkan::bind::TextureFacts.array_length pub array_length: u32
field metal2vulkan::bind::TextureFacts.depth_twin pub depth_twin: bool
field metal2vulkan::bind::TextureFacts.mipmap_level_count pub mipmap_level_count: u32
field metal2vulkan::bind::TextureFacts.own_format_views pub own_format_views: bool
field metal2vulkan::bind::TextureFacts.parent_base_size pub parent_base_size: [u32; 3]
@@ -3749,15 +3728,12 @@ field metal2vulkan::device::DevicePolicy.handle_domain pub handle_domain: Handle
field metal2vulkan::device::DevicePolicy.heap_compression pub heap_compression: HeapCompressionPolicy
field metal2vulkan::device::DevicePolicy.host_page_textures pub host_page_textures: HostPageTexturePolicy
field metal2vulkan::device::DevicePolicy.isolation pub isolation: GuestIsolation
field metal2vulkan::device::DevicePolicy.multisample_depth_twin pub multisample_depth_twin: MultisampleDepthTwinPolicy
field metal2vulkan::device::DevicePolicy.nan_and_min_max pub nan_and_min_max: NanMinMaxPolicy
field metal2vulkan::device::DevicePolicy.pointer_domain pub pointer_domain: PointerDomain
field metal2vulkan::device::DevicePolicy.render_lowering pub render_lowering: RenderLoweringPolicy
field metal2vulkan::device::DevicePolicy.resolve pub resolve: ResolvePolicy
field metal2vulkan::device::DevicePolicy.rounding_order pub rounding_order: RoundingOrderPolicy
field metal2vulkan::device::DevicePolicy.sampling pub sampling: SamplingPolicy
field metal2vulkan::device::DevicePolicy.texel_conversion pub texel_conversion: TexelConversionPolicy
field metal2vulkan::device::DevicePolicy.tile_store pub tile_store: TileStorePolicy
field metal2vulkan::device::DevicePolicy.unorm8_linear_filter pub unorm8_linear_filter: Unorm8LinearFilterPolicy
field metal2vulkan::device::DevicePolicy.vertex_normalized pub vertex_normalized: VertexNormalizedPolicy
field metal2vulkan::device::DevicePolicy.ycbcr_filter pub ycbcr_filter: YCbCrFilterPolicy
@@ -4624,7 +4600,6 @@ fn metal2vulkan::bind::chroma_decode_module pub fn chroma_decode_module(device:
fn metal2vulkan::bind::color_resolve_modules pub fn color_resolve_modules(device: &Device, format: ColorResolveFormat, samples: u32, source: ResolveSource, feature: Feature) -> Result<ColorResolveModules, Error>
fn metal2vulkan::bind::color_write_table pub fn color_write_table() -> &'static [u8]
fn metal2vulkan::bind::compressed_blit_module pub fn compressed_blit_module(device: &Device, rule: CompressedBlit) -> Result<CompressedBlitModule, Error>
fn metal2vulkan::bind::depth_magnitude_module pub fn depth_magnitude_module(device: &Device) -> Result<DepthMagnitudeModule, Error>
fn metal2vulkan::bind::depth_split_module pub fn depth_split_module(device: &Device, form: DepthStandInForm, feature: Feature) -> Result<DepthSplitModule, Error>
fn metal2vulkan::bind::depth_stencil_copy_modules pub fn depth_stencil_copy_modules(device: &Device, copy: DepthStencilCopy, feature: Feature) -> Result<DepthStencilCopyModules, Error>
fn metal2vulkan::bind::depth_stencil_resolve_modules pub fn depth_stencil_resolve_modules(device: &Device, draw: DepthStencilResolveDraw, feature: Feature) -> Result<DepthStencilResolveModules, Error>
@@ -5023,7 +4998,6 @@ macro-member metal2vulkan-runtime::Degradation::DecodedBlockTwin DecodedBlockTwi
macro-member metal2vulkan-runtime::Degradation::DecodedTexelPrecision DecodedTexelPrecision = "decoded-texel-precision", Precision,
macro-member metal2vulkan-runtime::Degradation::DepthBiasPastOne DepthBiasPastOne = "depth-bias-past-one", Precision,
macro-member metal2vulkan-runtime::Degradation::DepthDenormals DepthDenormals = "depth-denormals", Precision,
macro-member metal2vulkan-runtime::Degradation::DepthTwin DepthTwin = "depth-twin", Performance,
macro-member metal2vulkan-runtime::Degradation::DetachedStorageKeepsWrites DetachedStorageKeepsWrites = "detached-storage-keeps-writes", Precision,
macro-member metal2vulkan-runtime::Degradation::DeviceAnisotropicFilter DeviceAnisotropicFilter = "device-anisotropic-filter";
macro-member metal2vulkan-runtime::Degradation::DeviceArithmetic DeviceArithmetic = "device-arithmetic";
@@ -8437,9 +8411,6 @@ method metal2vulkan::bind::CompressedBlit::of pub fn of(pf: PixelFormat) -> Opti
method metal2vulkan::bind::CompressedBlit::texel_bytes pub fn texel_bytes(self) -> u32
method metal2vulkan::bind::CompressedBlit::word pub fn word(self, word: u32, odd: bool) -> u32
method metal2vulkan::bind::ContinuedResult::new pub fn new(offset: u64, first: u32, count: u32, sum: bool) -> ContinuedResult
method metal2vulkan::bind::DepthMagnitudeModule::shape pub fn shape(count: u32, merge: bool, flush: bool) -> [u8; 16]
method metal2vulkan::bind::DepthMagnitudeModule::stand_in pub fn stand_in(bits: u32, flush: bool) -> u32
method metal2vulkan::bind::DepthMagnitudeModule::strip pub fn strip(count: u32) -> [u8; 16]
method metal2vulkan::bind::DepthStencilResolveDraw::new pub fn new(pick: DepthPick, samples: u32, write: ResolveWrite) -> DepthStencilResolveDraw
method metal2vulkan::bind::Dispatch::threads_per_group pub fn threads_per_group(&self) -> [u32; 3]
method metal2vulkan::bind::DrawMergeModule::push_constants pub fn push_constants(header: u64, status: u64) -> Vec<u8>
@@ -9519,7 +9490,6 @@ struct metal2vulkan::bind::CompensatedViewport #[cfg_attr(feature = "serde", der
struct metal2vulkan::bind::CompressedBlitModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct CompressedBlitModule
struct metal2vulkan::bind::ComputeTemplate #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ComputeTemplate
struct metal2vulkan::bind::ContinuedResult #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ContinuedResult
struct metal2vulkan::bind::DepthMagnitudeModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DepthMagnitudeModule
struct metal2vulkan::bind::DepthSplitModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DepthSplitModule
struct metal2vulkan::bind::DepthStencilCopyModules #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DepthStencilCopyModules
struct metal2vulkan::bind::DepthStencilResolveDraw #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct DepthStencilResolveDraw
@@ -12096,8 +12066,6 @@ variant metal2vulkan::bind::DepthStencilCopy::Depth16Bits Depth16Bits
variant metal2vulkan::bind::DepthStencilCopy::Depth16Code Depth16Code
variant metal2vulkan::bind::DepthStencilCopy::DepthBits DepthBits
variant metal2vulkan::bind::DepthStencilCopy::DepthFromStandIn DepthFromStandIn { form: DepthStandInForm }
variant metal2vulkan::bind::DepthStencilCopy::DepthMagnitude DepthMagnitude
variant metal2vulkan::bind::DepthStencilCopy::MagnitudeBits MagnitudeBits
variant metal2vulkan::bind::DepthStencilCopy::StencilBits StencilBits
variant metal2vulkan::bind::DepthStencilCopy::StencilExport StencilExport { source: CopySource }
variant metal2vulkan::bind::DepthStencilCopy::StencilPlane StencilPlane { source: CopySource, bit: StencilBit }
@@ -12328,7 +12296,7 @@ variant metal2vulkan::bind::TessellationRecords::Pool Pool
variant metal2vulkan::bind::TexelWords::ColorPlane ColorPlane
variant metal2vulkan::bind::TexelWords::Raw Raw
variant metal2vulkan::bind::TextureShape::Buffer Buffer { pixel_format: metal::PixelFormat, swizzle: metal::TextureSwizzleChannels }
variant metal2vulkan::bind::TextureShape::Texture Texture { texture_type: metal::TextureType, pixel_format: metal::PixelFormat, sample_count: u32, usage: metal::TextureUsage, mipmap_level_count: u32, sparse: bool, depth_twin: bool, swizzle: metal::TextureSwizzleChannels, address_modes: metal::sampler::AddressModeMap, offset_base_axes: u8, own_format_views: bool, ycbcr_in_place: bool }
variant metal2vulkan::bind::TextureShape::Texture Texture { texture_type: metal::TextureType, pixel_format: metal::PixelFormat, sample_count: u32, usage: metal::TextureUsage, mipmap_level_count: u32, sparse: bool, swizzle: metal::TextureSwizzleChannels, address_modes: metal::sampler::AddressModeMap, offset_base_axes: u8, own_format_views: bool, ycbcr_in_place: bool }
variant metal2vulkan::bind::TileMapError::Region Region { level: u32, slice: u32, origin: [u32; 3], size: [u32; 3] }
variant metal2vulkan::bind::TileMapError::Shape Shape
variant metal2vulkan::bind::TileMapError::TextureType TextureType { texture_type: TextureType }
@@ -12557,8 +12525,6 @@ variant metal2vulkan::device::HostPageTexturePolicy::Shadow Shadow
variant metal2vulkan::device::Independence::All All
variant metal2vulkan::device::Independence::None None
variant metal2vulkan::device::Independence::Only32Bit Only32Bit
variant metal2vulkan::device::MultisampleDepthTwinPolicy::Device Device
variant metal2vulkan::device::MultisampleDepthTwinPolicy::Exact Exact
variant metal2vulkan::device::NanMinMaxPolicy::Exact Exact
variant metal2vulkan::device::NanMinMaxPolicy::Native Native
variant metal2vulkan::device::PointerDomain::ResidentTable ResidentTable
@@ -12568,8 +12534,6 @@ variant metal2vulkan::device::ResolveMode::Average Average
variant metal2vulkan::device::ResolveMode::Max Max
variant metal2vulkan::device::ResolveMode::Min Min
variant metal2vulkan::device::ResolveMode::SampleZero SampleZero
variant metal2vulkan::device::ResolvePolicy::Device Device
variant metal2vulkan::device::ResolvePolicy::Exact Exact
variant metal2vulkan::device::Robustness::None None
variant metal2vulkan::device::Robustness::Rba Rba
variant metal2vulkan::device::Robustness::Rba2 Rba2
@@ -12625,8 +12589,6 @@ variant metal2vulkan::device::Tier::Emulated Emulated
variant metal2vulkan::device::Tier::Linear Linear
variant metal2vulkan::device::Tier::NoSubgroup NoSubgroup
variant metal2vulkan::device::Tier::PartialFragment PartialFragment
variant metal2vulkan::device::TileStorePolicy::Device Device
variant metal2vulkan::device::TileStorePolicy::Exact Exact
variant metal2vulkan::device::Unorm8LinearFilterPolicy::DeviceWithinOneCode DeviceWithinOneCode
variant metal2vulkan::device::Unorm8LinearFilterPolicy::Exact Exact
variant metal2vulkan::device::VertexNormalizedPolicy::Device Device
Can't render this file because it is too large.
-5
View File
@@ -232,12 +232,9 @@ surface! {
enum VertexNormalizedPolicy N;
enum NanMinMaxPolicy N;
enum RoundingOrderPolicy N;
enum MultisampleDepthTwinPolicy N;
enum DecodedTexelsPolicy N;
enum HeapCompressionPolicy N;
enum CompletionPolicy N;
enum TileStorePolicy N;
enum ResolvePolicy N;
enum BatchOrderPolicy N;
enum RenderLoweringPolicy N;
enum HostPageTexturePolicy N;
@@ -659,8 +656,6 @@ surface! {
fn shadow_merge_kept_image_module;
struct ShadowMergeImageModule N;
enum ShadowMergeRead E;
fn depth_magnitude_module;
struct DepthMagnitudeModule N;
fn unused_bits_module;
struct UnusedBitsModule N;
fn extended_shadow_module;
+43 -89
View File
@@ -95,26 +95,6 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`:
[FAST-PATHS.md](FAST-PATHS.md) lists every choice, its bound and the measured cost of its exact
form. On MoltenVK on an Apple GPU, whose sampler and `float` functions are Metal's own, most of
these choices change nothing.
- **The device's load and store of a signed normalized or `RGB9E5Float` attachment**
(`TileStorePolicy::Device`, the runtime's choice; no pipeline differs). A render pass that loads
one and draws keeps the texels its draws do not write as they were, where Metal's tile store
writes a channel's minimum code back as the code above it and an unnormalized shared-exponent
word normalized, announced as `snorm-minimum-kept` and `shared-exponent-kept`.
`tile_store = TileStorePolicy::Exact`, which `exact_answers()` selects, rewrites them before
the pass as Metal's store leaves them, through the extended-range attachments' load pass. On
MoltenVK the pass is a Metal pass and stores them as Metal's under either value.
- **The device's resolve of a multisampled color attachment** (`ResolvePolicy::Device`, the
runtime's choice; no pipeline differs). A pass resolves a color attachment by the device's
`AVERAGE` in the pass, which rounds the average (a tie, an sRGB average) as the device does and
answers a NaN or infinite sample as the device does, announced as `device-rounded-resolve`.
`resolve = ResolvePolicy::Exact`, which `exact_answers()` selects, resolves an attachment whose
format has Metal's rule at its sample count by that rule in one more render pass instance after
the pass (`shader-resolve`). On MoltenVK the device's resolve is Metal's own under either value,
and an attachment a fetching pass's sample planes hold as it ends resolves from them by Metal's
rule under either. An extended-range attachment (`BGR10_XR`, `BGRA10_XR`, their sRGB twins,
`RGB10A2Unorm_sRGB`), held in raw codes no device averages, resolves after the pass under either
value, on every device: a linear form's colors by Metal's rule, its alpha and an sRGB form's
colors by a near-equivalent (`extended-range-resolve`).
- **Batches of a queue ordered by their ends** (`BatchOrderPolicy::Ends`, the runtime's choice; no
pipeline differs). On ANV, RADV and NVIDIA's driver, each measured to start no kernel submission
of a `VkQueue` before the one before it completed, each batch of command buffers ends with a
@@ -1239,10 +1219,10 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
imported as dma-bufs where the device makes no image over a dma-buf of the texture's own pages
(the notice names why; `WorkCounts::dma_buf_image_fallbacks` counts it). A heap's texture is a
shadow of the heap's bytes in its range in three more shapes, each announced with its own reason.
A single-sample depth or stencil texture held with no depth twin, whose texels fit its image's
bytes, on a device whose driver lays such images apart from the memory they are bound to
(`DriverFact::DepthStencilImagesLieApart`): one no such shadow serves, a multisampled one or a
depth twin among them, is `heap-depth-stencil-apart` instead. A texture the device binds no image
A single-sample depth or stencil texture whose texels fit its image's bytes, on a device whose
driver lays such images apart from the memory they are bound to
(`DriverFact::DepthStencilImagesLieApart`): one no such shadow serves, a multisampled one among
them, is `heap-depth-stencil-apart` instead. A texture the device binds no image
of to the heap's memory where the heap places it: its optimal image takes no memory type of the
heap's and no linear image of the device serves (a `Shared` heap's depth texture on MoltenVK), or
the heap lies over host pages that no linear image over them serves, or its images ask more than
@@ -1505,8 +1485,9 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
texture whose slices from the resolve slice hold fewer layers than the pass's. Cost: the pass
resolves into a scratch image, whose render area is copied into the texture after the pass.
- `metal2vulkan-degrade-shader-resolve` (performance). `ShaderResolve`: A multisample color resolve
drawn after the pass by Metal's exact rules, where the device's `AVERAGE` resolve is not measured
to be Metal's, under `ResolvePolicy::Exact` or from a fetching pass's sample planes; or a stencil resolved by `DepthResolvedSample` after `Min` or `Max`, which no
drawn after the pass by the crate-owned resolve: of an extended-range attachment, whose codes no
device's resolve averages, into the attachment's format's sRGB twin, whose encoding no device's
resolve writes, or from a fetching pass's sample planes; or a stencil resolved by `DepthResolvedSample` after `Min` or `Max`, which no
Vulkan resolve mode states, or a `Min` or `Max` depth on a device without the mode, drawn after
the pass. Cost: one more render pass instance after the pass reads the stored samples (or the
sample planes) and writes the resolve texture, where the device would resolve in the pass; where
@@ -1669,13 +1650,10 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
and end.
- `metal2vulkan-degrade-device-rounded-resolve` (precision). `DeviceRoundedResolve`: A multisample
color resolve averages through Vulkan's `AVERAGE` mode, which leaves the rounding of the average
(and the sRGB encoding) to the device, on a device not measured to round as Metal does: under
`ResolvePolicy::Device`, the default, any color attachment but one a fetching pass's sample
planes hold as it ends (resolved from them by Metal's rule); under `ResolvePolicy::Exact` a format
without Metal's closed rule at its count (the 16-bit float, `RG11B10Float` and `RGB9E5Float`
formats past 4 samples, and a format no rule covers), or an attachment whose image the exact
resolve can neither read nor copy: an image without input attachment usage of a format the
device does not copy. Never, whatever the format, on a device whose resolve is measured to round
(and the sRGB encoding) to the device, on a device not measured to round as Metal does: any
color attachment but an extended-range one, one resolving into its format's sRGB twin, and one a
fetching pass's sample planes hold as it ends (each resolved after the pass). Never, whatever the
format, on a device whose resolve is measured to round
as Metal does (`DriverFact::ColorResolveAverageIsMetals`: MoltenVK's resolve is Metal's own).
Measured against Metal's rules at 2 and 4 samples on RADV (Mesa 26.0.8, the Radeon 780M and the RX
7900 XTX), ANV (Mesa 26.2.4, the Iris Xe), NVIDIA (615.71, the RTX 5080 Laptop GPU) and lavapipe
@@ -1693,9 +1671,9 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
- `metal2vulkan-degrade-unmeasured-resolve` (precision). `UnmeasuredResolve`: A multisample color
resolve of more than 4 samples, of which Apple's GPUs make no texture: no Metal answer is measured
there; likewise a stencil resolved by `DepthResolvedSample` after `Min` or `Max`, whose pick among
equal depths is measured at 2 and 4 samples. Cost: the resolve applies the rules Metal's resolve
follows at 2 and 4 samples (or the device's average, for a format without them), which no Metal
answer confirms at this count.
equal depths is measured at 2 and 4 samples. Cost: the resolve is the device's average, or after
the pass the rules Metal's resolve follows at 2 and 4 samples, which no Metal answer confirms at
this count.
- `metal2vulkan-degrade-extended-range-resolve` (precision). `ExtendedRangeResolve`: A multisample
resolve of an extended-range color attachment whose resolve Metal averages from values finer than
the codes the attachment holds (`BGRA10_XR`'s alpha, an `_sRGB` twin's color,
@@ -1760,19 +1738,14 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
reaches for a cubic filter (a fragment stage never does); and one whose elements could not be
written. Cost: a function reading the state through its ID in an argument buffer reads the
neutral sampler, where Metal's reads the state.
- `metal2vulkan-degrade-depth-twin` (performance). `DepthTwin`: A `Depth32Float` texture the program
only reads or samples, on a device whose driver is not measured to keep every `float` in a depth
image, is held in an `R32_SFLOAT` image with a `D32_SFLOAT` twin for the comparisons the device
makes. Cost: a second image of its size, which every copy into it writes too; a copy into it from
a depth texture without a twin goes through a scratch buffer.
- `metal2vulkan-degrade-restricted-depth-upload` (precision). `RestrictedDepthUpload`: An upload
(`replace_region`, a blit from a buffer) into the 32-bit float depth of a texture's depth image,
on a device without `VK_EXT_depth_range_unrestricted` enabled, where Vulkan leaves a value outside
`[0, 1]` undefined, whose driver is not measured to keep one
(`DriverFact::DepthImageKeepsValuesOutsideUnitRange`): a texture without a twin. And a render
pass's NaN clear depth on such a device, which Metal stores as `0x7fc00000`, cleared to 1.0. Cost:
a value outside [0, 1] may be stored clamped to [0, 1], where Metal's keeps it, so reads, samples,
comparisons and depth tests of it can differ.
(`DriverFact::DepthImageKeepsValuesOutsideUnitRange`). And a render pass's NaN clear depth on such
a device, which Metal stores as `0x7fc00000`, cleared to 1.0. Cost: a value outside [0, 1] may be
stored clamped to [0, 1], where Metal's keeps it, so reads, samples, comparisons and depth tests
of it can differ.
- `metal2vulkan-degrade-host-read-dispatch-arguments` (performance). `HostReadDispatchArguments`: An
indirect dispatch, or a dispatch after `setStageInRegionWithIndirectBuffer:indirectBufferOffset:`:
its arguments or its stage-in region are GPU memory the work before it may write, so they are
@@ -1814,8 +1787,8 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
- `metal2vulkan-degrade-heap-depth-stencil-apart` (precision). `HeapDepthStencilApart`: A depth or
stencil texture made in a heap on a device whose driver lays depth and stencil images apart from
the memory they are bound to (`DriverFact::DepthStencilImagesLieApart`) that no shadow of the
heap's bytes serves: a multisampled texture, which Vulkan copies to and from no buffer, one whose
texels do not fit its bytes, or one with a depth twin. Cost: the texture's texels lie apart from
heap's bytes serves: a multisampled texture, which Vulkan copies to and from no buffer, or one
whose texels do not fit its bytes. Cost: the texture's texels lie apart from
the heap's bytes: a write through a buffer
or texture over its bytes changes none of them, and its writes change none of those resources'
bytes, where Metal's texture aliases them.
@@ -1899,7 +1872,7 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
sized or made in a heap (never a device's own texture, whose layout nothing shows), on a device
whose driver keeps depth and stencil images GPU-optimized whatever their create info
(`DriverFact::DepthStencilImagesStayGpuOptimized`), that no shadow of Metal's tiles in the heap's
bytes serves (a multisample texture, a depth twin, a format whose layout is not measured): Metal
bytes serves (a multisample texture, a format whose layout is not measured): Metal
lays the texture out without its compression metadata, and the runtime's image keeps it. Cost: the
texture's image keeps the GPU-optimized layout Metal
drops with the property off, so its bytes in the heap are not Metal's layout of its texels (where
@@ -1907,8 +1880,7 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
name for the shapes they cover); heap_texture_size_and_align answers Metal's own size and
alignment for the descriptor wherever the runtime models them, and the larger of the images' and
Metal's for a texture whose images need more bytes or a coarser alignment that no shadow of the
heap's bytes holds it to (a depth twin among them), where a heap sized by Metal's answers holds
fewer such textures.
heap's bytes holds it to, where a heap sized by Metal's answers holds fewer such textures.
- `metal2vulkan-degrade-narrow-surface-rows` (precision). `NarrowSurfaceRows`: A texture of an
IOSurface plane of more than one row under 16 bytes a row: Metal's GPU writes its rows 16 bytes
apart and reads every row past the first as memory-dependent bytes (zeros in a fresh process;
@@ -2078,16 +2050,14 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
minimum code (-128, or -32768 for 16 bits) as the code above it (-127, -32767) in each tile a draw
reaches: a texel whose bytes no Metal write left (uploaded or copied bytes) keeps a code Metal's
pass would change. Not on a driver whose pass stores the codes as Metal's
(`DriverFact::TileStoreIsMetals`: MoltenVK on Apple's GPUs, whose pass is a Metal pass), nor under
`TileStorePolicy::Exact` for an attachment the load pass rewrites as Metal's store leaves it.
(`DriverFact::TileStoreIsMetals`: MoltenVK on Apple's GPUs, whose pass is a Metal pass).
- `metal2vulkan-degrade-shared-exponent-kept` (precision). `SharedExponentKept`: A draw in a render
pass that loads a single-sampled `RGB9E5Float` color attachment and does not discard it at the
store. Cost: the texels the pass's draws do not write keep their words; Metal's pass normalizes a
word whose largest mantissa is below 256 (its exponent above 0) in each tile a draw reaches: a
texel whose bytes no Metal write left (uploaded or copied words) keeps a word Metal's pass would
change, of the same value. Not on a driver whose pass stores the words as Metal's
(`DriverFact::TileStoreIsMetals`), nor under `TileStorePolicy::Exact` for an attachment the load
pass rewrites as Metal's store leaves it.
(`DriverFact::TileStoreIsMetals`).
- `metal2vulkan-degrade-two-plane-buffer-blit` (precision). `TwoPlaneBufferBlit`: A blit between a
buffer and a level of `RGB10A8_2P_XR10` or its sRGB twin whose width is not a multiple of 4,
where Metal's blit addresses the level's rows `⌊4 w / 16⌋ · 16` bytes apart, short of where they
@@ -2201,8 +2171,7 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
- `metal2vulkan-degrade-unreached-tiles-rewritten` (precision). `UnreachedTilesRewritten`: A render
pass that loads a color attachment of an extended-range, padded 10-bit or bfloat format
(`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`, `RG10Unorm_X12` and their sRGB twins,
`RGB10A2Unorm_sRGB`, `R16Bfloat`, `RG16Bfloat` and `RGBA16Bfloat`), or under
`TileStorePolicy::Exact` of a signed normalized format or `RGB9E5Float`, stores it and draws,
`RGB10A2Unorm_sRGB`, `R16Bfloat`, `RG16Bfloat` and `RGBA16Bfloat`), stores it and draws,
whose load pass rewrites every 32 x 32 tile of its render area: Metal's pass rewrites
only the tiles a draw's primitives reach, and every tile only where a color attachment of the pass
is cleared and stored (announced where none is, or where the pass renders more than one layer).
@@ -2211,8 +2180,7 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
word's top two bits zeros) and BGRA10_XR alpha codes clamped to [384, 894], so an out-of-range raw
alpha reads back changed, a padded word's low six bits zeroed (an sRGB twin's code moved through
Metal's table), a bfloat code moved through half (out of half's range to an infinity or zero, a
NaN to 0x7fc0) and, under the exact tile store, a signed normalized minimum code raised and an
RGB9E5Float word normalized; the tiles a draw reaches are Metal's.
NaN to 0x7fc0); the tiles a draw reaches are Metal's.
- `metal2vulkan-degrade-zero-layer-map-after-release` (precision). `ZeroLayerMapAfterRelease`: A
draw in a render pass over a rasterization-rate map of no layers that was made after the device
released a map of one or more layers, or reset from one of layers. Cost: the draws write nothing,
@@ -2417,8 +2385,7 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
heap texture sized or made (`heap_texture_size_and_align`, `Heap::new_texture`) whose images on the
device need more bytes or a coarser alignment than Metal's answer, which the runtime models, and
which no shadow of the texture's bytes holds it to: not a multisample texture, whose image lies in
memory of its own, nor one whose planes or Metal's tiles fit its bytes, and not one held with a
depth twin. The answer is then the larger of the two, since no image binds at Metal's offsets.
memory of its own, nor one whose planes or Metal's tiles fit its bytes. The answer is then the larger of the two, since no image binds at Metal's offsets.
Every other such texture answers Metal's numbers and announces nothing here. Not where
`optimized-depth-stencil-texture` says why. Cost:
heap_texture_size_and_align answers more bytes or a coarser alignment than Metal's, so a heap
@@ -2504,39 +2471,26 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
one), on a device whose driver stores one a write on the GPU gives it as a zero (no
`DriverFact::DepthImageKeepsDenormals`: RADV, ANV; a host copy keeps it) or whose depth test
compares one otherwise than Metal's (no `DriverFact::DepthTestKeepsDenormals`: every driver
measured but MoltenVK on an Apple M4). Where the driver stores it and only its depth test differs,
a single-sample `Depth32Float` render target's passes test the smallest normal in its place (the
magnitude stand-in of `signed-depth-test`): Metal's answer but for a fragment at exactly 2^-126,
which passes `Equal` and fails `Greater` against it, where Metal's fails and passes; the payload
says so. Cost: a denormal depth may read, sample and copy out as a zero, or the depth test may
compare it as zero (a positive one) or below zero (a negative one), where Metal keeps it and
compares a positive one above zero and a negative one not below it; a render target whose passes
test the smallest normal in its place differs only for a fragment at exactly 2^-126.
measured but MoltenVK on an Apple M4). Cost: a denormal depth may read, sample and copy out as a
zero, or the depth test may compare it as zero (a positive one) or below zero (a negative one),
where Metal keeps it and compares a positive one above zero and a negative one not below it.
- `metal2vulkan-degrade-signed-depth-test` (precision). `SignedDepthTest`: A depth test that may
compare a negative value or a NaN stored in the 32-bit float depth of a render target as it is, or
a pass with depth writes that may store such a value with its sign, where Metal's test compares
the stored value's magnitude (a NaN above +inf) and its pass with depth writes stores every texel
no fragment wrote without its sign. A single-sample `Depth32Float` render target a write may give
such a value, or whose new texture's pattern (a NaN with the sign set) a pass loads before a write
covered it, is switched on (`WorkCounts::signed_depth_switch_ons`): each pass that loads its depth
renders over a magnitude stand-in, merged back after a pass with depth writes
(`WorkCounts::magnitude_stand_in_passes`, `magnitude_write_backs`); other targets' signs are
stripped after such a pass (`WorkCounts::sign_strips`); MoltenVK's test is Metal's own
(`DriverFact::DepthTestComparesMagnitudes`). Announced for what that misses: a merge under a
draw's exact +inf, a depth loaded through another image, a switch while another command buffer is
uncommitted, a multisampled or `Depth32Float_Stencil8` target's test (at the write, or at the pass
that loads its new pattern, on a device that keeps such a value in a depth image:
`VK_EXT_depth_range_unrestricted` enabled, or `DriverFact::DepthImageKeepsValuesOutsideUnitRange`;
elsewhere `restricted-depth-upload` is announced), a strip the device does not make, and a NaN
clear depth the device does not write before the pass. Cost: a depth test against the stored
value, or the value a pass with depth writes stores, can differ from Metal's in the pass or target
named: the device compares
a negative value below zero and a NaN by its own rule and keeps the value's sign, or a pass's
merge keeps a stored NaN where a draw wrote +inf over it, where Metal compares the value's
magnitude, orders a NaN above every value, stores the value without its sign and stores the
draw's; or a NaN clear depth is stored and tested as 1.0, where Metal stores `0x7fc00000`. A
texture never switched on renders in place; a switched-on texture's loading pass adds two copies
and a dispatch over its render area before it, and the same after it where it writes the depth.
no fragment wrote without its sign. Announced at a write that may give a render target's depth
such a value, or at the pass that loads a new texture's pattern (a NaN with the sign set) before a
write covered it, on a device that keeps such a value in a depth image:
`VK_EXT_depth_range_unrestricted` enabled, or `DriverFact::DepthImageKeepsValuesOutsideUnitRange`
(elsewhere `restricted-depth-upload` is announced). MoltenVK's test is Metal's own
(`DriverFact::DepthTestComparesMagnitudes`): there it is announced at a pass that loads and stores
the depth and sets a state with depth writes but draws under none, whose pass keeps the signs.
Also announced for a NaN clear depth the device does not write before the pass. Cost: a depth test
against the stored value, or the value a pass with depth writes stores, can differ from Metal's in
the pass or target named: the device compares a negative value below zero and a NaN by its own
rule and keeps the value's sign, where Metal compares the value's magnitude, orders a NaN above
every value and stores the value without its sign; or a NaN clear depth is stored and tested as
1.0, where Metal stores `0x7fc00000`.
- `metal2vulkan-degrade-first-sparse-resource-wait` (performance). `FirstSparseResourceWait`: The
device's first sparse texture made (`Heap::new_texture` in a sparse heap) on a device whose
driver's first sparse resource waits for the work submitted before it on every queue
-55
View File
@@ -40,11 +40,8 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X
| A blend into a packed 16-bit attachment the device renders through its word view (`A1BGR5Unorm`, `ABGR4Unorm` on the RTX 5080; `WordAttachment`), which the function computes in the interlocked storage form, reads the attachment's codes, where Metal's tile holds the pass's clear and each earlier blend's result as a `half`, finer; under fast math it also sums a few states otherwise than Metal. Every device rendering such an attachment. | The in-shader blend over the codes (no switch) | **Not built yet:** the extended-range attachments' `half` shadow (`render/extended_shadow.rs`, `VariantKey::extended_shadows`) taken by word attachments: the runtime's shadow start and end, its load of the codes and the clear's halves, and the word's shadowed variant in `lower::fragment::fetch`, for a single-sampled pass (a multisampled one keeps the codes, as an extended-range one does). Fast math's regrouped sums have no model | One code: without fast math exact over a loaded attachment (the 2,891 states of the M3 sweep, every channel), under fast math 3,527 of 94,732,288 channels a code apart; after a clear or an earlier blend in the pass, a code apart where the two readings store different codes. `DeviceColorConversion` (`device-color-conversion`) | Not measured. Expected from the shadow's form: an `R16G16B16A16_SFLOAT` image of the pass's extent per such color (8 bytes a pixel, 16.6 MB at 1920x1080), set at the draw it starts by a fill or a load dispatch, and an 8-byte storage read and write per blended fragment inside the interlock beside the word's |
| A bicubic sample of an 8- or 16-bit normalized texture sums its taps exactly and rounds half up; Metal truncates its row terms, row sums and column terms first. Every device. | The exact sum (no switch) | **Not built yet:** Metal's datapath is pinned (17.75M lanes measured, no miss); its emitter is not written | One grid step (1/4080 at 8 bits) within about 2^-21 of a tie. `BicubicFilterArithmetic` (`bicubic-filter-arithmetic`) | Not measured (Metal's form is expected no larger) |
| A bicubic sample of an extended-range texture (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their sRGB twins) sums its taps' steps exactly, rounds half up and clamps into the format's decoded endpoints; within 0.014 of a grid step of a rounding tie Metal may round the other way. Every device. | The exact sum (no switch) | **None known:** no model of Metal's datapath tried fits; 3,317,760 lanes measured on the M3 Max (macOS 26.7) | One grid step (1/8160 a color lane, 1/8192 an sRGB color lane, 1/4080 alpha), 4,050 of the lanes measured, each within 0.014 of a step of a tie. `BicubicFilterArithmetic` (`bicubic-filter-arithmetic`) | No accurate form |
| A multisampled `Depth32Float` texture the program only reads (shader-read usage, no render target) is held in a `D32_SFLOAT` image on a device whose depth images may not keep its texels, where a single-sampled one of it is already held in `R32_SFLOAT`: `plan_depth_twin` left the multisampled case out on the reading that it has no writer, and `BlitCommandEncoder::fill_texture` is one. Metal's fill stores the pattern's bytes as given, a denormal included. The runtime's choice: no pipeline differs. | `multisample_depth_twin = MultisampleDepthTwinPolicy::Device` | `multisample_depth_twin = MultisampleDepthTwinPolicy::Exact`: the texels in a multisampled `R32_SFLOAT` image, which keeps every `float` the fills and the sample copies write, where the device holds one it samples and copies; elsewhere the depth image, announced as under the default. No depth twin beside it: Metal reads a `depth2d_ms` and compares nothing | A denormal a GPU write puts into a `D32_SFLOAT` image comes back as a zero on RADV, which keeps only a CPU store's and so carries no `DriverFact::DepthImageKeepsDenormals`, and a multisampled image takes no CPU store: a fill's sample holds `0x00000000` where Metal's stored `0x00000001`. Measured on both RADV chips over render-target textures, which this switch does not cover (`sample-fills-d32-2`, `-d32-4`, `-d32s8-4` and `runtime_lane::sample_fills::multisample_fills_write_metal_s_samples` all make the texture `RenderTarget | ShaderRead | PixelFormatView`; exact on MoltenVK, whose depth images keep a denormal). A read-only multisampled texture's fill is unmeasured: the same driver fact covers it, and a RADV run of a fill of a `ShaderRead`-only multisampled `Depth32Float` would confirm it. Announced `depth-twin` where the colour image is taken and `depth-denormals` at the write where it is not; the render-target shape stays open (known gaps) | Unmeasured. The image's depth attachment usage, which such a texture does not ask for; same extent, samples and layers, and no second image (a single-sampled one's `D32_SFLOAT` twin doubles its memory, this does not) |
| A texture of an ASTC LDR format on a device without that ASTC format reads a decoded twin of 8-bit codes, each channel the code nearest Metal's 12-bit value (`C >> 4` over 4095). (An sRGB form's twin holds Metal's own 8-bit codes under either value, which its slots decode through Metal's table: exact.) A texture of an EAC 11-bit format (`R11`, `RG11`, unsigned and signed) on a device without ETC2 reads one of 16-bit normalized codes, each nearest Metal's value (`c / 2047`, signed `c / 1023`). The runtime's choice: no pipeline differs. | `decoded_texels = DecodedTexelsPolicy::Compact` | `decoded_texels = DecodedTexelsPolicy::Exact`: Metal's values in an `R32G32B32A32_SFLOAT` twin (an EAC 11-bit one's in `R32_SFLOAT` or `R32G32_SFLOAT`) | Within 1/510 of Metal's value. An EAC 11-bit channel within half a 16-bit step (1/131070, signed 1/65534). `decoded-texel-precision`, announced where such a texture is made; `runtime_lane::astc_textures`, `runtime_lane::etc_textures` | The twin's memory, 16 bytes a texel against 4 (a 2048 x 2048 texture's chain: 85 MiB against 21 MiB), and as much again for a second twin once the texture is viewed in its other colour space; an EAC 11-bit twin's 4 bytes a channel against 2. The CPU decode of that chain of 8 x 8 blocks on one core of the Iris Xe host: 79 ms against 68 ms. Sampling not measured |
| A heap's colour texture that Metal keeps losslessly compressed (`allowGPUOptimizedContents`, no `ShaderWrite`, `PixelFormatView` or `ShaderAtomic` usage, 16 texels or more a side), on a driver whose compressed images may keep their texels apart from the memory they are bound to (`DriverFact::CompressedImagesHideAliasedWrites`: ANV), is the driver's compressed optimal image, its compression and fast clears kept. A texture Metal keeps uncompressed takes the uncompressed image under either value. The runtime's choice: no pipeline differs. | `heap_compression = HeapCompressionPolicy::Compressed` | `heap_compression = HeapCompressionPolicy::Uncompressed`: an image the driver keeps uncompressed in the heap's bytes, as for a texture Metal keeps uncompressed: host-transfer usage where the device enabled `hostImageCopy` (`heap-texture-host-transfer`), else a linear image (`heap-texture-linear`), else the optimal one (`heap-texture-hides-aliased-writes`) | A write through a buffer or another texture over the texture's bytes may leave its texels as they were or change them otherwise than as written, where Metal's texture reads opaque magenta (`0xffff00ff`) in every texel of drawn content the write covers and the written bytes where it held only a clear; the texture's own writes may show in those bytes compressed. Within Metal's contract: Metal documents such a texture's layout as its own (`allowGPUOptimizedContents` lets it "adjust the private layout"), so no write through another view over its bytes has a defined result there either. `HeapTextureCompressed` (`heap-texture-compressed`), announced once per device where such a texture is made; `runtime_lane::heap_textures` | ANV (Iris Xe of RPL-P; `heap_textures::heap_compression_costs`), a 2048x2048 `RGBA8Unorm` render target in a `Private` placement heap: a pass that clears it 26.9 us against 676.2-676.5 us; a copy into another such texture 647.7-649.1 us against 673.9-693.2 us |
| A signed normalized color attachment (`R8Snorm`, `RG8Snorm`, `RGBA8Snorm`, `R16Snorm`, `RG16Snorm`, `RGBA16Snorm`) or an `RGB9E5Float` one, single-sampled and loaded by a pass that draws, keeps the texels its draws do not write as they were, where Metal's tile store writes each 32x32 tile a draw reaches back through its values: a channel's minimum code (-128, or -32768) as the code above it (-127, -32767), and a shared-exponent word whose largest mantissa is below 256 under an exponent above 0 normalized (its mantissas shifted up as the exponent steps down). The runtime's: no pipeline differs. Not on a driver whose pass stores them as Metal's (`DriverFact::TileStoreIsMetals`: MoltenVK on Apple's GPUs), under either value, with no load pass and no notice. | `tile_store = TileStorePolicy::Device` | `tile_store = TileStorePolicy::Exact`: the extended-range attachments' load pass (`render/unused_bits_load.rs`) takes such an attachment too, raising each minimum code and normalizing each word in the tiles the pass's draws reach (`bind::unused_bits_module` of the format); one it cannot take (a texture held as a shadow, a sparse one, or one whose image the device does not copy both ways) keeps the device's, announced | One code, only at a minimum code, which no Metal write leaves (uploaded or copied bytes); none in value for a shared-exponent word (another encoding of the same value). Within Metal's contract: `MTLLoadAction.load` is documented as "The GPU preserves the existing contents", which the kept texels are; the rewrite is Apple's tile store's own. `SnormMinimumKept` (`snorm-minimum-kept`) and `SharedExponentKept` (`shared-exponent-kept`), announced at each such draw; `runtime_lane::snorm_tile_store` | The load pass before each such pass: the render area copied into a scratch buffer and back, with a dispatch. Timed for the extended-range attachments, whose load pass runs under both values: at 1920x1080 on the Radeon 780M (RADV), a pass that loads one and draws a full-screen triangle takes 1,959 us of GPU time for `BGRA10_XR` against 135 us for `RGBA16Float`, and 1,341 us for `BGR10_XR` and 1,378 us for `RG16Bfloat` against 69 us for `RGBA8Unorm`: about 1.3 ms a loaded attachment for a 4-byte texel and 1.8 ms for an 8-byte one. Under `Exact` a snorm or `RGB9E5Float` attachment takes the same pass (not timed) |
| A multisampled color attachment whose format has Metal's resolve rule at its sample count (unorm, snorm, sRGB, 32-bit float and packed 16-bit unorm formats at every count; 16-bit float, `RG11B10Float` and `RGB9E5Float` ones at 2 and 4) resolves by the device's `AVERAGE` in the pass, which leaves the average's rounding, an sRGB average's space and what a NaN or infinite sample makes of it to the device. The runtime's: no pipeline differs. Not on a driver whose average is Metal's (`DriverFact::ColorResolveAverageIsMetals`: MoltenVK on Apple's GPUs, at 2 and 4 samples), under either value, with no notice; nor for an attachment a fetching pass's sample planes hold as it ends, which resolves from them by Metal's rule under either value. Nor for a resolve into the attachment's format's sRGB twin, which Metal resolves in the resolve texture's encoding: a subpass's resolve attachment is of its color attachment's own format (`VUID-VkSubpassDescription-pResolveAttachments-00850`), so no device's average writes that encoding and the crate-owned resolve draws it under either value, announced `shader-resolve`. | `resolve = ResolvePolicy::Device` | `resolve = ResolvePolicy::Exact`: after the pass, one render pass instance per resolved attachment, between barriers, reads its samples (as an input attachment, or from a copy of them into a scratch image where its image takes no input attachment usage) and writes Metal's rule (`color_resolve.rs`), announced `shader-resolve` | At 2 and 4 samples, every unorm, snorm and packed 16-bit unorm channel within one code of Metal's and an sRGB channel within two (NVIDIA's at 4 samples; one elsewhere), on RADV (Mesa 26.0.8, the Radeon 780M and the RX 7900 XTX), ANV (Mesa 26.2.4, the Iris Xe), NVIDIA (615.71, the RTX 5080 Laptop GPU) and lavapipe (Mesa 26.2.4, at 4 samples). Each rounds an 8-bit unorm tie down (RADV and ANV: 32512 of `R8Unorm`'s 65536 pairs of samples one code below at 2 samples; NVIDIA 31872; lavapipe 8205 of 131072 texels at 4). A float channel differs in its last bits (counted, not bounded), and wholly at a NaN or infinite sample. `DeviceRoundedResolve` (`device-rounded-resolve`), announced at the first such pass; `runtime_lane::resolve_rounding::the_device_resolve_rounds_as_announced` | The extra pass per resolved attachment. A 1920x1080 frame of 97 command buffers of one pass of 4 indexed draws, every 4th pass resolving an `RGBA8Unorm` x4 attachment (`runtime_lane::frame_costs::frame_costs_scout_gpu`), GPU busy a frame, exact against the device's: the Iris Xe (ANV) 2.52 and 2.41 ms against 1.92 ms (a resolved pass's command buffer 77 against 51 us; the guest's queues and imports 3.04 and 2.77 against 2.43 ms); the Radeon 780M (RADV) 2.33 to 2.78 against 2.00 to 2.13 ms (63 to 75 against 45 to 48 us); the RX 7900 XTX 1.38 against 1.36 ms. Untimed, the frames were bound by the encoding thread's CPU, which neither changed. Where the pass stores nothing of the attachment (`MultisampleResolve`), also the image its texture keeps for the queue, which the pass renders and the resolve reads so the texture keeps the samples it held before the pass, as Metal's does (`resolve::keep_samples`): copied into where the pass loads the attachment, never back |
| Batches of command buffers committed on one queue that the scheduler finds ready together (a backlog) go to the driver in one `vkQueueSubmit`, at most four, only the last signalling the queue's timeline, on a driver measured to merge a submission that signals nothing into the next (`DriverFact::SubmissionsWithoutSignalsMerge`: Mesa 26.2.4's ANV on the Iris Xe of RPL-P and the UHD 770 of RPL-S, RADV on the Radeon 780M and the RX 7900 XTX, and llvmpipe; every other driver, measured or not, takes the ungrouped form under either value of the switch): one kernel submission, where ANV on i915 lists every `VkDeviceMemory` in each (the consumer's guest drag on the Iris Xe: about 300 entries per execbuffer, 260 of them its host imports, at 112 to 128 execbuffers a frame). A batch's event signals ride to the group's end, which signals each event's semaphore to the highest index the batches held signal it to (an event's indices rise in commit order). A batch that signals a binary semaphore, takes a fence, binds a sparse update, does first work, names the caller's wrapped image, or waits for anything not seen complete (an event, another queue's work) goes alone, after the batches held: a batch with a wait leads a group, never joins one. So that checked command buffers (the consumer checks each) are found ready together, the submission checks of up to three batches right behind a line's head that goes run with the head's, in commit order, none committed after another queue's batch: such a check runs before the previous batch's `vkQueueSubmit` rather than after it, in the scheduler pass that submits its own batch. A pass that finds no batch ready sends the batches held, unless two or more earlier submissions of their `VkQueue` are not seen complete: the GPU runs those first in any case, so the batches stay held, and those committed meanwhile join them, until one submission is left in flight (a completion turn wakes the scheduler at its value), the group fills, a later batch sends it, a head waits for the GPU, or a thread waits for one of their command buffers' completion, which sends them at once; a batch that ends a command buffer with a switch of storage forms riding on it, which settles by its submission's outcome, is never kept so. A held batch that ends its command buffer is `Scheduled` as it is held, its submission handlers run first, then its scheduled handlers, and its kernel end time set, as an M3 Max schedules a command buffer committed behind running work 0.04 to 0.18 ms after its commit. The runtime's: no pipeline differs. | `completion = CompletionPolicy::Grouped` | `completion = CompletionPolicy::Exact`: one submission per batch, each signalling its own values; each line's head checked alone | Each command buffer of a submission but the last is seen complete (status, completed handlers, waits), and the event values it signals are reached (by the GPU waits on other queues, the host's waits, value reads and listeners), once the last completed: late by the GPU time of at most three later batches (about 0.1 to 0.2 ms each in the consumer's compositor frames on the Iris Xe; about 20 ms behind a 20 ms batch), never early, in commit order. Metal's contract states no bound on when completion is seen (an M3 Max reports a command buffer complete, its handlers, status, waits and event listeners alike, 0.04 to 0.10 ms after its GPU end), and no member but the first waits, so no wait holds a member back: a valid program sees only later completion, as of slower GPU work. A batch kept while earlier work runs is seen complete within the same bound, and, where the one submission left in flight ends before its group reaches the GPU, late besides by that gap: at most a completion turn's reaction and the group's `vkQueueSubmit`. Commands, barriers and GPU times are unchanged. `GroupedCompletion` (`grouped-completion`), announced once per device at its first such submission; `runtime_lane::grouped_submissions` | ANV (Iris Xe of RPL-P; `frame_costs::frame_costs_over_imports`, the checked device, 67 command buffers a frame, GPU at 467-783 MHz), with 520 host imports live, where the Exact form's submissions fall behind the commits as the guest's do: 32.0-33.2 kernel submissions a frame against 67.0, 3.4-3.5 ms of execbuffer ioctl a frame against 6.9-7.9 ms, the scheduler thread's CPU 61-63 us a command buffer against 121-136 us, a frame through completion 4.7-5.9 ms against 8.6-9.7 ms; in the guest's shape with 520 (a second queue taking every 20th command buffer, each signalling a shared event, every 10th waiting for one): 26.2-26.7 kernel submissions a frame against 67.0, 2.8 ms of ioctl a frame against 6.9-7.0 ms, the scheduler 52-53 us a command buffer against 122-123 us, a frame through completion 6.0 ms against 8.7 ms; with 260, where it keeps up, 64.9-66.3 kernel submissions a frame against 67.0, the CPU and wall times alike. The cost (`grouped_submissions::grouped_completion_delays`, 8 command buffers of 0.3-0.5 ms of GLine truncated
| Batches of command buffers on one `VkQueue`, on a driver measured to start no kernel submission of a queue before the one before it completed (ANV, RADV and NVIDIA's; `batch_order.rs`), are ordered by their ends: each ends with a barrier ordering its work before every later command of its `VkQueue` (the exact form's end orders it before the host's reads and writes alone), so a batch that depends on an earlier one there begins with no barrier of its own, often no command buffer of barriers, and its first encoder's GPU start is written at the bottom of the pipe, once everything before it completed. Metal starts an independent command buffer committed behind running work while that work runs (an M3 Max under macOS 27.0.1, probe `gpustart`); those drivers ran two batches of independent work one after the other under every shape measured (no end barrier, the host's or the widened one; in one `vkQueueSubmit` or two, merged into one kernel submission or not), where two dispatches of one command buffer ran side by side. The runtime's: no pipeline differs. | `batch_order = BatchOrderPolicy::Ends` | `batch_order = BatchOrderPolicy::Exact`: a barrier for each dependency of a batch's work on an earlier batch's of its `VkQueue`, the end's barrier to the host's reads and writes alone, the GPU start written at the top of the pipe; every other driver takes it under either value | None: on those drivers each batch starts once the one before it completed under either value, so the work's order, its results and its GPU times are the same, and a batch's GPU start is the end of the work before it, when such a driver starts it. Not announced; `runtime_lane::commit_work` and `runtime_lane::gpu_times` test both values | UHD 770 (ANV, RPL-S), the consumer's frame shape over 520 host imports, 67 command buffers a frame, Grouped completion, the widened end barrier against the exact form (a probe build of each): with no fill ahead of each command buffer, 67.0 command buffers submitted a frame against 129.3-129.7, the GPU's span a frame 1.84-1.90 ms against 1.99-2.06 ms, a frame through completion 2.13-2.22 ms against 2.27-2.38 ms; with a 1 MiB fill ahead of each, 134.0 against 262.9, 8.03-8.22 ms against 8.32-8.42 ms, 9.00-9.15 ms against 9.25-9.36 ms. Radeon 780M (RADV, Mesa 26.0.8), this switch: with no fill, 67.0 against 128.9-129.0, a frame through completion 48.3-48.6 ms against 42.6-47.0 ms; with a 16 MiB fill committed at once, 134.0 against 251.0-251.1, 50.6-50.8 ms against 50.8-57.3 ms; committed every 1 ms, 134.0 against 249.7-250.2, 71.3-83.6 ms against 106.3-113.6 ms (each kernel submission there leaves about 2.5 ms of the GPU idle over 520 host imports, which sets these frames) |
| A texture that only samples or reads (no `RenderTarget`, `ShaderWrite` or `ShaderAtomic` usage) over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their pointer or as dma-bufs; or a buffer in fresh pages) is a linear image aliasing the pages in place, where the device's own check shows that the image's first move, which Vulkan lets read and write every byte bound to it (`VUID-VkImageCreateInfo-pNext-01443` makes such an image start `UNDEFINED`), leaves every byte alone while the CPU writes beside it: a deliberate, scoped exception to relying on documented Vulkan behaviour alone, the owner's ruling (`in_place.rs`). The check runs once per driver, release and runtime, per class of pages, on a thread of its own, its verdict kept in the shader cache's directory; a texture made before its class's verdict is a shadow. A texture whose usage renders or writes, a check that failed or made no image, and a pitch no image takes keep the shadow (`shadowed-texture`, its reason named, `WorkCounts::host_texture_shadows_*`). | `host_page_textures = HostPageTexturePolicy::InPlace` | `host_page_textures = HostPageTexturePolicy::Shadow`: every texture over host pages a shadow, its texels copied in before each command buffer that uses it and merged back after each write (the host-pages bullet under **Costs of matching Metal**) | Exact where the driver keeps what its check showed: the check covers texels, the bytes between rows and those after the image, of 1, 2, 4, 8 and 16-byte texels and a 3840x2160 surface, three rounds each; a driver whose first move changed a byte outside every round's window would undo a CPU write made meanwhile. Not announced where the check passed. A CPU write reaches the image's reads as it reaches the buffer's (Host Write Ordering Guarantees) | See **Costs of matching Metal** (host pages): the shadow copies a sampled 3840x2160 surface in whole each command buffer |
@@ -192,22 +189,6 @@ recorded here.
(`RGBA16Float` at 30% of a 1920x1080 target), and on the Iris Xe from an eighth of the reader's
scissor covered, whatever its area, so the rule costs up to 2.1 times there (a 320x180 scissor
covered whole over a private 1920x1080 `BGRA8Unorm` texture).
- **A `Depth16Unorm` depth whose code the fragment stage writes is tested after the stage.** Where
the device's conversion is not measured to store Metal's code
(`DriverDeviation::MetalDepth16Stores`, or `MetalDepth16BiasedStores` for a biased draw), a
single-sampled draw writes each depth as Metal's code from its fragment stage
(`ShaderUnormDepth`), so a fragment the depth hides still runs it. A bias of a known side
declares it (`DepthGreater` or `DepthLess`) and the device may test first; an unbiased draw and
a bias whose side a triangle's slope decides keep the cost. On the Iris Xe 16 full-screen layers
drawn front to back under a constant bias took 9.42 ms of GPU time with no side declared and
1.85 ms with one, against 1.46 ms unbiased through the device's conversion
(`runtime_lane::unorm_depth_bias`).
- **A stored negative or NaN depth is tested by its magnitude.** A switched-on single-sample
`Depth32Float` texture's pass that loads its depth takes two copies through a scratch buffer and
a dispatch over the render area before it, and the same after it where it writes the depth; a
sign strip (two copies and a dispatch, or a draw per layer when multisampled) follows a pass with
depth writes where no stand-in runs (`texture/signed_depth.rs`). A texture never switched on pays
a flag read per pass.
- **A texture over a no-copy buffer's host pages, or over a host-visible buffer longer than 32
MiB, that renders or writes (or whose class's check has not passed, or whose pitch no image
takes, or under `HostPageTexturePolicy::Shadow`), and a texture over a buffer of the runtime's
@@ -662,24 +643,6 @@ driver's. Each is open work.
(`render/executions.rs`). In an instance that holds the attachment in the feedback loop layout,
those reads name `VK_IMAGE_LAYOUT_GENERAL` in their descriptors, against the layout the instance
holds.
- **A stored negative or NaN depth where the magnitude stand-in and the sign strip do not reach.**
Metal's depth test compares the stored value's magnitude (a NaN above +inf), and a pass with depth
writes stores every texel no fragment wrote without its sign; the runtime matches both through a
magnitude stand-in or a sign strip (`texture/signed_depth.rs`, docs/API.md's
`signed-depth-test`). Still open:
- a multisampled or `Depth32Float_Stencil8` target's test, which compares a negative value or a
NaN as it is, and a pass with depth writes on a device that makes no strip for it, which keeps
the signs: announced (`signed-depth-test`); its resolve in such a pass resolves the samples
before the strip, unmeasured on Metal;
- a merge that keeps a stored NaN where a draw wrote exactly +inf over it, and a denormal at
exactly 2^-126 where the device's test flushes one: announced (`signed-depth-test`,
`depth-denormals`);
- a pass that loads the depth through another image, and one encoded before the switching write
in another command buffer uncommitted then: announced (`signed-depth-test`);
- a NaN clear depth where the device writes no `0x7fc00000` into the depth before the pass:
cleared to 1.0, announced (`signed-depth-test`);
- a device that may clamp a depth outside `[0, 1]` (ANV): announced as `restricted-depth-upload`;
a form that keeps the value in a 32-bit float colour image beside the stand-in is not built.
- **Compute private memory past a device's Function storage is refused.** A kernel, object or mesh
function whose private memory (its `alloca`s, a call stack among them, and constants held as
`Private` variables) passes what the device holds is refused (`Unsupported{PrivateMemory}`, or
@@ -898,24 +861,6 @@ driver's. Each is open work.
image through an unsigned-integer alias so no device decode sees the texel. The fetch half of this
difference is the first gap above, which is a different cause and needs its own fix.
- **A multisampled `Depth32Float` texture's fill of a denormal on RADV**: Metal's private fill
stores the pattern's bytes, `0x00000001`, where this stores `0x00000000` (`sample-fills-d32-2`,
`-d32-4`, `-d32s8-4`; both RADV chips, exact on MoltenVK;
`runtime_lane::sample_fills::multisample_fills_write_metal_s_samples` takes the word where the
device announces the loss and compares every other). **The device's, and announced**: RADV gives a
denormal that a GPU write puts into a `D32_SFLOAT` depth image back as a zero and keeps only a CPU
store's, which is why it carries no `DriverFact::DepthImageKeepsDenormals`
(`device/driver_facts.rs`), and a multisampled image takes no CPU store. The runtime announces
`depth-denormals` and the case declares it at its notices site while still comparing every depth
word. Each of these textures is a render target, which is the half still open:
`MultisampleDepthTwinPolicy::Exact` holds a multisampled `Depth32Float` texture's texels in a
colour image, as a read-only depth texture's already are, only where no pass renders it. The exact
form for a render target, not built: the texels of record in the multisampled `R32_SFLOAT` image
for the texture's life, with a `D32_SFLOAT` stand-in each pass renders into
(`attachment_stand_in::kept_backing`, as `Cause::Magnitude` keeps one for a signed depth), copied
in where Metal loads the depth and back where it stores it, so that every fill and copy writes the
colour image exactly and only a pass's own texels pass through the depth image.
- **A blend's result on RADV, by 1 to 64 codes** (`half-output-blends-*`, `blend-sweep-operations`,
`blend-interaction-format-unorm8` and `-srgb8`, `argb8-targets-*`, `a2c-on-*`; 24 cases). The
one-code rows are what a driver's own rounding of a normalized blend produces, which Vulkan does
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more