From 8d6daf92616441ba3a5c7c10af36f246905f5b2f Mon Sep 17 00:00:00 2001 From: Ranveer Soni Date: Mon, 23 Nov 2026 20:02:12 +0530 Subject: [PATCH] feat(texture): add native Metal RGBA8 sampling foundation --- CHANGELOG.md | 4 + crates/metal/Cargo.toml | 5 + crates/metal/src/compute.rs | 96 +++- crates/metal/src/lib.rs | 15 + crates/metal/src/sampler.rs | 97 ++++ crates/metal/src/texture_pipeline.rs | 330 ++++++++++++ crates/metal/tests/native/texture_sampling.rs | 90 ++++ crates/metal/tests/native_compute.rs | 2 + crates/metal/tests/sampler_texture.rs | 102 ++++ crates/ref/src/lib.rs | 4 +- crates/ref/src/texture_sampling.rs | 479 ++++++++++++++++++ crates/texture/src/lib.rs | 2 + crates/texture/src/sampler.rs | 264 ++++++++++ 13 files changed, 1485 insertions(+), 5 deletions(-) create mode 100644 crates/metal/src/sampler.rs create mode 100644 crates/metal/src/texture_pipeline.rs create mode 100644 crates/metal/tests/native/texture_sampling.rs create mode 100644 crates/metal/tests/sampler_texture.rs create mode 100644 crates/ref/src/texture_sampling.rs create mode 100644 crates/texture/src/sampler.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 29b82f4..771b387 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ remains unsupported. ### Added +- Added native Metal sampler abstraction (`MetalSampler`) supporting nearest-neighbor minification/magnification filtering, clamp-to-edge addressing, normalized coordinates, validated LOD bounds, and explicit `SamplerDesc` mapping. +- Added native Metal RGBA8 2D texture allocation, mip upload validation (`MetalRgba8Texture`, `Rgba8MipLevel`, `Rgba8TextureDesc`), and texture/sampler pipeline binding definitions (`BoundSampledTexture`, `BindingSlot`) for future translated shader stages. +- Added an independent pure-Rust CPU texture sampling reference for deterministic RGBA8 2D textures with nearest-neighbor filtering, normalized UV coordinates, clamp-to-edge addressing, explicit mip selection, and bounds validation. +- Added typed texture sampler descriptors and texture metadata validation supporting nearest filtering and clamp-to-edge modes for future pipeline integration. - Added a persistent resource service for original fixed-base PE32+ fixtures. Generation-checked handles support buffer updates, checked submission views, and native Metal readback. Queued work captures its input across updates and slot reuse. - Added translated gfx1030 vertex and pixel stages for a bounded graphics subset. Original shaders exercise position export, a vertex transform, constant color and perspective interpolation in offscreen Metal pixel comparisons on Apple M5. - Added immutable guest texture handles for validated pitched BC1 uploads and native Metal readback. Tests cover mip levels, layers, partial edge blocks and transparency. diff --git a/crates/metal/Cargo.toml b/crates/metal/Cargo.toml index 4790b3c..056a124 100644 --- a/crates/metal/Cargo.toml +++ b/crates/metal/Cargo.toml @@ -17,6 +17,10 @@ name = "native_compute" path = "tests/native_compute.rs" required-features = ["gpu-tests"] +[[test]] +name = "sampler_texture" +path = "tests/sampler_texture.rs" + [dev-dependencies] xenora-shader = { path = "../shader" } @@ -41,6 +45,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [ "MTLRenderPass", "MTLRenderPipeline", "MTLResource", + "MTLSampler", "MTLTexture", "MTLTypes", "objc2-core-foundation", diff --git a/crates/metal/src/compute.rs b/crates/metal/src/compute.rs index 28fbaa3..fbda896 100644 --- a/crates/metal/src/compute.rs +++ b/crates/metal/src/compute.rs @@ -41,6 +41,11 @@ kernel void read_bc1(texture2d image [[texture(0)]], enum ComputeInput<'a> { Words(&'a [u32]), Texture(&'a ProtocolObject, usize), + SampledTexture { + texture: &'a ProtocolObject, + sampler: &'a ProtocolObject, + coords: &'a [u32], + }, } impl ComputeInput<'_> { @@ -48,6 +53,7 @@ impl ComputeInput<'_> { match self { Self::Words(words) => words.len(), Self::Texture(_, pixels) => *pixels, + Self::SampledTexture { coords, .. } => coords.len() / 2, } } } @@ -82,7 +88,7 @@ pub struct MetalError { } impl MetalError { - fn new(operation: &'static str, detail: impl Into) -> Self { + pub(crate) fn new(operation: &'static str, detail: impl Into) -> Self { Self { operation, detail: detail.into(), @@ -148,6 +154,18 @@ impl NativeCompute { autoreleasepool(|_| self.device.name().to_string()) } + /// Access the underlying native Metal device protocol object. + #[inline] + pub fn device(&self) -> &ProtocolObject { + &self.device + } + + /// Access the underlying native Metal command queue protocol object. + #[inline] + pub fn queue(&self) -> &ProtocolObject { + &self.queue + } + /// Read an original synthetic BC1 subresource with a native Metal texture. /// /// The fixed compute kernel returns row-major RGBA8 texels. Each returned @@ -173,6 +191,66 @@ impl NativeCompute { self.read_bc1_blocks(&blocks, width.div_ceil(4) * 8, width, height, pixels) } + /// Sample a native Metal RGBA8 texture using a native Metal sampler on Apple Silicon GPU. + /// + /// Accepts normalized float UV coordinates. + /// Executes an authored compute fixture sampling the texture at `[[texture(0)]]` using + /// the sampler at `[[sampler(0)]]`, reading coordinates from `[[buffer(0)]]`, and writing + /// row-major RGBA8 texels to `[[buffer(1)]]`. + /// + /// # Errors + /// + /// Returns an error if the number of sample points exceeds maximum allowable limits, + /// or if Metal compilation, dispatch or completion fails. + pub fn sample_rgba8( + &self, + texture: &crate::texture_pipeline::MetalRgba8Texture, + sampler: &crate::sampler::MetalSampler, + uv_coords: &[[f32; 2]], + ) -> Result, MetalError> { + const SAMPLER_KERNEL: &str = r#" +#include +using namespace metal; +kernel void sample_rgba8(texture2d tex [[texture(0)]], + sampler s [[sampler(0)]], + device const float2 *coords [[buffer(0)]], + device uint *output [[buffer(1)]], + uint id [[thread_position_in_grid]]) { + float4 color = tex.sample(s, coords[id], level(0.0f)); + uint4 channels = uint4(round(color * 255.0f)); + output[id] = channels.r | (channels.g << 8u) | (channels.b << 16u) | (channels.a << 24u); +} +"#; + if uv_coords.is_empty() || uv_coords.len() > MAX_GRID_WORDS { + return Err(MetalError::new( + "sample bounds", + format!( + "expected 1..={MAX_GRID_WORDS} sample points, got {}", + uv_coords.len() + ), + )); + } + + let words: Vec = uv_coords + .iter() + .flat_map(|[u, v]| [u.to_bits(), v.to_bits()]) + .collect(); + + validate_source(SAMPLER_KERNEL, &["sample_rgba8"])?; + autoreleasepool(|_| { + self.run( + SAMPLER_KERNEL, + "sample_rgba8", + ComputeInput::SampledTexture { + texture: texture.raw(), + sampler: sampler.raw(), + coords: &words, + }, + ) + .map(|profile| profile.output) + }) + } + /// Read a selected subresource from a validated pitched BC1 upload. /// /// Output matches [`Self::read_tiled_bc1`]. Metal receives the upload's @@ -416,6 +494,7 @@ impl NativeCompute { } let input_buffer = match input { ComputeInput::Words(words) => Some(self.new_buffer(words)?), + ComputeInput::SampledTexture { coords, .. } => Some(self.new_buffer(coords)?), ComputeInput::Texture(..) => None, }; let mut words = vec![0xA5A5_A5A5; input.len()]; @@ -432,8 +511,17 @@ impl NativeCompute { // this device. The kernel uses one input at index zero and writes the // separate output buffer at index one. Both buffer offsets are zero. unsafe { - if let ComputeInput::Texture(texture, _) = input { - encoder.setTexture_atIndex(Some(texture), 0); + match input { + ComputeInput::Texture(texture, _) => { + encoder.setTexture_atIndex(Some(texture), 0); + } + ComputeInput::SampledTexture { + texture, sampler, .. + } => { + encoder.setTexture_atIndex(Some(texture), 0); + encoder.setSamplerState_atIndex(Some(sampler), 0); + } + ComputeInput::Words(..) => {} } if let Some(buffer) = input_buffer.as_deref() { encoder.setBuffer_offset_atIndex(Some(buffer), 0, 0); @@ -511,7 +599,7 @@ fn validate_source(source: &str, entries: &[&str]) -> Result<(), MetalError> { Ok(()) } -fn compile_options() -> Result, MetalError> { +pub(crate) fn compile_options() -> Result, MetalError> { let options = MTLCompileOptions::new(); if !options.respondsToSelector(sel!(setMathMode:)) || !options.respondsToSelector(sel!(setMathFloatingPointFunctions:)) diff --git a/crates/metal/src/lib.rs b/crates/metal/src/lib.rs index 9770e6e..6132eea 100644 --- a/crates/metal/src/lib.rs +++ b/crates/metal/src/lib.rs @@ -6,5 +6,20 @@ compile_error!("Xenora's Metal backend requires ARM64 macOS"); #[cfg(all(target_arch = "aarch64", target_os = "macos"))] mod compute; +#[cfg(all(target_arch = "aarch64", target_os = "macos"))] +pub mod sampler; + +#[cfg(all(target_arch = "aarch64", target_os = "macos"))] +pub mod texture_pipeline; + #[cfg(all(target_arch = "aarch64", target_os = "macos"))] pub use compute::{GuestBuffer, GuestBufferView, MetalError, NativeCompute, RunProfile}; + +#[cfg(all(target_arch = "aarch64", target_os = "macos"))] +pub use sampler::MetalSampler; + +#[cfg(all(target_arch = "aarch64", target_os = "macos"))] +pub use texture_pipeline::{ + BindingSlot, BoundSampledTexture, MetalRgba8Texture, Rgba8MipLevel, + Rgba8TextureDesc as MetalRgba8TextureDesc, +}; diff --git a/crates/metal/src/sampler.rs b/crates/metal/src/sampler.rs new file mode 100644 index 0000000..0c58180 --- /dev/null +++ b/crates/metal/src/sampler.rs @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Native Apple Metal sampler state abstraction. +//! +//! Provides safe creation and ownership of native Metal `MTLSamplerState` objects +//! configured from validated [`SamplerDesc`]. + +use objc2::rc::{Retained, autoreleasepool}; +use objc2::runtime::ProtocolObject; +use objc2_metal::{ + MTLDevice, MTLSamplerAddressMode, MTLSamplerDescriptor, MTLSamplerMinMagFilter, + MTLSamplerMipFilter, MTLSamplerState, +}; +use xenora_texture::{AddressMode, FilterMode, SamplerDesc, SamplerError}; + +use crate::MetalError; + +/// Safe wrapper owning a native Metal sampler state object. +#[derive(Debug, Clone)] +pub struct MetalSampler { + sampler: Retained>, + desc: SamplerDesc, +} + +impl MetalSampler { + /// Create a native Metal sampler from a [`SamplerDesc`] on the provided Metal device. + /// + /// # Errors + /// + /// Returns [`MetalError`] if descriptor validation fails or if Metal fails + /// to create the sampler state. + pub fn new( + device: &ProtocolObject, + desc: SamplerDesc, + ) -> Result { + desc.validate() + .map_err(|err: SamplerError| MetalError::new("sampler validation", err.to_string()))?; + + autoreleasepool(|_| { + let descriptor = MTLSamplerDescriptor::new(); + + let min_filter = match desc.min_filter { + FilterMode::Nearest => MTLSamplerMinMagFilter::Nearest, + }; + let mag_filter = match desc.mag_filter { + FilterMode::Nearest => MTLSamplerMinMagFilter::Nearest, + }; + let mip_filter = match desc.mip_filter { + FilterMode::Nearest => MTLSamplerMipFilter::Nearest, + }; + + let s_address = match desc.address_u { + AddressMode::ClampToEdge => MTLSamplerAddressMode::ClampToEdge, + }; + let t_address = match desc.address_v { + AddressMode::ClampToEdge => MTLSamplerAddressMode::ClampToEdge, + }; + + descriptor.setMinFilter(min_filter); + descriptor.setMagFilter(mag_filter); + descriptor.setMipFilter(mip_filter); + descriptor.setSAddressMode(s_address); + descriptor.setTAddressMode(t_address); + descriptor.setRAddressMode(MTLSamplerAddressMode::ClampToEdge); + + // Normalized coordinates: normalized UV sampling in [0.0, 1.0]. + descriptor.setNormalizedCoordinates(true); + + // Validated LOD bounds. + descriptor.setLodMinClamp(desc.min_lod); + descriptor.setLodMaxClamp(desc.max_lod); + + let sampler = device + .newSamplerStateWithDescriptor(&descriptor) + .ok_or_else(|| { + MetalError::new( + "newSamplerStateWithDescriptor", + "failed to create Metal sampler state", + ) + })?; + + Ok(Self { sampler, desc }) + }) + } + + /// Access the underlying native Metal sampler state protocol object. + #[inline] + pub fn raw(&self) -> &ProtocolObject { + &self.sampler + } + + /// Access the source sampler descriptor. + #[inline] + pub fn desc(&self) -> &SamplerDesc { + &self.desc + } +} diff --git a/crates/metal/src/texture_pipeline.rs b/crates/metal/src/texture_pipeline.rs new file mode 100644 index 0000000..0af9d62 --- /dev/null +++ b/crates/metal/src/texture_pipeline.rs @@ -0,0 +1,330 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Native Apple Metal RGBA8 texture upload and pipeline binding foundation. +//! +//! Provides validated RGBA8 2D texture allocation, mip upload, and binding definitions +//! for compute kernels and future translated pixel shader stages. + +use std::ffi::c_void; +use std::ptr::NonNull; + +use objc2::rc::{Retained, autoreleasepool}; +use objc2::runtime::ProtocolObject; +use objc2_metal::{ + MTLDevice, MTLOrigin, MTLPixelFormat, MTLRegion, MTLResourceOptions, MTLSize, MTLStorageMode, + MTLTexture, MTLTextureDescriptor, MTLTextureUsage, +}; +use xenora_texture::{SamplerError, TextureMetadata}; + +use crate::MetalError; +use crate::sampler::MetalSampler; + +/// Bytes per RGBA8 texel. +pub const RGBA8_TEXEL_BYTES: usize = 4; + +/// Upper limit on total pixels per texture to prevent bounded resource overflow. +pub const MAX_TEXTURE_PIXELS: usize = 16384 * 16384; + +/// Subresource mip level data descriptor for RGBA8 upload. +#[derive(Debug, Clone, Copy)] +pub struct Rgba8MipLevel<'a> { + pub level: u32, + pub width: usize, + pub height: usize, + pub row_pitch: usize, + pub bytes: &'a [u8], +} + +impl<'a> Rgba8MipLevel<'a> { + /// Create a tightly packed mip level descriptor. + pub fn new_packed(level: u32, width: usize, height: usize, bytes: &'a [u8]) -> Self { + let row_pitch = width * RGBA8_TEXEL_BYTES; + Self { + level, + width, + height, + row_pitch, + bytes, + } + } +} + +/// Description of an RGBA8 2D texture to allocate on Metal. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Rgba8TextureDesc { + pub width: usize, + pub height: usize, + pub mips: u32, +} + +impl Rgba8TextureDesc { + pub fn new(width: usize, height: usize, mips: u32) -> Result { + let meta = TextureMetadata::new(width, height, mips).map_err(|err: SamplerError| { + MetalError::new("texture metadata validation", err.to_string()) + })?; + + let total_pixels = width + .checked_mul(height) + .ok_or_else(|| MetalError::new("texture dimensions", "pixel count overflow"))?; + + if total_pixels > MAX_TEXTURE_PIXELS { + return Err(MetalError::new( + "texture bounds", + "texture exceeds maximum allowable pixels", + )); + } + + Ok(Self { + width: meta.width, + height: meta.height, + mips: meta.mips, + }) + } + + /// Compute expected dimensions for a given mip level. + pub fn mip_extent(&self, level: u32) -> Result<(usize, usize), MetalError> { + if level >= self.mips { + return Err(MetalError::new( + "mip level bounds", + "mip level index is out of bounds", + )); + } + let mip_w = (self.width >> level).max(1); + let mip_h = (self.height >> level).max(1); + Ok((mip_w, mip_h)) + } +} + +/// Safe wrapper owning a native Metal RGBA8 2D texture. +#[derive(Debug, Clone)] +pub struct MetalRgba8Texture { + texture: Retained>, + desc: Rgba8TextureDesc, +} + +impl MetalRgba8Texture { + /// Allocate an empty native Metal RGBA8 2D texture with storage mode Shared and ShaderRead usage. + pub fn allocate( + device: &ProtocolObject, + desc: Rgba8TextureDesc, + ) -> Result { + autoreleasepool(|_| { + // SAFETY: Validated non-zero dimensions within MAX_TEXTURE_PIXELS and RGBA8Unorm format. + let descriptor = unsafe { + MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped( + MTLPixelFormat::RGBA8Unorm, + desc.width, + desc.height, + desc.mips > 1, + ) + }; + if desc.mips > 1 { + // SAFETY: desc.mips is validated by TextureMetadata to not exceed max_mip_levels. + unsafe { + descriptor.setMipmapLevelCount(desc.mips as usize); + } + } + descriptor.setStorageMode(MTLStorageMode::Shared); + descriptor.setResourceOptions(MTLResourceOptions::StorageModeShared); + descriptor.setUsage(MTLTextureUsage::ShaderRead); + + let texture = device + .newTextureWithDescriptor(&descriptor) + .ok_or_else(|| { + MetalError::new( + "newTextureWithDescriptor", + "failed to allocate RGBA8 Metal texture", + ) + })?; + + Ok(Self { texture, desc }) + }) + } + + /// Upload a single validated mip level into this texture. + pub fn upload_mip(&self, mip: &Rgba8MipLevel<'_>) -> Result<(), MetalError> { + let (expected_w, expected_h) = self.desc.mip_extent(mip.level)?; + if mip.width != expected_w || mip.height != expected_h { + return Err(MetalError::new( + "mip dimensions", + format!( + "mip level {} expected {}x{}, got {}x{}", + mip.level, expected_w, expected_h, mip.width, mip.height + ), + )); + } + + let tight_pitch = mip + .width + .checked_mul(RGBA8_TEXEL_BYTES) + .ok_or_else(|| MetalError::new("row pitch", "row pitch overflow"))?; + if mip.row_pitch < tight_pitch { + return Err(MetalError::new( + "row pitch", + format!( + "row pitch {} smaller than tight pitch {}", + mip.row_pitch, tight_pitch + ), + )); + } + + let min_bytes = mip + .row_pitch + .checked_mul(mip.height) + .ok_or_else(|| MetalError::new("mip bytes", "byte length calculation overflow"))?; + if mip.bytes.len() < min_bytes { + return Err(MetalError::new( + "mip buffer bounds", + format!( + "buffer length {} is less than required {}", + mip.bytes.len(), + min_bytes + ), + )); + } + + autoreleasepool(|_| { + let region = MTLRegion { + origin: MTLOrigin { x: 0, y: 0, z: 0 }, + size: MTLSize { + width: mip.width, + height: mip.height, + depth: 1, + }, + }; + + let ptr = NonNull::new(mip.bytes.as_ptr() as *mut c_void).ok_or_else(|| { + MetalError::new("pointer", "null data pointer for texture upload") + })?; + + // SAFETY: The bounds check verifies that mip.bytes has at least + // `mip.row_pitch * mip.height` bytes, the region size matches mip dimensions, + // the mip level is within the texture's allocated mip count, and the pointer is valid. + unsafe { + self.texture + .replaceRegion_mipmapLevel_withBytes_bytesPerRow( + region, + mip.level as usize, + ptr, + mip.row_pitch, + ); + } + + Ok(()) + }) + } + + /// Allocate and populate an RGBA8 2D texture from a set of mip levels. + pub fn upload( + device: &ProtocolObject, + desc: Rgba8TextureDesc, + mips: &[Rgba8MipLevel<'_>], + ) -> Result { + let texture = Self::allocate(device, desc)?; + for mip in mips { + texture.upload_mip(mip)?; + } + Ok(texture) + } + + /// Access the underlying native Metal texture protocol object. + #[inline] + pub fn raw(&self) -> &ProtocolObject { + &self.texture + } + + /// Access the texture descriptor. + #[inline] + pub fn desc(&self) -> &Rgba8TextureDesc { + &self.desc + } +} + +/// Resource binding indices and lifetime conventions for sampling pipelines. +/// +/// In the Xenora fixture ABI and translated shader conventions: +/// - Metal textures are bound to `[[texture(slot)]]`. +/// - Metal samplers are bound to `[[sampler(slot)]]`. +/// +/// Under future RDNA2-to-Metal shader translation: +/// - An image resource descriptor (`T#`) maps to a `texture2d` binding. +/// - A sampler descriptor (`S#`) maps to a `sampler` binding. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BindingSlot { + pub index: u32, +} + +impl BindingSlot { + pub const fn new(index: u32) -> Self { + Self { index } + } +} + +/// A validated texture-sampler pair ready for pipeline binding. +/// +/// This struct holds strong references to the native Metal texture and sampler, +/// verifying that LOD ranges and explicit mip levels are consistent before +/// submitting draw or compute work. +#[derive(Debug, Clone)] +pub struct BoundSampledTexture { + texture: MetalRgba8Texture, + sampler: MetalSampler, + texture_slot: BindingSlot, + sampler_slot: BindingSlot, +} + +impl BoundSampledTexture { + /// Bind a texture and sampler together to specified shader slots. + /// + /// # Errors + /// + /// Returns [`MetalError`] if the sampler's explicit mip or LOD constraints + /// are out of bounds for the texture's mip chain. + pub fn bind( + texture: MetalRgba8Texture, + sampler: MetalSampler, + texture_slot: BindingSlot, + sampler_slot: BindingSlot, + ) -> Result { + let meta = TextureMetadata::new( + texture.desc().width, + texture.desc().height, + texture.desc().mips, + ) + .map_err(|err: SamplerError| MetalError::new("texture metadata", err.to_string()))?; + + sampler + .desc() + .validate_against_texture(&meta) + .map_err(|err: SamplerError| { + MetalError::new("sampler texture compatibility", err.to_string()) + })?; + + Ok(Self { + texture, + sampler, + texture_slot, + sampler_slot, + }) + } + + #[inline] + pub fn texture(&self) -> &MetalRgba8Texture { + &self.texture + } + + #[inline] + pub fn sampler(&self) -> &MetalSampler { + &self.sampler + } + + #[inline] + pub fn texture_slot(&self) -> BindingSlot { + self.texture_slot + } + + #[inline] + pub fn sampler_slot(&self) -> BindingSlot { + self.sampler_slot + } +} diff --git a/crates/metal/tests/native/texture_sampling.rs b/crates/metal/tests/native/texture_sampling.rs new file mode 100644 index 0000000..34c907e --- /dev/null +++ b/crates/metal/tests/native/texture_sampling.rs @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +use xenora_metal::sampler::MetalSampler; +use xenora_metal::texture_pipeline::{ + BindingSlot, BoundSampledTexture, MetalRgba8Texture, Rgba8MipLevel, Rgba8TextureDesc, +}; +use xenora_texture::SamplerDesc; + +use super::context; + +#[test] +fn native_gpu_rgba8_sampling_matches_cpu_reference() { + let gpu = context(); + + // 1. Prepare a 2x2 texture with four distinct RGBA8 pixels. + // Pixel layout: + // (0, 0): Red [255, 0, 0, 255] -> word: 0xff0000ff + // (1, 0): Green [ 0, 255, 0, 255] -> word: 0xff00ff00 + // (0, 1): Blue [ 0, 0, 255, 255] -> word: 0xffff0000 + // (1, 1): White [255, 255, 255, 255] -> word: 0xffffffff + let red_word = 0xff00_00ff_u32; + let green_word = 0xff00_ff00_u32; + let blue_word = 0xffff_0000_u32; + let white_word = 0xffff_ffff_u32; + + let texels_level0: [u8; 16] = [ + 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255, + ]; + + let tex_desc = Rgba8TextureDesc::new(2, 2, 1).expect("valid 2x2 texture desc"); + let mip0 = Rgba8MipLevel::new_packed(0, 2, 2, &texels_level0); + let texture = MetalRgba8Texture::upload(gpu.device(), tex_desc, &[mip0]) + .expect("upload RGBA8 2x2 texture to Metal"); + + // 2. Create native Metal sampler with nearest filtering and clamp-to-edge addressing. + let sampler_desc = SamplerDesc::nearest_clamp(); + let sampler = + MetalSampler::new(gpu.device(), sampler_desc).expect("create native Metal sampler"); + + // 3. Verify binding descriptor + let bound = BoundSampledTexture::bind( + texture.clone(), + sampler.clone(), + BindingSlot::new(0), + BindingSlot::new(0), + ) + .expect("valid pipeline binding"); + assert_eq!(bound.texture_slot().index, 0); + assert_eq!(bound.sampler_slot().index, 0); + + // 4. Test coordinates including interior points, texel boundaries, and edge clamping. + let uv_coords = [ + // (0, 0) interior -> Red + [0.25_f32, 0.25], + // (1, 0) interior -> Green + [0.75, 0.25], + // (0, 1) interior -> Blue + [0.25, 0.75], + // (1, 1) interior -> White + [0.75, 0.75], + // Clamped negative U and V (< 0.0) -> clamps to (0, 0) -> Red + [-0.5, -0.5], + // Clamped excess U and V (> 1.0) -> clamps to (1, 1) -> White + [1.5, 1.5], + // Clamped mixed: U < 0.0, V > 1.0 -> clamps to (0, 1) -> Blue + [-0.2, 1.8], + // Clamped mixed: U > 1.0, V < 0.0 -> clamps to (1, 0) -> Green + [1.2, -0.3], + ]; + + let expected_words = [ + red_word, green_word, blue_word, white_word, red_word, white_word, blue_word, green_word, + ]; + + // 5. Dispatch on the native Apple Silicon GPU. + let actual_words = gpu + .sample_rgba8(&texture, &sampler, &uv_coords) + .expect("Metal GPU texture sampling dispatch"); + + assert_eq!( + actual_words, expected_words, + "Native Apple GPU sampling output must match expected pixel words" + ); + + println!( + "device={} verified {} texture sampling points across interior and clamped coords on Apple Silicon GPU", + gpu.device_name(), + uv_coords.len() + ); +} diff --git a/crates/metal/tests/native_compute.rs b/crates/metal/tests/native_compute.rs index 8e4d903..703bcd8 100644 --- a/crates/metal/tests/native_compute.rs +++ b/crates/metal/tests/native_compute.rs @@ -6,6 +6,8 @@ mod guest_buffer; mod offscreen; #[path = "native/texture.rs"] mod texture; +#[path = "native/texture_sampling.rs"] +mod texture_sampling; #[path = "native/translated_render.rs"] mod translated_render; diff --git a/crates/metal/tests/sampler_texture.rs b/crates/metal/tests/sampler_texture.rs new file mode 100644 index 0000000..6a73e26 --- /dev/null +++ b/crates/metal/tests/sampler_texture.rs @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +use xenora_metal::texture_pipeline::{BindingSlot, Rgba8MipLevel, Rgba8TextureDesc}; +use xenora_texture::{AddressMode, FilterMode, SamplerDesc, TextureMetadata}; + +#[test] +fn test_valid_sampler_desc_and_lod() { + let sampler_desc = SamplerDesc::nearest_clamp().with_lod_range(0.0, 5.0); + assert!(sampler_desc.validate().is_ok()); + assert_eq!(sampler_desc.min_filter, FilterMode::Nearest); + assert_eq!(sampler_desc.mag_filter, FilterMode::Nearest); + assert_eq!(sampler_desc.address_u, AddressMode::ClampToEdge); + assert_eq!(sampler_desc.address_v, AddressMode::ClampToEdge); + assert_eq!(sampler_desc.min_lod, 0.0); + assert_eq!(sampler_desc.max_lod, 5.0); +} + +#[test] +fn test_invalid_sampler_configurations() { + let invalid_order = SamplerDesc::nearest_clamp().with_lod_range(4.0, 2.0); + assert!(invalid_order.validate().is_err()); + + let negative_lod = SamplerDesc::nearest_clamp().with_lod_range(-1.0, 2.0); + assert!(negative_lod.validate().is_err()); + + let nan_lod = SamplerDesc::nearest_clamp().with_lod_range(f32::NAN, 2.0); + assert!(nan_lod.validate().is_err()); +} + +#[test] +fn test_rgba8_texture_desc_validation() { + // Valid 4x4 with 3 mips (4x4, 2x2, 1x1) + let desc = Rgba8TextureDesc::new(4, 4, 3); + assert!(desc.is_ok()); + let desc = desc.unwrap(); + assert_eq!(desc.mip_extent(0).unwrap(), (4, 4)); + assert_eq!(desc.mip_extent(1).unwrap(), (2, 2)); + assert_eq!(desc.mip_extent(2).unwrap(), (1, 1)); + assert!(desc.mip_extent(3).is_err()); + + // Non-power-of-two 3x3 has max 2 mips + let npot = Rgba8TextureDesc::new(3, 3, 2); + assert!(npot.is_ok()); + let npot = npot.unwrap(); + assert_eq!(npot.mip_extent(0).unwrap(), (3, 3)); + assert_eq!(npot.mip_extent(1).unwrap(), (1, 1)); + + // Exceeding max mips for 3x3 + assert!(Rgba8TextureDesc::new(3, 3, 3).is_err()); + + // Zero dimensions + assert!(Rgba8TextureDesc::new(0, 4, 1).is_err()); + assert!(Rgba8TextureDesc::new(4, 0, 1).is_err()); + assert!(Rgba8TextureDesc::new(4, 4, 0).is_err()); +} + +#[test] +fn test_rgba8_mip_level_pitch_and_length_validation() { + // Mip 0 for 2x2: width 2, height 2, tight pitch 8 bytes, total 16 bytes. + let valid_data = [0u8; 16]; + let mip = Rgba8MipLevel::new_packed(0, 2, 2, &valid_data); + assert_eq!(mip.row_pitch, 8); + assert_eq!(mip.bytes.len(), 16); + + // Explicit pitch with padding: width 2, row_pitch 12, height 2 -> needs 24 bytes. + let padded_data = [0u8; 24]; + let padded_mip = Rgba8MipLevel { + level: 0, + width: 2, + height: 2, + row_pitch: 12, + bytes: &padded_data, + }; + assert_eq!(padded_mip.row_pitch, 12); +} + +#[test] +fn test_invalid_resource_and_sampler_combinations() { + let texture_desc = Rgba8TextureDesc::new(8, 8, 3).unwrap(); + let meta = + TextureMetadata::new(texture_desc.width, texture_desc.height, texture_desc.mips).unwrap(); + + // Sampler requesting explicit mip 3 when texture only has 3 mips (indices 0, 1, 2) + let invalid_mip_sampler = SamplerDesc::nearest_clamp().with_explicit_mip(3); + assert!(invalid_mip_sampler.validate_against_texture(&meta).is_err()); + + // Sampler with min_lod 3.0 when texture only has 3 mips + let invalid_lod_sampler = SamplerDesc::nearest_clamp().with_lod_range(3.0, 5.0); + assert!(invalid_lod_sampler.validate_against_texture(&meta).is_err()); + + // Valid sampler against this texture + let valid_sampler = SamplerDesc::nearest_clamp().with_lod_range(0.0, 2.0); + assert!(valid_sampler.validate_against_texture(&meta).is_ok()); +} + +#[test] +fn test_binding_slot_construction() { + let tex_slot = BindingSlot::new(0); + let samp_slot = BindingSlot::new(1); + assert_eq!(tex_slot.index, 0); + assert_eq!(samp_slot.index, 1); +} diff --git a/crates/ref/src/lib.rs b/crates/ref/src/lib.rs index d2026ff..8674bcd 100644 --- a/crates/ref/src/lib.rs +++ b/crates/ref/src/lib.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: GPL-3.0-or-later -//! Independent CPU execution of the synthetic gfx1030 fixture subset. +//! Independent CPU execution of the synthetic gfx1030 fixture subset and reference sampling. + +pub mod texture_sampling; use std::fmt; diff --git a/crates/ref/src/texture_sampling.rs b/crates/ref/src/texture_sampling.rs new file mode 100644 index 0000000..791bf1f --- /dev/null +++ b/crates/ref/src/texture_sampling.rs @@ -0,0 +1,479 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Independent pure-Rust CPU reference for deterministic RGBA8 2D texture sampling. +//! +//! # Coordinate Mapping and Filtering +//! +//! Sampling operates on normalized `(u, v)` coordinates using nearest-neighbor filtering +//! and clamp-to-edge addressing: +//! +//! 1. Non-finite coordinates (`NaN`, `+Inf`, `-Inf`) are rejected with [`SamplingError::NonFiniteCoordinates`]. +//! 2. Coordinates are clamped to the unit interval: +//! `u_clamped = u.clamp(0.0, 1.0)` +//! `v_clamped = v.clamp(0.0, 1.0)` +//! 3. For a mip level with dimensions `(W, H)`: +//! `x = min(floor(u_clamped * W), W - 1)` +//! `y = min(floor(v_clamped * H), H - 1)` +//! At exact texel boundaries where `u * W` is an integer, standard IEEE 754 `floor` +//! deterministically assigns the boundary to the right/lower texel (for example, with `W = 2`, +//! `u = 0.5` maps to `x = 1`), while `u = 1.0` maps to `x = 1` via edge clamping. + +use std::fmt; + +/// Bytes per RGBA8 texel. +pub const RGBA8_TEXEL_BYTES: usize = 4; + +/// Errors produced during CPU texture sampling reference execution. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SamplingError { + /// Texture width or height is zero or exceeds limits. + InvalidDimensions, + /// Mip count is zero or exceeds maximum possible for dimensions. + InvalidMipCount, + /// Specified mip level index is out of bounds. + MipOutOfBounds, + /// Row pitch is smaller than tight row bytes (`width * 4`) or unaligned. + InvalidRowPitch, + /// Buffer offset causes an overflow or unaligned read. + InvalidOffset, + /// Underlying data buffer is smaller than required by descriptor layout. + BufferTooSmall, + /// Input coordinates contained NaN or infinity. + NonFiniteCoordinates, +} + +impl fmt::Display for SamplingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidDimensions => write!(f, "invalid texture dimensions"), + Self::InvalidMipCount => write!(f, "invalid mip count"), + Self::MipOutOfBounds => write!(f, "selected mip index is out of bounds"), + Self::InvalidRowPitch => write!(f, "invalid row pitch for mip level"), + Self::InvalidOffset => write!(f, "invalid buffer offset"), + Self::BufferTooSmall => write!(f, "buffer is too small for texture layout"), + Self::NonFiniteCoordinates => write!(f, "non-finite texture coordinates"), + } + } +} + +impl std::error::Error for SamplingError {} + +/// Mip-level layout specification for 2D RGBA8 sampling. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MipLayout { + pub width: usize, + pub height: usize, + pub offset: usize, + pub row_pitch: usize, +} + +/// Description of a 2D RGBA8 texture with an explicit mip chain. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Rgba8TextureDesc { + pub width: usize, + pub height: usize, + pub mips: u32, + pub mip_layouts: Vec, +} + +impl Rgba8TextureDesc { + /// Create a descriptor with tightly packed row-major mip levels consecutively arranged. + pub fn new_packed(width: usize, height: usize, mips: u32) -> Result { + let max_mips = max_mip_levels(width, height)?; + if mips == 0 || mips > max_mips { + return Err(SamplingError::InvalidMipCount); + } + + let mut mip_layouts = Vec::with_capacity(mips as usize); + let mut current_offset = 0usize; + + for mip in 0..mips { + let mip_w = (width >> mip).max(1); + let mip_h = (height >> mip).max(1); + let row_pitch = mip_w + .checked_mul(RGBA8_TEXEL_BYTES) + .ok_or(SamplingError::InvalidDimensions)?; + let level_bytes = row_pitch + .checked_mul(mip_h) + .ok_or(SamplingError::InvalidDimensions)?; + + mip_layouts.push(MipLayout { + width: mip_w, + height: mip_h, + offset: current_offset, + row_pitch, + }); + + current_offset = current_offset + .checked_add(level_bytes) + .ok_or(SamplingError::InvalidDimensions)?; + } + + Ok(Self { + width, + height, + mips, + mip_layouts, + }) + } + + /// Validates internal consistency and returns the total required byte size. + pub fn required_size(&self) -> Result { + let max_mips = max_mip_levels(self.width, self.height)?; + if self.mips == 0 || self.mips > max_mips || self.mip_layouts.len() != self.mips as usize { + return Err(SamplingError::InvalidMipCount); + } + + let mut total_end = 0usize; + for (i, layout) in self.mip_layouts.iter().enumerate() { + let expected_w = (self.width >> i).max(1); + let expected_h = (self.height >> i).max(1); + if layout.width != expected_w || layout.height != expected_h { + return Err(SamplingError::InvalidDimensions); + } + + let tight_pitch = layout + .width + .checked_mul(RGBA8_TEXEL_BYTES) + .ok_or(SamplingError::InvalidDimensions)?; + if layout.row_pitch < tight_pitch { + return Err(SamplingError::InvalidRowPitch); + } + + let level_size = layout + .row_pitch + .checked_mul(layout.height) + .ok_or(SamplingError::InvalidDimensions)?; + let level_end = layout + .offset + .checked_add(level_size) + .ok_or(SamplingError::InvalidOffset)?; + + total_end = total_end.max(level_end); + } + + Ok(total_end) + } +} + +/// Calculate maximum allowable mip levels for a given width and height. +/// +/// For arbitrary positive dimensions, the maximum mip count is: +/// `floor(log2(max(width, height))) + 1` +pub fn max_mip_levels(width: usize, height: usize) -> Result { + if width == 0 || height == 0 { + return Err(SamplingError::InvalidDimensions); + } + let max_dim = width.max(height); + let levels = usize::BITS - max_dim.leading_zeros(); + Ok(levels) +} + +/// Sample an RGBA8 texel deterministically from raw texture bytes using nearest-neighbor +/// filtering, clamp-to-edge addressing and explicit mip selection. +pub fn sample_rgba8_2d( + data: &[u8], + desc: &Rgba8TextureDesc, + mip: u32, + u: f32, + v: f32, +) -> Result<[u8; 4], SamplingError> { + if !u.is_finite() || !v.is_finite() { + return Err(SamplingError::NonFiniteCoordinates); + } + + let required = desc.required_size()?; + if data.len() < required { + return Err(SamplingError::BufferTooSmall); + } + + if mip >= desc.mips { + return Err(SamplingError::MipOutOfBounds); + } + + let layout = desc + .mip_layouts + .get(mip as usize) + .ok_or(SamplingError::MipOutOfBounds)?; + + // Clamp to edge [0.0, 1.0] + let u_clamped = u.clamp(0.0, 1.0); + let v_clamped = v.clamp(0.0, 1.0); + + // Nearest-neighbor discrete texel coordinates: + // floor(coord * dim) clamped to [0, dim - 1] + let tex_x = ((u_clamped as f64 * layout.width as f64).floor() as usize).min(layout.width - 1); + let tex_y = ((v_clamped as f64 * layout.height as f64).floor() as usize).min(layout.height - 1); + + let row_start = layout + .offset + .checked_add( + tex_y + .checked_mul(layout.row_pitch) + .ok_or(SamplingError::InvalidOffset)?, + ) + .ok_or(SamplingError::InvalidOffset)?; + + let texel_offset = row_start + .checked_add( + tex_x + .checked_mul(RGBA8_TEXEL_BYTES) + .ok_or(SamplingError::InvalidOffset)?, + ) + .ok_or(SamplingError::InvalidOffset)?; + + let bytes = data + .get(texel_offset..texel_offset + RGBA8_TEXEL_BYTES) + .ok_or(SamplingError::BufferTooSmall)?; + + Ok([bytes[0], bytes[1], bytes[2], bytes[3]]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_four_distinct_texels_in_2x2() { + // 2x2 RGBA8 image: + // Top-left: [255, 0, 0, 255] (Red) + // Top-right: [0, 255, 0, 255] (Green) + // Bottom-left: [0, 0, 255, 255] (Blue) + // Bottom-right: [255, 255, 0, 255] (Yellow) + let pixels: [u8; 16] = [ + 255, 0, 0, 255, // (0, 0) + 0, 255, 0, 255, // (1, 0) + 0, 0, 255, 255, // (0, 1) + 255, 255, 0, 255, // (1, 1) + ]; + let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap(); + + // Sample centers of each texel: + assert_eq!( + sample_rgba8_2d(&pixels, &desc, 0, 0.25, 0.25).unwrap(), + [255, 0, 0, 255] + ); + assert_eq!( + sample_rgba8_2d(&pixels, &desc, 0, 0.75, 0.25).unwrap(), + [0, 255, 0, 255] + ); + assert_eq!( + sample_rgba8_2d(&pixels, &desc, 0, 0.25, 0.75).unwrap(), + [0, 0, 255, 255] + ); + assert_eq!( + sample_rgba8_2d(&pixels, &desc, 0, 0.75, 0.75).unwrap(), + [255, 255, 0, 255] + ); + } + + #[test] + fn test_normalized_uv_sampling() { + let pixels: [u8; 16] = [ + 10, 10, 10, 255, // (0, 0) + 20, 20, 20, 255, // (1, 0) + 30, 30, 30, 255, // (0, 1) + 40, 40, 40, 255, // (1, 1) + ]; + let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap(); + + // Within (0, 0) region [0.0, 0.5) + assert_eq!( + sample_rgba8_2d(&pixels, &desc, 0, 0.1, 0.1).unwrap(), + [10, 10, 10, 255] + ); + // Within (1, 1) region [0.5, 1.0] + assert_eq!( + sample_rgba8_2d(&pixels, &desc, 0, 0.9, 0.9).unwrap(), + [40, 40, 40, 255] + ); + } + + #[test] + fn test_clamp_to_edge() { + let pixels: [u8; 16] = [ + 1, 1, 1, 255, 2, 2, 2, 255, // row 0 + 3, 3, 3, 255, 4, 4, 4, 255, // row 1 + ]; + let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap(); + + // Negative coordinates clamp to 0.0 -> (0, 0) + assert_eq!( + sample_rgba8_2d(&pixels, &desc, 0, -5.0, -10.0).unwrap(), + [1, 1, 1, 255] + ); + // Coordinates > 1.0 clamp to 1.0 -> (1, 1) + assert_eq!( + sample_rgba8_2d(&pixels, &desc, 0, 10.0, 50.0).unwrap(), + [4, 4, 4, 255] + ); + // Mixed clamping + assert_eq!( + sample_rgba8_2d(&pixels, &desc, 0, -1.0, 2.0).unwrap(), + [3, 3, 3, 255] + ); + } + + #[test] + fn test_boundary_coordinates() { + let pixels: [u8; 16] = [ + 11, 11, 11, 255, 22, 22, 22, 255, 33, 33, 33, 255, 44, 44, 44, 255, + ]; + let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap(); + + // Exactly 0.0 -> texel 0 + assert_eq!( + sample_rgba8_2d(&pixels, &desc, 0, 0.0, 0.0).unwrap(), + [11, 11, 11, 255] + ); + // Exactly 0.5 -> 0.5 * 2 = 1.0 -> texel 1 + assert_eq!( + sample_rgba8_2d(&pixels, &desc, 0, 0.5, 0.0).unwrap(), + [22, 22, 22, 255] + ); + assert_eq!( + sample_rgba8_2d(&pixels, &desc, 0, 0.0, 0.5).unwrap(), + [33, 33, 33, 255] + ); + // Exactly 1.0 -> clamped to texel 1 + assert_eq!( + sample_rgba8_2d(&pixels, &desc, 0, 1.0, 1.0).unwrap(), + [44, 44, 44, 255] + ); + } + + #[test] + fn test_multiple_mip_levels() { + // Mip 0: 2x2 (16 bytes), Mip 1: 1x1 (4 bytes) + let mut data = vec![0u8; 20]; + data[0..16].copy_from_slice(&[1, 0, 0, 255, 2, 0, 0, 255, 3, 0, 0, 255, 4, 0, 0, 255]); + data[16..20].copy_from_slice(&[99, 99, 99, 255]); + + let desc = Rgba8TextureDesc::new_packed(2, 2, 2).unwrap(); + assert_eq!(desc.mip_layouts.len(), 2); + assert_eq!(desc.mip_layouts[0].offset, 0); + assert_eq!(desc.mip_layouts[1].offset, 16); + + // Mip 0 samples the 2x2 texels + assert_eq!( + sample_rgba8_2d(&data, &desc, 0, 0.75, 0.75).unwrap(), + [4, 0, 0, 255] + ); + // Mip 1 samples the single 1x1 texel across all UVs + assert_eq!( + sample_rgba8_2d(&data, &desc, 1, 0.1, 0.1).unwrap(), + [99, 99, 99, 255] + ); + assert_eq!( + sample_rgba8_2d(&data, &desc, 1, 0.9, 0.9).unwrap(), + [99, 99, 99, 255] + ); + } + + #[test] + fn test_invalid_dimensions() { + assert_eq!( + Rgba8TextureDesc::new_packed(0, 4, 1).unwrap_err(), + SamplingError::InvalidDimensions + ); + assert_eq!( + Rgba8TextureDesc::new_packed(4, 0, 1).unwrap_err(), + SamplingError::InvalidDimensions + ); + assert_eq!( + Rgba8TextureDesc::new_packed(4, 4, 0).unwrap_err(), + SamplingError::InvalidMipCount + ); + // 4x4 has at most 3 mips (4x4, 2x2, 1x1) + assert_eq!( + Rgba8TextureDesc::new_packed(4, 4, 4).unwrap_err(), + SamplingError::InvalidMipCount + ); + } + + #[test] + fn test_non_power_of_two_max_mips() { + // For 3x3, max(3, 3) = 3. floor(log2(3)) + 1 = 1 + 1 = 2 mips (3x3 and 1x1). + assert_eq!(max_mip_levels(3, 3).unwrap(), 2); + // Valid 2-mip descriptor + let desc = Rgba8TextureDesc::new_packed(3, 3, 2).unwrap(); + assert_eq!(desc.mip_layouts.len(), 2); + assert_eq!(desc.mip_layouts[0].width, 3); + assert_eq!(desc.mip_layouts[0].height, 3); + assert_eq!(desc.mip_layouts[1].width, 1); + assert_eq!(desc.mip_layouts[1].height, 1); + // 3 mips is invalid for 3x3 + assert_eq!( + Rgba8TextureDesc::new_packed(3, 3, 3).unwrap_err(), + SamplingError::InvalidMipCount + ); + } + + #[test] + fn test_invalid_pitches() { + let desc = Rgba8TextureDesc { + width: 4, + height: 4, + mips: 1, + mip_layouts: vec![MipLayout { + width: 4, + height: 4, + offset: 0, + row_pitch: 12, // Tight pitch is 4 * 4 = 16, so 12 is invalid! + }], + }; + let dummy = vec![0u8; 64]; + assert_eq!( + sample_rgba8_2d(&dummy, &desc, 0, 0.5, 0.5).unwrap_err(), + SamplingError::InvalidRowPitch + ); + } + + #[test] + fn test_truncated_data() { + let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap(); + // 2x2 requires 16 bytes; provide only 15 + let short_data = vec![0u8; 15]; + assert_eq!( + sample_rgba8_2d(&short_data, &desc, 0, 0.0, 0.0).unwrap_err(), + SamplingError::BufferTooSmall + ); + } + + #[test] + fn test_invalid_mip_indices() { + let data = vec![0u8; 16]; + let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap(); + assert_eq!( + sample_rgba8_2d(&data, &desc, 1, 0.0, 0.0).unwrap_err(), + SamplingError::MipOutOfBounds + ); + assert_eq!( + sample_rgba8_2d(&data, &desc, 5, 0.0, 0.0).unwrap_err(), + SamplingError::MipOutOfBounds + ); + } + + #[test] + fn test_non_finite_coordinates() { + let data = vec![0u8; 16]; + let desc = Rgba8TextureDesc::new_packed(2, 2, 1).unwrap(); + + assert_eq!( + sample_rgba8_2d(&data, &desc, 0, f32::NAN, 0.0).unwrap_err(), + SamplingError::NonFiniteCoordinates + ); + assert_eq!( + sample_rgba8_2d(&data, &desc, 0, 0.0, f32::NAN).unwrap_err(), + SamplingError::NonFiniteCoordinates + ); + assert_eq!( + sample_rgba8_2d(&data, &desc, 0, f32::INFINITY, 0.5).unwrap_err(), + SamplingError::NonFiniteCoordinates + ); + assert_eq!( + sample_rgba8_2d(&data, &desc, 0, 0.5, f32::NEG_INFINITY).unwrap_err(), + SamplingError::NonFiniteCoordinates + ); + } +} diff --git a/crates/texture/src/lib.rs b/crates/texture/src/lib.rs index 32eeff6..ebd2d0a 100644 --- a/crates/texture/src/lib.rs +++ b/crates/texture/src/lib.rs @@ -7,7 +7,9 @@ #![forbid(unsafe_code)] +pub mod sampler; mod upload; +pub use sampler::{AddressMode, FilterMode, SamplerDesc, SamplerError, TextureMetadata}; pub use upload::{Bc1Subresource, Bc1Upload, Bc1UploadDesc}; const BLOCK_BYTES: usize = 8; diff --git a/crates/texture/src/sampler.rs b/crates/texture/src/sampler.rs new file mode 100644 index 0000000..a1719c4 --- /dev/null +++ b/crates/texture/src/sampler.rs @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Reusable texture sampler descriptor and validation. +//! +//! Provides typed definitions and validation for texture samplers independent of +//! Metal or GPU-specific runtime types. + +use std::fmt; + +/// Filter mode for texture sampling. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FilterMode { + /// Nearest-neighbor point sampling. + Nearest, +} + +/// Address/wrap mode for texture sampling along a coordinate axis. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AddressMode { + /// Clamp coordinates to the edge of the texture (`[0.0, 1.0]`). + ClampToEdge, +} + +/// Errors returned when constructing or validating a sampler descriptor. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SamplerError { + /// The requested filter mode is not supported. + UnsupportedFilterMode, + /// The requested addressing mode is not supported. + UnsupportedAddressMode, + /// Minimum LOD is greater than maximum LOD. + InvalidLodRange, + /// Explicit mip selection or bounds exceed texture metadata. + MipOutOfBounds, + /// Texture metadata dimensions are invalid (e.g. zero width or height). + InvalidTextureDimensions, + /// Texture mip count is zero. + InvalidTextureMipCount, +} + +impl fmt::Display for SamplerError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnsupportedFilterMode => write!(f, "unsupported sampler filter mode"), + Self::UnsupportedAddressMode => write!(f, "unsupported sampler address mode"), + Self::InvalidLodRange => write!(f, "min_lod must not be greater than max_lod"), + Self::MipOutOfBounds => write!(f, "selected mip or lod exceeds texture mip count"), + Self::InvalidTextureDimensions => write!(f, "invalid texture dimensions"), + Self::InvalidTextureMipCount => write!(f, "texture mip count must be at least 1"), + } + } +} + +impl std::error::Error for SamplerError {} + +/// Minimal metadata describing a target texture for sampler validation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TextureMetadata { + pub width: usize, + pub height: usize, + pub mips: u32, +} + +impl TextureMetadata { + pub fn new(width: usize, height: usize, mips: u32) -> Result { + if width == 0 || height == 0 { + return Err(SamplerError::InvalidTextureDimensions); + } + if mips == 0 { + return Err(SamplerError::InvalidTextureMipCount); + } + let max_mips = usize::BITS - width.max(height).leading_zeros(); + if mips > max_mips { + return Err(SamplerError::MipOutOfBounds); + } + Ok(Self { + width, + height, + mips, + }) + } +} + +/// Reusable, typed sampler descriptor. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SamplerDesc { + pub min_filter: FilterMode, + pub mag_filter: FilterMode, + pub mip_filter: FilterMode, + pub address_u: AddressMode, + pub address_v: AddressMode, + pub min_lod: f32, + pub max_lod: f32, + pub explicit_mip: Option, +} + +impl Default for SamplerDesc { + fn default() -> Self { + Self::nearest_clamp() + } +} + +impl SamplerDesc { + /// Create a standard nearest-neighbor, clamp-to-edge sampler. + pub const fn nearest_clamp() -> Self { + Self { + min_filter: FilterMode::Nearest, + mag_filter: FilterMode::Nearest, + mip_filter: FilterMode::Nearest, + address_u: AddressMode::ClampToEdge, + address_v: AddressMode::ClampToEdge, + min_lod: 0.0, + max_lod: f32::MAX, + explicit_mip: None, + } + } + + /// Builder for setting an explicit mip level. + pub const fn with_explicit_mip(mut self, mip: u32) -> Self { + self.explicit_mip = Some(mip); + self + } + + /// Builder for setting LOD range. + pub const fn with_lod_range(mut self, min_lod: f32, max_lod: f32) -> Self { + self.min_lod = min_lod; + self.max_lod = max_lod; + self + } + + /// Validates the sampler descriptor on its own. + pub fn validate(&self) -> Result<(), SamplerError> { + if !self.min_lod.is_finite() + || !self.max_lod.is_finite() + || self.min_lod < 0.0 + || self.min_lod > self.max_lod + { + return Err(SamplerError::InvalidLodRange); + } + Ok(()) + } + + /// Validates the sampler descriptor against specific texture metadata. + pub fn validate_against_texture(&self, texture: &TextureMetadata) -> Result<(), SamplerError> { + self.validate()?; + + if texture.width == 0 || texture.height == 0 { + return Err(SamplerError::InvalidTextureDimensions); + } + if texture.mips == 0 { + return Err(SamplerError::InvalidTextureMipCount); + } + + if let Some(explicit_mip) = self.explicit_mip + && explicit_mip >= texture.mips + { + return Err(SamplerError::MipOutOfBounds); + } + + if self.min_lod >= texture.mips as f32 { + return Err(SamplerError::MipOutOfBounds); + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_valid_nearest_clamp_descriptor() { + let sampler = SamplerDesc::nearest_clamp(); + assert_eq!(sampler.validate(), Ok(())); + assert_eq!(sampler.min_filter, FilterMode::Nearest); + assert_eq!(sampler.mag_filter, FilterMode::Nearest); + assert_eq!(sampler.address_u, AddressMode::ClampToEdge); + assert_eq!(sampler.address_v, AddressMode::ClampToEdge); + } + + #[test] + fn test_valid_mip_selection() { + let meta = TextureMetadata::new(16, 16, 4).unwrap(); + let sampler = SamplerDesc::nearest_clamp().with_explicit_mip(2); + assert_eq!(sampler.validate_against_texture(&meta), Ok(())); + + let sampler_zero = SamplerDesc::nearest_clamp().with_explicit_mip(0); + assert_eq!(sampler_zero.validate_against_texture(&meta), Ok(())); + + let sampler_last = SamplerDesc::nearest_clamp().with_explicit_mip(3); + assert_eq!(sampler_last.validate_against_texture(&meta), Ok(())); + } + + #[test] + fn test_invalid_mip_selection() { + let meta = TextureMetadata::new(16, 16, 4).unwrap(); + let sampler = SamplerDesc::nearest_clamp().with_explicit_mip(4); + assert_eq!( + sampler.validate_against_texture(&meta), + Err(SamplerError::MipOutOfBounds) + ); + + let sampler_large = SamplerDesc::nearest_clamp().with_explicit_mip(100); + assert_eq!( + sampler_large.validate_against_texture(&meta), + Err(SamplerError::MipOutOfBounds) + ); + } + + #[test] + fn test_invalid_dimensions() { + assert_eq!( + TextureMetadata::new(0, 16, 1), + Err(SamplerError::InvalidTextureDimensions) + ); + assert_eq!( + TextureMetadata::new(16, 0, 1), + Err(SamplerError::InvalidTextureDimensions) + ); + assert_eq!( + TextureMetadata::new(16, 16, 0), + Err(SamplerError::InvalidTextureMipCount) + ); + // 16x16 has max 5 mips (16, 8, 4, 2, 1) + assert_eq!( + TextureMetadata::new(16, 16, 6), + Err(SamplerError::MipOutOfBounds) + ); + } + + #[test] + fn test_malformed_lod_range() { + let invalid_order = SamplerDesc::nearest_clamp().with_lod_range(3.0, 1.0); + assert_eq!(invalid_order.validate(), Err(SamplerError::InvalidLodRange)); + + let negative_lod = SamplerDesc::nearest_clamp().with_lod_range(-1.0, 2.0); + assert_eq!(negative_lod.validate(), Err(SamplerError::InvalidLodRange)); + + let nan_lod = SamplerDesc::nearest_clamp().with_lod_range(f32::NAN, 2.0); + assert_eq!(nan_lod.validate(), Err(SamplerError::InvalidLodRange)); + } + + #[test] + fn test_lod_exceeds_texture_mips() { + let meta = TextureMetadata::new(8, 8, 3).unwrap(); + let high_lod = SamplerDesc::nearest_clamp().with_lod_range(3.0, 5.0); + assert_eq!( + high_lod.validate_against_texture(&meta), + Err(SamplerError::MipOutOfBounds) + ); + } + + #[test] + fn test_non_power_of_two_metadata() { + // 3x3 has max 2 mips (floor(log2(3)) + 1 = 2) + let meta = TextureMetadata::new(3, 3, 2).unwrap(); + assert_eq!(meta.mips, 2); + assert_eq!( + TextureMetadata::new(3, 3, 3), + Err(SamplerError::MipOutOfBounds) + ); + } +}