shader: apply texel offsets of image_sample*_o #1220

Closed
github-bot wants to merge 1 commit from gh-pr/1220/head into gh-pr/1220/base
Owner

@⁠TheCruZ on GitHub · 2026-10-08 18:39 UTC · original
pr/sample-texel-offsets → main · +304 −12 · 4 files · 1 commits · closed without merging

Summary

Applies the texel offsets of IMAGE_SAMPLE*_O instructions. In Grand Theft Auto V (PPSA04263) pixel shader 0xe59f3254a91fedb0 fetches its +1 texel neighbour this way and read the unshifted texel instead.

Problem

The offset DWORD of the SAMPLE*_O variants was decoded into the address layout (layout.offset) but never reached the SPIR-V sample instruction, so every offset sample read the texel at the unshifted coordinate.

Change

  • Offsets that are constant and inside Vulkan's guaranteed ConstOffset range [-8, 7] become a ConstOffset image operand (only emitted when an offset is non-zero; cube maps have no offsets).
  • Vulkan forbids a runtime Offset on sample instructions, so other offsets shift the coordinates by offset / size of the sampled mip: the explicit LOD, the LOD of the gradients of derivative samples, level zero, or the LOD queried with OpImageQueryLod plus the instruction's bias in pixel shaders, clamped to the view's last level.
  • The translator re-applies exec to the offset DWORD, and constant propagation now folds nested selects on the same condition, so an exec-predicated v_mov of the offsets stays a constant and takes the ConstOffset path.

Testing

  • Grand Theft Auto V (PPSA04263): played in my fork with this change, no regressions seen.
  • shader_recompiler_compute_tests: new ImageSampleOffsetMovesTexel case (also in the default run; it also checks runtime offsets on IMAGE_SAMPLE_L_O with a LOD past the last level and on IMAGE_SAMPLE_D_O) and the --image-sample-offset-only selector, which also runs ImageSampleA16OffsetKeepsTexelOffset32BitOnGpu and ImageSampleAndGather. The default run and shader_cfg_tests pass.
  • Tested on Windows 11 with AMD Ryzen 5900x and RTX 3090.

AI usage

AI (Claude Opus 5.5) was used to investigate the issue and to implement the change. I reviewed the code, understand it, tested it as described above, and wrote this description myself, in general fully tested the game while doing few missions and playing in-game with my GTA V fork, i will be bringing PRs here after test them enough.

**@⁠TheCruZ** on GitHub · 2026-10-08 18:39 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220) `pr/sample-texel-offsets` → `main` · +304 −12 · 4 files · 1 commits · closed without merging ## Summary Applies the texel offsets of `IMAGE_SAMPLE*_O` instructions. In Grand Theft Auto V (PPSA04263) pixel shader `0xe59f3254a91fedb0` fetches its +1 texel neighbour this way and read the unshifted texel instead. ## Problem The offset DWORD of the `SAMPLE*_O` variants was decoded into the address layout (`layout.offset`) but never reached the SPIR-V sample instruction, so every offset sample read the texel at the unshifted coordinate. ## Change - Offsets that are constant and inside Vulkan's guaranteed `ConstOffset` range [-8, 7] become a `ConstOffset` image operand (only emitted when an offset is non-zero; cube maps have no offsets). - Vulkan forbids a runtime `Offset` on sample instructions, so other offsets shift the coordinates by `offset / size` of the sampled mip: the explicit LOD, the LOD of the gradients of derivative samples, level zero, or the LOD queried with `OpImageQueryLod` plus the instruction's bias in pixel shaders, clamped to the view's last level. - The translator re-applies exec to the offset DWORD, and constant propagation now folds nested selects on the same condition, so an exec-predicated `v_mov` of the offsets stays a constant and takes the `ConstOffset` path. ## Testing - Grand Theft Auto V (PPSA04263): played in my fork with this change, no regressions seen. - `shader_recompiler_compute_tests`: new `ImageSampleOffsetMovesTexel` case (also in the default run; it also checks runtime offsets on `IMAGE_SAMPLE_L_O` with a LOD past the last level and on `IMAGE_SAMPLE_D_O`) and the `--image-sample-offset-only` selector, which also runs `ImageSampleA16OffsetKeepsTexelOffset32BitOnGpu` and `ImageSampleAndGather`. The default run and `shader_cfg_tests` pass. - Tested on Windows 11 with AMD Ryzen 5900x and RTX 3090. ## AI usage AI (Claude Opus 5.5) was used to investigate the issue and to implement the change. I reviewed the code, understand it, tested it as described above, and wrote this description myself, in general fully tested the game while doing few missions and playing in-game with my [GTA V fork](https://github.com/TheCruZ/KytyPS5-GTA), i will be bringing PRs here after test them enough.
The SAMPLE*_O offset DWORD was decoded into the address layout but never
reached the SPIR-V sample, so every offset sample read the unshifted
texel (GTA V pixel shader 0xe59f3254a91fedb0 fetches its +1 texel
neighbour this way).

Offsets that are constant and inside Vulkan's guaranteed ConstOffset
range [-8, 7] become ConstOffset. Vulkan forbids a runtime Offset on
sample instructions, so other offsets shift the coordinates by
offset / size of the sampled mip (explicit LOD, the LOD of the gradients
of derivative samples, level zero, or the queried LOD plus the
instruction's bias in pixel shaders), clamped to the view's last level.
The translator re-applies exec to the offset DWORD and constant
propagation now folds nested selects on the same condition, so an
exec-predicated v_mov of the offsets stays a constant.

Test: --image-sample-offset-only (ImageSampleOffsetMovesTexel, also with
runtime offsets on IMAGE_SAMPLE_L_O past the last level and on
IMAGE_SAMPLE_D_O).
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:48:36 +00:00
github-bot closed this pull request 2026-11-26 09:48:36 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 18:46 UTC · original · edited 2026-10-08 21:09 UTC

Review in Change Stack →

📝 Walkthrough

Walkthrough

The SPIR-V emitter now supports image sampling offsets. It uses ConstOffset for supported constant offsets and adjusts coordinates using mip dimensions for other offsets on non-cube images. Image offset addresses are masked by the execution predicate, and constant propagation simplifies matching nested selects. Compute tests cover constant and runtime offsets.

Suggested reviewers: nmzik

Priority: ⬇️ Low

Change: Bug fix

Merge Risk: 🟡 Moderate · up to d9103

Some offset samples can read the wrong texel, particularly with explicit LOD, gradients, bias, or unnormalized coordinates. Resolve the sampling mismatches before merging.

🚥 Pre-merge checks | ✅ 4 | ❓ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ❓ Inconclusive Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 3 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The description clearly explains the image sampling offset bug, the implementation, and the related tests. It is directly related to the changeset.
Title check ✅ Passed The title clearly and concisely identifies the main change: applying texel offsets for image_sample*_o instructions.
Full details: Docstring Coverage

Explanation

Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 3 files. (1 skipped: 1 too large.)

  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 18:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#issuecomment-6066737900) · edited 2026-10-08 21:09 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/1220?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The SPIR-V emitter now supports image sampling offsets. It uses `ConstOffset` for supported constant offsets and adjusts coordinates using mip dimensions for other offsets on non-cube images. Image offset addresses are masked by the execution predicate, and constant propagation simplifies matching nested selects. Compute tests cover constant and runtime offsets. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ⬇️ Low <!-- change_assessment_commit:"d910353575d2a6e2c3d58768782553cff00eb25e" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** **🟡 Moderate** · up to `d9103` <!-- final_review_risk_coverage:{"sourceCommitId":"d910353575d2a6e2c3d58768782553cff00eb25e","coveredCommitId":"d910353575d2a6e2c3d58768782553cff00eb25e","kind":"reviewed"} --> Some offset samples can read the wrong texel, particularly with explicit LOD, gradients, bias, or unnormalized coordinates. Resolve the sampling mismatches before merging. <!-- final_review_risk_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❓ 1</summary> ### ❌ Failed checks (1 inconclusive) | Check name | Status | Explanation | Resolution | | :---------------- | :------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ❓ Inconclusive | Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 3 files. (1 skipped: 1… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------ | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------- | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Description check | ✅ Passed | The description clearly explains the image sampling offset bug, the implementation, and the related tests. It is directly related to the changeset. | | Title check | ✅ Passed | The title clearly and concisely identifies the main change: applying texel offsets for image_sample*_o instructions. | </details> <details> <summary>Full details: Docstring Coverage</summary> **Explanation** Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 3 files. (1 skipped: 1 too large.) </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autopilot</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1220)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 18:46 UTC · original · edited 2026-10-08 21:08 UTC
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp line 681 (outdated):

@@ -615,6 +619,94 @@ uint32_t StoreTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t d
 	return PackImageTexel(ctx, mem, texel);
 }
 
+// Texel offsets of SAMPLE*_O are three 6-bit signed values at bits [5:0], [13:8] and
+// [21:16] of one address DWORD. Returns them when the DWORD is an IR immediate.
+std::optional<std::array<int32_t, 3>> ConstantSampleOffsets(const IR::MemoryInfo& mem,
+                                                            const IR::Inst&       address,
+                                                            uint32_t              component) {
+	const auto layout = Decoder::ImageAddressComponentLayout(mem.image_sample_flags, component);
+	const auto packed = layout.bit_offset / 32u;
+	if (packed >= address.NumArgs()) return std::array<int32_t, 3> {};
+	auto value = address.Arg(packed).Resolve();
+	// The translator wraps the offset DWORD in select(exec, offset, 0): lanes that consume the
+	// sample take the true arm, so a constant there is the offset of every live lane.
+	if (const auto* select = value.TryInstruction();
+	    select != nullptr && select->GetOpcode() == IR::ValueOpcode::SelectU32 &&
+	    select->NumArgs() == 3u && select->Arg(2).Resolve().IsImmediate() &&
+	    select->Arg(2).Resolve().U32() == 0u) {
+		value = select->Arg(1).Resolve();
+	}
+	if (!value.IsImmediate()) return std::nullopt;
+	const auto bits = value.U32();
+	std::array<int32_t, 3> offsets {};
+	for (uint32_t index = 0; index < offsets.size(); index++) {
+		offsets[index] = static_cast<int32_t>(bits << (26u - index * 8u)) >> 26;
+	}
+	return offsets;
+}
+
+uint32_t ConstSampleOffsetOperand(EmitterState& state, const std::array<int32_t, 3>& offsets,
+                                  uint32_t components) {
+	if (components == 1u) return ConstantI32(state, offsets[0]);
+	const auto x = ConstantI32(state, offsets[0]);
+	const auto y = ConstantI32(state, offsets[1]);
+	if (components == 2u) {
+		return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), x, y);
+	}
+	return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 3), x, y,
+	                              ConstantI32(state, offsets[2]));
+}
+
+// Vulkan only accepts non-constant Offset on gathers and only guarantees ConstOffset values in
+// [-8, 7], so other offsets move the coordinates by offset / size of the sampled mip level.
+uint32_t OffsetSampleCoordinates(ValueEmitContext& ctx, const IR::MemoryInfo& mem,
+                                 const IR::Inst& address, uint32_t offset_component,
+                                 uint32_t resource, uint32_t array_index, uint32_t coord,
+                                 uint32_t level) {
+	auto&       state = ctx.state;
+	const auto& info  = ImageDimensionInfoFor(state.program.info.images[resource].dimension);
+	state.builder.RequireCapability(spv::CapabilityImageQuery);
+	const auto rounded = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpExtInst, TypeF32(state), rounded, GlslStd450(state),
+	                          GLSLstd450Floor,
+	                          Binary(state, spv::OpFAdd, TypeF32(state), level,
+	                                 ConstantF32(state, 0x3f000000u)));
+	const auto clamped = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpExtInst, TypeF32(state), clamped, GlslStd450(state),
+	                          GLSLstd450FMax, rounded, ZeroF32(state));
+	const auto level_u32 = Unary(state, spv::OpConvertFToU, TypeU32(state), clamped);
+	const auto image     = LoadImageDescriptor(state, resource, 0u, array_index);
+	const auto size      = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, info.dimension),
+	                          size, image, level_u32);

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Clamp the level before querying mip dimensions.

If an explicit LOD exceeds the image view’s last level, level_u32 can exceed its level count. Vulkan leaves the OpImageQuerySizeLod result undefined in that case. The fallback then divides the offset by undefined dimensions. Clamp the query level to the view’s last available level before OpImageQuerySizeLod. (docs.vulkan.org)

✅ Confirmed as addressed by @⁠TheCruZ

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 18:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#discussion_r4222869713) · edited 2026-10-08 21:08 UTC On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` line 681 (outdated): ```diff @@ -615,6 +619,94 @@ uint32_t StoreTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t d return PackImageTexel(ctx, mem, texel); } +// Texel offsets of SAMPLE*_O are three 6-bit signed values at bits [5:0], [13:8] and +// [21:16] of one address DWORD. Returns them when the DWORD is an IR immediate. +std::optional<std::array<int32_t, 3>> ConstantSampleOffsets(const IR::MemoryInfo& mem, + const IR::Inst& address, + uint32_t component) { + const auto layout = Decoder::ImageAddressComponentLayout(mem.image_sample_flags, component); + const auto packed = layout.bit_offset / 32u; + if (packed >= address.NumArgs()) return std::array<int32_t, 3> {}; + auto value = address.Arg(packed).Resolve(); + // The translator wraps the offset DWORD in select(exec, offset, 0): lanes that consume the + // sample take the true arm, so a constant there is the offset of every live lane. + if (const auto* select = value.TryInstruction(); + select != nullptr && select->GetOpcode() == IR::ValueOpcode::SelectU32 && + select->NumArgs() == 3u && select->Arg(2).Resolve().IsImmediate() && + select->Arg(2).Resolve().U32() == 0u) { + value = select->Arg(1).Resolve(); + } + if (!value.IsImmediate()) return std::nullopt; + const auto bits = value.U32(); + std::array<int32_t, 3> offsets {}; + for (uint32_t index = 0; index < offsets.size(); index++) { + offsets[index] = static_cast<int32_t>(bits << (26u - index * 8u)) >> 26; + } + return offsets; +} + +uint32_t ConstSampleOffsetOperand(EmitterState& state, const std::array<int32_t, 3>& offsets, + uint32_t components) { + if (components == 1u) return ConstantI32(state, offsets[0]); + const auto x = ConstantI32(state, offsets[0]); + const auto y = ConstantI32(state, offsets[1]); + if (components == 2u) { + return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), x, y); + } + return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 3), x, y, + ConstantI32(state, offsets[2])); +} + +// Vulkan only accepts non-constant Offset on gathers and only guarantees ConstOffset values in +// [-8, 7], so other offsets move the coordinates by offset / size of the sampled mip level. +uint32_t OffsetSampleCoordinates(ValueEmitContext& ctx, const IR::MemoryInfo& mem, + const IR::Inst& address, uint32_t offset_component, + uint32_t resource, uint32_t array_index, uint32_t coord, + uint32_t level) { + auto& state = ctx.state; + const auto& info = ImageDimensionInfoFor(state.program.info.images[resource].dimension); + state.builder.RequireCapability(spv::CapabilityImageQuery); + const auto rounded = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpExtInst, TypeF32(state), rounded, GlslStd450(state), + GLSLstd450Floor, + Binary(state, spv::OpFAdd, TypeF32(state), level, + ConstantF32(state, 0x3f000000u))); + const auto clamped = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpExtInst, TypeF32(state), clamped, GlslStd450(state), + GLSLstd450FMax, rounded, ZeroF32(state)); + const auto level_u32 = Unary(state, spv::OpConvertFToU, TypeU32(state), clamped); + const auto image = LoadImageDescriptor(state, resource, 0u, array_index); + const auto size = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, info.dimension), + size, image, level_u32); ``` **🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win** **Clamp the level before querying mip dimensions.** If an explicit LOD exceeds the image view’s last level, `level_u32` can exceed its level count. Vulkan leaves the `OpImageQuerySizeLod` result undefined in that case. The fallback then divides the offset by undefined dimensions. Clamp the query level to the view’s last available level before `OpImageQuerySizeLod`. ([docs.vulkan.org](https://docs.vulkan.org/spec/latest/chapters/images.html?utm_source=openai)) <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:02062f5bf66d5d1d2cd3bf3c --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠TheCruZ <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 18:46 UTC · original · edited 2026-10-08 20:53 UTC
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp line 704 (outdated):

@@ -615,6 +619,94 @@ uint32_t StoreTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t d
 	return PackImageTexel(ctx, mem, texel);
 }
 
+// Texel offsets of SAMPLE*_O are three 6-bit signed values at bits [5:0], [13:8] and
+// [21:16] of one address DWORD. Returns them when the DWORD is an IR immediate.
+std::optional<std::array<int32_t, 3>> ConstantSampleOffsets(const IR::MemoryInfo& mem,
+                                                            const IR::Inst&       address,
+                                                            uint32_t              component) {
+	const auto layout = Decoder::ImageAddressComponentLayout(mem.image_sample_flags, component);
+	const auto packed = layout.bit_offset / 32u;
+	if (packed >= address.NumArgs()) return std::array<int32_t, 3> {};
+	auto value = address.Arg(packed).Resolve();
+	// The translator wraps the offset DWORD in select(exec, offset, 0): lanes that consume the
+	// sample take the true arm, so a constant there is the offset of every live lane.
+	if (const auto* select = value.TryInstruction();
+	    select != nullptr && select->GetOpcode() == IR::ValueOpcode::SelectU32 &&
+	    select->NumArgs() == 3u && select->Arg(2).Resolve().IsImmediate() &&
+	    select->Arg(2).Resolve().U32() == 0u) {
+		value = select->Arg(1).Resolve();
+	}
+	if (!value.IsImmediate()) return std::nullopt;
+	const auto bits = value.U32();
+	std::array<int32_t, 3> offsets {};
+	for (uint32_t index = 0; index < offsets.size(); index++) {
+		offsets[index] = static_cast<int32_t>(bits << (26u - index * 8u)) >> 26;
+	}
+	return offsets;
+}
+
+uint32_t ConstSampleOffsetOperand(EmitterState& state, const std::array<int32_t, 3>& offsets,
+                                  uint32_t components) {
+	if (components == 1u) return ConstantI32(state, offsets[0]);
+	const auto x = ConstantI32(state, offsets[0]);
+	const auto y = ConstantI32(state, offsets[1]);
+	if (components == 2u) {
+		return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), x, y);
+	}
+	return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 3), x, y,
+	                              ConstantI32(state, offsets[2]));
+}
+
+// Vulkan only accepts non-constant Offset on gathers and only guarantees ConstOffset values in
+// [-8, 7], so other offsets move the coordinates by offset / size of the sampled mip level.
+uint32_t OffsetSampleCoordinates(ValueEmitContext& ctx, const IR::MemoryInfo& mem,
+                                 const IR::Inst& address, uint32_t offset_component,
+                                 uint32_t resource, uint32_t array_index, uint32_t coord,
+                                 uint32_t level) {
+	auto&       state = ctx.state;
+	const auto& info  = ImageDimensionInfoFor(state.program.info.images[resource].dimension);
+	state.builder.RequireCapability(spv::CapabilityImageQuery);
+	const auto rounded = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpExtInst, TypeF32(state), rounded, GlslStd450(state),
+	                          GLSLstd450Floor,
+	                          Binary(state, spv::OpFAdd, TypeF32(state), level,
+	                                 ConstantF32(state, 0x3f000000u)));
+	const auto clamped = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpExtInst, TypeF32(state), clamped, GlslStd450(state),
+	                          GLSLstd450FMax, rounded, ZeroF32(state));
+	const auto level_u32 = Unary(state, spv::OpConvertFToU, TypeU32(state), clamped);
+	const auto image     = LoadImageDescriptor(state, resource, 0u, array_index);
+	const auto size      = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, info.dimension),
+	                          size, image, level_u32);
+	const auto packed = Unary(state, spv::OpBitcast, TypeI32(state),
+	                          AddressU32(ctx, mem, address, offset_component));
+	auto result = coord;
+	for (uint32_t index = 0; index < info.spatial_components; index++) {
+		const auto offset = state.builder.AllocateId();
+		state.builder.AddFunction(spv::OpBitFieldSExtract, TypeI32(state), offset, packed,
+		                          ConstantU32(state, index * 8u), ConstantU32(state, 6));
+		auto extent = size;
+		auto value  = coord;
+		if (info.coordinate_components != 1u) {
+			extent = state.builder.AllocateId();
+			state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(state), extent, size, index);
+			value = state.builder.AllocateId();
+			state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), value, coord, index);
+		}
+		const auto delta = Binary(state, spv::OpFDiv, TypeF32(state),
+		                          Unary(state, spv::OpConvertSToF, TypeF32(state), offset),
+		                          Unary(state, spv::OpConvertUToF, TypeF32(state), extent));
+		const auto moved = Binary(state, spv::OpFAdd, TypeF32(state), value, delta);
+		if (info.coordinate_components == 1u) return moved;
+		const auto inserted = state.builder.AllocateId();
+		state.builder.AddFunction(spv::OpCompositeInsert, TypeF32Vector(state, info.coordinate_components),
+		                          inserted, moved, result, index);

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '660,710p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
rg -n 'unnormalizedCoordinates|UnnormalizedCoordinates|unnormalized_coordinates|unnormalized' src/graphics/shader/recompiler src/graphics

Repository: KytyPS5/KytyPS5

Length of output: 3323


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- changed hunks and callers ---'
git diff --unified=80 58978d154a57cb5f4d68867c8e966af42fc7770c d910353575d2a6e2c3d58768782553cff00eb25e -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
printf '%s\n' '--- OffsetSampleCoordinates references ---'
rg -n -F -- 'OffsetSampleCoordinates' src/graphics/shader/recompiler
printf '%s\n' '--- ForceUnormCoords references/definition ---'
rg -n -F -- 'ForceUnormCoords' src/graphics
printf '%s\n' '--- sampler cache surrounding code ---'
sed -n '1,220p' src/graphics/host_gpu/renderer/cache/samplerCache.cpp
printf '%s\n' '--- sampler-related declarations ---'
rg -n -F -- 'ForceUnormCoords' src include || true
rg -n -i -- 'unnormalizedCoordinates|UnnormalizedCoordinates|ForceUnorm|normalized coordinates|normaliz' src/graphics/shader src/graphics/host_gpu | head -200

Repository: KytyPS5/KytyPS5

Length of output: 42294


🏁 Script executed:

set -o pipefail
git diff --unified=80 58978d154a57cb5f4d68867c8e966af42fc7770c d910353575d2a6e2c3d58768782553cff00eb25e -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
rg -n -F -- 'OffsetSampleCoordinates' src/graphics/shader/recompiler
rg -n -F -- 'ForceUnormCoords' src/graphics
sed -n '1,220p' src/graphics/host_gpu/renderer/cache/samplerCache.cpp
rg -n -i -- 'unnormalizedCoordinates|UnnormalizedCoordinates|ForceUnorm|normalized coordinates' src/graphics/shader src/graphics/host_gpu

Repository: KytyPS5/KytyPS5

Length of output: 35466


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- sampler resource declaration and callers ---'
sed -n '90,165p' src/graphics/shader/shaderBindings.h
rg -n -F -- 'GetSampler(' src/graphics
rg -n -F -- 'LoadSamplerDescriptor' src/graphics/shader/recompiler
printf '%s\n' '--- image offset definitions and decoding ---'
rg -n -i -- 'ImageSampleFlagOffset|IMAGE_SAMPLE|SAMPLE.*_O|image_sample_flags|offset' src/graphics/shader/recompiler/frontend src/graphics/shader/recompiler/ir | head -300
printf '%s\n' '--- coordinate helpers and emitted sample context ---'
rg -n -F -- 'CoordF32' src/graphics/shader/recompiler/backend/spirv
sed -n '880,970p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
printf '%s\n' '--- descriptor/pipeline validation involving samplers or dimensions ---'
rg -n -i -- 'sampler.*(dimension|unnorm|normalized)|unnorm.*sampler|ForceUnorm|image.*sampler|sampler.*image' src/graphics | head -300

Repository: KytyPS5/KytyPS5

Length of output: 42211


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- coordinate helper and dimension metadata ---'
sed -n '120,190p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
rg -n -F -- 'ImageDimensionInfoFor' src/graphics/shader/recompiler
rg -n -F -- 'CoordF32' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
printf '%s\n' '--- image address construction for sampled images ---'
sed -n '300,370p' src/graphics/shader/recompiler/frontend/translate/Memory.cpp
sed -n '680,735p' src/graphics/shader/recompiler/frontend/translate/Memory.cpp
printf '%s\n' '--- sampler descriptor binding path ---'
sed -n '700,750p' src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
sed -n '150,195p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterAnalysis.cpp
printf '%s\n' '--- image dimension declarations ---'
rg -n -i -- 'struct ImageDimension|coordinate_components|spatial_components|enum class ImageDimension' src/graphics/shader/recompiler

Repository: KytyPS5/KytyPS5

Length of output: 21020


🌐 Web query:

Khronos Vulkan specification sampler unnormalizedCoordinates texel coordinates restrictions

💡 Result:

With `unnormalizedCoordinates = VK_TRUE`, shader coordinates are **unnormalized texel-space coordinates**: each component ranges from zero to the image size in that dimension—not the normalized 0–1 range. ([docs.vulkan.org](https://docs.vulkan.org/spec/latest/chapters/samplers.html))

The Vulkan specification requires:

- A **1D or 2D** image view with exactly **one layer and one mip level**.
- Sampling functions must not use **projection or offsets**.
- `minFilter` and `magFilter` must match; `mipmapMode` must be `VK_SAMPLER_MIPMAP_MODE_NEAREST`; `minLod` and `maxLod` must both be zero.
- U and V address modes must each be `CLAMP_TO_EDGE` or `CLAMP_TO_BORDER`.
- Anisotropy and comparison sampling must be disabled. ([docs.vulkan.org](https://docs.vulkan.org/spec/latest/chapters/samplers.html))

These are the current Vulkan specification’s stated restrictions; the cited pages do not identify a specific Vulkan version.

Citations:

- 1: https://docs.vulkan.org/spec/latest/chapters/samplers.html
- 2: https://docs.vulkan.org/spec/latest/chapters/samplers.html

🏁 Script executed:

set -o pipefail
printf '%s\n' '--- sampler metadata and available mode information ---'
rg -n -i -- 'struct .*Sampler|force_.*sampler|samplers\b|SamplerInfo|sampler.*force|force.*unorm' src/graphics/shader/recompiler src/graphics/host_gpu/renderer/pipeline
sed -n '80,145p' src/graphics/shader/recompiler/ir/ShaderIR.h
sed -n '1260,1330p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp

Repository: KytyPS5/KytyPS5

Length of output: 13814


Apply the offset in texel space for unnormalized samplers.

When ForceUnormCoords() is set, Vulkan interprets sampling coordinates as texel coordinates. The fallback currently adds float(offset) / float(extent), which is valid only for normalized coordinates. For an unnormalized sampler, this can leave the sample on the original texel or produce a different sampled value instead of applying the requested texel offset.

Select the coordinate-space conversion from the sampler mode. Add the signed offset directly for unnormalized samplers, and keep division by the mip extent for normalized samplers.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 18:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#discussion_r4222869717) · edited 2026-10-08 20:53 UTC On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` line 704 (outdated): ```diff @@ -615,6 +619,94 @@ uint32_t StoreTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t d return PackImageTexel(ctx, mem, texel); } +// Texel offsets of SAMPLE*_O are three 6-bit signed values at bits [5:0], [13:8] and +// [21:16] of one address DWORD. Returns them when the DWORD is an IR immediate. +std::optional<std::array<int32_t, 3>> ConstantSampleOffsets(const IR::MemoryInfo& mem, + const IR::Inst& address, + uint32_t component) { + const auto layout = Decoder::ImageAddressComponentLayout(mem.image_sample_flags, component); + const auto packed = layout.bit_offset / 32u; + if (packed >= address.NumArgs()) return std::array<int32_t, 3> {}; + auto value = address.Arg(packed).Resolve(); + // The translator wraps the offset DWORD in select(exec, offset, 0): lanes that consume the + // sample take the true arm, so a constant there is the offset of every live lane. + if (const auto* select = value.TryInstruction(); + select != nullptr && select->GetOpcode() == IR::ValueOpcode::SelectU32 && + select->NumArgs() == 3u && select->Arg(2).Resolve().IsImmediate() && + select->Arg(2).Resolve().U32() == 0u) { + value = select->Arg(1).Resolve(); + } + if (!value.IsImmediate()) return std::nullopt; + const auto bits = value.U32(); + std::array<int32_t, 3> offsets {}; + for (uint32_t index = 0; index < offsets.size(); index++) { + offsets[index] = static_cast<int32_t>(bits << (26u - index * 8u)) >> 26; + } + return offsets; +} + +uint32_t ConstSampleOffsetOperand(EmitterState& state, const std::array<int32_t, 3>& offsets, + uint32_t components) { + if (components == 1u) return ConstantI32(state, offsets[0]); + const auto x = ConstantI32(state, offsets[0]); + const auto y = ConstantI32(state, offsets[1]); + if (components == 2u) { + return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), x, y); + } + return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 3), x, y, + ConstantI32(state, offsets[2])); +} + +// Vulkan only accepts non-constant Offset on gathers and only guarantees ConstOffset values in +// [-8, 7], so other offsets move the coordinates by offset / size of the sampled mip level. +uint32_t OffsetSampleCoordinates(ValueEmitContext& ctx, const IR::MemoryInfo& mem, + const IR::Inst& address, uint32_t offset_component, + uint32_t resource, uint32_t array_index, uint32_t coord, + uint32_t level) { + auto& state = ctx.state; + const auto& info = ImageDimensionInfoFor(state.program.info.images[resource].dimension); + state.builder.RequireCapability(spv::CapabilityImageQuery); + const auto rounded = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpExtInst, TypeF32(state), rounded, GlslStd450(state), + GLSLstd450Floor, + Binary(state, spv::OpFAdd, TypeF32(state), level, + ConstantF32(state, 0x3f000000u))); + const auto clamped = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpExtInst, TypeF32(state), clamped, GlslStd450(state), + GLSLstd450FMax, rounded, ZeroF32(state)); + const auto level_u32 = Unary(state, spv::OpConvertFToU, TypeU32(state), clamped); + const auto image = LoadImageDescriptor(state, resource, 0u, array_index); + const auto size = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, info.dimension), + size, image, level_u32); + const auto packed = Unary(state, spv::OpBitcast, TypeI32(state), + AddressU32(ctx, mem, address, offset_component)); + auto result = coord; + for (uint32_t index = 0; index < info.spatial_components; index++) { + const auto offset = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitFieldSExtract, TypeI32(state), offset, packed, + ConstantU32(state, index * 8u), ConstantU32(state, 6)); + auto extent = size; + auto value = coord; + if (info.coordinate_components != 1u) { + extent = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(state), extent, size, index); + value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), value, coord, index); + } + const auto delta = Binary(state, spv::OpFDiv, TypeF32(state), + Unary(state, spv::OpConvertSToF, TypeF32(state), offset), + Unary(state, spv::OpConvertUToF, TypeF32(state), extent)); + const auto moved = Binary(state, spv::OpFAdd, TypeF32(state), value, delta); + if (info.coordinate_components == 1u) return moved; + const auto inserted = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeInsert, TypeF32Vector(state, info.coordinate_components), + inserted, moved, result, index); ``` **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '660,710p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp rg -n 'unnormalizedCoordinates|UnnormalizedCoordinates|unnormalized_coordinates|unnormalized' src/graphics/shader/recompiler src/graphics ``` Repository: KytyPS5/KytyPS5 Length of output: 3323 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- changed hunks and callers ---' git diff --unified=80 58978d154a57cb5f4d68867c8e966af42fc7770c d910353575d2a6e2c3d58768782553cff00eb25e -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp printf '%s\n' '--- OffsetSampleCoordinates references ---' rg -n -F -- 'OffsetSampleCoordinates' src/graphics/shader/recompiler printf '%s\n' '--- ForceUnormCoords references/definition ---' rg -n -F -- 'ForceUnormCoords' src/graphics printf '%s\n' '--- sampler cache surrounding code ---' sed -n '1,220p' src/graphics/host_gpu/renderer/cache/samplerCache.cpp printf '%s\n' '--- sampler-related declarations ---' rg -n -F -- 'ForceUnormCoords' src include || true rg -n -i -- 'unnormalizedCoordinates|UnnormalizedCoordinates|ForceUnorm|normalized coordinates|normaliz' src/graphics/shader src/graphics/host_gpu | head -200 ``` Repository: KytyPS5/KytyPS5 Length of output: 42294 --- 🏁 Script executed: ```bash set -o pipefail git diff --unified=80 58978d154a57cb5f4d68867c8e966af42fc7770c d910353575d2a6e2c3d58768782553cff00eb25e -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp rg -n -F -- 'OffsetSampleCoordinates' src/graphics/shader/recompiler rg -n -F -- 'ForceUnormCoords' src/graphics sed -n '1,220p' src/graphics/host_gpu/renderer/cache/samplerCache.cpp rg -n -i -- 'unnormalizedCoordinates|UnnormalizedCoordinates|ForceUnorm|normalized coordinates' src/graphics/shader src/graphics/host_gpu ``` Repository: KytyPS5/KytyPS5 Length of output: 35466 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- sampler resource declaration and callers ---' sed -n '90,165p' src/graphics/shader/shaderBindings.h rg -n -F -- 'GetSampler(' src/graphics rg -n -F -- 'LoadSamplerDescriptor' src/graphics/shader/recompiler printf '%s\n' '--- image offset definitions and decoding ---' rg -n -i -- 'ImageSampleFlagOffset|IMAGE_SAMPLE|SAMPLE.*_O|image_sample_flags|offset' src/graphics/shader/recompiler/frontend src/graphics/shader/recompiler/ir | head -300 printf '%s\n' '--- coordinate helpers and emitted sample context ---' rg -n -F -- 'CoordF32' src/graphics/shader/recompiler/backend/spirv sed -n '880,970p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp printf '%s\n' '--- descriptor/pipeline validation involving samplers or dimensions ---' rg -n -i -- 'sampler.*(dimension|unnorm|normalized)|unnorm.*sampler|ForceUnorm|image.*sampler|sampler.*image' src/graphics | head -300 ``` Repository: KytyPS5/KytyPS5 Length of output: 42211 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- coordinate helper and dimension metadata ---' sed -n '120,190p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp rg -n -F -- 'ImageDimensionInfoFor' src/graphics/shader/recompiler rg -n -F -- 'CoordF32' src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp printf '%s\n' '--- image address construction for sampled images ---' sed -n '300,370p' src/graphics/shader/recompiler/frontend/translate/Memory.cpp sed -n '680,735p' src/graphics/shader/recompiler/frontend/translate/Memory.cpp printf '%s\n' '--- sampler descriptor binding path ---' sed -n '700,750p' src/graphics/host_gpu/renderer/pipeline/descriptors.cpp sed -n '150,195p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterAnalysis.cpp printf '%s\n' '--- image dimension declarations ---' rg -n -i -- 'struct ImageDimension|coordinate_components|spatial_components|enum class ImageDimension' src/graphics/shader/recompiler ``` Repository: KytyPS5/KytyPS5 Length of output: 21020 --- 🌐 Web query: `Khronos Vulkan specification sampler unnormalizedCoordinates texel coordinates restrictions` 💡 Result: ``` With `unnormalizedCoordinates = VK_TRUE`, shader coordinates are **unnormalized texel-space coordinates**: each component ranges from zero to the image size in that dimension—not the normalized 0–1 range. ([docs.vulkan.org](https://docs.vulkan.org/spec/latest/chapters/samplers.html)) The Vulkan specification requires: - A **1D or 2D** image view with exactly **one layer and one mip level**. - Sampling functions must not use **projection or offsets**. - `minFilter` and `magFilter` must match; `mipmapMode` must be `VK_SAMPLER_MIPMAP_MODE_NEAREST`; `minLod` and `maxLod` must both be zero. - U and V address modes must each be `CLAMP_TO_EDGE` or `CLAMP_TO_BORDER`. - Anisotropy and comparison sampling must be disabled. ([docs.vulkan.org](https://docs.vulkan.org/spec/latest/chapters/samplers.html)) These are the current Vulkan specification’s stated restrictions; the cited pages do not identify a specific Vulkan version. Citations: - 1: https://docs.vulkan.org/spec/latest/chapters/samplers.html - 2: https://docs.vulkan.org/spec/latest/chapters/samplers.html ``` --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- sampler metadata and available mode information ---' rg -n -i -- 'struct .*Sampler|force_.*sampler|samplers\b|SamplerInfo|sampler.*force|force.*unorm' src/graphics/shader/recompiler src/graphics/host_gpu/renderer/pipeline sed -n '80,145p' src/graphics/shader/recompiler/ir/ShaderIR.h sed -n '1260,1330p' src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 13814 --- </details> **Apply the offset in texel space for unnormalized samplers.** When `ForceUnormCoords()` is set, Vulkan interprets sampling coordinates as texel coordinates. The fallback currently adds `float(offset) / float(extent)`, which is valid only for normalized coordinates. For an unnormalized sampler, this can leave the sample on the original texel or produce a different sampled value instead of applying the requested texel offset. Select the coordinate-space conversion from the sampler mode. Add the signed offset directly for unnormalized samplers, and keep division by the mip extent for normalized samplers. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:2d38c5e0bde7d789fd9674f4 --> <!-- This is an auto-generated reply by CodeRabbit -->
@ -821,0 +997,4 @@
level = Binary(state, spv::OpFAdd, TypeF32(state), level,
AddressF32(ctx, mem, *address, layout.bias));
}
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 18:46 UTC · original · edited 2026-10-08 21:08 UTC

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Derive fallback dimensions from the sample’s LOD inputs.

If a runtime offset accompanies Grad or instruction Bias, this branch uses OpImageQueryLod to choose dimensions. That query models an implicit-LOD sample; it does not receive this sample’s explicit gradients or bias. The fallback can therefore divide by the wrong mip dimensions and shift the sampled texel incorrectly. Account for the actual Grad or Bias inputs when selecting the dimensions. (registry.khronos.org)

✅ Confirmed as addressed by @⁠TheCruZ

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 18:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#discussion_r4222869727) · edited 2026-10-08 21:08 UTC **🎯 Functional Correctness** | **🟠 Major** | **🏗️ Heavy lift** **Derive fallback dimensions from the sample’s LOD inputs.** If a runtime offset accompanies `Grad` or instruction `Bias`, this branch uses `OpImageQueryLod` to choose dimensions. That query models an implicit-LOD sample; it does not receive this sample’s explicit gradients or bias. The fallback can therefore divide by the wrong mip dimensions and shift the sampled texel incorrectly. Account for the actual `Grad` or `Bias` inputs when selecting the dimensions. ([registry.khronos.org](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html)) <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:781bf2128df9425daec31847 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠TheCruZ <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 18:46 UTC · original · reviewed

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3d74cb8d-83a7-4ea0-8f71-4fe06a15dfdf
📥 Commits

Reviewing files that changed from the base of the PR and between 2f4b8a335d and d910353575d2a6e2c3d58768782553cff00eb25e.

📒 Files selected for processing (4)
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp
  • src/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp
  • tests/ShaderRecompilerComputeTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 18:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#pullrequestreview-5461358712) · **reviewed** **Actionable comments posted: 3** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `3d74cb8d-83a7-4ea0-8f71-4fe06a15dfdf` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 2f4b8a335d5e27a5153bdea670bd877a061e37b1 and d910353575d2a6e2c3d58768782553cff00eb25e. </details> <details> <summary>📒 Files selected for processing (4)</summary> * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` * `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` * `src/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=a558d291-18a3-432f-a451-b70ae0d910c5 attempt=617aefe2-6280-4536-a085-1d6d627ac0e9 batch=1/1 -->
Author
Owner

@⁠TheCruZ on GitHub · 2026-10-08 20:53 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp line 704 (outdated):

@@ -615,6 +619,94 @@ uint32_t StoreTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t d
 	return PackImageTexel(ctx, mem, texel);
 }
 
+// Texel offsets of SAMPLE*_O are three 6-bit signed values at bits [5:0], [13:8] and
+// [21:16] of one address DWORD. Returns them when the DWORD is an IR immediate.
+std::optional<std::array<int32_t, 3>> ConstantSampleOffsets(const IR::MemoryInfo& mem,
+                                                            const IR::Inst&       address,
+                                                            uint32_t              component) {
+	const auto layout = Decoder::ImageAddressComponentLayout(mem.image_sample_flags, component);
+	const auto packed = layout.bit_offset / 32u;
+	if (packed >= address.NumArgs()) return std::array<int32_t, 3> {};
+	auto value = address.Arg(packed).Resolve();
+	// The translator wraps the offset DWORD in select(exec, offset, 0): lanes that consume the
+	// sample take the true arm, so a constant there is the offset of every live lane.
+	if (const auto* select = value.TryInstruction();
+	    select != nullptr && select->GetOpcode() == IR::ValueOpcode::SelectU32 &&
+	    select->NumArgs() == 3u && select->Arg(2).Resolve().IsImmediate() &&
+	    select->Arg(2).Resolve().U32() == 0u) {
+		value = select->Arg(1).Resolve();
+	}
+	if (!value.IsImmediate()) return std::nullopt;
+	const auto bits = value.U32();
+	std::array<int32_t, 3> offsets {};
+	for (uint32_t index = 0; index < offsets.size(); index++) {
+		offsets[index] = static_cast<int32_t>(bits << (26u - index * 8u)) >> 26;
+	}
+	return offsets;
+}
+
+uint32_t ConstSampleOffsetOperand(EmitterState& state, const std::array<int32_t, 3>& offsets,
+                                  uint32_t components) {
+	if (components == 1u) return ConstantI32(state, offsets[0]);
+	const auto x = ConstantI32(state, offsets[0]);
+	const auto y = ConstantI32(state, offsets[1]);
+	if (components == 2u) {
+		return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), x, y);
+	}
+	return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 3), x, y,
+	                              ConstantI32(state, offsets[2]));
+}
+
+// Vulkan only accepts non-constant Offset on gathers and only guarantees ConstOffset values in
+// [-8, 7], so other offsets move the coordinates by offset / size of the sampled mip level.
+uint32_t OffsetSampleCoordinates(ValueEmitContext& ctx, const IR::MemoryInfo& mem,
+                                 const IR::Inst& address, uint32_t offset_component,
+                                 uint32_t resource, uint32_t array_index, uint32_t coord,
+                                 uint32_t level) {
+	auto&       state = ctx.state;
+	const auto& info  = ImageDimensionInfoFor(state.program.info.images[resource].dimension);
+	state.builder.RequireCapability(spv::CapabilityImageQuery);
+	const auto rounded = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpExtInst, TypeF32(state), rounded, GlslStd450(state),
+	                          GLSLstd450Floor,
+	                          Binary(state, spv::OpFAdd, TypeF32(state), level,
+	                                 ConstantF32(state, 0x3f000000u)));
+	const auto clamped = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpExtInst, TypeF32(state), clamped, GlslStd450(state),
+	                          GLSLstd450FMax, rounded, ZeroF32(state));
+	const auto level_u32 = Unary(state, spv::OpConvertFToU, TypeU32(state), clamped);
+	const auto image     = LoadImageDescriptor(state, resource, 0u, array_index);
+	const auto size      = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, info.dimension),
+	                          size, image, level_u32);
+	const auto packed = Unary(state, spv::OpBitcast, TypeI32(state),
+	                          AddressU32(ctx, mem, address, offset_component));
+	auto result = coord;
+	for (uint32_t index = 0; index < info.spatial_components; index++) {
+		const auto offset = state.builder.AllocateId();
+		state.builder.AddFunction(spv::OpBitFieldSExtract, TypeI32(state), offset, packed,
+		                          ConstantU32(state, index * 8u), ConstantU32(state, 6));
+		auto extent = size;
+		auto value  = coord;
+		if (info.coordinate_components != 1u) {
+			extent = state.builder.AllocateId();
+			state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(state), extent, size, index);
+			value = state.builder.AllocateId();
+			state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), value, coord, index);
+		}
+		const auto delta = Binary(state, spv::OpFDiv, TypeF32(state),
+		                          Unary(state, spv::OpConvertSToF, TypeF32(state), offset),
+		                          Unary(state, spv::OpConvertUToF, TypeF32(state), extent));
+		const auto moved = Binary(state, spv::OpFAdd, TypeF32(state), value, delta);
+		if (info.coordinate_components == 1u) return moved;
+		const auto inserted = state.builder.AllocateId();
+		state.builder.AddFunction(spv::OpCompositeInsert, TypeF32Vector(state, info.coordinate_components),
+		                          inserted, moved, result, index);

I'm leaving this one out. Whether a sampler uses unnormalized coordinates is a bit of the runtime S# (ForceUnormCoords), which the shader does not see when it is translated; supporting it would mean passing that word into the shader (or specializing on it) for a combination I haven't seen in any title. Also, Vulkan does not allow ConstOffset/Offset at all on samples through a sampler with unnormalizedCoordinates, so the constant-offset path could not be made valid for that case either; a proper fix would have to emulate the whole unnormalized sample, which is out of scope for this PR.

**@⁠TheCruZ** on GitHub · 2026-10-08 20:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#discussion_r4224021352) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` line 704 (outdated): ```diff @@ -615,6 +619,94 @@ uint32_t StoreTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t d return PackImageTexel(ctx, mem, texel); } +// Texel offsets of SAMPLE*_O are three 6-bit signed values at bits [5:0], [13:8] and +// [21:16] of one address DWORD. Returns them when the DWORD is an IR immediate. +std::optional<std::array<int32_t, 3>> ConstantSampleOffsets(const IR::MemoryInfo& mem, + const IR::Inst& address, + uint32_t component) { + const auto layout = Decoder::ImageAddressComponentLayout(mem.image_sample_flags, component); + const auto packed = layout.bit_offset / 32u; + if (packed >= address.NumArgs()) return std::array<int32_t, 3> {}; + auto value = address.Arg(packed).Resolve(); + // The translator wraps the offset DWORD in select(exec, offset, 0): lanes that consume the + // sample take the true arm, so a constant there is the offset of every live lane. + if (const auto* select = value.TryInstruction(); + select != nullptr && select->GetOpcode() == IR::ValueOpcode::SelectU32 && + select->NumArgs() == 3u && select->Arg(2).Resolve().IsImmediate() && + select->Arg(2).Resolve().U32() == 0u) { + value = select->Arg(1).Resolve(); + } + if (!value.IsImmediate()) return std::nullopt; + const auto bits = value.U32(); + std::array<int32_t, 3> offsets {}; + for (uint32_t index = 0; index < offsets.size(); index++) { + offsets[index] = static_cast<int32_t>(bits << (26u - index * 8u)) >> 26; + } + return offsets; +} + +uint32_t ConstSampleOffsetOperand(EmitterState& state, const std::array<int32_t, 3>& offsets, + uint32_t components) { + if (components == 1u) return ConstantI32(state, offsets[0]); + const auto x = ConstantI32(state, offsets[0]); + const auto y = ConstantI32(state, offsets[1]); + if (components == 2u) { + return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), x, y); + } + return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 3), x, y, + ConstantI32(state, offsets[2])); +} + +// Vulkan only accepts non-constant Offset on gathers and only guarantees ConstOffset values in +// [-8, 7], so other offsets move the coordinates by offset / size of the sampled mip level. +uint32_t OffsetSampleCoordinates(ValueEmitContext& ctx, const IR::MemoryInfo& mem, + const IR::Inst& address, uint32_t offset_component, + uint32_t resource, uint32_t array_index, uint32_t coord, + uint32_t level) { + auto& state = ctx.state; + const auto& info = ImageDimensionInfoFor(state.program.info.images[resource].dimension); + state.builder.RequireCapability(spv::CapabilityImageQuery); + const auto rounded = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpExtInst, TypeF32(state), rounded, GlslStd450(state), + GLSLstd450Floor, + Binary(state, spv::OpFAdd, TypeF32(state), level, + ConstantF32(state, 0x3f000000u))); + const auto clamped = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpExtInst, TypeF32(state), clamped, GlslStd450(state), + GLSLstd450FMax, rounded, ZeroF32(state)); + const auto level_u32 = Unary(state, spv::OpConvertFToU, TypeU32(state), clamped); + const auto image = LoadImageDescriptor(state, resource, 0u, array_index); + const auto size = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, info.dimension), + size, image, level_u32); + const auto packed = Unary(state, spv::OpBitcast, TypeI32(state), + AddressU32(ctx, mem, address, offset_component)); + auto result = coord; + for (uint32_t index = 0; index < info.spatial_components; index++) { + const auto offset = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitFieldSExtract, TypeI32(state), offset, packed, + ConstantU32(state, index * 8u), ConstantU32(state, 6)); + auto extent = size; + auto value = coord; + if (info.coordinate_components != 1u) { + extent = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(state), extent, size, index); + value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), value, coord, index); + } + const auto delta = Binary(state, spv::OpFDiv, TypeF32(state), + Unary(state, spv::OpConvertSToF, TypeF32(state), offset), + Unary(state, spv::OpConvertUToF, TypeF32(state), extent)); + const auto moved = Binary(state, spv::OpFAdd, TypeF32(state), value, delta); + if (info.coordinate_components == 1u) return moved; + const auto inserted = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeInsert, TypeF32Vector(state, info.coordinate_components), + inserted, moved, result, index); ``` I'm leaving this one out. Whether a sampler uses unnormalized coordinates is a bit of the runtime S# (`ForceUnormCoords`), which the shader does not see when it is translated; supporting it would mean passing that word into the shader (or specializing on it) for a combination I haven't seen in any title. Also, Vulkan does not allow `ConstOffset`/`Offset` at all on samples through a sampler with `unnormalizedCoordinates`, so the constant-offset path could not be made valid for that case either; a proper fix would have to emulate the whole unnormalized sample, which is out of scope for this PR.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 20:53 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp line 704 (outdated):

@@ -615,6 +619,94 @@ uint32_t StoreTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t d
 	return PackImageTexel(ctx, mem, texel);
 }
 
+// Texel offsets of SAMPLE*_O are three 6-bit signed values at bits [5:0], [13:8] and
+// [21:16] of one address DWORD. Returns them when the DWORD is an IR immediate.
+std::optional<std::array<int32_t, 3>> ConstantSampleOffsets(const IR::MemoryInfo& mem,
+                                                            const IR::Inst&       address,
+                                                            uint32_t              component) {
+	const auto layout = Decoder::ImageAddressComponentLayout(mem.image_sample_flags, component);
+	const auto packed = layout.bit_offset / 32u;
+	if (packed >= address.NumArgs()) return std::array<int32_t, 3> {};
+	auto value = address.Arg(packed).Resolve();
+	// The translator wraps the offset DWORD in select(exec, offset, 0): lanes that consume the
+	// sample take the true arm, so a constant there is the offset of every live lane.
+	if (const auto* select = value.TryInstruction();
+	    select != nullptr && select->GetOpcode() == IR::ValueOpcode::SelectU32 &&
+	    select->NumArgs() == 3u && select->Arg(2).Resolve().IsImmediate() &&
+	    select->Arg(2).Resolve().U32() == 0u) {
+		value = select->Arg(1).Resolve();
+	}
+	if (!value.IsImmediate()) return std::nullopt;
+	const auto bits = value.U32();
+	std::array<int32_t, 3> offsets {};
+	for (uint32_t index = 0; index < offsets.size(); index++) {
+		offsets[index] = static_cast<int32_t>(bits << (26u - index * 8u)) >> 26;
+	}
+	return offsets;
+}
+
+uint32_t ConstSampleOffsetOperand(EmitterState& state, const std::array<int32_t, 3>& offsets,
+                                  uint32_t components) {
+	if (components == 1u) return ConstantI32(state, offsets[0]);
+	const auto x = ConstantI32(state, offsets[0]);
+	const auto y = ConstantI32(state, offsets[1]);
+	if (components == 2u) {
+		return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), x, y);
+	}
+	return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 3), x, y,
+	                              ConstantI32(state, offsets[2]));
+}
+
+// Vulkan only accepts non-constant Offset on gathers and only guarantees ConstOffset values in
+// [-8, 7], so other offsets move the coordinates by offset / size of the sampled mip level.
+uint32_t OffsetSampleCoordinates(ValueEmitContext& ctx, const IR::MemoryInfo& mem,
+                                 const IR::Inst& address, uint32_t offset_component,
+                                 uint32_t resource, uint32_t array_index, uint32_t coord,
+                                 uint32_t level) {
+	auto&       state = ctx.state;
+	const auto& info  = ImageDimensionInfoFor(state.program.info.images[resource].dimension);
+	state.builder.RequireCapability(spv::CapabilityImageQuery);
+	const auto rounded = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpExtInst, TypeF32(state), rounded, GlslStd450(state),
+	                          GLSLstd450Floor,
+	                          Binary(state, spv::OpFAdd, TypeF32(state), level,
+	                                 ConstantF32(state, 0x3f000000u)));
+	const auto clamped = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpExtInst, TypeF32(state), clamped, GlslStd450(state),
+	                          GLSLstd450FMax, rounded, ZeroF32(state));
+	const auto level_u32 = Unary(state, spv::OpConvertFToU, TypeU32(state), clamped);
+	const auto image     = LoadImageDescriptor(state, resource, 0u, array_index);
+	const auto size      = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, info.dimension),
+	                          size, image, level_u32);
+	const auto packed = Unary(state, spv::OpBitcast, TypeI32(state),
+	                          AddressU32(ctx, mem, address, offset_component));
+	auto result = coord;
+	for (uint32_t index = 0; index < info.spatial_components; index++) {
+		const auto offset = state.builder.AllocateId();
+		state.builder.AddFunction(spv::OpBitFieldSExtract, TypeI32(state), offset, packed,
+		                          ConstantU32(state, index * 8u), ConstantU32(state, 6));
+		auto extent = size;
+		auto value  = coord;
+		if (info.coordinate_components != 1u) {
+			extent = state.builder.AllocateId();
+			state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(state), extent, size, index);
+			value = state.builder.AllocateId();
+			state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), value, coord, index);
+		}
+		const auto delta = Binary(state, spv::OpFDiv, TypeF32(state),
+		                          Unary(state, spv::OpConvertSToF, TypeF32(state), offset),
+		                          Unary(state, spv::OpConvertUToF, TypeF32(state), extent));
+		const auto moved = Binary(state, spv::OpFAdd, TypeF32(state), value, delta);
+		if (info.coordinate_components == 1u) return moved;
+		const auto inserted = state.builder.AllocateId();
+		state.builder.AddFunction(spv::OpCompositeInsert, TypeF32Vector(state, info.coordinate_components),
+		                          inserted, moved, result, index);

@TheCruZ, thanks for the clarification. My suggested coordinate-space switch was incomplete. ForceUnormCoords comes from runtime S# state that the shader translator cannot inspect. Vulkan also forbids ConstOffset and Offset with unnormalizedCoordinates.

I accept leaving this unsupported combination outside this PR. Would you like a follow-up issue for unnormalized sampling with texel offsets?


✏️ Learnings added
Learnt from: TheCruZ
Repo: KytyPS5/KytyPS5 PR: 1220
File: src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp:690-704
Timestamp: 2026-10-08T20:53:30.159Z
Learning: In KytyPS5/KytyPS5, sampler ForceUnormCoords comes from runtime S# state and is not available during shader translation. Supporting unnormalized sampling with texel offsets in src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp requires exposing the sampler mode to the shader or specializing on it. Changing only OffsetSampleCoordinates is insufficient because Vulkan forbids ConstOffset and Offset when unnormalizedCoordinates is enabled.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 20:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#discussion_r4224024971) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` line 704 (outdated): ```diff @@ -615,6 +619,94 @@ uint32_t StoreTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t d return PackImageTexel(ctx, mem, texel); } +// Texel offsets of SAMPLE*_O are three 6-bit signed values at bits [5:0], [13:8] and +// [21:16] of one address DWORD. Returns them when the DWORD is an IR immediate. +std::optional<std::array<int32_t, 3>> ConstantSampleOffsets(const IR::MemoryInfo& mem, + const IR::Inst& address, + uint32_t component) { + const auto layout = Decoder::ImageAddressComponentLayout(mem.image_sample_flags, component); + const auto packed = layout.bit_offset / 32u; + if (packed >= address.NumArgs()) return std::array<int32_t, 3> {}; + auto value = address.Arg(packed).Resolve(); + // The translator wraps the offset DWORD in select(exec, offset, 0): lanes that consume the + // sample take the true arm, so a constant there is the offset of every live lane. + if (const auto* select = value.TryInstruction(); + select != nullptr && select->GetOpcode() == IR::ValueOpcode::SelectU32 && + select->NumArgs() == 3u && select->Arg(2).Resolve().IsImmediate() && + select->Arg(2).Resolve().U32() == 0u) { + value = select->Arg(1).Resolve(); + } + if (!value.IsImmediate()) return std::nullopt; + const auto bits = value.U32(); + std::array<int32_t, 3> offsets {}; + for (uint32_t index = 0; index < offsets.size(); index++) { + offsets[index] = static_cast<int32_t>(bits << (26u - index * 8u)) >> 26; + } + return offsets; +} + +uint32_t ConstSampleOffsetOperand(EmitterState& state, const std::array<int32_t, 3>& offsets, + uint32_t components) { + if (components == 1u) return ConstantI32(state, offsets[0]); + const auto x = ConstantI32(state, offsets[0]); + const auto y = ConstantI32(state, offsets[1]); + if (components == 2u) { + return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), x, y); + } + return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 3), x, y, + ConstantI32(state, offsets[2])); +} + +// Vulkan only accepts non-constant Offset on gathers and only guarantees ConstOffset values in +// [-8, 7], so other offsets move the coordinates by offset / size of the sampled mip level. +uint32_t OffsetSampleCoordinates(ValueEmitContext& ctx, const IR::MemoryInfo& mem, + const IR::Inst& address, uint32_t offset_component, + uint32_t resource, uint32_t array_index, uint32_t coord, + uint32_t level) { + auto& state = ctx.state; + const auto& info = ImageDimensionInfoFor(state.program.info.images[resource].dimension); + state.builder.RequireCapability(spv::CapabilityImageQuery); + const auto rounded = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpExtInst, TypeF32(state), rounded, GlslStd450(state), + GLSLstd450Floor, + Binary(state, spv::OpFAdd, TypeF32(state), level, + ConstantF32(state, 0x3f000000u))); + const auto clamped = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpExtInst, TypeF32(state), clamped, GlslStd450(state), + GLSLstd450FMax, rounded, ZeroF32(state)); + const auto level_u32 = Unary(state, spv::OpConvertFToU, TypeU32(state), clamped); + const auto image = LoadImageDescriptor(state, resource, 0u, array_index); + const auto size = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, info.dimension), + size, image, level_u32); + const auto packed = Unary(state, spv::OpBitcast, TypeI32(state), + AddressU32(ctx, mem, address, offset_component)); + auto result = coord; + for (uint32_t index = 0; index < info.spatial_components; index++) { + const auto offset = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitFieldSExtract, TypeI32(state), offset, packed, + ConstantU32(state, index * 8u), ConstantU32(state, 6)); + auto extent = size; + auto value = coord; + if (info.coordinate_components != 1u) { + extent = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(state), extent, size, index); + value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), value, coord, index); + } + const auto delta = Binary(state, spv::OpFDiv, TypeF32(state), + Unary(state, spv::OpConvertSToF, TypeF32(state), offset), + Unary(state, spv::OpConvertUToF, TypeF32(state), extent)); + const auto moved = Binary(state, spv::OpFAdd, TypeF32(state), value, delta); + if (info.coordinate_components == 1u) return moved; + const auto inserted = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeInsert, TypeF32Vector(state, info.coordinate_components), + inserted, moved, result, index); ``` `@TheCruZ`, thanks for the clarification. My suggested coordinate-space switch was incomplete. `ForceUnormCoords` comes from runtime S# state that the shader translator cannot inspect. Vulkan also forbids `ConstOffset` and `Offset` with `unnormalizedCoordinates`. I accept leaving this unsupported combination outside this PR. Would you like a follow-up issue for unnormalized sampling with texel offsets? --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: TheCruZ Repo: KytyPS5/KytyPS5 PR: 1220 File: src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp:690-704 Timestamp: 2026-10-08T20:53:30.159Z Learning: In KytyPS5/KytyPS5, sampler ForceUnormCoords comes from runtime S# state and is not available during shader translation. Supporting unnormalized sampling with texel offsets in src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp requires exposing the sampler mode to the shader or specializing on it. Changing only OffsetSampleCoordinates is insufficient because Vulkan forbids ConstOffset and Offset when unnormalizedCoordinates is enabled. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠TheCruZ on GitHub · 2026-10-08 21:08 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp line 681 (outdated):

@@ -615,6 +619,94 @@ uint32_t StoreTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t d
 	return PackImageTexel(ctx, mem, texel);
 }
 
+// Texel offsets of SAMPLE*_O are three 6-bit signed values at bits [5:0], [13:8] and
+// [21:16] of one address DWORD. Returns them when the DWORD is an IR immediate.
+std::optional<std::array<int32_t, 3>> ConstantSampleOffsets(const IR::MemoryInfo& mem,
+                                                            const IR::Inst&       address,
+                                                            uint32_t              component) {
+	const auto layout = Decoder::ImageAddressComponentLayout(mem.image_sample_flags, component);
+	const auto packed = layout.bit_offset / 32u;
+	if (packed >= address.NumArgs()) return std::array<int32_t, 3> {};
+	auto value = address.Arg(packed).Resolve();
+	// The translator wraps the offset DWORD in select(exec, offset, 0): lanes that consume the
+	// sample take the true arm, so a constant there is the offset of every live lane.
+	if (const auto* select = value.TryInstruction();
+	    select != nullptr && select->GetOpcode() == IR::ValueOpcode::SelectU32 &&
+	    select->NumArgs() == 3u && select->Arg(2).Resolve().IsImmediate() &&
+	    select->Arg(2).Resolve().U32() == 0u) {
+		value = select->Arg(1).Resolve();
+	}
+	if (!value.IsImmediate()) return std::nullopt;
+	const auto bits = value.U32();
+	std::array<int32_t, 3> offsets {};
+	for (uint32_t index = 0; index < offsets.size(); index++) {
+		offsets[index] = static_cast<int32_t>(bits << (26u - index * 8u)) >> 26;
+	}
+	return offsets;
+}
+
+uint32_t ConstSampleOffsetOperand(EmitterState& state, const std::array<int32_t, 3>& offsets,
+                                  uint32_t components) {
+	if (components == 1u) return ConstantI32(state, offsets[0]);
+	const auto x = ConstantI32(state, offsets[0]);
+	const auto y = ConstantI32(state, offsets[1]);
+	if (components == 2u) {
+		return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), x, y);
+	}
+	return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 3), x, y,
+	                              ConstantI32(state, offsets[2]));
+}
+
+// Vulkan only accepts non-constant Offset on gathers and only guarantees ConstOffset values in
+// [-8, 7], so other offsets move the coordinates by offset / size of the sampled mip level.
+uint32_t OffsetSampleCoordinates(ValueEmitContext& ctx, const IR::MemoryInfo& mem,
+                                 const IR::Inst& address, uint32_t offset_component,
+                                 uint32_t resource, uint32_t array_index, uint32_t coord,
+                                 uint32_t level) {
+	auto&       state = ctx.state;
+	const auto& info  = ImageDimensionInfoFor(state.program.info.images[resource].dimension);
+	state.builder.RequireCapability(spv::CapabilityImageQuery);
+	const auto rounded = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpExtInst, TypeF32(state), rounded, GlslStd450(state),
+	                          GLSLstd450Floor,
+	                          Binary(state, spv::OpFAdd, TypeF32(state), level,
+	                                 ConstantF32(state, 0x3f000000u)));
+	const auto clamped = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpExtInst, TypeF32(state), clamped, GlslStd450(state),
+	                          GLSLstd450FMax, rounded, ZeroF32(state));
+	const auto level_u32 = Unary(state, spv::OpConvertFToU, TypeU32(state), clamped);
+	const auto image     = LoadImageDescriptor(state, resource, 0u, array_index);
+	const auto size      = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, info.dimension),
+	                          size, image, level_u32);

Fixed in 3aa2037: the fallback clamps the level to OpImageQueryLevels - 1 before OpImageQuerySizeLod. ImageSampleOffsetMovesTexel now also samples with IMAGE_SAMPLE_L_O at LOD 3 on a single-level image with a runtime offset.

**@⁠TheCruZ** on GitHub · 2026-10-08 21:08 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#discussion_r4224148905) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` line 681 (outdated): ```diff @@ -615,6 +619,94 @@ uint32_t StoreTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t d return PackImageTexel(ctx, mem, texel); } +// Texel offsets of SAMPLE*_O are three 6-bit signed values at bits [5:0], [13:8] and +// [21:16] of one address DWORD. Returns them when the DWORD is an IR immediate. +std::optional<std::array<int32_t, 3>> ConstantSampleOffsets(const IR::MemoryInfo& mem, + const IR::Inst& address, + uint32_t component) { + const auto layout = Decoder::ImageAddressComponentLayout(mem.image_sample_flags, component); + const auto packed = layout.bit_offset / 32u; + if (packed >= address.NumArgs()) return std::array<int32_t, 3> {}; + auto value = address.Arg(packed).Resolve(); + // The translator wraps the offset DWORD in select(exec, offset, 0): lanes that consume the + // sample take the true arm, so a constant there is the offset of every live lane. + if (const auto* select = value.TryInstruction(); + select != nullptr && select->GetOpcode() == IR::ValueOpcode::SelectU32 && + select->NumArgs() == 3u && select->Arg(2).Resolve().IsImmediate() && + select->Arg(2).Resolve().U32() == 0u) { + value = select->Arg(1).Resolve(); + } + if (!value.IsImmediate()) return std::nullopt; + const auto bits = value.U32(); + std::array<int32_t, 3> offsets {}; + for (uint32_t index = 0; index < offsets.size(); index++) { + offsets[index] = static_cast<int32_t>(bits << (26u - index * 8u)) >> 26; + } + return offsets; +} + +uint32_t ConstSampleOffsetOperand(EmitterState& state, const std::array<int32_t, 3>& offsets, + uint32_t components) { + if (components == 1u) return ConstantI32(state, offsets[0]); + const auto x = ConstantI32(state, offsets[0]); + const auto y = ConstantI32(state, offsets[1]); + if (components == 2u) { + return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), x, y); + } + return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 3), x, y, + ConstantI32(state, offsets[2])); +} + +// Vulkan only accepts non-constant Offset on gathers and only guarantees ConstOffset values in +// [-8, 7], so other offsets move the coordinates by offset / size of the sampled mip level. +uint32_t OffsetSampleCoordinates(ValueEmitContext& ctx, const IR::MemoryInfo& mem, + const IR::Inst& address, uint32_t offset_component, + uint32_t resource, uint32_t array_index, uint32_t coord, + uint32_t level) { + auto& state = ctx.state; + const auto& info = ImageDimensionInfoFor(state.program.info.images[resource].dimension); + state.builder.RequireCapability(spv::CapabilityImageQuery); + const auto rounded = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpExtInst, TypeF32(state), rounded, GlslStd450(state), + GLSLstd450Floor, + Binary(state, spv::OpFAdd, TypeF32(state), level, + ConstantF32(state, 0x3f000000u))); + const auto clamped = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpExtInst, TypeF32(state), clamped, GlslStd450(state), + GLSLstd450FMax, rounded, ZeroF32(state)); + const auto level_u32 = Unary(state, spv::OpConvertFToU, TypeU32(state), clamped); + const auto image = LoadImageDescriptor(state, resource, 0u, array_index); + const auto size = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, info.dimension), + size, image, level_u32); ``` Fixed in 3aa2037: the fallback clamps the level to `OpImageQueryLevels - 1` before `OpImageQuerySizeLod`. `ImageSampleOffsetMovesTexel` now also samples with `IMAGE_SAMPLE_L_O` at LOD 3 on a single-level image with a runtime offset.
@ -821,0 +997,4 @@
level = Binary(state, spv::OpFAdd, TypeF32(state), level,
AddressF32(ctx, mem, *address, layout.bias));
}
}
Author
Owner

@⁠TheCruZ on GitHub · 2026-10-08 21:08 UTC · original

Fixed in 3aa2037: derivative samples now pick the fallback level from their own gradients (log2 of the longer gradient in base-level texels), and in pixel shaders the instruction's bias is added to the queried LOD. ImageSampleOffsetMovesTexel also covers IMAGE_SAMPLE_D_O with a runtime offset.

**@⁠TheCruZ** on GitHub · 2026-10-08 21:08 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#discussion_r4224149190) Fixed in 3aa2037: derivative samples now pick the fallback level from their own gradients (log2 of the longer gradient in base-level texels), and in pixel shaders the instruction's bias is added to the queried LOD. `ImageSampleOffsetMovesTexel` also covers `IMAGE_SAMPLE_D_O` with a runtime offset.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 21:08 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp line 681 (outdated):

@@ -615,6 +619,94 @@ uint32_t StoreTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t d
 	return PackImageTexel(ctx, mem, texel);
 }
 
+// Texel offsets of SAMPLE*_O are three 6-bit signed values at bits [5:0], [13:8] and
+// [21:16] of one address DWORD. Returns them when the DWORD is an IR immediate.
+std::optional<std::array<int32_t, 3>> ConstantSampleOffsets(const IR::MemoryInfo& mem,
+                                                            const IR::Inst&       address,
+                                                            uint32_t              component) {
+	const auto layout = Decoder::ImageAddressComponentLayout(mem.image_sample_flags, component);
+	const auto packed = layout.bit_offset / 32u;
+	if (packed >= address.NumArgs()) return std::array<int32_t, 3> {};
+	auto value = address.Arg(packed).Resolve();
+	// The translator wraps the offset DWORD in select(exec, offset, 0): lanes that consume the
+	// sample take the true arm, so a constant there is the offset of every live lane.
+	if (const auto* select = value.TryInstruction();
+	    select != nullptr && select->GetOpcode() == IR::ValueOpcode::SelectU32 &&
+	    select->NumArgs() == 3u && select->Arg(2).Resolve().IsImmediate() &&
+	    select->Arg(2).Resolve().U32() == 0u) {
+		value = select->Arg(1).Resolve();
+	}
+	if (!value.IsImmediate()) return std::nullopt;
+	const auto bits = value.U32();
+	std::array<int32_t, 3> offsets {};
+	for (uint32_t index = 0; index < offsets.size(); index++) {
+		offsets[index] = static_cast<int32_t>(bits << (26u - index * 8u)) >> 26;
+	}
+	return offsets;
+}
+
+uint32_t ConstSampleOffsetOperand(EmitterState& state, const std::array<int32_t, 3>& offsets,
+                                  uint32_t components) {
+	if (components == 1u) return ConstantI32(state, offsets[0]);
+	const auto x = ConstantI32(state, offsets[0]);
+	const auto y = ConstantI32(state, offsets[1]);
+	if (components == 2u) {
+		return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), x, y);
+	}
+	return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 3), x, y,
+	                              ConstantI32(state, offsets[2]));
+}
+
+// Vulkan only accepts non-constant Offset on gathers and only guarantees ConstOffset values in
+// [-8, 7], so other offsets move the coordinates by offset / size of the sampled mip level.
+uint32_t OffsetSampleCoordinates(ValueEmitContext& ctx, const IR::MemoryInfo& mem,
+                                 const IR::Inst& address, uint32_t offset_component,
+                                 uint32_t resource, uint32_t array_index, uint32_t coord,
+                                 uint32_t level) {
+	auto&       state = ctx.state;
+	const auto& info  = ImageDimensionInfoFor(state.program.info.images[resource].dimension);
+	state.builder.RequireCapability(spv::CapabilityImageQuery);
+	const auto rounded = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpExtInst, TypeF32(state), rounded, GlslStd450(state),
+	                          GLSLstd450Floor,
+	                          Binary(state, spv::OpFAdd, TypeF32(state), level,
+	                                 ConstantF32(state, 0x3f000000u)));
+	const auto clamped = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpExtInst, TypeF32(state), clamped, GlslStd450(state),
+	                          GLSLstd450FMax, rounded, ZeroF32(state));
+	const auto level_u32 = Unary(state, spv::OpConvertFToU, TypeU32(state), clamped);
+	const auto image     = LoadImageDescriptor(state, resource, 0u, array_index);
+	const auto size      = state.builder.AllocateId();
+	state.builder.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, info.dimension),
+	                          size, image, level_u32);

@TheCruZ, the supplied code clamps the query level to OpImageQueryLevels - 1 before OpImageQuerySizeLod. This addresses the undefined-dimensions concern. The reported single-level image test covers the out-of-range explicit LOD case.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 21:08 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#discussion_r4224152379) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` line 681 (outdated): ```diff @@ -615,6 +619,94 @@ uint32_t StoreTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t d return PackImageTexel(ctx, mem, texel); } +// Texel offsets of SAMPLE*_O are three 6-bit signed values at bits [5:0], [13:8] and +// [21:16] of one address DWORD. Returns them when the DWORD is an IR immediate. +std::optional<std::array<int32_t, 3>> ConstantSampleOffsets(const IR::MemoryInfo& mem, + const IR::Inst& address, + uint32_t component) { + const auto layout = Decoder::ImageAddressComponentLayout(mem.image_sample_flags, component); + const auto packed = layout.bit_offset / 32u; + if (packed >= address.NumArgs()) return std::array<int32_t, 3> {}; + auto value = address.Arg(packed).Resolve(); + // The translator wraps the offset DWORD in select(exec, offset, 0): lanes that consume the + // sample take the true arm, so a constant there is the offset of every live lane. + if (const auto* select = value.TryInstruction(); + select != nullptr && select->GetOpcode() == IR::ValueOpcode::SelectU32 && + select->NumArgs() == 3u && select->Arg(2).Resolve().IsImmediate() && + select->Arg(2).Resolve().U32() == 0u) { + value = select->Arg(1).Resolve(); + } + if (!value.IsImmediate()) return std::nullopt; + const auto bits = value.U32(); + std::array<int32_t, 3> offsets {}; + for (uint32_t index = 0; index < offsets.size(); index++) { + offsets[index] = static_cast<int32_t>(bits << (26u - index * 8u)) >> 26; + } + return offsets; +} + +uint32_t ConstSampleOffsetOperand(EmitterState& state, const std::array<int32_t, 3>& offsets, + uint32_t components) { + if (components == 1u) return ConstantI32(state, offsets[0]); + const auto x = ConstantI32(state, offsets[0]); + const auto y = ConstantI32(state, offsets[1]); + if (components == 2u) { + return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 2), x, y); + } + return state.builder.Constant(spv::OpConstantComposite, TypeI32Vector(state, 3), x, y, + ConstantI32(state, offsets[2])); +} + +// Vulkan only accepts non-constant Offset on gathers and only guarantees ConstOffset values in +// [-8, 7], so other offsets move the coordinates by offset / size of the sampled mip level. +uint32_t OffsetSampleCoordinates(ValueEmitContext& ctx, const IR::MemoryInfo& mem, + const IR::Inst& address, uint32_t offset_component, + uint32_t resource, uint32_t array_index, uint32_t coord, + uint32_t level) { + auto& state = ctx.state; + const auto& info = ImageDimensionInfoFor(state.program.info.images[resource].dimension); + state.builder.RequireCapability(spv::CapabilityImageQuery); + const auto rounded = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpExtInst, TypeF32(state), rounded, GlslStd450(state), + GLSLstd450Floor, + Binary(state, spv::OpFAdd, TypeF32(state), level, + ConstantF32(state, 0x3f000000u))); + const auto clamped = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpExtInst, TypeF32(state), clamped, GlslStd450(state), + GLSLstd450FMax, rounded, ZeroF32(state)); + const auto level_u32 = Unary(state, spv::OpConvertFToU, TypeU32(state), clamped); + const auto image = LoadImageDescriptor(state, resource, 0u, array_index); + const auto size = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpImageQuerySizeLod, ImageViewSizeType(state, info.dimension), + size, image, level_u32); ``` `@TheCruZ`, the supplied code clamps the query level to `OpImageQueryLevels - 1` before `OpImageQuerySizeLod`. This addresses the undefined-dimensions concern. The reported single-level image test covers the out-of-range explicit LOD case. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=Clamp%20explicit%20LOD%20before%20%60OpImageQuerySizeLod%60%20to%20avoid%20undefined%20dimensions%3B%20test%20single-level%20images%20with%20runtime%20offsets.%20Try%20%40coderabbitai%20for%20actionable%20code%20reviews!%20%F0%9F%90%87&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1220%23discussion_r4222869713)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
@ -821,0 +997,4 @@
level = Binary(state, spv::OpFAdd, TypeF32(state), level,
AddressF32(ctx, mem, *address, layout.bias));
}
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-08 21:08 UTC · original

@TheCruZ, thanks for the fix. The supplied code uses the sample’s explicit gradients to select fallback mip dimensions and adds the instruction bias to the queried pixel-shader LOD. This addresses both parts of the finding.

The reported runtime-offset IMAGE_SAMPLE_D_O test covers the derivative path. I have not run the tests.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-08 21:08 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#discussion_r4224152712) `@TheCruZ`, thanks for the fix. The supplied code uses the sample’s explicit gradients to select fallback mip dimensions and adds the instruction bias to the queried pixel-shader LOD. This addresses both parts of the finding. The reported runtime-offset `IMAGE_SAMPLE_D_O` test covers the derivative path. I have not run the tests. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=%40coderabbitai%20caught%20a%20mip-dimension%20bug%3A%20implicit%20LOD%20ignored%20explicit%20gradients%20and%20bias.%20The%20fix%20derives%20fallback%20levels%20from%20the%20sample%E2%80%99s%20own%20inputs%20and%20tests%20runtime%20offsets%20for%20%60IMAGE_SAMPLE_D_O%60.%20%F0%9F%9B%A0%EF%B8%8F%20Try%20%40coderabbitai!&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1220%23discussion_r4222869727)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠overlordxrz-source on GitHub · 2026-10-12 02:26 UTC · original

@⁠TheCruZ heads-up on this one. Since 984cfcebd ("shader: emit native texel offsets using sample execution context", nmzik/netwarex, 10-11), main does the constant part itself: ConstOffset when the offset is constant in the active lanes, which it resolves through the exec mask. For runtime offsets on samples it now calls ctx.Fail("has a nonconstant sample texel offset"). So this PR conflicts now, and its runtime path is the piece main is still missing.

NHL 27 (#1101) hits exactly that on compute shader 0x8ff7afec7c5ab786, so it's no longer just GTA V.

I rebased only your coordinate-shift path onto 5b730d4. I kept main's ConstOffset/exec handling and left out your select folding, since main resolves exec its own way. I also left out the [-8, 7] range check: main currently emits ConstOffset for any constant in [-32, 31], so that part of yours still adds something and could go in separately. It's a single commit with you as co-author, plus a smaller version of your ImageSampleOffsetMovesTexel test. How would you like to do it? Would you rather rebase #1220 yourself, should I push mine as a branch you can cherry-pick, or should I open it as a follow-up PR with credit to you? Whichever you prefer.

**@⁠overlordxrz-source** on GitHub · 2026-10-12 02:26 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#issuecomment-6116650362) @⁠TheCruZ heads-up on this one. Since 984cfcebd ("shader: emit native texel offsets using sample execution context", nmzik/netwarex, 10-11), main does the constant part itself: `ConstOffset` when the offset is constant in the active lanes, which it resolves through the exec mask. For runtime offsets on samples it now calls `ctx.Fail("has a nonconstant sample texel offset")`. So this PR conflicts now, and its runtime path is the piece main is still missing. NHL 27 (#1101) hits exactly that on compute shader `0x8ff7afec7c5ab786`, so it's no longer just GTA V. I rebased only your coordinate-shift path onto 5b730d4. I kept main's ConstOffset/exec handling and left out your select folding, since main resolves exec its own way. I also left out the [-8, 7] range check: main currently emits `ConstOffset` for any constant in [-32, 31], so that part of yours still adds something and could go in separately. It's a single commit with you as co-author, plus a smaller version of your `ImageSampleOffsetMovesTexel` test. How would you like to do it? Would you rather rebase #1220 yourself, should I push mine as a branch you can cherry-pick, or should I open it as a follow-up PR with credit to you? Whichever you prefer.
Author
Owner

@⁠TheCruZ on GitHub · 2026-10-12 08:37 UTC · original

@⁠TheCruZ heads-up on this one. Since 984cfce ("shader: emit native texel offsets using sample execution context", nmzik/netwarex, 10-11), main does the constant part itself: ConstOffset when the offset is constant in the active lanes, which it resolves through the exec mask. For runtime offsets on samples it now calls ctx.Fail("has a nonconstant sample texel offset"). So this PR conflicts now, and its runtime path is the piece main is still missing.

NHL 27 (#1101) hits exactly that on compute shader 0x8ff7afec7c5ab786, so it's no longer just GTA V.

I rebased only your coordinate-shift path onto 5b730d4. I kept main's ConstOffset/exec handling and left out your select folding, since main resolves exec its own way. I also left out the [-8, 7] range check: main currently emits ConstOffset for any constant in [-32, 31], so that part of yours still adds something and could go in separately. It's a single commit with you as co-author, plus a smaller version of your ImageSampleOffsetMovesTexel test. How would you like to do it? Would you rather rebase #1220 yourself, should I push mine as a branch you can cherry-pick, or should I open it as a follow-up PR with credit to you? Whichever you prefer.

Please go ahead and open it as a follow-up PR. Your version is a better fit for main now: keeping main's ConstOffset/exec handling and dropping my select folding makes sense. Good to know NHL 27 needs the runtime path too.

I'll close #1220 once your PR is up and link it from here.

**@⁠TheCruZ** on GitHub · 2026-10-12 08:37 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#issuecomment-6120716435) > @⁠TheCruZ heads-up on this one. Since [984cfce](https://github.com/KytyPS5/KytyPS5/commit/984cfcebd141b211aa9e0a8cde63b0ebe652d07a) ("shader: emit native texel offsets using sample execution context", nmzik/netwarex, 10-11), main does the constant part itself: `ConstOffset` when the offset is constant in the active lanes, which it resolves through the exec mask. For runtime offsets on samples it now calls `ctx.Fail("has a nonconstant sample texel offset")`. So this PR conflicts now, and its runtime path is the piece main is still missing. > > NHL 27 (#1101) hits exactly that on compute shader `0x8ff7afec7c5ab786`, so it's no longer just GTA V. > > I rebased only your coordinate-shift path onto [5b730d4](https://github.com/KytyPS5/KytyPS5/commit/5b730d4df0089fde1679a0afda245c9536a64a7c). I kept main's ConstOffset/exec handling and left out your select folding, since main resolves exec its own way. I also left out the [-8, 7] range check: main currently emits `ConstOffset` for any constant in [-32, 31], so that part of yours still adds something and could go in separately. It's a single commit with you as co-author, plus a smaller version of your `ImageSampleOffsetMovesTexel` test. How would you like to do it? Would you rather rebase #1220 yourself, should I push mine as a branch you can cherry-pick, or should I open it as a follow-up PR with credit to you? Whichever you prefer. Please go ahead and open it as a follow-up PR. Your version is a better fit for main now: keeping main's ConstOffset/exec handling and dropping my select folding makes sense. Good to know NHL 27 needs the runtime path too. I'll close #1220 once your PR is up and link it from here.
Author
Owner

@⁠overlordxrz-source on GitHub · 2026-10-12 08:55 UTC · original

@⁠TheCruZ thanks, opened as #1446 with you as co-author. It keeps main's ConstOffset/exec handling and adds only your coordinate-shift path for runtime offsets, plus the smaller test. The [-8, 7] range check isn't in it; I can send that separately if you'd like.

**@⁠overlordxrz-source** on GitHub · 2026-10-12 08:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#issuecomment-6120977860) @⁠TheCruZ thanks, opened as #1446 with you as co-author. It keeps main's ConstOffset/exec handling and adds only your coordinate-shift path for runtime offsets, plus the smaller test. The [-8, 7] range check isn't in it; I can send that separately if you'd like.
Author
Owner

@⁠TheCruZ on GitHub · 2026-10-12 09:10 UTC · original

@⁠TheCruZ thanks, opened as #1446 with you as co-author. It keeps main's ConstOffset/exec handling and adds only your coordinate-shift path for runtime offsets, plus the smaller test. The [-8, 7] range check isn't in it; I can send that separately if you'd like.

thanks, for the The [-8, 7] range check i think that we can just wait to see if any game really requires it

**@⁠TheCruZ** on GitHub · 2026-10-12 09:10 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1220#issuecomment-6121208841) > @⁠TheCruZ thanks, opened as #1446 with you as co-author. It keeps main's ConstOffset/exec handling and adds only your coordinate-shift path for runtime offsets, plus the smaller test. The [-8, 7] range check isn't in it; I can send that separately if you'd like. thanks, for the The [-8, 7] range check i think that we can just wait to see if any game really requires it

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.