diff --git a/CHANGELOG.md b/CHANGELOG.md index 6992acc9..7234a925 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Loader: `cmd_set_index_buffer` (DXGI `R16_UINT` and `R32_UINT` only) and `cmd_draw_indexed_instanced` fetch one triangle through the index buffer, start index and base vertex and pass it to the existing one-triangle backend. Both reject, with typed errors and before anything is drawn, an unsupported format, an unaligned or out-of-range offset, a bad index count, indices past the buffer, and any `index + base vertex` outside the vertex buffer, negative results and primitive-restart values included; the loader also rejects an unknown or missing index buffer. Checked on the GPU with Metal validation in 13 passes (both index sizes, odd 16-bit start, positive and negative base vertex, reversed winding, two triangles per draw, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's indexed fetch is checked against literal positions and through the native Metal renderer. Synthetic fixtures only; no guest index buffers or console draw state are involved. + - Added a native Metal depth pass, `NativeCompute::render_depth`: up to 16 triangles drawn in order into an RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. A pass without an attachment accepts only `DepthState::DISABLED`. Colour and the stored depth are both read back; the depth values are returned as the texture read gives them, without numeric conversion. A draw can sample an original BC1 texture whose blocks are uploaded to a native `BC1_RGBA` texture without CPU decoding, gated on `supportsBCTextureCompression`. Checked on the GPU with Metal validation in 30 passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled (`Always` without writes) with an attachment and no attachment at all, and a BC1-textured draw. Colour and depth are compared per pixel against expectations derived independently from the geometry, the Metal compare semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces. These are synthetic fixtures only; no console depth formats or guest render state are involved. - Added a CPU BC7 block decoder in `xenora-texture` for all eight modes, with explicit handling of the invalid all-zero mode byte. It is checked by hand-derived tests and 430 known-answer vectors from a separate clean-room reference written from the Khronos Data Format Specification (merged in PR #224 without a changelog entry). - Added independent negative tests for gfx1030 extension words: truncated literal, SDWA, DPP16, DPP8 and MIMG NSA trailers (62 prefixes of 18 LLVM-assembled instructions), disallowed extensions, and length recognition kept apart from semantic validity. Tests only, with no decoder change (merged in PR #231 without a changelog entry). diff --git a/crates/loader/src/graphics.rs b/crates/loader/src/graphics.rs index bf53d0d1..e7d313dc 100644 --- a/crates/loader/src/graphics.rs +++ b/crates/loader/src/graphics.rs @@ -117,6 +117,11 @@ pub enum GraphicsError { DeviceCreationFailure(String), BackendError(String), NativeMetalRequired, + /// An index buffer format other than DXGI `R16_UINT` (57) or `R32_UINT` (42). + InvalidIndexFormat(u32), + /// An indexed draw reads past its index buffer or fetches a vertex, + /// after applying the base vertex, outside its vertex buffer. + IndexOutOfRange, } impl std::fmt::Display for GraphicsError { @@ -140,6 +145,10 @@ impl std::fmt::Display for GraphicsError { f, "native Metal backend required but not provided or failed" ), + Self::InvalidIndexFormat(format) => { + write!(f, "unsupported index buffer format {format}") + } + Self::IndexOutOfRange => write!(f, "indexed draw outside its index or vertex buffer"), } } } @@ -173,6 +182,32 @@ pub struct GraphicsResource { pub data: Vec, } +/// Index size of an index buffer view, as `D3D12_INDEX_BUFFER_VIEW::Format`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum IndexFormat { + R16Uint, + R32Uint, +} + +impl IndexFormat { + /// The format for a DXGI format code: `R16_UINT` (57) or `R32_UINT` (42). + pub const fn from_dxgi(format: u32) -> Option { + match format { + 57 => Some(Self::R16Uint), + 42 => Some(Self::R32Uint), + _ => None, + } + } + + /// Bytes per index. + pub const fn size(self) -> usize { + match self { + Self::R16Uint => 2, + Self::R32Uint => 4, + } + } +} + /// Primitive Draw Command recorded in a Command List. #[derive(Clone, Debug)] pub enum GraphicsCommand { @@ -200,6 +235,18 @@ pub enum GraphicsCommand { start_vertex_location: u32, start_instance_location: u32, }, + SetIndexBuffer { + resource: GraphicsHandle, + offset: usize, + format: IndexFormat, + }, + DrawIndexedInstanced { + index_count_per_instance: u32, + instance_count: u32, + start_index_location: u32, + base_vertex_location: i32, + start_instance_location: u32, + }, } /// Command List in recording or closed state. @@ -548,6 +595,70 @@ impl GraphicsContext { Ok(()) } + /// Record set index buffer. `format` is a DXGI format code; only + /// `R16_UINT` (57) and `R32_UINT` (42) are index formats. + pub fn cmd_set_index_buffer( + &mut self, + list: GraphicsHandle, + resource: GraphicsHandle, + offset: usize, + format: u32, + ) -> Result<(), GraphicsError> { + let cmd_list = self + .command_lists + .get_mut(&list) + .ok_or(GraphicsError::InvalidCommandListHandle)?; + if !cmd_list.is_recording { + return Err(GraphicsError::CommandListNotRecording); + } + let format = + IndexFormat::from_dxgi(format).ok_or(GraphicsError::InvalidIndexFormat(format))?; + let res = self + .resources + .get(&resource) + .ok_or(GraphicsError::InvalidResourceHandle)?; + if !offset.is_multiple_of(format.size()) || offset > res.data.len() { + return Err(GraphicsError::InvalidDescriptor); + } + cmd_list.commands.push(GraphicsCommand::SetIndexBuffer { + resource, + offset, + format, + }); + Ok(()) + } + + /// Record draw indexed instanced. Each draw renders one triangle, so the + /// index count must be 3, or 0 (with a zero instance count) to draw nothing; + /// execution rejects any other count. + pub fn cmd_draw_indexed_instanced( + &mut self, + list: GraphicsHandle, + index_count_per_instance: u32, + instance_count: u32, + start_index_location: u32, + base_vertex_location: i32, + start_instance_location: u32, + ) -> Result<(), GraphicsError> { + let cmd_list = self + .command_lists + .get_mut(&list) + .ok_or(GraphicsError::InvalidCommandListHandle)?; + if !cmd_list.is_recording { + return Err(GraphicsError::CommandListNotRecording); + } + cmd_list + .commands + .push(GraphicsCommand::DrawIndexedInstanced { + index_count_per_instance, + instance_count, + start_index_location, + base_vertex_location, + start_instance_location, + }); + Ok(()) + } + /// Close command list. pub fn close_command_list(&mut self, list: GraphicsHandle) -> Result<(), GraphicsError> { let cmd_list = self @@ -649,6 +760,8 @@ impl GraphicsContext { let mut target_handle: Option = None; let mut vertex_resource: Option = None; let mut vertex_offset = 0usize; + let mut vertex_stride = 0usize; + let mut index_buffer: Option<(GraphicsHandle, usize, IndexFormat)> = None; let mut rendered_output: Option> = None; let mut draw_count = 0usize; @@ -679,10 +792,54 @@ impl GraphicsContext { viewport = (*width, *height); } GraphicsCommand::SetVertexBuffer { - resource, offset, .. + resource, + offset, + stride, } => { vertex_resource = Some(*resource); vertex_offset = *offset; + vertex_stride = *stride; + } + GraphicsCommand::SetIndexBuffer { + resource, + offset, + format, + } => index_buffer = Some((*resource, *offset, *format)), + GraphicsCommand::DrawIndexedInstanced { + index_count_per_instance, + instance_count, + start_index_location, + base_vertex_location, + .. + } => { + if *index_count_per_instance == 0 || *instance_count == 0 { + continue; + } + if *index_count_per_instance != 3 { + return Err(GraphicsError::InvalidDescriptor); + } + let vertices = self.fetch_indexed_triangle( + memory, + index_buffer, + (vertex_resource, vertex_offset, vertex_stride), + *start_index_location, + *base_vertex_location, + )?; + draw_count += 1; + let pixels = if let Some(renderer) = backend_renderer { + renderer(&vertices, viewport, clear_color)? + } else if backend_id == GraphicsBackendId::MetalNative { + return Err(GraphicsError::NativeMetalRequired); + } else { + Self::execute_software_reference_draw(&vertices, viewport, clear_color)? + }; + if let Some(th) = target_handle + && let Some(target_res) = self.resources.get_mut(&th) + && target_res.data.len() >= pixels.len() + { + target_res.data[..pixels.len()].copy_from_slice(&pixels); + } + rendered_output = Some(pixels); } GraphicsCommand::DrawInstanced { vertex_count_per_instance, @@ -761,6 +918,78 @@ impl GraphicsContext { }) } + /// The three float4 positions one indexed triangle fetches: index `k` is + /// read at `offset + (start + k) * size` of the index buffer, and vertex + /// `index + base_vertex` at `offset + vertex * stride` of the vertex buffer. + fn fetch_indexed_triangle( + &self, + memory: &GuestMemory, + index_buffer: Option<(GraphicsHandle, usize, IndexFormat)>, + (vertex_resource, vertex_offset, vertex_stride): (Option, usize, usize), + start: u32, + base_vertex: i32, + ) -> Result<[[f32; 4]; 3], GraphicsError> { + let resource = |handle: Option| { + handle + .and_then(|handle| self.resources.get(&handle)) + .ok_or(GraphicsError::InvalidResourceHandle) + }; + let (index_handle, index_offset, format) = + index_buffer.ok_or(GraphicsError::InvalidResourceHandle)?; + let index_res = resource(Some(index_handle))?; + let vertex_res = resource(vertex_resource)?; + if vertex_stride < 16 { + return Err(GraphicsError::InvalidDescriptor); + } + let size = format.size(); + let mut raw_indices = [0u8; 12]; + let raw_indices = &mut raw_indices[..3 * size]; + let first = (start as usize) + .checked_mul(size) + .and_then(|bytes| bytes.checked_add(index_offset)) + .ok_or(GraphicsError::IndexOutOfRange)?; + Self::read_resource(index_res, memory, first, raw_indices)?; + let mut vertices = [[0.0f32; 4]; 3]; + for (row, index) in vertices.iter_mut().zip(raw_indices.chunks_exact(size)) { + let index = if size == 2 { + u32::from(u16::from_le_bytes([index[0], index[1]])) + } else { + u32::from_le_bytes(index.try_into().unwrap()) + }; + let vertex = usize::try_from(i64::from(index) + i64::from(base_vertex)) + .map_err(|_| GraphicsError::IndexOutOfRange)?; + let at = vertex + .checked_mul(vertex_stride) + .and_then(|bytes| bytes.checked_add(vertex_offset)) + .ok_or(GraphicsError::IndexOutOfRange)?; + let mut raw = [0u8; 16]; + Self::read_resource(vertex_res, memory, at, &mut raw)?; + for (value, bytes) in row.iter_mut().zip(raw.as_chunks::<4>().0) { + *value = f32::from_le_bytes(*bytes); + } + } + Ok(vertices) + } + + /// Read `out.len()` bytes at `offset` of a resource, from its guest backing + /// when it has one. The range must lie inside the resource's size. + fn read_resource( + res: &GraphicsResource, + memory: &GuestMemory, + offset: usize, + out: &mut [u8], + ) -> Result<(), GraphicsError> { + let end = offset + .checked_add(out.len()) + .filter(|&end| end <= res.data.len()) + .ok_or(GraphicsError::IndexOutOfRange)?; + match res.guest_backing_addr { + Some(guest_addr) => memory.read_bytes(guest_addr + offset as u64, out)?, + None => out.copy_from_slice(&res.data[offset..end]), + } + Ok(()) + } + /// Software reference rasterizer for deterministic test verification when GPU tests are off. pub fn execute_software_reference_draw( vertices: &[[f32; 4]; 3], diff --git a/crates/loader/tests/graphics_d3d12.rs b/crates/loader/tests/graphics_d3d12.rs index 7191e52e..d0422864 100644 --- a/crates/loader/tests/graphics_d3d12.rs +++ b/crates/loader/tests/graphics_d3d12.rs @@ -590,3 +590,335 @@ fn test_guest_dbt_graphics_pipeline_metal_render_dual_inputs() { let expected_clear = [10, 20, 30, 255]; assert_eq!(pixels2, expected_clear.repeat(12)); } + +/// Guest addresses of the indexed-draw fixtures. +const INDEXED_VB: u64 = 0x7000_0000; +const INDEXED_IB: u64 = 0x7100_0000; +/// Vertex stride of the indexed fixtures: a float4 position and 16 unused bytes. +const INDEXED_STRIDE: usize = 32; + +/// Triangle (4,3) (16,4) (6,16) of a 16x16 target in clip space; no pixel +/// centre lies on one of its edges. +const INDEXED_TRIANGLE: [[f32; 4]; 3] = [ + [-0.5, 0.625, 0.5, 1.0], + [1.0, 0.5, 0.5, 1.0], + [-0.25, -1.0, 0.5, 1.0], +]; + +/// Ten vertices: the triangle at vertices 5, 7 and 2, and decoys elsewhere, +/// so a wrong fetch passes different positions. +fn indexed_vertices() -> Vec { + let mut bytes = Vec::new(); + for vertex in 0..10 { + let position = match vertex { + 5 => INDEXED_TRIANGLE[0], + 7 => INDEXED_TRIANGLE[1], + 2 => INDEXED_TRIANGLE[2], + other => [other as f32 * 0.125 - 0.75, -0.5, 0.5, 1.0], + }; + for value in position { + bytes.extend(value.to_le_bytes()); + } + bytes.extend([0xAB; 16]); + } + bytes +} + +struct IndexedRig { + ctx: GraphicsContext, + memory: GuestMemory, + queue: GraphicsHandle, + alloc: GraphicsHandle, + list: GraphicsHandle, + vb: GraphicsHandle, + ib16: GraphicsHandle, + ib32: GraphicsHandle, +} + +/// A context with guest-backed vertex and index buffers. The 16-bit buffer +/// holds 9, 9, 6, 8, 3, 5, 0 and the 32-bit buffer 9, 3, 5, 0, 7 and three +/// indices above 16 bits, 0x10003, 0x10005, 0x10000. +fn indexed_rig() -> IndexedRig { + use xenora_loader::memory::MemoryPermissions; + let mut ctx = GraphicsContext::new(); + let device = ctx.create_device().unwrap(); + let queue = ctx + .create_command_queue(device, CommandListType::Direct) + .unwrap(); + let alloc = ctx + .create_command_allocator(device, CommandListType::Direct) + .unwrap(); + let list = ctx + .create_command_list(device, alloc, CommandListType::Direct) + .unwrap(); + let buffer = |ctx: &mut GraphicsContext, bytes: usize, addr| { + let desc = ResourceDesc { + dimension: ResourceDimension::Buffer, + width: bytes as u64, + height: 1, + depth_or_array_size: 1, + mip_levels: 1, + format_rgba8: false, + }; + ctx.create_committed_resource(device, desc, ResourceStates::COMMON, Some(addr)) + .unwrap() + }; + let vertices = indexed_vertices(); + let ib16: Vec = [9u16, 9, 6, 8, 3, 5, 0] + .iter() + .flat_map(|index| index.to_le_bytes()) + .collect(); + let ib32: Vec = [9u32, 3, 5, 0, 7, 0x1_0003, 0x1_0005, 0x1_0000] + .iter() + .flat_map(|index| index.to_le_bytes()) + .collect(); + let vb = buffer(&mut ctx, vertices.len(), INDEXED_VB); + let ib16_handle = buffer(&mut ctx, ib16.len(), INDEXED_IB); + let ib32_handle = buffer(&mut ctx, ib32.len(), INDEXED_IB + 0x1000); + let mut memory = GuestMemory::new(); + for (addr, bytes) in [ + (INDEXED_VB, &vertices), + (INDEXED_IB, &ib16), + (INDEXED_IB + 0x1000, &ib32), + ] { + memory + .map_region_with_data(addr, 0x1000, MemoryPermissions::READ_ONLY, bytes) + .unwrap(); + } + IndexedRig { + ctx, + memory, + queue, + alloc, + list, + vb, + ib16: ib16_handle, + ib32: ib32_handle, + } +} + +/// Record one indexed draw (16x16 viewport, the rig's vertex buffer) and run it. +fn run_indexed( + rig: &mut IndexedRig, + index_buffer: (GraphicsHandle, usize, u32), + draw: (u32, u32, u32, i32), +) -> Result { + let ctx = &mut rig.ctx; + ctx.reset_command_list(rig.list, rig.alloc)?; + ctx.cmd_set_viewport(rig.list, 16, 16)?; + ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE)?; + ctx.cmd_set_index_buffer(rig.list, index_buffer.0, index_buffer.1, index_buffer.2)?; + let (count, instances, start, base) = draw; + ctx.cmd_draw_indexed_instanced(rig.list, count, instances, start, base, 0)?; + ctx.close_command_list(rig.list)?; + ctx.execute_command_list(rig.queue, rig.list, &rig.memory) +} + +const R16_UINT: u32 = 57; +const R32_UINT: u32 = 42; + +/// Start index, signed base vertex, index size and buffer offset all select +/// vertices 5, 7, 2: the backend receives exactly the triangle's positions +/// (literal values), never a decoy. +#[test] +fn test_d3d12_indexed_draw_fetches_start_and_base_vertex() { + let mut rig = indexed_rig(); + let seen = Arc::new(std::sync::Mutex::new(Vec::new())); + let record = seen.clone(); + rig.ctx.set_metal_backend(move |vtx, viewport, clear| { + record.lock().unwrap().push(*vtx); + GraphicsContext::execute_software_reference_draw(vtx, viewport, clear) + }); + let (ib16, ib32) = (rig.ib16, rig.ib32); + for (name, buffer, draw) in [ + // 16-bit indices 3, 5, 0 at index 4, base vertex +2. + ("u16 positive base", (ib16, 0, R16_UINT), (3, 1, 4, 2)), + // 16-bit indices 6, 8, 3 at index 2, base vertex -1. + ("u16 negative base", (ib16, 0, R16_UINT), (3, 1, 2, -1)), + // The same through a buffer offset of one index (2 bytes). + ("u16 buffer offset", (ib16, 2, R16_UINT), (3, 1, 1, -1)), + // 32-bit indices 3, 5, 0 at index 1, base vertex +2. + ("u32 positive base", (ib32, 0, R32_UINT), (3, 1, 1, 2)), + // 32-bit indices above 16 bits, base vertex -65534: all 32 bits count. + ("u32 wide indices", (ib32, 0, R32_UINT), (3, 1, 5, -65534)), + ] { + seen.lock().unwrap().clear(); + let outcome = run_indexed(&mut rig, buffer, draw).expect(name); + assert_eq!(outcome.draw_count, 1, "{name}"); + assert_eq!(*seen.lock().unwrap(), vec![INDEXED_TRIANGLE], "{name}"); + assert_eq!( + outcome.pixels, + GraphicsContext::execute_software_reference_draw( + &INDEXED_TRIANGLE, + (16, 16), + [0, 0, 0, 255] + ) + .unwrap(), + "{name}" + ); + } + // Zero indices or zero instances draw nothing. + for draw in [(0, 1, 0, 0), (3, 0, 0, 0)] { + let outcome = run_indexed(&mut rig, (ib16, 0, R16_UINT), draw).unwrap(); + assert_eq!(outcome.draw_count, 0); + } +} + +/// Index format, offset, count, range, negative fetch and unknown or missing +/// buffers each fail with a typed error, and nothing reaches the backend. +#[test] +fn test_d3d12_indexed_draw_errors() { + let mut rig = indexed_rig(); + let (ib16, ib32) = (rig.ib16, rig.ib32); + let unknown = GraphicsHandle { + id: 999, + generation: 1, + }; + for format in [0, 41, 56, 58, 28] { + assert_eq!( + run_indexed(&mut rig, (ib16, 0, format), (3, 1, 0, 0)).unwrap_err(), + GraphicsError::InvalidIndexFormat(format) + ); + } + for (name, buffer, draw, error) in [ + ( + "misaligned offset", + (ib32, 2, R32_UINT), + (3, 1, 0, 0), + GraphicsError::InvalidDescriptor, + ), + ( + "offset past buffer", + (ib16, 16, R16_UINT), + (3, 1, 0, 0), + GraphicsError::InvalidDescriptor, + ), + ( + "unknown buffer", + (unknown, 0, R16_UINT), + (3, 1, 0, 0), + GraphicsError::InvalidResourceHandle, + ), + ( + "count not one triangle", + (ib16, 0, R16_UINT), + (6, 1, 0, 0), + GraphicsError::InvalidDescriptor, + ), + ( + "indices past buffer", + (ib16, 0, R16_UINT), + (3, 1, 5, 0), + GraphicsError::IndexOutOfRange, + ), + ( + "start overflow", + (ib32, 0, R32_UINT), + (3, 1, u32::MAX, 0), + GraphicsError::IndexOutOfRange, + ), + ( + "negative vertex", + (ib16, 0, R16_UINT), + (3, 1, 4, -1), + GraphicsError::IndexOutOfRange, + ), + ( + "vertex past buffer", + (ib16, 0, R16_UINT), + (3, 1, 0, 1), + GraphicsError::IndexOutOfRange, + ), + ( + "base overflow", + (ib32, 0, R32_UINT), + (3, 1, 0, i32::MAX), + GraphicsError::IndexOutOfRange, + ), + ] { + let got = run_indexed(&mut rig, buffer, draw); + assert_eq!(got.unwrap_err(), error, "{name}"); + } + + // A draw without an index buffer is rejected at execution. + let ctx = &mut rig.ctx; + ctx.reset_command_list(rig.list, rig.alloc).unwrap(); + ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE) + .unwrap(); + ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 0, 0, 0) + .unwrap(); + ctx.close_command_list(rig.list).unwrap(); + assert_eq!( + ctx.execute_command_list(rig.queue, rig.list, &rig.memory), + Err(GraphicsError::InvalidResourceHandle) + ); + // A stride smaller than one float4 position is rejected. + ctx.reset_command_list(rig.list, rig.alloc).unwrap(); + ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, 12).unwrap(); + ctx.cmd_set_index_buffer(rig.list, ib16, 0, R16_UINT) + .unwrap(); + ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 4, 2, 0) + .unwrap(); + ctx.close_command_list(rig.list).unwrap(); + assert_eq!( + ctx.execute_command_list(rig.queue, rig.list, &rig.memory), + Err(GraphicsError::InvalidDescriptor) + ); +} + +/// The loader's indexed fetch feeds the native Metal renderer: the GPU image +/// of the fetched triangle equals the image of the literal triangle. +#[test] +#[cfg_attr( + not(feature = "gpu-tests"), + ignore = "needs native Metal device; run scripts/test-gpu.sh" +)] +fn test_d3d12_indexed_draw_native_metal() { + use xenora_metal::NativeCompute; + use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; + + let vs_bytes = include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"); + let ps_bytes = include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"); + let msl = compile_graphics(Architecture::Gfx1030, vs_bytes, ps_bytes) + .expect("compile graphics RDNA2 shaders") + .msl; + let gpu = Arc::new(NativeCompute::new().expect("native Metal GPU device")); + let render = { + let gpu = gpu.clone(); + let msl = msl.clone(); + move |vtx: &[[f32; 4]; 3], vp: (usize, usize), cc: [u8; 4]| { + gpu.render_rgba8( + &msl, + [VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT], + vtx, + &[[0.0; 4]; 3], + [vp.0, vp.1], + cc, + ) + .map_err(|e| GraphicsError::BackendError(format!("Metal GPU error: {e:?}"))) + } + }; + let direct = render(&INDEXED_TRIANGLE, (16, 16), [0, 0, 0, 255]).expect("direct render"); + let mut rig = indexed_rig(); + rig.ctx.set_metal_backend(render); + let ib16 = rig.ib16; + let outcome = run_indexed(&mut rig, (ib16, 0, R16_UINT), (3, 1, 2, -1)).expect("indexed"); + assert_eq!(outcome.backend, GraphicsBackendId::MetalNative); + assert_eq!(outcome.pixels, direct); + // The constant shader paints the covered pixels red; the CPU rasteriser + // agrees pixel for pixel, and the triangle covers some but not all pixels. + let reference = GraphicsContext::execute_software_reference_draw( + &INDEXED_TRIANGLE, + (16, 16), + [0, 0, 0, 255], + ) + .unwrap(); + assert_eq!(outcome.pixels, reference); + let red = outcome + .pixels + .chunks(4) + .filter(|p| *p == [255, 0, 0, 255]) + .count(); + assert!((1..256).contains(&red), "{red} red pixels"); + println!("indexed native Metal draw: {red} of 256 pixels covered"); +} diff --git a/crates/metal/Cargo.toml b/crates/metal/Cargo.toml index d68622b7..9f5789fa 100644 --- a/crates/metal/Cargo.toml +++ b/crates/metal/Cargo.toml @@ -32,6 +32,7 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = [" objc2-metal = { version = "=0.3.2", default-features = false, features = [ "std", "MTLAllocation", + "MTLArgument", "MTLBuffer", "MTLCommandBuffer", "MTLCommandEncoder", diff --git a/crates/metal/src/compute.rs b/crates/metal/src/compute.rs index fca3bcf3..24c465ab 100644 --- a/crates/metal/src/compute.rs +++ b/crates/metal/src/compute.rs @@ -23,7 +23,10 @@ use xenora_texture::{ #[path = "render.rs"] mod render; -pub use render::{DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState}; +pub use render::{ + DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, IndexBuffer, + IndexedDraw, IndexedPass, +}; const MAX_THREADS_PER_GROUP: usize = 64; const MAX_GROUPS: usize = 64; diff --git a/crates/metal/src/lib.rs b/crates/metal/src/lib.rs index 9cbab06e..60636f6f 100644 --- a/crates/metal/src/lib.rs +++ b/crates/metal/src/lib.rs @@ -15,7 +15,7 @@ pub mod texture_pipeline; #[cfg(all(target_arch = "aarch64", target_os = "macos"))] pub use compute::{ DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer, - GuestBufferView, MetalError, NativeCompute, RunProfile, + GuestBufferView, IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile, }; #[cfg(all(target_arch = "aarch64", target_os = "macos"))] diff --git a/crates/metal/src/render.rs b/crates/metal/src/render.rs index 6b3e5f1d..a9340927 100644 --- a/crates/metal/src/render.rs +++ b/crates/metal/src/render.rs @@ -7,8 +7,8 @@ use objc2::runtime::{NSObjectProtocol, ProtocolObject}; use objc2::sel; use objc2_metal::{ MTLClearColor, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction, - MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDevice, MTLFunction, MTLLoadAction, - MTLOrigin, MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder, + MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDevice, MTLFunction, MTLIndexType, + MTLLoadAction, MTLOrigin, MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder, MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, MTLRenderPipelineState, MTLShaderValidation, MTLSize, MTLStorageMode, MTLStoreAction, MTLTexture, MTLTextureDescriptor, MTLTextureUsage, MTLViewport, @@ -717,6 +717,296 @@ impl NativeCompute { } } +const MAX_INDEXED_VERTICES: usize = 1024; +const MAX_INDICES: usize = 4096; + +/// An index buffer of 16- or 32-bit unsigned indices. +#[derive(Clone, Copy, Debug)] +pub enum IndexBuffer<'a> { + U16(&'a [u16]), + U32(&'a [u32]), +} + +impl IndexBuffer<'_> { + fn len(self) -> usize { + match self { + Self::U16(indices) => indices.len(), + Self::U32(indices) => indices.len(), + } + } + + fn index(self, position: usize) -> u32 { + match self { + Self::U16(indices) => u32::from(indices[position]), + Self::U32(indices) => indices[position], + } + } + + fn size(self) -> usize { + match self { + Self::U16(_) => 2, + Self::U32(_) => 4, + } + } + + /// The indices packed into little-endian words, the last one zero-padded. + fn words(self) -> Vec { + match self { + Self::U16(indices) => indices + .chunks(2) + .map(|pair| { + u32::from(pair[0]) | pair.get(1).map_or(0, |&high| u32::from(high) << 16) + }) + .collect(), + Self::U32(indices) => indices.to_vec(), + } + } +} + +/// One indexed triangle-list draw: `index_count` indices from `start_index`, +/// each fetching vertex `index + base_vertex`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct IndexedDraw { + pub start_index: usize, + pub index_count: usize, + pub base_vertex: i32, + pub fill: DepthFill, +} + +/// An offscreen pass of up to 16 indexed draws, in order, into a cleared +/// RGBA8Unorm target without depth attachment. +#[derive(Clone, Copy, Debug)] +pub struct IndexedPass<'a> { + pub extent: [usize; 2], + pub clear_color: [u8; 4], + /// Up to 1024 clip-space float4 positions. + pub vertices: &'a [[f32; 4]], + /// Up to 4096 indices shared by every draw. + pub indices: IndexBuffer<'a>, + pub draws: &'a [IndexedDraw], + /// As [`DepthPass::texture`], for [`DepthFill::Bc1Texture`] draws. + pub texture: Option<&'a Bc1Upload<'a>>, +} + +impl NativeCompute { + /// Draw an indexed offscreen pass and read back its colour. + /// + /// Each draw is one native `drawIndexedPrimitives` call on the pass's + /// index buffer with the draw's start offset and signed base vertex, so + /// Metal itself fetches the vertices. Every fetched vertex is checked + /// against the vertex buffer first: out-of-range fetches are rejected, + /// never left to the GPU. Base vertex needs no capability query: the + /// Apple family 7 that [`NativeCompute::new`] requires supports it. + /// + /// # Errors + /// + /// Returns an error for an invalid extent, too many draws, vertices or + /// indices, non-finite positions, an index count that is zero or not a + /// multiple of 3, an index range past the buffer, a fetched vertex outside + /// the vertex buffer, a textured draw without texture, unavailable BC + /// compression (operation `supportsBCTextureCompression`), or Metal setup + /// or execution failure. + pub fn render_indexed(&self, pass: &IndexedPass<'_>) -> Result, MetalError> { + let [width, height] = pass.extent; + let pixels = width + .checked_mul(height) + .filter(|&count| (1..=MAX_PIXELS).contains(&count)) + .ok_or_else(|| MetalError::new("render bounds", "expected 1..=4096 pixels"))?; + validate_indexed_pass(pass)?; + let bc1 = pass + .texture + .map(|upload| { + let level = upload.subresource(0, 0).map_err(|error| { + MetalError::new("texture subresource", format!("{error:?}")) + })?; + self.validate_bc_extent(level.width, level.height, "BC1")?; + self.new_bc1_texture(&level) + }) + .transpose()?; + + autoreleasepool(|_| { + let options = compile_options()?; + let library = self.compile_library(DEPTH_SOURCE, &options)?; + let vertex = find_function(&library, "depth_vertex")?; + let flat = self.depth_pipeline( + &vertex, + &*find_function(&library, "depth_flat")?, + MTLPixelFormat::Invalid, + )?; + let textured = self.depth_pipeline( + &vertex, + &*find_function(&library, "depth_textured")?, + MTLPixelFormat::Invalid, + )?; + let color = self.new_target( + PIXEL_FORMAT, + width, + height, + MTLStorageMode::Shared, + MTLTextureUsage::RenderTarget, + )?; + let pass_descriptor = MTLRenderPassDescriptor::renderPassDescriptor(); + // SAFETY: Slot zero is the only color attachment for this pass. + let attachment = unsafe { + pass_descriptor + .colorAttachments() + .objectAtIndexedSubscript(0) + }; + attachment.setTexture(Some(&color)); + attachment.setLoadAction(MTLLoadAction::Clear); + let [red, green, blue, alpha] = pass.clear_color.map(|value| f64::from(value) / 255.0); + attachment.setClearColor(MTLClearColor { + red, + green, + blue, + alpha, + }); + attachment.setStoreAction(MTLStoreAction::Store); + let positions: Vec = pass + .vertices + .as_flattened() + .iter() + .map(|value| value.to_bits()) + .collect(); + let positions = self.new_buffer(&positions)?; + let indices = self.new_buffer(&pass.indices.words())?; + let index_type = match pass.indices { + IndexBuffer::U16(_) => MTLIndexType::UInt16, + IndexBuffer::U32(_) => MTLIndexType::UInt32, + }; + let command = self.queue.commandBuffer().ok_or_else(|| { + MetalError::new("commandBuffer", "render command buffer creation failed") + })?; + let encoder = command + .renderCommandEncoderWithDescriptor(&pass_descriptor) + .ok_or_else(|| { + MetalError::new( + "renderCommandEncoderWithDescriptor", + "render encoder creation failed", + ) + })?; + encoder.setViewport(MTLViewport { + originX: 0.0, + originY: 0.0, + width: width as f64, + height: height as f64, + znear: 0.0, + zfar: 1.0, + }); + let extent = [width as f32, height as f32]; + for draw in pass.draws { + // SAFETY: Validation proved that every index the draw reads lies + // inside the index buffer, that the offset is a multiple of the + // index size, and that every `index + base_vertex` names a float4 + // of the position buffer, the only memory the vertex stage reads. + // Fragment constants are copied by Metal and match the declared + // types. The texture, when bound, is a live BC1 texture of this + // device; both buffers outlive the command. + unsafe { + encoder.setVertexBuffer_offset_atIndex(Some(&positions), 0, 0); + match draw.fill { + DepthFill::Flat(rgba) => { + encoder.setRenderPipelineState(&flat); + let rgba = rgba.map(|value| f32::from(value) / 255.0); + encoder.setFragmentBytes_length_atIndex( + NonNull::from(&rgba).cast(), + size_of_val(&rgba), + 0, + ); + } + DepthFill::Bc1Texture => { + encoder.setRenderPipelineState(&textured); + encoder.setFragmentTexture_atIndex(bc1.as_deref(), 0); + encoder.setFragmentBytes_length_atIndex( + NonNull::from(&extent).cast(), + size_of_val(&extent), + 0, + ); + } + } + encoder.drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_baseVertex_baseInstance( + MTLPrimitiveType::Triangle, + draw.index_count, + index_type, + &indices, + draw.start_index * pass.indices.size(), + 1, + draw.base_vertex as isize, + 0, + ); + } + } + encoder.endEncoding(); + complete_command(&command)?; + + let mut output = vec![0; pixels * 4]; + // SAFETY: GPU writes have completed, and the initialized output + // allocation fits the entire shared texture with tightly packed rows. + unsafe { + color.getBytes_bytesPerRow_fromRegion_mipmapLevel( + NonNull::from(output.as_mut_slice()).cast(), + width * 4, + whole(width, height), + 0, + ); + } + Ok(output) + }) + } +} + +fn validate_indexed_pass(pass: &IndexedPass<'_>) -> Result<(), MetalError> { + let invalid = |reason: String| Err(MetalError::new("indexed pass", reason)); + if pass.draws.len() > MAX_DEPTH_DRAWS { + return invalid("expected at most 16 draws".to_owned()); + } + if !(1..=MAX_INDEXED_VERTICES).contains(&pass.vertices.len()) + || !(1..=MAX_INDICES).contains(&pass.indices.len()) + { + return invalid("expected 1..=1024 vertices and 1..=4096 indices".to_owned()); + } + if pass + .vertices + .as_flattened() + .iter() + .any(|value| !value.is_finite()) + { + return Err(MetalError::new( + "render input", + "expected finite vertex data", + )); + } + for (number, draw) in pass.draws.iter().enumerate() { + if draw.index_count == 0 || !draw.index_count.is_multiple_of(3) { + return invalid(format!( + "draw {number}: index count must be a nonzero multiple of 3" + )); + } + let end = draw + .start_index + .checked_add(draw.index_count) + .filter(|&end| end <= pass.indices.len()) + .ok_or_else(|| { + MetalError::new( + "indexed pass", + format!("draw {number}: index range past the index buffer"), + ) + })?; + for position in draw.start_index..end { + let vertex = i64::from(pass.indices.index(position)) + i64::from(draw.base_vertex); + if !(0..pass.vertices.len() as i64).contains(&vertex) { + return invalid(format!( + "draw {number}: index {position} fetches vertex {vertex} outside the vertex buffer" + )); + } + } + if draw.fill == DepthFill::Bc1Texture && pass.texture.is_none() { + return invalid("textured draw without texture".to_owned()); + } + } + Ok(()) +} + fn validate_depth_pass(pass: &DepthPass<'_>) -> Result<(), MetalError> { if pass.draws.len() > MAX_DEPTH_DRAWS { return Err(MetalError::new("depth pass", "expected at most 16 draws")); diff --git a/crates/metal/tests/fixtures/indexed_expected.txt b/crates/metal/tests/fixtures/indexed_expected.txt new file mode 100644 index 00000000..19eea09c --- /dev/null +++ b/crates/metal/tests/fixtures/indexed_expected.txt @@ -0,0 +1,294 @@ +case clear +palette A 16 32 48 255 +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +end +case u16_first +fetch 0 1 2 +palette A 255 0 0 255 +palette B 0 0 0 255 +color AAAAAAAAAAAAAAAB +color AAAAAAAAAAAAAABB +color AAAAAAAAAAAAABBB +color AAAAAAAAAAABBBBB +color AAAAAAAAAABBBBBB +color AAAAAAAAABBBBBBB +color AAAAAAABBBBBBBBB +color AAAAAABBBBBBBBBB +color AAAAABBBBBBBBBBB +color AAABBBBBBBBBBBBB +color AABBBBBBBBBBBBBB +color ABBBBBBBBBBBBBBB +color BBBBBBBBBBBBBBBB +color BBBBBBBBBBBBBBBB +color BBBBBBBBBBBBBBBB +color BBBBBBBBBBBBBBBB +end +case u32_first +fetch 0 1 2 +palette A 255 0 0 255 +palette B 0 0 0 255 +color AAAAAAAAAAAAAAAB +color AAAAAAAAAAAAAABB +color AAAAAAAAAAAAABBB +color AAAAAAAAAAABBBBB +color AAAAAAAAAABBBBBB +color AAAAAAAAABBBBBBB +color AAAAAAABBBBBBBBB +color AAAAAABBBBBBBBBB +color AAAAABBBBBBBBBBB +color AAABBBBBBBBBBBBB +color AABBBBBBBBBBBBBB +color ABBBBBBBBBBBBBBB +color BBBBBBBBBBBBBBBB +color BBBBBBBBBBBBBBBB +color BBBBBBBBBBBBBBBB +color BBBBBBBBBBBBBBBB +end +case u16_odd_start +fetch 3 4 5 +palette A 0 0 0 255 +palette B 0 255 0 255 +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAABBBBBBAAAAAA +color AAAABBBBBBBBBBBB +color AAAABBBBBBBBBBBA +color AAAAABBBBBBBBBAA +color AAAAABBBBBBBBAAA +color AAAAABBBBBBBAAAA +color AAAAABBBBBBAAAAA +color AAAAABBBBBBAAAAA +color AAAAABBBBBAAAAAA +color AAAAABBBBAAAAAAA +color AAAAAABBAAAAAAAA +color AAAAAABAAAAAAAAA +color AAAAAAAAAAAAAAAA +end +case u32_start +fetch 3 4 5 +palette A 0 0 0 255 +palette B 0 255 0 255 +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAABBBBBBAAAAAA +color AAAABBBBBBBBBBBB +color AAAABBBBBBBBBBBA +color AAAAABBBBBBBBBAA +color AAAAABBBBBBBBAAA +color AAAAABBBBBBBAAAA +color AAAAABBBBBBAAAAA +color AAAAABBBBBBAAAAA +color AAAAABBBBBAAAAAA +color AAAAABBBBAAAAAAA +color AAAAAABBAAAAAAAA +color AAAAAABAAAAAAAAA +color AAAAAAAAAAAAAAAA +end +case u16_base_positive +fetch 6 7 8 +palette A 0 0 0 255 +palette B 0 0 255 255 +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color BBBBBBBBBAAAAAAA +color BBBBBBBBAAAAAAAA +color BBBBBBBAAAAAAAAA +color BBBBBBAAAAAAAAAA +color BBBBAAAAAAAAAAAA +color BBBAAAAAAAAAAAAA +color BBAAAAAAAAAAAAAA +color BAAAAAAAAAAAAAAA +end +case u16_base_negative +fetch 6 7 8 +palette A 0 0 0 255 +palette B 0 0 255 255 +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color BBBBBBBBBAAAAAAA +color BBBBBBBBAAAAAAAA +color BBBBBBBAAAAAAAAA +color BBBBBBAAAAAAAAAA +color BBBBAAAAAAAAAAAA +color BBBAAAAAAAAAAAAA +color BBAAAAAAAAAAAAAA +color BAAAAAAAAAAAAAAA +end +case u32_base_negative +fetch 6 7 8 +palette A 0 0 0 255 +palette B 0 0 255 255 +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color AAAAAAAAAAAAAAAA +color BBBBBBBBBAAAAAAA +color BBBBBBBBAAAAAAAA +color BBBBBBBAAAAAAAAA +color BBBBBBAAAAAAAAAA +color BBBBAAAAAAAAAAAA +color BBBAAAAAAAAAAAAA +color BBAAAAAAAAAAAAAA +color BAAAAAAAAAAAAAAA +end +case reversed_winding +fetch 2 1 0 +palette A 255 0 0 255 +palette B 0 0 0 255 +color AAAAAAAAAAAAAAAB +color AAAAAAAAAAAAAABB +color AAAAAAAAAAAAABBB +color AAAAAAAAAAABBBBB +color AAAAAAAAAABBBBBB +color AAAAAAAAABBBBBBB +color AAAAAAABBBBBBBBB +color AAAAAABBBBBBBBBB +color AAAAABBBBBBBBBBB +color AAABBBBBBBBBBBBB +color AABBBBBBBBBBBBBB +color ABBBBBBBBBBBBBBB +color BBBBBBBBBBBBBBBB +color BBBBBBBBBBBBBBBB +color BBBBBBBBBBBBBBBB +color BBBBBBBBBBBBBBBB +end +case two_triangles_textured +fetch 9 10 11 9 11 12 +palette A 255 0 0 255 +palette B 0 0 255 255 +palette C 0 0 0 0 +palette D 0 255 0 255 +palette E 255 255 255 255 +palette F 255 255 0 255 +palette G 132 130 132 255 +palette H 8 8 8 255 +palette I 0 0 0 255 +color AABBAABBCCCCDDDD +color AABBAABBCCCCDDDD +color BBAABBAADDDDCCCC +color BBAABBAADDDDCCCC +color AAAABBBBDDCCDDEE +color AAAABBBBDDCCDDEE +color BBBBAAAAEEDDCCDD +color BBBBAAAAEEDDCCDD +color FFFFFFFFGGHHHHGG +color FFFFFFFFGGHHHHGG +color IIIIIIIIHHGGGGHH +color IIIIIIIIHHGGGGHH +color FFFFFFFFGGHHHHGG +color FFFFFFFFGGHHHHGG +color IIIIIIIIHHGGGGHH +color IIIIIIIIIIIIIIII +end +case textured_base_vertex +fetch 9 10 11 +palette A 0 0 0 255 +palette B 255 0 0 255 +palette C 0 0 255 255 +palette D 0 0 0 0 +palette E 0 255 0 255 +palette F 255 255 255 255 +palette G 132 130 132 255 +palette H 8 8 8 255 +color ABCCBBCCDDDDEEEE +color AACCBBCCDDDDEEEE +color AAABCCBBEEEEDDDD +color AAAACCBBEEEEDDDD +color AAAAACCCEEDDEEFF +color AAAAAACCEEDDEEFF +color AAAAAAABFFEEDDEE +color AAAAAAAAFFEEDDEE +color AAAAAAAAAGHHHHGG +color AAAAAAAAAAHHHHGG +color AAAAAAAAAAAGGGHH +color AAAAAAAAAAAAGGHH +color AAAAAAAAAAAAAHGG +color AAAAAAAAAAAAAAGG +color AAAAAAAAAAAAAAAH +color AAAAAAAAAAAAAAAA +end +case painter_order +fetch 0 1 2 +fetch 3 4 5 +fetch 6 7 8 +palette A 255 0 0 255 +palette B 0 0 0 255 +palette C 0 255 0 255 +palette D 0 0 255 255 +color AAAAAAAAAAAAAAAB +color AAAAAAAAAAAAAABB +color AAAAAAAAAAAAABBB +color AAAACCCCCCABBBBB +color AAAACCCCCCCCCCCC +color AAAACCCCCCCCCCCB +color AAAAACCCCCCCCCBB +color AAAAACCCCCCCCBBB +color DDDDDDDDDCCCBBBB +color DDDDDDDDCCCBBBBB +color DDDDDDDCCCCBBBBB +color DDDDDDCCCCBBBBBB +color DDDDBCCCCBBBBBBB +color DDDBBBCCBBBBBBBB +color DDBBBBCBBBBBBBBB +color DBBBBBBBBBBBBBBB +end +case u32_mixed +fetch 9 10 11 9 11 12 +fetch 9 10 11 +fetch 0 1 2 +palette A 255 0 0 255 +palette B 0 255 0 255 +palette C 255 255 0 255 +palette D 132 130 132 255 +palette E 0 0 0 255 +palette F 8 8 8 255 +color AAAAAAAAAAAAAAAB +color AAAAAAAAAAAAAABB +color AAAAAAAAAAAAABBB +color AAAAAAAAAAABBBBB +color AAAAAAAAAABBBBBB +color AAAAAAAAABBBBBBB +color AAAAAAABBBBBBBBB +color AAAAAAAABBBBBBBB +color AAAAACCCDBBBBBBB +color AAACCCCCDDBBBBBB +color AAEEEEEEFFDBBBBB +color AEEEEEEEFFDDBBBB +color CCCCCCCCDDFFFBBB +color CCCCCCCCDDFFFFBB +color EEEEEEEEFFDDDDFB +color EEEEEEEEEEEEEEEE +end diff --git a/crates/metal/tests/indexed_reference.rs b/crates/metal/tests/indexed_reference.rs new file mode 100644 index 00000000..f4067d2b --- /dev/null +++ b/crates/metal/tests/indexed_reference.rs @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! CPU check: the reference index fetch and rasteriser agree with the +//! independently derived expectations for every indexed case. Runs without a GPU. + +#[path = "support/indexed_cases.rs"] +mod indexed_cases; + +use indexed_cases::{BC1_BLOCKS, Fill, INDICES, SIZE, cases, expected, vertices}; +use xenora_ref::depth::{RefFill, RefTexture}; +use xenora_ref::indexed::{RefIndexedDraw, RefIndices, fetch, render_indexed}; + +fn bc1_texels() -> Vec<[u8; 4]> { + let mut texels = vec![[0; 4]; 64]; + for (block, bytes) in BC1_BLOCKS.as_chunks::<8>().0.iter().enumerate() { + for (index, texel) in xenora_texture::decode_bc1(*bytes).iter().enumerate() { + texels[((block / 2) * 4 + index / 4) * 8 + (block % 2) * 4 + index % 4] = *texel; + } + } + texels +} + +#[test] +fn reference_matches_independent_expectations() { + let texels = bc1_texels(); + let texture = RefTexture { + width: 8, + height: 8, + texels: &texels, + }; + let wide = INDICES.map(u32::from); + let vertices = vertices(); + let (cases, expected) = (cases(), expected()); + assert_eq!(cases.len(), 13); + assert_eq!(expected.len(), cases.len()); + for (case, want) in cases.iter().zip(&expected) { + assert_eq!(case.name, want.name); + let indices = if case.wide { + RefIndices::U32(&wide) + } else { + RefIndices::U16(&INDICES) + }; + let draws: Vec<_> = case + .draws + .iter() + .map(|draw| RefIndexedDraw { + start: draw.start, + count: draw.count, + base_vertex: draw.base_vertex, + fill: match draw.fill { + Fill::Flat(rgba) => RefFill::Flat(rgba), + Fill::Texture => RefFill::Texture, + }, + }) + .collect(); + let fetched: Vec<_> = draws + .iter() + .enumerate() + .map(|(number, draw)| fetch(number, draw, indices, vertices.len()).expect("fetch")) + .collect(); + assert_eq!(fetched, want.fetch, "{} fetch", case.name); + let color = render_indexed( + [SIZE, SIZE], + case.clear_color, + &vertices, + indices, + &draws, + Some(texture), + ) + .expect("reference render"); + assert_eq!(color, want.color, "{} colour", case.name); + } +} diff --git a/crates/metal/tests/native/indexed.rs b/crates/metal/tests/native/indexed.rs new file mode 100644 index 00000000..bdd089b0 --- /dev/null +++ b/crates/metal/tests/native/indexed.rs @@ -0,0 +1,138 @@ +use xenora_metal::{DepthFill, IndexBuffer, IndexedDraw, IndexedPass}; +use xenora_texture::{Bc1Upload, Bc1UploadDesc}; + +use super::indexed_cases::{BC1_BLOCKS, Case, Fill, INDICES, SIZE, cases, expected, vertices}; +use super::{context, native}; + +fn metal_draws(case: &Case) -> Vec { + case.draws + .iter() + .map(|draw| IndexedDraw { + start_index: draw.start, + index_count: draw.count, + base_vertex: draw.base_vertex, + fill: match draw.fill { + Fill::Flat(rgba) => DepthFill::Flat(rgba), + Fill::Texture => DepthFill::Bc1Texture, + }, + }) + .collect() +} + +fn bc1_upload() -> Bc1Upload<'static> { + Bc1Upload::new( + &BC1_BLOCKS, + Bc1UploadDesc { + width: 8, + height: 8, + mips: 1, + layers: 1, + format: 1, + usage: 1, + row_pitch: 16, + slice_pitch: 32, + }, + ) + .expect("valid BC1 upload") +} + +/// Each case's native colour must equal the independently derived image +/// (which the CPU reference also reproduces in `indexed_reference`), per pixel. +/// Metal fetches the vertices itself from the index buffer, start offset and +/// base vertex of each `drawIndexedPrimitives` call. +#[test] +fn indexed_draw_known_answers() { + let gpu = context(); + let upload = bc1_upload(); + let vertices = vertices(); + let wide = INDICES.map(u32::from); + let (cases, expected) = (cases(), expected()); + assert_eq!(cases.len(), expected.len()); + let mut checked = 0; + for (case, want) in cases.iter().zip(&expected) { + assert_eq!(case.name, want.name); + // One independently derived fetch list per draw keeps the fixtures aligned. + assert_eq!(want.fetch.len(), case.draws.len(), "{}", case.name); + let draws = metal_draws(case); + let color = native( + gpu.render_indexed(&IndexedPass { + extent: [SIZE, SIZE], + clear_color: case.clear_color, + vertices: &vertices, + indices: if case.wide { + IndexBuffer::U32(&wide) + } else { + IndexBuffer::U16(&INDICES) + }, + draws: &draws, + // Only textured cases need BC support, so a device without it fails + // those cases alone, as a capability error. + texture: case + .draws + .iter() + .any(|draw| draw.fill == Fill::Texture) + .then_some(&upload), + }), + ); + assert_eq!(color.len(), SIZE * SIZE * 4); + for (index, (pixel, wanted)) in color.as_chunks::<4>().0.iter().zip(&want.color).enumerate() + { + let (x, y) = (index % SIZE, index / SIZE); + assert_eq!(pixel, wanted, "{} colour at ({x}, {y})", case.name); + } + checked += 1; + } + println!("checked {checked} indexed passes of {} pixels", SIZE * SIZE); +} + +/// Every malformed draw is rejected before encoding, with its own reason. +#[test] +fn invalid_indexed_draws_are_rejected() { + let gpu = context(); + let vertices = vertices(); + let restart = [0, 1, u16::MAX]; + let flat = DepthFill::Flat([255; 4]); + let run = |indices, start_index, index_count, base_vertex, fill| { + gpu.render_indexed(&IndexedPass { + extent: [SIZE, SIZE], + clear_color: [0; 4], + vertices: &vertices, + indices, + draws: &[IndexedDraw { + start_index, + index_count, + base_vertex, + fill, + }], + texture: None, + }) + .expect_err("invalid draw must be rejected") + .to_string() + }; + let short = IndexBuffer::U16(&INDICES); + for (reason, error) in [ + // First: Metal itself would draw this one, so only the check rejects it. + ("count not a multiple of 3", run(short, 0, 4, 0, flat)), + ("zero count", run(short, 0, 0, 0, flat)), + ("range past buffer", run(short, 19, 3, 0, flat)), + ("start overflow", run(short, usize::MAX, 3, 0, flat)), + ("negative vertex", run(short, 0, 3, -1, flat)), + ("vertex past buffer", run(short, 9, 3, 2, flat)), + ( + "32-bit index past buffer", + run(IndexBuffer::U32(&[0, 1, 13]), 0, 3, 0, flat), + ), + ( + "restart value", + run(IndexBuffer::U16(&restart), 0, 3, 0, flat), + ), + ("base overflow", run(short, 0, 3, i32::MAX, flat)), + ( + "texture missing", + run(short, 0, 3, 0, DepthFill::Bc1Texture), + ), + ] { + println!("{reason}: {error}"); + assert!(error.contains("indexed pass"), "{reason}: {error}"); + } +} diff --git a/crates/metal/tests/native_compute.rs b/crates/metal/tests/native_compute.rs index ac89281e..6404bcd3 100644 --- a/crates/metal/tests/native_compute.rs +++ b/crates/metal/tests/native_compute.rs @@ -6,6 +6,10 @@ mod depth; mod depth_cases; #[path = "native/guest_buffer.rs"] mod guest_buffer; +#[path = "native/indexed.rs"] +mod indexed; +#[path = "support/indexed_cases.rs"] +mod indexed_cases; #[path = "native/offscreen.rs"] mod offscreen; #[path = "native/texture.rs"] diff --git a/crates/metal/tests/support/indexed_cases.rs b/crates/metal/tests/support/indexed_cases.rs new file mode 100644 index 00000000..8de6c1b2 --- /dev/null +++ b/crates/metal/tests/support/indexed_cases.rs @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Original indexed-draw fixtures shared by the CPU reference check and the +//! native Metal test, and the parser for the independently derived +//! expectations in `fixtures/indexed_expected.txt`. + +pub const SIZE: usize = 16; +const RED: [u8; 4] = [255, 0, 0, 255]; +const GREEN: [u8; 4] = [0, 255, 0, 255]; +const BLUE: [u8; 4] = [0, 0, 255, 255]; +const BLACK: [u8; 4] = [0, 0, 0, 255]; + +/// The four original BC1 blocks of the depth fixtures (8x8 texels), using +/// only endpoint and transparent selectors so every decoded texel is exact. +pub const BC1_BLOCKS: [u8; 32] = [ + 0x00, 0xF8, 0x1F, 0x00, 0x44, 0x11, 0x50, 0x05, // red / blue, four-colour + 0xE0, 0x07, 0xFF, 0xFF, 0x0F, 0xF0, 0x4C, 0x31, // green / white, three-colour + 0xE0, 0xFF, 0x00, 0x00, 0x00, 0x55, 0x00, 0x55, // yellow / black + 0x10, 0x84, 0x41, 0x08, 0x14, 0x41, 0x14, 0x41, // grey / near black +]; + +/// Vertex buffer in pixel coordinates; no pixel centre lies on any edge of +/// a triangle the cases draw. +const VERTICES: [[f32; 2]; 13] = [ + [0.0, 0.0], + [16.0, 0.0], + [0.0, 12.0], + [4.0, 3.0], + [16.0, 4.0], + [6.0, 16.0], + [0.0, 8.0], + [10.0, 8.0], + [0.0, 16.0], + [0.0, 0.0], + [16.0, 0.0], + [16.0, 15.0], + [0.0, 16.0], +]; + +/// The index buffer every case uses, as 16- or 32-bit indices. +pub const INDICES: [u16; 21] = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 9, 11, 12, 2, 1, 0, 10, 11, 12, +]; + +/// Clip-space positions of [`VERTICES`] at depth 0.5. +pub fn vertices() -> Vec<[f32; 4]> { + VERTICES + .iter() + .map(|[x, y]| [x / 8.0 - 1.0, 1.0 - y / 8.0, 0.5, 1.0]) + .collect() +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Fill { + Flat([u8; 4]), + Texture, +} + +#[derive(Clone, Copy, Debug)] +pub struct Draw { + pub start: usize, + pub count: usize, + pub base_vertex: i32, + pub fill: Fill, +} + +#[derive(Debug)] +pub struct Case { + pub name: &'static str, + pub wide: bool, + pub clear_color: [u8; 4], + pub draws: Vec, +} + +/// Every case, in fixture order. +pub fn cases() -> Vec { + let draw = |start, count, base_vertex, fill| Draw { + start, + count, + base_vertex, + fill, + }; + let (red, green, blue, texture) = ( + Fill::Flat(RED), + Fill::Flat(GREEN), + Fill::Flat(BLUE), + Fill::Texture, + ); + let case = |name, wide, draws| Case { + name, + wide, + clear_color: BLACK, + draws, + }; + vec![ + Case { + clear_color: [16, 32, 48, 255], + ..case("clear", false, Vec::new()) + }, + case("u16_first", false, vec![draw(0, 3, 0, red)]), + case("u32_first", true, vec![draw(0, 3, 0, red)]), + case("u16_odd_start", false, vec![draw(3, 3, 0, green)]), + case("u32_start", true, vec![draw(3, 3, 0, green)]), + case("u16_base_positive", false, vec![draw(0, 3, 6, blue)]), + case("u16_base_negative", false, vec![draw(18, 3, -4, blue)]), + case("u32_base_negative", true, vec![draw(18, 3, -4, blue)]), + case("reversed_winding", false, vec![draw(15, 3, 0, red)]), + case( + "two_triangles_textured", + false, + vec![draw(9, 6, 0, texture)], + ), + case("textured_base_vertex", false, vec![draw(0, 3, 9, texture)]), + case( + "painter_order", + false, + vec![ + draw(0, 3, 0, red), + draw(3, 3, 0, green), + draw(0, 3, 6, blue), + ], + ), + case( + "u32_mixed", + true, + vec![ + draw(9, 6, 0, texture), + draw(18, 3, -1, green), + draw(6, 3, -6, red), + ], + ), + ] +} + +/// One case of `indexed_expected.txt`: fetched vertices per draw and colours. +#[derive(Debug)] +pub struct Expected { + pub name: String, + pub fetch: Vec>, + pub color: Vec<[u8; 4]>, +} + +/// Parse the independently derived expectations. +pub fn expected() -> Vec { + let text = include_str!("../fixtures/indexed_expected.txt"); + let mut out = Vec::new(); + let mut lines = text.lines().filter(|line| !line.trim().is_empty()); + while let Some(header) = lines.next() { + let name = header.strip_prefix("case ").expect("case line").to_owned(); + let (mut fetch, mut palette, mut color) = (Vec::new(), Vec::new(), Vec::new()); + for line in lines.by_ref() { + let mut words = line.split_whitespace(); + match words.next().expect("keyword") { + "fetch" => fetch.push(words.map(|word| word.parse().unwrap()).collect()), + "palette" => { + let key = words.next().unwrap().chars().next().unwrap(); + let rgba: Vec = words.map(|word| word.parse().unwrap()).collect(); + palette.push((key, <[u8; 4]>::try_from(rgba).unwrap())); + } + "color" => color.extend(words.next().unwrap().chars().map(|c| { + palette + .iter() + .find(|(key, _)| *key == c) + .expect("palette key") + .1 + })), + "end" => break, + other => panic!("unexpected fixture line {other}"), + } + } + assert_eq!(color.len(), SIZE * SIZE, "{name} colour rows"); + out.push(Expected { name, fetch, color }); + } + out +} diff --git a/crates/ref/src/indexed.rs b/crates/ref/src/indexed.rs new file mode 100644 index 00000000..55630de7 --- /dev/null +++ b/crates/ref/src/indexed.rs @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Independent CPU reference for indexed triangle-list draws. +//! +//! A draw reads `count` indices starting at index `start` and fetches vertex +//! `index + base_vertex` for each, as `DrawIndexedInstanced` and Metal's +//! `drawIndexedPrimitives` describe. Every fetched vertex must lie inside the +//! vertex buffer; the reference rejects the draw instead of defining +//! out-of-range behaviour. The triangles are then rasterised by +//! [`crate::depth::render_depth`] without a depth attachment. + +use std::fmt; + +use crate::depth::{CompareFunction, RefDraw, RefFill, RefTexture, render_depth}; + +/// An index buffer of 16- or 32-bit unsigned indices. +#[derive(Clone, Copy, Debug)] +pub enum RefIndices<'a> { + U16(&'a [u16]), + U32(&'a [u32]), +} + +impl RefIndices<'_> { + fn len(self) -> usize { + match self { + Self::U16(indices) => indices.len(), + Self::U32(indices) => indices.len(), + } + } + + fn get(self, position: usize) -> Option { + match self { + Self::U16(indices) => indices.get(position).map(|&index| u32::from(index)), + Self::U32(indices) => indices.get(position).copied(), + } + } +} + +/// One indexed draw: a range of the index buffer, a signed base vertex and a fill. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct RefIndexedDraw { + pub start: usize, + pub count: usize, + pub base_vertex: i32, + pub fill: RefFill, +} + +#[derive(Debug, Eq, PartialEq)] +pub enum IndexedRefError { + /// The index count of the draw is zero or not a multiple of 3: (draw). + Count(usize), + /// The index range of the draw ends past the index buffer: (draw). + IndexRange(usize), + /// `index + base_vertex` lies outside the vertex buffer: (draw, index position). + VertexRange(usize, usize), + /// The resolved triangles could not be rasterised. + Raster(crate::depth::DepthRefError), +} + +impl fmt::Display for IndexedRefError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{self:?}") + } +} + +impl std::error::Error for IndexedRefError {} + +/// The vertex numbers draw `draw` of a pass fetches, in index order. +/// +/// # Errors +/// +/// Returns an error for a count that is zero or not a multiple of 3, an index +/// range past the buffer, or a fetched vertex outside `0..vertex_count`. +pub fn fetch( + draw_number: usize, + draw: &RefIndexedDraw, + indices: RefIndices<'_>, + vertex_count: usize, +) -> Result, IndexedRefError> { + if draw.count == 0 || !draw.count.is_multiple_of(3) { + return Err(IndexedRefError::Count(draw_number)); + } + let end = draw + .start + .checked_add(draw.count) + .filter(|&end| end <= indices.len()) + .ok_or(IndexedRefError::IndexRange(draw_number))?; + (draw.start..end) + .map(|position| { + let index = i64::from(indices.get(position).expect("position checked above")); + usize::try_from(index + i64::from(draw.base_vertex)) + .ok() + .filter(|&vertex| vertex < vertex_count) + .ok_or(IndexedRefError::VertexRange(draw_number, position)) + }) + .collect() +} + +/// Render indexed draws in order over a target cleared to `clear_color`. +/// +/// # Errors +/// +/// Returns an error when [`fetch`] rejects a draw or the resolved triangles +/// cannot be rasterised (see [`render_depth`]). +pub fn render_indexed( + extent: [usize; 2], + clear_color: [u8; 4], + vertices: &[[f32; 4]], + indices: RefIndices<'_>, + draws: &[RefIndexedDraw], + texture: Option>, +) -> Result, IndexedRefError> { + let mut triangles = Vec::new(); + for (number, draw) in draws.iter().enumerate() { + let fetched = fetch(number, draw, indices, vertices.len())?; + triangles.extend(fetched.as_chunks::<3>().0.iter().map(|triangle| RefDraw { + positions: triangle.map(|vertex| vertices[vertex]), + fill: draw.fill, + compare: CompareFunction::Always, + write: false, + })); + } + render_depth(extent, clear_color, None, &triangles, texture) + .map(|(color, _)| color) + .map_err(IndexedRefError::Raster) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn draw(start: usize, count: usize, base_vertex: i32) -> RefIndexedDraw { + RefIndexedDraw { + start, + count, + base_vertex, + fill: RefFill::Flat([255; 4]), + } + } + + #[test] + fn fetch_applies_start_and_signed_base_vertex() { + let indices = RefIndices::U16(&[7, 0, 1, 2, 5]); + assert_eq!(fetch(0, &draw(1, 3, 2), indices, 5), Ok(vec![2, 3, 4])); + assert_eq!(fetch(0, &draw(2, 3, -1), indices, 5), Ok(vec![0, 1, 4])); + } + + #[test] + fn fetch_rejects_bad_counts_ranges_and_vertices() { + let indices = RefIndices::U32(&[0, 1, 2, u32::MAX]); + assert_eq!( + fetch(3, &draw(0, 0, 0), indices, 3), + Err(IndexedRefError::Count(3)) + ); + assert_eq!( + fetch(0, &draw(0, 2, 0), indices, 3), + Err(IndexedRefError::Count(0)) + ); + assert_eq!( + fetch(0, &draw(2, 3, 0), indices, 3), + Err(IndexedRefError::IndexRange(0)) + ); + assert_eq!( + fetch(0, &draw(usize::MAX, 3, 0), indices, 3), + Err(IndexedRefError::IndexRange(0)) + ); + assert_eq!( + fetch(0, &draw(0, 3, -1), indices, 3), + Err(IndexedRefError::VertexRange(0, 0)) + ); + assert_eq!( + fetch(0, &draw(0, 3, 1), indices, 3), + Err(IndexedRefError::VertexRange(0, 2)) + ); + // The primitive-restart value is just another out-of-range index here. + assert_eq!( + fetch(0, &draw(1, 3, 0), indices, 3), + Err(IndexedRefError::VertexRange(0, 3)) + ); + } +} diff --git a/crates/ref/src/lib.rs b/crates/ref/src/lib.rs index a7ad2b0f..43a56c2c 100644 --- a/crates/ref/src/lib.rs +++ b/crates/ref/src/lib.rs @@ -1,8 +1,9 @@ // SPDX-License-Identifier: GPL-3.0-or-later -//! Independent CPU execution of the synthetic gfx1030 fixture subset, reference sampling and depth-tested rendering. +//! Independent CPU execution of the synthetic gfx1030 fixture subset, reference sampling, depth-tested rendering and indexed draws. pub mod depth; +pub mod indexed; pub mod texture_sampling; use std::fmt;