mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 03:39:52 +00:00
metal: depth attachment known-answer rendering (#191)
Draw ordered triangles with an optional Depth32Float attachment, per-draw compare function and write enable, and read back colour and stored depth, so depth compare, clear, write enable and disabled depth can each be checked against independently derived values. One draw samples an original BC1 texture through the native BC1 path, so the BC upload is exercised by rendering, not only by compute readback. Also adds the missing changelog lines for PR #224 (BC7) and PR #231 (#172). Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
This commit is contained in:
1 parent
0e7fa4aa93
commit
840eca0a29
12 files changed
+2344
-5
No files matched your search
@@ -11,6 +11,9 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- 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 bit-exactly. A draw can sample an original BC1 texture placed unchanged in a native `BC1_RGBA` texture, 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 with and without an attachment, 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).
|
||||
- Added the gfx1030 SOP2 forms `s_add_i32` and `s_sub_i32`, with SCC as signed overflow as defined in the AMD RDNA 2 ISA guide (sections 5.3 and 12.1). They are checked on CPU and on native Metal with validation on 400 boundary programs, four immediate-operand overflows and the scalar ALU fixture, plus eight hand-worked overflow and no-overflow cases on CPU.
|
||||
- Added the gfx1030 SOP2 scalar forms `s_add_u32`, `s_sub_u32`, `s_addc_u32`, `s_subb_u32`, `s_and_b32`, `s_or_b32` and `s_xor_b32`. They are decoded, executed by the reference and independent interpreters, and resolved by the translator, with SCC as carry, borrow or nonzero result. `v_mov_b32_e32` can now read a normal SGPR. Verified on 1,400 original operand vectors plus an LLVM-assembled fixture, on CPU and on native Metal with validation. The other SOP2 forms stay unsupported. See `docs/shaders/scalar-alu.md`.
|
||||
- Added `scripts/audit/test_inventory.py`, which lists the Cargo test inventory of two commits in temporary detached worktrees and reports removed, added, newly ignored and newly un-ignored tests, failing on any loss not explained in an `--allow` file. Run against the old PR #166 head 5450612 and main 951189c, it reports the 12 BC texture tests that head was missing (exit 1); the same commit against itself reports no change. Default features only; see `docs/testing/test-inventory.md`.
|
||||
|
||||
@@ -38,6 +38,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [
|
||||
"MTLCommandQueue",
|
||||
"MTLComputeCommandEncoder",
|
||||
"MTLComputePipeline",
|
||||
"MTLDepthStencil",
|
||||
"MTLDevice",
|
||||
"MTLLibrary",
|
||||
"MTLPixelFormat",
|
||||
|
||||
@@ -23,6 +23,8 @@ use xenora_texture::{
|
||||
#[path = "render.rs"]
|
||||
mod render;
|
||||
|
||||
pub use render::{DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState};
|
||||
|
||||
const MAX_THREADS_PER_GROUP: usize = 64;
|
||||
const MAX_GROUPS: usize = 64;
|
||||
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
|
||||
|
||||
@@ -13,7 +13,10 @@ pub mod sampler;
|
||||
pub mod texture_pipeline;
|
||||
|
||||
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
|
||||
pub use compute::{GuestBuffer, GuestBufferView, MetalError, NativeCompute, RunProfile};
|
||||
pub use compute::{
|
||||
DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer,
|
||||
GuestBufferView, MetalError, NativeCompute, RunProfile,
|
||||
};
|
||||
|
||||
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
|
||||
pub use sampler::MetalSampler;
|
||||
|
||||
+489
-3
@@ -2,19 +2,23 @@
|
||||
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use objc2::rc::autoreleasepool;
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
|
||||
use objc2::sel;
|
||||
use objc2_metal::{
|
||||
MTLClearColor, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLDevice, MTLLoadAction,
|
||||
MTLClearColor, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction,
|
||||
MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDevice, MTLFunction, MTLLoadAction,
|
||||
MTLOrigin, MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder,
|
||||
MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, MTLRenderPipelineState,
|
||||
MTLShaderValidation, MTLSize, MTLStorageMode, MTLStoreAction, MTLTexture, MTLTextureDescriptor,
|
||||
MTLTextureUsage, MTLViewport,
|
||||
};
|
||||
|
||||
use xenora_texture::Bc1Subresource;
|
||||
|
||||
use super::{
|
||||
MetalError, NativeCompute, compile_options, complete_command, find_function, validate_source,
|
||||
ComputeInput, MetalError, NativeCompute, compile_options, complete_command, find_function,
|
||||
validate_source,
|
||||
};
|
||||
|
||||
const MAX_PIXELS: usize = 4096;
|
||||
@@ -282,3 +286,485 @@ fn verify_render_validation(
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const DEPTH_FORMAT: MTLPixelFormat = MTLPixelFormat::Depth32Float;
|
||||
const MAX_DEPTH_DRAWS: usize = 16;
|
||||
|
||||
const DEPTH_SOURCE: &str = r"
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
|
||||
vertex float4 depth_vertex(uint id [[vertex_id]],
|
||||
const device float4 *positions [[buffer(0)]]) {
|
||||
return positions[id];
|
||||
}
|
||||
|
||||
fragment float4 depth_flat(constant float4 &color [[buffer(0)]]) {
|
||||
return color;
|
||||
}
|
||||
|
||||
fragment float4 depth_textured(float4 position [[position]],
|
||||
texture2d<float> image [[texture(0)]],
|
||||
constant float2 &extent [[buffer(0)]]) {
|
||||
constexpr sampler nearest(coord::normalized, filter::nearest, address::clamp_to_edge);
|
||||
return image.sample(nearest, position.xy / extent);
|
||||
}
|
||||
";
|
||||
|
||||
const DEPTH_READBACK: &str = r"
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void read_depth(depth2d<float, access::read> depth [[texture(0)]],
|
||||
device uint *output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint width = depth.get_width();
|
||||
output[index] = as_type<uint>(depth.read(uint2(index % width, index / width)));
|
||||
}
|
||||
";
|
||||
|
||||
/// Comparison of a fragment's depth against the stored depth; it passes when
|
||||
/// `fragment <compare> stored` holds.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum DepthCompare {
|
||||
Never,
|
||||
Less,
|
||||
Equal,
|
||||
LessEqual,
|
||||
Greater,
|
||||
NotEqual,
|
||||
GreaterEqual,
|
||||
Always,
|
||||
}
|
||||
|
||||
impl DepthCompare {
|
||||
fn metal(self) -> MTLCompareFunction {
|
||||
match self {
|
||||
Self::Never => MTLCompareFunction::Never,
|
||||
Self::Less => MTLCompareFunction::Less,
|
||||
Self::Equal => MTLCompareFunction::Equal,
|
||||
Self::LessEqual => MTLCompareFunction::LessEqual,
|
||||
Self::Greater => MTLCompareFunction::Greater,
|
||||
Self::NotEqual => MTLCompareFunction::NotEqual,
|
||||
Self::GreaterEqual => MTLCompareFunction::GreaterEqual,
|
||||
Self::Always => MTLCompareFunction::Always,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Depth test and write enable of one draw.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct DepthState {
|
||||
pub compare: DepthCompare,
|
||||
pub write: bool,
|
||||
}
|
||||
|
||||
impl DepthState {
|
||||
/// No depth test and no depth write: the only state allowed without a
|
||||
/// depth attachment.
|
||||
pub const DISABLED: Self = Self {
|
||||
compare: DepthCompare::Always,
|
||||
write: false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Colour source of one depth-pass draw.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum DepthFill {
|
||||
/// A constant RGBA8 colour.
|
||||
Flat([u8; 4]),
|
||||
/// The pass's BC1 texture, sampled with nearest filtering at the pixel centre.
|
||||
Bc1Texture,
|
||||
}
|
||||
|
||||
/// One triangle of a depth pass: three clip-space positions, colour and depth state.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct DepthDraw {
|
||||
pub positions: [[f32; 4]; 3],
|
||||
pub fill: DepthFill,
|
||||
pub depth: DepthState,
|
||||
}
|
||||
|
||||
/// An offscreen pass of up to 16 triangles drawn in order into a cleared
|
||||
/// RGBA8Unorm target with viewport depth range 0..1.
|
||||
///
|
||||
/// With `clear_depth`, the pass has a `Depth32Float` attachment cleared to that
|
||||
/// value and stored after the pass. Without it, the pass has no depth
|
||||
/// attachment and every draw must use [`DepthState::DISABLED`].
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct DepthPass<'a> {
|
||||
pub extent: [usize; 2],
|
||||
pub clear_color: [u8; 4],
|
||||
pub clear_depth: Option<f32>,
|
||||
pub draws: &'a [DepthDraw],
|
||||
/// A validated BC1 level placed unchanged in a native `BC1_RGBA` texture.
|
||||
pub texture: Option<&'a Bc1Subresource<'a>>,
|
||||
}
|
||||
|
||||
/// Colour bytes, tightly packed top-to-bottom, and the stored depth values
|
||||
/// when the pass has a depth attachment.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DepthOutput {
|
||||
pub color: Vec<u8>,
|
||||
pub depth: Option<Vec<f32>>,
|
||||
}
|
||||
|
||||
impl NativeCompute {
|
||||
/// Draw a depth-tested offscreen pass and read back colour and depth.
|
||||
///
|
||||
/// Each draw sets its own depth state before drawing, so depth compare,
|
||||
/// clear and write enable act exactly as the pass describes. The stored
|
||||
/// depth is read back bit-exactly by a compute kernel.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error for an invalid extent, too many draws, non-finite
|
||||
/// positions, a depth state without depth attachment, a non-finite clear
|
||||
/// depth or one outside 0..=1, a textured draw without texture, unavailable
|
||||
/// BC compression (operation `supportsBCTextureCompression`), or Metal
|
||||
/// setup or execution failure.
|
||||
pub fn render_depth(&self, pass: &DepthPass<'_>) -> Result<DepthOutput, 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_depth_pass(pass)?;
|
||||
let bc1 = pass
|
||||
.texture
|
||||
.map(|level| {
|
||||
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 depth_format = if pass.clear_depth.is_some() {
|
||||
DEPTH_FORMAT
|
||||
} else {
|
||||
MTLPixelFormat::Invalid
|
||||
};
|
||||
let flat = self.depth_pipeline(
|
||||
&vertex,
|
||||
&*find_function(&library, "depth_flat")?,
|
||||
depth_format,
|
||||
)?;
|
||||
let textured = self.depth_pipeline(
|
||||
&vertex,
|
||||
&*find_function(&library, "depth_textured")?,
|
||||
depth_format,
|
||||
)?;
|
||||
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 depth = pass
|
||||
.clear_depth
|
||||
.map(|clear| {
|
||||
let texture = self.new_target(
|
||||
DEPTH_FORMAT,
|
||||
width,
|
||||
height,
|
||||
MTLStorageMode::Private,
|
||||
MTLTextureUsage::RenderTarget | MTLTextureUsage::ShaderRead,
|
||||
)?;
|
||||
let depth_attachment = pass_descriptor.depthAttachment();
|
||||
depth_attachment.setTexture(Some(&texture));
|
||||
depth_attachment.setLoadAction(MTLLoadAction::Clear);
|
||||
depth_attachment.setClearDepth(f64::from(clear));
|
||||
depth_attachment.setStoreAction(MTLStoreAction::Store);
|
||||
Ok::<_, MetalError>(texture)
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
// A pass without draws still clears and stores both attachments.
|
||||
let words: Vec<u32> = pass
|
||||
.draws
|
||||
.iter()
|
||||
.flat_map(|draw| draw.positions.as_flattened())
|
||||
.map(|value| value.to_bits())
|
||||
.collect();
|
||||
let positions = (!words.is_empty())
|
||||
.then(|| self.new_buffer(&words))
|
||||
.transpose()?;
|
||||
// Everything fallible is resolved before encoding starts, so an
|
||||
// error never leaves an encoder without endEncoding.
|
||||
let states = pass
|
||||
.draws
|
||||
.iter()
|
||||
.map(|draw| {
|
||||
depth
|
||||
.as_ref()
|
||||
.map(|_| self.depth_state(draw.depth))
|
||||
.transpose()
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
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 (index, (draw, state)) in pass.draws.iter().zip(&states).enumerate() {
|
||||
if let Some(state) = state {
|
||||
encoder.setDepthStencilState(Some(state));
|
||||
}
|
||||
// SAFETY: The position buffer holds three float4s per draw and
|
||||
// the vertex stage reads only this draw's three. Fragment
|
||||
// constants are copied by Metal and match the declared types.
|
||||
// The texture, when bound, is a live BC1 texture of this device.
|
||||
unsafe {
|
||||
encoder.setVertexBuffer_offset_atIndex(positions.as_deref(), index * 48, 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.drawPrimitives_vertexStart_vertexCount(
|
||||
MTLPrimitiveType::Triangle,
|
||||
0,
|
||||
3,
|
||||
);
|
||||
}
|
||||
}
|
||||
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,
|
||||
);
|
||||
}
|
||||
let depth = depth
|
||||
.map(|texture| {
|
||||
self.run(
|
||||
DEPTH_READBACK,
|
||||
"read_depth",
|
||||
ComputeInput::Texture(&texture, pixels),
|
||||
)
|
||||
.map(|profile| profile.output.into_iter().map(f32::from_bits).collect())
|
||||
})
|
||||
.transpose()?;
|
||||
Ok(DepthOutput {
|
||||
color: output,
|
||||
depth,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn depth_pipeline(
|
||||
&self,
|
||||
vertex: &ProtocolObject<dyn MTLFunction>,
|
||||
fragment: &ProtocolObject<dyn MTLFunction>,
|
||||
depth_format: MTLPixelFormat,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLRenderPipelineState>>, MetalError> {
|
||||
let descriptor = MTLRenderPipelineDescriptor::new();
|
||||
descriptor.setVertexFunction(Some(vertex));
|
||||
descriptor.setFragmentFunction(Some(fragment));
|
||||
// SAFETY: Slot zero is the only color attachment for this pipeline.
|
||||
unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }
|
||||
.setPixelFormat(PIXEL_FORMAT);
|
||||
descriptor.setDepthAttachmentPixelFormat(depth_format);
|
||||
let pipeline = self
|
||||
.device
|
||||
.newRenderPipelineStateWithDescriptor_error(&descriptor)
|
||||
.map_err(|error| {
|
||||
MetalError::new(
|
||||
"newRenderPipelineStateWithDescriptor",
|
||||
error.localizedDescription().to_string(),
|
||||
)
|
||||
})?;
|
||||
verify_render_validation(&pipeline)?;
|
||||
Ok(pipeline)
|
||||
}
|
||||
|
||||
fn depth_state(
|
||||
&self,
|
||||
state: DepthState,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLDepthStencilState>>, MetalError> {
|
||||
let descriptor = MTLDepthStencilDescriptor::new();
|
||||
descriptor.setDepthCompareFunction(state.compare.metal());
|
||||
descriptor.setDepthWriteEnabled(state.write);
|
||||
self.device
|
||||
.newDepthStencilStateWithDescriptor(&descriptor)
|
||||
.ok_or_else(|| {
|
||||
MetalError::new(
|
||||
"newDepthStencilStateWithDescriptor",
|
||||
"depth state creation failed",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn new_target(
|
||||
&self,
|
||||
format: MTLPixelFormat,
|
||||
width: usize,
|
||||
height: usize,
|
||||
storage: MTLStorageMode,
|
||||
usage: MTLTextureUsage,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLTexture>>, MetalError> {
|
||||
// SAFETY: The nonzero dimensions are bounded by MAX_PIXELS, and both
|
||||
// RGBA8Unorm and Depth32Float are renderable on every Apple GPU family.
|
||||
let descriptor = unsafe {
|
||||
MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
|
||||
format, width, height, false,
|
||||
)
|
||||
};
|
||||
descriptor.setStorageMode(storage);
|
||||
descriptor.setUsage(usage);
|
||||
self.device
|
||||
.newTextureWithDescriptor(&descriptor)
|
||||
.ok_or_else(|| {
|
||||
MetalError::new(
|
||||
"newTextureWithDescriptor",
|
||||
"render target allocation failed",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn new_bc1_texture(
|
||||
&self,
|
||||
level: &Bc1Subresource<'_>,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLTexture>>, MetalError> {
|
||||
let texture = self.new_target(
|
||||
MTLPixelFormat::BC1_RGBA,
|
||||
level.width,
|
||||
level.height,
|
||||
MTLStorageMode::Shared,
|
||||
MTLTextureUsage::ShaderRead,
|
||||
)?;
|
||||
// Apple documents a zero stride for a single compressed block row.
|
||||
let bytes_per_row = if level.height <= 4 {
|
||||
0
|
||||
} else {
|
||||
level.row_pitch
|
||||
};
|
||||
// SAFETY: The region spans the whole level. `Bc1Upload::subresource`
|
||||
// validated that the bytes hold every block row at this stride.
|
||||
unsafe {
|
||||
texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
|
||||
whole(level.width, level.height),
|
||||
0,
|
||||
NonNull::from(level.bytes).cast(),
|
||||
bytes_per_row,
|
||||
);
|
||||
}
|
||||
Ok(texture)
|
||||
}
|
||||
}
|
||||
|
||||
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"));
|
||||
}
|
||||
if pass
|
||||
.draws
|
||||
.iter()
|
||||
.flat_map(|draw| draw.positions.as_flattened())
|
||||
.any(|value| !value.is_finite())
|
||||
{
|
||||
return Err(MetalError::new(
|
||||
"render input",
|
||||
"expected finite vertex data",
|
||||
));
|
||||
}
|
||||
if let Some(clear) = pass.clear_depth
|
||||
&& !(0.0..=1.0).contains(&clear)
|
||||
{
|
||||
return Err(MetalError::new(
|
||||
"depth pass",
|
||||
"expected a clear depth in 0..=1",
|
||||
));
|
||||
}
|
||||
if pass.clear_depth.is_none()
|
||||
&& pass
|
||||
.draws
|
||||
.iter()
|
||||
.any(|draw| draw.depth != DepthState::DISABLED)
|
||||
{
|
||||
return Err(MetalError::new(
|
||||
"depth pass",
|
||||
"a depth test or write needs a depth attachment",
|
||||
));
|
||||
}
|
||||
if pass.texture.is_none()
|
||||
&& pass
|
||||
.draws
|
||||
.iter()
|
||||
.any(|draw| draw.fill == DepthFill::Bc1Texture)
|
||||
{
|
||||
return Err(MetalError::new(
|
||||
"depth pass",
|
||||
"textured draw without texture",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn whole(width: usize, height: usize) -> MTLRegion {
|
||||
MTLRegion {
|
||||
origin: MTLOrigin { x: 0, y: 0, z: 0 },
|
||||
size: MTLSize {
|
||||
width,
|
||||
height,
|
||||
depth: 1,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! CPU check: the reference rasteriser agrees with the independently derived
|
||||
//! expectations for every depth case. Runs without a GPU.
|
||||
|
||||
#[path = "support/depth_cases.rs"]
|
||||
mod depth_cases;
|
||||
|
||||
use depth_cases::{BC1_BLOCKS, Fill, SIZE, cases, expected};
|
||||
use xenora_ref::depth::{RefDraw, RefFill, RefTexture, render_depth};
|
||||
|
||||
/// Row-major 8x8 texels decoded block by block with the CPU BC1 decoder.
|
||||
pub 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() {
|
||||
let decoded = xenora_texture::decode_bc1(*bytes);
|
||||
for (index, texel) in decoded.iter().enumerate() {
|
||||
let x = (block % 2) * 4 + index % 4;
|
||||
let y = (block / 2) * 4 + index / 4;
|
||||
texels[y * 8 + x] = *texel;
|
||||
}
|
||||
}
|
||||
texels
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_matches_independent_expectations() {
|
||||
let texels = bc1_texels();
|
||||
let texture = RefTexture {
|
||||
width: 8,
|
||||
height: 8,
|
||||
texels: &texels,
|
||||
};
|
||||
let expected = expected();
|
||||
let cases = cases();
|
||||
assert_eq!(cases.len(), 30);
|
||||
assert_eq!(expected.len(), cases.len());
|
||||
for (case, want) in cases.iter().zip(&expected) {
|
||||
assert_eq!(case.name, want.name);
|
||||
let draws: Vec<_> = case
|
||||
.draws
|
||||
.iter()
|
||||
.map(|draw| RefDraw {
|
||||
positions: draw.positions,
|
||||
fill: match draw.fill {
|
||||
Fill::Flat(rgba) => RefFill::Flat(rgba),
|
||||
Fill::Texture => RefFill::Texture,
|
||||
},
|
||||
compare: draw.compare,
|
||||
write: draw.write,
|
||||
})
|
||||
.collect();
|
||||
let (color, depth) = render_depth(
|
||||
[SIZE, SIZE],
|
||||
case.clear_color,
|
||||
case.clear_depth,
|
||||
&draws,
|
||||
Some(texture),
|
||||
)
|
||||
.expect("reference render");
|
||||
assert_eq!(color, want.color, "{} colour", case.name);
|
||||
assert_eq!(depth, want.depth, "{} depth", case.name);
|
||||
}
|
||||
}
|
||||
+1161
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,144 @@
|
||||
use xenora_metal::{DepthCompare, DepthDraw, DepthFill, DepthPass, DepthState};
|
||||
use xenora_ref::depth::CompareFunction;
|
||||
use xenora_texture::{Bc1Upload, Bc1UploadDesc};
|
||||
|
||||
use super::depth_cases::{BC1_BLOCKS, Case, Fill, GREEN, SIZE, cases, expected};
|
||||
use super::{context, native};
|
||||
|
||||
fn compare(function: CompareFunction) -> DepthCompare {
|
||||
match function {
|
||||
CompareFunction::Never => DepthCompare::Never,
|
||||
CompareFunction::Less => DepthCompare::Less,
|
||||
CompareFunction::Equal => DepthCompare::Equal,
|
||||
CompareFunction::LessEqual => DepthCompare::LessEqual,
|
||||
CompareFunction::Greater => DepthCompare::Greater,
|
||||
CompareFunction::NotEqual => DepthCompare::NotEqual,
|
||||
CompareFunction::GreaterEqual => DepthCompare::GreaterEqual,
|
||||
CompareFunction::Always => DepthCompare::Always,
|
||||
}
|
||||
}
|
||||
|
||||
fn metal_draws(case: &Case) -> Vec<DepthDraw> {
|
||||
case.draws
|
||||
.iter()
|
||||
.map(|draw| DepthDraw {
|
||||
positions: draw.positions,
|
||||
fill: match draw.fill {
|
||||
Fill::Flat(rgba) => DepthFill::Flat(rgba),
|
||||
Fill::Texture => DepthFill::Bc1Texture,
|
||||
},
|
||||
depth: DepthState {
|
||||
compare: compare(draw.compare),
|
||||
write: draw.write,
|
||||
},
|
||||
})
|
||||
.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 and depth must equal the independently derived
|
||||
/// values (which the CPU reference also reproduces in `depth_reference`).
|
||||
/// Colour and depth are compared separately, per pixel.
|
||||
#[test]
|
||||
fn depth_attachment_known_answers() {
|
||||
let gpu = context();
|
||||
let upload = bc1_upload();
|
||||
let level = upload.subresource(0, 0).expect("BC1 level 0");
|
||||
let expected = expected();
|
||||
let cases = cases();
|
||||
assert_eq!(cases.len(), expected.len());
|
||||
let mut checked = 0;
|
||||
for (case, want) in cases.iter().zip(&expected) {
|
||||
assert_eq!(case.name, want.name);
|
||||
let draws = metal_draws(case);
|
||||
let output = native(gpu.render_depth(&DepthPass {
|
||||
extent: [SIZE, SIZE],
|
||||
clear_color: case.clear_color,
|
||||
clear_depth: case.clear_depth,
|
||||
draws: &draws,
|
||||
texture: Some(&level),
|
||||
}));
|
||||
for (index, (pixel, wanted)) in output
|
||||
.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);
|
||||
}
|
||||
assert_eq!(output.color.len(), SIZE * SIZE * 4);
|
||||
match (&output.depth, &want.depth) {
|
||||
(Some(depth), Some(wanted)) => {
|
||||
assert_eq!(depth.len(), wanted.len());
|
||||
for (index, (value, wanted)) in depth.iter().zip(wanted).enumerate() {
|
||||
let (x, y) = (index % SIZE, index / SIZE);
|
||||
assert_eq!(
|
||||
value.to_bits(),
|
||||
wanted.to_bits(),
|
||||
"{} depth at ({x}, {y}): {value} vs {wanted}",
|
||||
case.name
|
||||
);
|
||||
}
|
||||
}
|
||||
(None, None) => {}
|
||||
(got, want) => panic!("{}: depth presence {got:?} vs {want:?}", case.name),
|
||||
}
|
||||
checked += 1;
|
||||
}
|
||||
println!("checked {checked} depth passes of {} pixels", SIZE * SIZE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_state_without_attachment_is_rejected() {
|
||||
let gpu = context();
|
||||
let draw = DepthDraw {
|
||||
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],
|
||||
],
|
||||
fill: DepthFill::Flat(GREEN),
|
||||
depth: DepthState {
|
||||
compare: DepthCompare::Less,
|
||||
write: false,
|
||||
},
|
||||
};
|
||||
let pass = |clear_depth, draw: DepthDraw| {
|
||||
gpu.render_depth(&DepthPass {
|
||||
extent: [SIZE, SIZE],
|
||||
clear_color: [0; 4],
|
||||
clear_depth,
|
||||
draws: &[draw],
|
||||
texture: None,
|
||||
})
|
||||
};
|
||||
let error = pass(None, draw).expect_err("depth test without attachment");
|
||||
assert!(!error.is_capability_unavailable(), "{error}");
|
||||
for clear in [-0.25, 1.5, f32::NAN] {
|
||||
pass(Some(clear), draw).expect_err("clear depth outside 0..=1");
|
||||
}
|
||||
let textured = DepthDraw {
|
||||
fill: DepthFill::Bc1Texture,
|
||||
..draw
|
||||
};
|
||||
pass(Some(1.0), textured).expect_err("textured draw without texture");
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
use xenora_metal::NativeCompute;
|
||||
|
||||
#[path = "native/depth.rs"]
|
||||
mod depth;
|
||||
#[path = "support/depth_cases.rs"]
|
||||
mod depth_cases;
|
||||
#[path = "native/guest_buffer.rs"]
|
||||
mod guest_buffer;
|
||||
#[path = "native/offscreen.rs"]
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Original depth-pass fixtures shared by the CPU reference check and the
|
||||
//! native Metal test, and the parser for the independently derived
|
||||
//! expectations in `fixtures/depth_expected.txt`.
|
||||
|
||||
use xenora_ref::depth::CompareFunction;
|
||||
|
||||
pub const SIZE: usize = 16;
|
||||
pub const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
pub const GREEN: [u8; 4] = [0, 255, 0, 255];
|
||||
pub const BLUE: [u8; 4] = [0, 0, 255, 255];
|
||||
const BLACK: [u8; 4] = [0, 0, 0, 255];
|
||||
|
||||
/// Four original BC1 blocks (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
|
||||
];
|
||||
|
||||
// Triangles in pixel coordinates; no pixel centre lies on any edge.
|
||||
const FULL: [[f32; 2]; 3] = [[0.0, 16.0], [32.0, 16.0], [0.0, -16.0]];
|
||||
const A: [[f32; 2]; 3] = [[0.0, 0.0], [16.0, 0.0], [0.0, 12.0]];
|
||||
const B: [[f32; 2]; 3] = [[4.0, 3.0], [16.0, 4.0], [6.0, 16.0]];
|
||||
const C: [[f32; 2]; 3] = [[0.0, 8.0], [10.0, 8.0], [0.0, 16.0]];
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Fill {
|
||||
Flat([u8; 4]),
|
||||
Texture,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Draw {
|
||||
pub positions: [[f32; 4]; 3],
|
||||
pub fill: Fill,
|
||||
pub compare: CompareFunction,
|
||||
pub write: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Case {
|
||||
pub name: String,
|
||||
pub clear_color: [u8; 4],
|
||||
pub clear_depth: Option<f32>,
|
||||
pub draws: Vec<Draw>,
|
||||
}
|
||||
|
||||
fn draw(tri: [[f32; 2]; 3], z: f32, fill: Fill, compare: CompareFunction, write: bool) -> Draw {
|
||||
Draw {
|
||||
positions: tri.map(|[x, y]| [x / 8.0 - 1.0, 1.0 - y / 8.0, z, 1.0]),
|
||||
fill,
|
||||
compare,
|
||||
write,
|
||||
}
|
||||
}
|
||||
|
||||
fn case(name: &str, clear_color: [u8; 4], clear_depth: Option<f32>, draws: Vec<Draw>) -> Case {
|
||||
Case {
|
||||
name: name.to_owned(),
|
||||
clear_color,
|
||||
clear_depth,
|
||||
draws,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every case, each exercising one feature, in fixture order.
|
||||
pub fn cases() -> Vec<Case> {
|
||||
use CompareFunction::{Always, Less, LessEqual};
|
||||
let red = Fill::Flat(RED);
|
||||
let green = Fill::Flat(GREEN);
|
||||
let blue = Fill::Flat(BLUE);
|
||||
let mut cases = vec![case("clear", [16, 32, 48, 255], Some(0.375), Vec::new())];
|
||||
for compare in CompareFunction::ALL {
|
||||
for z in [0.25, 0.5, 0.75] {
|
||||
cases.push(case(
|
||||
&format!("compare_{compare:?}_{z}"),
|
||||
BLACK,
|
||||
Some(1.0),
|
||||
vec![
|
||||
draw(A, 0.5, red, Always, true),
|
||||
draw(B, z, green, compare, true),
|
||||
],
|
||||
));
|
||||
}
|
||||
}
|
||||
for (name, write) in [("write_disabled", false), ("write_enabled", true)] {
|
||||
cases.push(case(
|
||||
name,
|
||||
BLACK,
|
||||
Some(1.0),
|
||||
vec![
|
||||
draw(A, 0.5, red, Always, true),
|
||||
draw(B, 0.25, green, Always, write),
|
||||
draw(C, 0.75, blue, LessEqual, true),
|
||||
],
|
||||
));
|
||||
}
|
||||
let painter = |depth| {
|
||||
case(
|
||||
if depth {
|
||||
"disabled_attachment"
|
||||
} else {
|
||||
"no_attachment"
|
||||
},
|
||||
BLACK,
|
||||
depth.then_some(1.0),
|
||||
vec![
|
||||
draw(A, 0.25, red, Always, false),
|
||||
draw(B, 0.75, green, Always, false),
|
||||
],
|
||||
)
|
||||
};
|
||||
cases.push(painter(true));
|
||||
cases.push(painter(false));
|
||||
cases.push(case(
|
||||
"textured",
|
||||
BLACK,
|
||||
Some(1.0),
|
||||
vec![
|
||||
draw(FULL, 0.5, Fill::Texture, Less, true),
|
||||
draw(B, 0.75, green, Less, true),
|
||||
draw(A, 0.25, red, Less, true),
|
||||
],
|
||||
));
|
||||
cases
|
||||
}
|
||||
|
||||
/// Independently derived colour and depth of one case.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct Expected {
|
||||
pub name: String,
|
||||
pub color: Vec<[u8; 4]>,
|
||||
pub depth: Option<Vec<f32>>,
|
||||
}
|
||||
|
||||
pub fn expected() -> Vec<Expected> {
|
||||
let text = include_str!("../fixtures/depth_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 palette, mut depthkey) = (Vec::new(), Vec::new());
|
||||
let (mut color, mut depth, mut no_depth) = (Vec::new(), Vec::new(), false);
|
||||
for line in lines.by_ref() {
|
||||
let mut words = line.split_whitespace();
|
||||
match words.next().expect("keyword") {
|
||||
"palette" => {
|
||||
let key = words.next().unwrap().chars().next().unwrap();
|
||||
let rgba: Vec<u8> = words.map(|w| w.parse().unwrap()).collect();
|
||||
palette.push((key, <[u8; 4]>::try_from(rgba).unwrap()));
|
||||
}
|
||||
"depthkey" => {
|
||||
let key = words.next().unwrap().chars().next().unwrap();
|
||||
depthkey.push((key, words.next().unwrap().parse::<f32>().unwrap()));
|
||||
}
|
||||
"color" => color.extend(words.next().unwrap().chars().map(|c| {
|
||||
palette
|
||||
.iter()
|
||||
.find(|(k, _)| *k == c)
|
||||
.expect("palette key")
|
||||
.1
|
||||
})),
|
||||
"depth" => match words.next().unwrap() {
|
||||
"none" => no_depth = true,
|
||||
row => depth.extend(
|
||||
row.chars()
|
||||
.map(|c| depthkey.iter().find(|(k, _)| *k == c).expect("depth key").1),
|
||||
),
|
||||
},
|
||||
"end" => break,
|
||||
other => panic!("unexpected fixture line {other}"),
|
||||
}
|
||||
}
|
||||
assert_eq!(color.len(), SIZE * SIZE, "{name} colour rows");
|
||||
assert!(no_depth || depth.len() == SIZE * SIZE, "{name} depth rows");
|
||||
out.push(Expected {
|
||||
name,
|
||||
color,
|
||||
depth: (!no_depth).then_some(depth),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent CPU reference for depth-tested offscreen triangle rendering.
|
||||
//!
|
||||
//! A pixel is covered when its centre lies strictly inside a triangle. Inputs
|
||||
//! whose pixel centres lie exactly on an edge are rejected rather than resolved
|
||||
//! by a fill rule, so the reference never depends on rasteriser tie-breaking.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// Depth comparison of the fragment depth against the stored depth.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CompareFunction {
|
||||
Never,
|
||||
Less,
|
||||
Equal,
|
||||
LessEqual,
|
||||
Greater,
|
||||
NotEqual,
|
||||
GreaterEqual,
|
||||
Always,
|
||||
}
|
||||
|
||||
impl CompareFunction {
|
||||
pub const ALL: [Self; 8] = [
|
||||
Self::Never,
|
||||
Self::Less,
|
||||
Self::Equal,
|
||||
Self::LessEqual,
|
||||
Self::Greater,
|
||||
Self::NotEqual,
|
||||
Self::GreaterEqual,
|
||||
Self::Always,
|
||||
];
|
||||
|
||||
#[must_use]
|
||||
pub fn passes(self, fragment: f32, stored: f32) -> bool {
|
||||
match self {
|
||||
Self::Never => false,
|
||||
Self::Less => fragment < stored,
|
||||
Self::Equal => fragment == stored,
|
||||
Self::LessEqual => fragment <= stored,
|
||||
Self::Greater => fragment > stored,
|
||||
Self::NotEqual => fragment != stored,
|
||||
Self::GreaterEqual => fragment >= stored,
|
||||
Self::Always => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Colour source of one reference draw.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum RefFill {
|
||||
Flat([u8; 4]),
|
||||
/// Nearest texel of the pass texture at the pixel centre.
|
||||
Texture,
|
||||
}
|
||||
|
||||
/// One triangle with clip-space positions (`w` must be 1).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct RefDraw {
|
||||
pub positions: [[f32; 4]; 3],
|
||||
pub fill: RefFill,
|
||||
pub compare: CompareFunction,
|
||||
pub write: bool,
|
||||
}
|
||||
|
||||
/// Decoded RGBA8 texels in row-major order.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct RefTexture<'a> {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub texels: &'a [[u8; 4]],
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub enum DepthRefError {
|
||||
Extent,
|
||||
NonUnitW,
|
||||
/// A pixel centre lies on a triangle edge: (draw, x, y).
|
||||
EdgeTie(usize, usize, usize),
|
||||
MissingTexture,
|
||||
/// Without a depth attachment every draw must be `Always` without writes.
|
||||
DepthStateWithoutAttachment(usize),
|
||||
}
|
||||
|
||||
impl fmt::Display for DepthRefError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{self:?}")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for DepthRefError {}
|
||||
|
||||
/// Colour (row-major, top row first) and, with an attachment, stored depth.
|
||||
pub type DepthRefOutput = (Vec<[u8; 4]>, Option<Vec<f32>>);
|
||||
|
||||
/// Render `draws` in order over a cleared target with viewport depth range 0..1.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error for an empty extent, non-unit `w`, a pixel centre on an
|
||||
/// edge, a textured draw without texture, or a depth state without attachment.
|
||||
pub fn render_depth(
|
||||
[width, height]: [usize; 2],
|
||||
clear_color: [u8; 4],
|
||||
clear_depth: Option<f32>,
|
||||
draws: &[RefDraw],
|
||||
texture: Option<RefTexture<'_>>,
|
||||
) -> Result<DepthRefOutput, DepthRefError> {
|
||||
let pixels = width.checked_mul(height).filter(|&n| n > 0);
|
||||
let pixels = pixels.ok_or(DepthRefError::Extent)?;
|
||||
if let Some(texture) = texture
|
||||
&& (texture.width == 0
|
||||
|| texture.height == 0
|
||||
|| texture.texels.len() != texture.width * texture.height)
|
||||
{
|
||||
return Err(DepthRefError::Extent);
|
||||
}
|
||||
let mut color = vec![clear_color; pixels];
|
||||
let mut depth = clear_depth.map(|value| vec![value; pixels]);
|
||||
for (index, draw) in draws.iter().enumerate() {
|
||||
if depth.is_none() && (draw.compare != CompareFunction::Always || draw.write) {
|
||||
return Err(DepthRefError::DepthStateWithoutAttachment(index));
|
||||
}
|
||||
if draw.fill == RefFill::Texture && texture.is_none() {
|
||||
return Err(DepthRefError::MissingTexture);
|
||||
}
|
||||
if draw.positions.iter().any(|p| p[3] != 1.0) {
|
||||
return Err(DepthRefError::NonUnitW);
|
||||
}
|
||||
// Viewport transform: NDC x, y in -1..1 map to pixels, y down.
|
||||
let screen = draw.positions.map(|[x, y, z, _]| {
|
||||
[
|
||||
(f64::from(x) + 1.0) * 0.5 * width as f64,
|
||||
(1.0 - f64::from(y)) * 0.5 * height as f64,
|
||||
f64::from(z),
|
||||
]
|
||||
});
|
||||
let area = edge(screen[0], screen[1], screen[2]);
|
||||
if area == 0.0 {
|
||||
continue;
|
||||
}
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let centre = [x as f64 + 0.5, y as f64 + 0.5, 0.0];
|
||||
let weights = [
|
||||
edge(screen[1], screen[2], centre),
|
||||
edge(screen[2], screen[0], centre),
|
||||
edge(screen[0], screen[1], centre),
|
||||
];
|
||||
if weights.contains(&0.0) {
|
||||
let others_inside = weights
|
||||
.iter()
|
||||
.filter(|&&w| w != 0.0)
|
||||
.all(|&w| (w > 0.0) == (area > 0.0));
|
||||
if others_inside {
|
||||
return Err(DepthRefError::EdgeTie(index, x, y));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !weights.iter().all(|&w| (w > 0.0) == (area > 0.0)) {
|
||||
continue;
|
||||
}
|
||||
let z = (weights[0] * screen[0][2]
|
||||
+ weights[1] * screen[1][2]
|
||||
+ weights[2] * screen[2][2])
|
||||
/ area;
|
||||
let z = z as f32;
|
||||
let slot = y * width + x;
|
||||
if let Some(stored) = depth.as_mut() {
|
||||
if !draw.compare.passes(z, stored[slot]) {
|
||||
continue;
|
||||
}
|
||||
if draw.write {
|
||||
stored[slot] = z;
|
||||
}
|
||||
}
|
||||
color[slot] = match (draw.fill, texture) {
|
||||
(RefFill::Flat(rgba), _) => rgba,
|
||||
(RefFill::Texture, Some(t)) => {
|
||||
let u = ((x as f64 + 0.5) / width as f64 * t.width as f64) as usize;
|
||||
let v = ((y as f64 + 0.5) / height as f64 * t.height as f64) as usize;
|
||||
t.texels[v.min(t.height - 1) * t.width + u.min(t.width - 1)]
|
||||
}
|
||||
(RefFill::Texture, None) => return Err(DepthRefError::MissingTexture),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((color, depth))
|
||||
}
|
||||
|
||||
fn edge(a: [f64; 3], b: [f64; 3], p: [f64; 3]) -> f64 {
|
||||
(b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
fn draw(positions: [[f32; 4]; 3], compare: CompareFunction, write: bool) -> RefDraw {
|
||||
RefDraw {
|
||||
positions,
|
||||
fill: RefFill::Flat(RED),
|
||||
compare,
|
||||
write,
|
||||
}
|
||||
}
|
||||
|
||||
// A 2x2 target; this triangle covers only the centre of pixel (0, 1).
|
||||
const LOWER_LEFT: [[f32; 4]; 3] = [
|
||||
[-1.0, -1.0, 0.25, 1.0],
|
||||
[0.5, -1.0, 0.25, 1.0],
|
||||
[-1.0, 0.5, 0.25, 1.0],
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn covers_by_pixel_centre_and_writes_depth() {
|
||||
let (color, depth) = render_depth(
|
||||
[2, 2],
|
||||
[0; 4],
|
||||
Some(1.0),
|
||||
&[draw(LOWER_LEFT, CompareFunction::Less, true)],
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(color, [[0; 4], [0; 4], RED, [0; 4]]);
|
||||
assert_eq!(depth.unwrap(), [1.0, 1.0, 0.25, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_functions_follow_metal_semantics() {
|
||||
let expect = [false, true, false, true, false, true, false, true];
|
||||
let equal = [false, false, true, true, false, false, true, true];
|
||||
for (function, (&less, &eq)) in CompareFunction::ALL.iter().zip(expect.iter().zip(&equal)) {
|
||||
assert_eq!(function.passes(0.25, 0.5), less, "{function:?} less");
|
||||
assert_eq!(function.passes(0.5, 0.5), eq, "{function:?} equal");
|
||||
assert_eq!(
|
||||
function.passes(0.75, 0.5),
|
||||
!matches!(
|
||||
function,
|
||||
CompareFunction::Never
|
||||
| CompareFunction::Less
|
||||
| CompareFunction::Equal
|
||||
| CompareFunction::LessEqual
|
||||
),
|
||||
"{function:?} greater"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_edge_ties_and_depth_without_attachment() {
|
||||
let tie = [
|
||||
[-1.0, -1.0, 0.5, 1.0],
|
||||
[1.0, 1.0, 0.5, 1.0],
|
||||
[-1.0, 1.0, 0.5, 1.0],
|
||||
];
|
||||
assert!(matches!(
|
||||
render_depth(
|
||||
[2, 2],
|
||||
[0; 4],
|
||||
Some(1.0),
|
||||
&[draw(tie, CompareFunction::Always, true)],
|
||||
None
|
||||
),
|
||||
Err(DepthRefError::EdgeTie(0, _, _))
|
||||
));
|
||||
assert_eq!(
|
||||
render_depth(
|
||||
[2, 2],
|
||||
[0; 4],
|
||||
None,
|
||||
&[draw(LOWER_LEFT, CompareFunction::Less, false)],
|
||||
None
|
||||
),
|
||||
Err(DepthRefError::DepthStateWithoutAttachment(0))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent CPU execution of the synthetic gfx1030 fixture subset and reference sampling.
|
||||
//! Independent CPU execution of the synthetic gfx1030 fixture subset, reference sampling and depth-tested rendering.
|
||||
|
||||
pub mod depth;
|
||||
pub mod texture_sampling;
|
||||
|
||||
use std::fmt;
|
||||
|
||||
Reference in new issue
Block a user