Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <array>
#include <bit>
#include <cstdint>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <span>
Expand Down Expand Up @@ -78,12 +79,22 @@ void FillTexture() {
}
}

void Draw(AgcDriver::VulkanDevice& device, std::array<std::uint32_t, 8> texture, std::array<std::uint32_t, 4> sampler, float bias) {
void Draw(AgcDriver::VulkanDevice& device, std::array<std::uint32_t, 8> texture, std::array<std::uint32_t, 4> sampler, float bias, bool mixedSamplers = false) {
const auto& target = device.Target();
alignas(256) std::array<std::uint32_t, 10> pixelCode{};
std::copy_n(BiasPixelCode.begin(), 3u, pixelCode.begin());
pixelCode[3] = 0x7e020212u;
std::copy(BiasPixelCode.begin() + 3, BiasPixelCode.end(), pixelCode.begin() + 4);
alignas(256) std::array<std::uint32_t, 13> code{};
std::copy_n(BiasPixelCode.begin(), 3u, code.begin());
code[3] = 0x7e020212u;
std::copy(BiasPixelCode.begin() + 3, BiasPixelCode.end(), code.begin() + 4);
if (mixedSamplers) {
code[6] = 0xf0940f08u;
code[7] = 0x00a10801u;
code[8] = 0xbf8c3f70u;
code[9] = 0x06081104u;
code[10] = 0xf800180fu;
code[11] = 0x07060504u;
code[12] = 0xbf810000u;
}
const auto pixelCode = std::span(code).first(mixedSamplers ? 13u : 10u);
Pixels.fill(std::byte{0});

std::vector<std::uint32_t> vertexUserData(4, 0u);
Expand All @@ -107,12 +118,15 @@ void Draw(AgcDriver::VulkanDevice& device, std::array<std::uint32_t, 8> texture,
pixel.posY = true;
pixel.targetOutputMode[0] = 9;
pixel.targetExportMapping.fill(0xe4u);
std::vector<std::uint32_t> pixelUserData(19, 0u);
std::vector<std::uint32_t> pixelUserData(24, 0u);
std::copy(texture.begin(), texture.end(), pixelUserData.begin() + 4);
std::copy(sampler.begin(), sampler.end(), pixelUserData.begin() + 12);
pixelUserData[16] = std::bit_cast<std::uint32_t>(1.0f / static_cast<float>(Size));
pixelUserData[17] = std::bit_cast<std::uint32_t>(SecondCoordinateScale);
pixelUserData[18] = std::bit_cast<std::uint32_t>(bias);
auto secondSampler = sampler;
secondSampler[0] &= ~(1u << 20u);
std::copy(secondSampler.begin(), secondSampler.end(), pixelUserData.begin() + 20);
const std::array<ShaderRecompiler::MemoryRegion, 1> pixelMemory{{{reinterpret_cast<std::uintptr_t>(pixelCode.data()), std::as_bytes(std::span(pixelCode))}}};
ShaderRecompiler::RecompileRequest fragment{
{ShaderStage::Fragment, reinterpret_cast<std::uintptr_t>(pixelCode.data()), pixelCode, 0, {}},
Expand Down Expand Up @@ -147,13 +161,20 @@ void Draw(AgcDriver::VulkanDevice& device, std::array<std::uint32_t, 8> texture,
device.WaitIdle();
}

void Check() {
void Check(bool degamma = false) {
for (std::uint32_t y = 0; y < Height; ++y) {
for (std::uint32_t x = 0; x < Width; ++x) {
const std::array<std::uint32_t, 4> expected{(x % Size) * 8u, ((x + y + 1u) % Size) * 8u, 99u, 255u};
std::array<std::uint32_t, 4> expected{(x % Size) * 8u, ((x + y + 1u) % Size) * 8u, 99u, 255u};
if (degamma) {
for (std::uint32_t component = 0; component < 3u; ++component) {
const float encoded = static_cast<float>(expected[component]) / 255.0f;
const float linear = encoded <= 0.04045f ? encoded / 12.92f : std::pow((encoded + 0.055f) / 1.055f, 2.4f);
expected[component] = static_cast<std::uint32_t>(std::lround(linear * 255.0f));
}
}
for (std::uint32_t component = 0; component < 4u; ++component) {
const auto value = std::to_integer<std::uint32_t>(Pixels[(y * Width + x) * 4u + component]);
Require(value == expected[component], "single-level volume bias: pixel " + std::to_string(x) + "," + std::to_string(y) + " component " + std::to_string(component) + " is " + std::to_string(value) + ", expected " + std::to_string(expected[component]));
Require(std::abs(static_cast<int>(value) - static_cast<int>(expected[component])) <= (degamma ? 1 : 0), "single-level volume bias: pixel " + std::to_string(x) + "," + std::to_string(y) + " component " + std::to_string(component) + " is " + std::to_string(value) + ", expected " + std::to_string(expected[component]));
}
}
}
Expand Down Expand Up @@ -186,6 +207,21 @@ int main() {
Draw(*device, VolumeDescriptor(), sampler, 8.0f);
Check();
}
auto integerTexture = VolumeDescriptor();
integerTexture[1] = (integerTexture[1] & ~(0x1ffu << 20u)) | (60u << 20u);
auto forcedSampler = SamplerDescriptor();
forcedSampler[0] |= 1u << 20u;
for (const float bias : {-16.0f, 0.0f, 16.0f}) {
Draw(*device, integerTexture, forcedSampler, bias);
Check(true);
}
std::string mixedRefusal;
try {
Draw(*device, integerTexture, forcedSampler, 0.0f, true);
} catch (const std::exception& error) {
mixedRefusal = error.what();
}
Require(mixedRefusal.find("mixed sampler states") != std::string::npos, "mixed FORCE_DEGAMMA samplers were not refused: " + mixedRefusal);
auto texture = VolumeDescriptor();
texture[4] = 1u;
RequireRefused(*device, texture, SamplerDescriptor(), "one slice and mip level zero only");
Expand Down
24 changes: 24 additions & 0 deletions core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,29 @@ void materializeSnapshot(const IrResourcePlan& plan, const SrtRuntime& runtime,
}
}

void materializeForcedDegamma(const IrResourcePlan& plan, ResourceSnapshot& snapshot) {
for (std::uint32_t index = 0; index < plan.info.images.size(); ++index) {
auto& descriptor = snapshot.images.at(index);
if (((descriptor.dwords[1] >> 20u) & 0x1ffu) != static_cast<std::uint32_t>(IrBufferFormat::Format8_8_8_8UInt)) continue;
bool forced = false;
bool plain = false;
for (const auto& pair : plan.info.sampledPairs) {
if (pair.image != index) continue;
const auto& sampler = snapshot.samplers.at(pair.sampler);
if (sampler.dwordCount != 4u) throw std::runtime_error("FORCE_DEGAMMA requires four sampler descriptor words");
const bool enabled = (sampler.dwords[0] & (1u << 20u)) != 0u;
forced = forced || enabled;
plain = plain || !enabled;
}
if (!forced) continue;
const auto& image = plan.info.images.at(index);
if (!image.singleMipPlaneBiasCompatible || image.dimension != RdnaImageDimension::Dim2D || image.table != NoTable || image.resourceClass != ImageResourceClass::Sampled || image.depthCompare || image.packed) throw std::runtime_error("FORCE_DEGAMMA on RGBA8_UINT requires a direct plain biased pixel sample");
if (plain) throw std::runtime_error("FORCE_DEGAMMA on RGBA8_UINT with mixed sampler states is not implemented");
if ((descriptor.dwords[3] >> 28u) != 10u || (descriptor.dwords[4] & 0x1fffu) != 0u || (descriptor.dwords[3] & 0xff000u) != 0u || (descriptor.dwords[5] & 0xf0u) != 0u) throw std::runtime_error("FORCE_DEGAMMA on RGBA8_UINT requires a one-slice volume at mip zero");
descriptor.dwords[1] = (descriptor.dwords[1] & ~(0x1ffu << 20u)) | (static_cast<std::uint32_t>(IrBufferFormat::Format8_8_8_8Srgb) << 20u);
}
}

std::uint32_t colorCompareReference(IrBufferFormat format) {
switch (format) {
case IrBufferFormat::Format16_16UNorm:
Expand Down Expand Up @@ -1601,6 +1624,7 @@ void ResourceMaterializer::Materialize(const IrResourcePlan& program, const SrtR
throw;
}
const auto started = MaterializeProfiled() ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
materializeForcedDegamma(plan, nextSnapshot);
materializeTables(plan, nextSnapshot);
materializeSrtGuards(plan, nextSnapshot);
if (MaterializeProfiled()) specializationNanoseconds.fetch_add(static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - started).count()), std::memory_order_relaxed);
Expand Down
1 change: 1 addition & 0 deletions docs/dev/debt/shader.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@
- [`ds_ordered_count`](../../../core/shader/recompiler/Translation/src/MemoryInstructions/SharedMemoryInstructions.cpp) (GDS only) reads its operand fields as LLVM encodes them for `llvm.amdgcn.ds.ordered.add` ([SIISelLowering.cpp](https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/AMDGPU/SIISelLowering.cpp#L8844-L8894)): `offset0` is the counter's byte offset (index times 4) and the whole GDS address, `offset1` bit 0 wave release, bit 1 wave done, bits 2-3 the shader type, bit 4 swap instead of add and bits 6-7 the dword count less one. `M0` holds the ordered wave ID, not a GDS address as for `ds_append` (radeonsi passes `TG_SIZE` bits 6-17 as the intrinsic's pointer in [si_compute_prim_discard.c](https://gitlab.freedesktop.org/mesa/mesa/-/blob/mesa-20.3.0/src/gallium/drivers/radeonsi/si_compute_prim_discard.c) and `gs_tg_info` bits 0-11 in [gfx10_shader_ngg.c](https://gitlab.freedesktop.org/mesa/mesa/-/blob/mesa-21.3.0/src/gallium/drivers/radeonsi/gfx10_shader_ngg.c), with "The GDS address is always 0 with ordered append"); it only orders the waves, which is not modeled, so it is ignored. Each wave adds the value of its first active lane to the counter with one device-scope atomic and every active lane gets the counter's previous value (the `ORDERED_APPEND_ENBL` dispatch modifier is accepted for it). The hardware also serializes the waves of a dispatch in launch order, which is not modeled: the waves add in any order, so counters a title reads back as ordered offsets give the same totals but may hand out ranges in another order. Which lane's value is added is not documented; the first active lane is assumed and not measured on hardware. Swap, counts of more than one dword and LDS forms throw. Covered by [GdsAppendConsume.cpp](../../../core/libs/prx/libSceAgcDriver/tests/execution/GdsAppendConsume.cpp).
- [s_swappc_b64](../../../core/shader/recompiler/Translation/src/ControlFlowInstructions.cpp) writes the link pair with the same model as `s_getpc_b64`: the guest return address `pc + 4` as a byte offset over `GetShaderBase`. Any other use of the link pair (arithmetic, hash, store) throws, apart from the overwrites, SOPC compares and shared links that [static scalar calls](../../../core/shader/recompiler/ControlFlow/src/GraphBuilder.cpp) allow; constant-offset folding over the link is not modeled. The special encoding `s_swappc_b64` with SDST 125 still decodes as `s_setpc_b64`, which matches the hardware: measured on RDNA2 (gfx1036) in wave32 and wave64, it branches to the source pair and leaves a marker SGPR pair untouched, and with an SGPR destination the link is `PC + 4`.
- [2D biased sampling through a one-slice, single-level 3D T#](../../../core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp) supplies a zero third coordinate and retains the bias operation, with normalized point minification and magnification and no linear mip filtering. Measured on RDNA2 (AMD integrated gfx1036, driver 32.0.21036.18, Windows 11) by running an OpenCL-loaded native kernel with `image_sample_b` DIM 2D against 16x16x1 R32_UINT and RGBA8_UNORM 3D images: biases -16, -0.5, 0, 0.5 and 16 read the (u,v) texel in slice zero, including wrapped coordinates, point min/max reduction and the title's sampler with Z border addressing. Wave32, IEEE off, DX10 clamp on, denormals preserved, round to nearest even, FP16 overflow off; wave64 and the PS5's gfx1013 are not measured. Pixel-stage, direct, non-depth, unpacked samples whose only use is the plain 32-bit bias form are accepted; extra slices, any nonzero mip range, linear or anisotropic filtering and unnormalized coordinates throw. Vulkan readback is checked on NVIDIA RTX 5070 and AMD integrated graphics for positive and negative bias and point weighted-average/min/max reduction.
- [FORCE_DEGAMMA on RGBA8_UINT](../../../core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp) materializes a direct image sampled only by plain biased pixel accesses as RGBA8_SRGB when every paired sampler forces degamma. Measured on AMD integrated RDNA2 gfx1036 (driver 32.0.21036.18, Windows 11, wave32, IEEE off, DX10 clamp on, denormals preserved, round to nearest even, FP16 overflow off): a native `image_sample_b` DIM 2D on a 16x16x1 RGBA8_UINT 3D T# returns integer channels without the bit, but the same floating-point decoded values as RGBA8_UNORM with it, including point min/max reduction and the title's exact sampler. The metadata and image view must both become floating-point sRGB; ignoring the sampler bit or retaining a UINT heap is incorrect. The accepted case requires one slice, mip zero, normalized point sampling and uniform FORCE_DEGAMMA across its samplers. Other image accesses, mixed sampler states, indirect descriptors and other integer formats remain refused. Wave64, other filtering modes and the PS5's gfx1013 are not measured.
- The [s_swappc_b64 fetch-shader call at vertex/local/tessellation/mesh entry](../../../core/shader/recompiler/ControlFlow/src/GraphBuilder.cpp) assumes the called fetch-shader blob ends in `s_setpc_b64` to the link pair (the GNM fetch-shader shape shadPS4's `EmitFetch` copies); the blob is not part of the shader program, so its return closes the pairing by assumption and any in-program reader of the link pair throws. Attribute fetches are inlined from the request's parsed fetch-shader plan through the same `GetAttribute` path as the embedded fetch analyzer, honoring the buffer resource `dst_sel`; an attribute writing more than four registers, or an entry call without a parsed plan, throws. The vertex/instance offset accumulator inside the fetch blob is not replayed for external blobs.
- The scalar aperture sources [src_shared_base, src_shared_limit, src_private_base, src_private_limit](../../../core/shader/recompiler/RdnaDecoder/src/RdnaInstructionDecoder.cpp) (core/shader/recompiler, scalar source codes 235 to 238) read as the 64-bit apertures the flat routing uses: a base is the aperture's high dword (`SharedApertureHigh`, `PrivateApertureHigh`) over a low dword of 0, a limit is the same high dword over 0xffffffff. A 64-bit read (`s_mov_b64`, a 64-bit VALU source, a wave64 lane mask) gets the whole value and a 32-bit read gets the low dword. This follows LLVM's `SIRegisterInfo.td` (aperture registers are 64-bit, their low 32 bits are always 0 for a base and -1 for a limit) and `getSegmentAperture` (`AMDGPULegalizerInfo.cpp`, `SIISelLowering.cpp`: a 64-bit read whose high half is the aperture), the KFD's `MAKE_LDS_APP_LIMIT` (limit = base | 0xffffffff) and the gfx1030 and gfx1035 readouts on [#1190](https://github.com/boykopovar/AnyPS5/pull/1190) and [#3803](https://github.com/boykopovar/AnyPS5/issues/3803). Not measured on a console: the PS5's high dwords are the inferred values of the flat aperture bases entry, and the wave is taken to be in 64-bit address mode (PTR32 clear)
- [EmitSetAttribute](../../../core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp) (shader recompiler) - a primitive with a vertex whose clip position is (0,0,0,0) is clipped away through an extra `gl_ClipDistance` element on vertex and tessellation evaluation shaders, matching what a Radeon 610M (RDNA2, RADV) and llvmpipe rasterise; NVIDIA 615.78.08 without it draws the vertex at the viewport centre. Measured for triangles (strip and list) and for a point at (0,0,0,0), which the Radeon 610M does not draw, NVIDIA draws at the viewport centre and llvmpipe at the top-left corner; lines with such a vertex are clipped by the same element and were not measured. Mesh, geometry and the generated rect-list and barycentric stages do not write it, a device without `shaderClipDistance` cannot compile vertex shaders (the compile throws), and guest clip distances are still refused by the pipeline validator. The PS5 rasteriser was not measured.
Expand Down
Loading