Compare commits

...
Author SHA1 Message Date
elforeign 17734cfb58 gpu: close the review's remaining texture-binding gaps (#303)
The re-review found three partial fixes. The public software reference
could overflow on a huge viewport. A texture in a combined write and read
state could be sampled. The sampler-slot test used two identical filled
slots. The viewport is now bounded to 4096 pixels. A sampled texture must be
COMMON or a read-only state that includes PIXEL_SHADER_RESOURCE. The sampler
heap now leaves its middle slot empty. The docs now state the start-instance
rule and when table bases are checked.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 11:11:47 -06:00
elforeign 75e664122e Merge remote-tracking branch 'origin/main' into task/303-guest-textures
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 11:09:11 -06:00
elforeign 1f0f8a7a89 loader: format the guest texture test (#303)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 11:08:52 -06:00
elforeign cde20d5635 gpu: tighten guest texture binding after independent review (#303)
The independent review found binding rules that diverged from D3D12:
changing descriptor heaps kept tables bound in the old heaps, setting the
same root signature again cleared its tables, and unsupported draw shapes
were drawn as one triangle. Now heap changes and a different root signature
invalidate tables, while redundant sets keep them. Table bases are checked
against the bound heap of their type when bound. Textured draws other than
one instance of three vertices fail, and zero vertices or instances draw
nothing.

Descriptor handle offsets can no longer carry into another heap's ID. SRVs
of array or multi-level textures are rejected. A texture whose state
excludes pixel-shader reads is not sampled. Vertex buffer offsets are
overflow-checked. The tests now cover swapped root parameters, a second
sampler slot, off-centre and out-of-range coordinates, state transitions,
draw shapes and resource bounds.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:42:54 -06:00
elforeign 0a69fb74b7 gpu: bind a texture and sampler to guest draws through descriptor tables (#303)
A guest command list had no way to bind a texture: GraphicsCommand stopped
at vertex and index buffers. This adds the smallest D3D12-shaped binding the
translated image_sample_lz pixel stage needs: shader-visible CBV_SRV_UAV and
sampler heaps, CreateShaderResourceView for one-level RGBA8 and BC1 2D
textures, a point/clamp CreateSampler, a root signature with one pixel-stage
SRV table and one sampler table, and SetDescriptorHeaps and
SetGraphicsRootDescriptorTable. Everything else fails explicitly before any
draw.

The native path hands the bound level to a textured backend.
NativeCompute::render_rgba8_sampled_bc1 binds a BC1 level natively to
fragment texture 0 and sampler 0. The software reference point-samples with
clamp addressing.

BC1 fixtures use only endpoint colours. Apple's hardware decoder gives
171/84 for the interpolated palette entries where the spec-exact decoder
gives 170/85.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:36:56 -06:00
10 changed files with 2450 additions and 5 deletions

No files matched your search

+1
View File
@@ -17,6 +17,7 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Added
- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted.
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
Generated
+1
View File
@@ -204,6 +204,7 @@ dependencies = [
"sha2",
"xenora-metal",
"xenora-shader",
"xenora-texture",
]
[[package]]
+1
View File
@@ -16,6 +16,7 @@ gpu-tests = []
[dependencies]
libc = "0.2"
sha2 = "0.10"
xenora-texture = { path = "../texture" }
[dev-dependencies]
xenora-metal = { path = "../metal" }
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+39 -3
View File
@@ -101,7 +101,43 @@ impl NativeCompute {
colors,
[width, height],
clear,
sampled,
sampled.map(|(texture, sampler)| (texture.raw(), sampler)),
)
.map(|(pixels, _)| pixels)
}
/// As [`Self::render_rgba8_sampled`], with level 0 of a BC1 upload bound
/// natively as a `BC1_RGBA` texture to fragment texture slot 0 and the
/// sampler to fragment sampler slot 0.
///
/// # Errors
///
/// As [`Self::render_rgba8_sampled`], and for an invalid BC1 level.
#[allow(clippy::too_many_arguments)]
pub fn render_rgba8_sampled_bc1(
&self,
source: &str,
entries: [&str; 2],
vertices: &[[f32; 4]; 3],
colors: &[[f32; 4]; 3],
extent: [usize; 2],
clear: [u8; 4],
texture: &Bc1Upload<'_>,
sampler: &crate::sampler::MetalSampler,
) -> Result<Vec<u8>, MetalError> {
let level = texture
.subresource(0, 0)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
self.validate_bc_extent(level.width, level.height, "BC1")?;
let bc1 = self.new_bc1_texture(&level)?;
self.render_rgba8_internal(
source,
entries,
vertices,
colors,
extent,
clear,
Some((&bc1, sampler)),
)
.map(|(pixels, _)| pixels)
}
@@ -116,7 +152,7 @@ impl NativeCompute {
[width, height]: [usize; 2],
clear: [u8; 4],
sampled: Option<(
&crate::texture_pipeline::MetalRgba8Texture,
&ProtocolObject<dyn MTLTexture>,
&crate::sampler::MetalSampler,
)>,
) -> Result<(Vec<u8>, Option<f64>), MetalError> {
@@ -228,7 +264,7 @@ impl NativeCompute {
encoder.setVertexBuffer_offset_atIndex(Some(&positions), 0, 0);
encoder.setVertexBuffer_offset_atIndex(Some(&colors), 0, 1);
if let Some((tex, samp)) = sampled {
encoder.setFragmentTexture_atIndex(Some(tex.raw()), 0);
encoder.setFragmentTexture_atIndex(Some(tex), 0);
encoder.setFragmentSamplerState_atIndex(Some(samp.raw()), 0);
}
encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::Triangle, 0, 3);
@@ -0,0 +1,99 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
use xenora_texture::{Bc1Upload, Bc1UploadDesc, SamplerDesc, decode_bc1};
use super::{context, native};
/// The translated `image_sample_lz` pixel stage samples a native BC1
/// texture bound by `render_rgba8_sampled_bc1`. Each of the 8×8 texture's
/// four blocks selects only its two endpoints, which expand exactly to 0 or
/// 255, so the image is known without a decoder: selector 1 (the second
/// endpoint) where `x == 0 || y == 3` within a block, else selector 0.
#[test]
fn translated_image_sample_lz_reads_bound_bc1_texture() {
let blocks: [[u8; 8]; 4] = [
[0x00, 0xF8, 0x1F, 0x00, 0x01, 0x01, 0x01, 0x55], // red, blue
[0xE0, 0x07, 0x00, 0x00, 0x01, 0x01, 0x01, 0x55], // green, black
[0xFF, 0xFF, 0x1F, 0xF8, 0x01, 0x01, 0x01, 0x55], // white, magenta
[0xE0, 0xFF, 0xFF, 0x07, 0x01, 0x01, 0x01, 0x55], // yellow, cyan
];
let endpoints: [[[u8; 4]; 2]; 4] = [
[[255, 0, 0, 255], [0, 0, 255, 255]],
[[0, 255, 0, 255], [0, 0, 0, 255]],
[[255, 255, 255, 255], [255, 0, 255, 255]],
[[255, 255, 0, 255], [0, 255, 255, 255]],
];
let mut expected = Vec::new();
for y in 0..8 {
for x in 0..8 {
let selector = usize::from(x % 4 == 0 || y % 4 == 3);
expected.extend(endpoints[(y / 4) * 2 + x / 4][selector]);
}
}
for (index, block) in blocks.into_iter().enumerate() {
let (bx, by) = (index % 2 * 4, index / 2 * 4);
for (i, texel) in decode_bc1(block).iter().enumerate() {
let at = ((by + i / 4) * 8 + bx + i % 4) * 4;
assert_eq!(texel, &expected[at..at + 4], "decoder, block {index}");
}
}
let ps: Vec<u8> = [
&[0x00, 0x00, 0x08, 0xc8][..], // v_interp_p1_f32 v2, v0, attr0.x
&[0x01, 0x00, 0x09, 0xc8], // v_interp_p2_f32 v2, v1, attr0.x
&[0x00, 0x01, 0x0c, 0xc8], // v_interp_p1_f32 v3, v0, attr0.y
&[0x01, 0x01, 0x0d, 0xc8], // v_interp_p2_f32 v3, v1, attr0.y
&[0x08, 0x0f, 0x9c, 0xf0, 0x02, 0x04, 0x40, 0x00], // image_sample_lz
&[0x0f, 0x18, 0x00, 0xf8, 0x04, 0x05, 0x06, 0x07], // exp mrt0
&[0x00, 0x00, 0x81, 0xbf], // s_endpgm
]
.concat();
let compiled = compile_graphics(
Architecture::Gfx1030,
include_bytes!("../../../../fixtures/rdna2/x9-varying-vs.bin"),
&ps,
)
.expect("compile translated image_sample_lz shader");
let gpu = context();
let upload = Bc1Upload::new(
blocks.as_flattened(),
Bc1UploadDesc {
width: 8,
height: 8,
mips: 1,
layers: 1,
format: 1,
usage: 1,
row_pitch: 16,
slice_pitch: 32,
},
)
.expect("valid BC1 upload");
let sampler = native(xenora_metal::sampler::MetalSampler::new(
gpu.device(),
SamplerDesc::nearest_clamp(),
));
// Pixel (x, y) of the 8×8 target samples uv ((x + 0.5) / 8, (y + 0.5) / 8).
let positions = [
[-1.0, -1.0, 0.5, 1.0],
[3.0, -1.0, 0.5, 1.0],
[-1.0, 3.0, 0.5, 1.0],
];
let uvs = [
[0.0, 1.0, 0.0, 1.0],
[2.0, 1.0, 0.0, 1.0],
[0.0, -1.0, 0.0, 1.0],
];
let pixels = native(gpu.render_rgba8_sampled_bc1(
&compiled.msl,
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
&positions,
&uvs,
[8, 8],
[19, 43, 93, 251],
&upload,
&sampler,
));
assert_eq!(pixels, expected);
}
+2
View File
@@ -26,6 +26,8 @@ mod texture_bc_alpha;
mod texture_bc_channel;
#[path = "native/texture_sampling.rs"]
mod texture_sampling;
#[path = "native/translated_bc1.rs"]
mod translated_bc1;
#[path = "native/translated_render.rs"]
mod translated_render;
+44
View File
@@ -498,3 +498,47 @@ compare function. Colour and the stored depth are both read back.
These passes are checked on the GPU with Metal validation against expectations
derived independently from the public semantics; synthetic fixtures only.
### Guest texture binding (descriptor tables)
`GraphicsContext` lets a guest command list sample one texture in the pixel
stage through a D3D12-shaped binding. A draw samples only if a root signature
is bound. Draws without one keep the flat-colour path. The supported subset
is fixed. Anything outside it fails with `GraphicsError::Unsupported` when the
object is created, or with an error at execution. A rejected draw never
reaches the backend. Draws recorded before it in the same list have already
run.
| Object | Supported |
| --- | --- |
| `create_descriptor_heap` | Shader-visible `CBV_SRV_UAV` (0) or `SAMPLER` (1) heaps of 1–64 descriptors. RTV, DSV and CPU-only heaps are unsupported. |
| `create_committed_texture2d` | One level of `R8G8B8A8_UNORM` (28) or `BC1_UNORM` (71), 1–64 texels per side. BC1 sizes must be multiples of four. Rows are linear: 4 bytes per texel, or 8 bytes per 4×4 block. Xbox tiling is not handled. |
| `create_shader_resource_view` | A `Texture2D` view of mip 0 of a single-level, single-slice 2D texture, in the resource's own format. |
| `create_sampler` | Point filtering (`MIN_MAG_MIP_POINT`), clamp addressing on U, V and W, no LOD bias and a minimum LOD of 0. |
| `create_root_signature` | Exactly two pixel-visibility descriptor tables, in either order: one with a single SRV range for `t0`, and one with a single sampler range for `s0` (one descriptor each, space 0). Root constants, root descriptors, CBV and UAV ranges, extra tables or ranges and static samplers are unsupported. |
| `cmd_set_descriptor_heaps` | At most one heap of each type. |
| `cmd_set_graphics_root_descriptor_table` | The base must be a GPU handle to a slot of the bound heap of the table's type. The slot must hold a descriptor when a draw reads it. Changing the heaps or binding a different root signature clears every table. Setting the same heaps or the same root signature again keeps them. |
Descriptor handles follow D3D12 pointer arithmetic: the heap start plus
`index × GetDescriptorHandleIncrementSize` (32 here; guests must query the
value). `offset` returns `None` rather than carry into the next heap. CPU and
GPU handles are separate spaces. A textured draw is a `DrawInstanced` of
one instance of three vertices with start instance 0, starting at any vertex. Zero vertices or
instances draw nothing. The sampled texture must be in `COMMON` or a read-only state that includes
`PIXEL_SHADER_RESOURCE`. The software reference draws at most 4096 pixels. Each vertex record holds a float4 position
at byte 0 and a float4 texture coordinate at byte 16, with a stride of at
least 32. Textured indexed draws are unsupported.
The native backend receives a `TexturedDraw` with the bound level and must
bind it to fragment texture 0 and sampler 0, which are the `tex0` and `samp0` arguments of
the translated `image_sample_lz` pixel stage. `NativeCompute::render_rgba8_sampled_bc1`
binds a BC1 level natively for that purpose. The software reference has no
clipping or depth test. A pixel is covered when its centre lies inside or on
an edge of the triangle. The texture coordinate is interpolated affinely, so
`w = 1` is required, and point sampled with
`min(floor(clamp(u, 0, 1) × width), width − 1)`. It decodes BC1 with the
spec-exact `xenora_texture::decode_bc1`. Apple's hardware rounds BC1's two
interpolated palette entries differently (171/84 against 170/85, measured
on an M5 Pro), so the tests use endpoint colours only. Pipeline
state objects do not exist yet, so the backend, not the guest, chooses the
pixel shader. These entry points are not yet wired to guest imports.
+5
View File
@@ -25,6 +25,11 @@ cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12
timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 -- \
--nocapture --test-threads=1
# Guest draws sample textures bound through descriptor tables (#303).
cargo test --locked -p xenora-loader --features gpu-tests --test graphics_textures --no-run
timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_textures -- \
--nocapture --test-threads=1
# The native app interface runs the trusted fixture's guest draw on Metal.
cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame -- \