Merge pull request #265 from MacosPorters/archive/pull/346/head

metal: budgeted staged RGBA8 texture upload into Private storage (#144)
This commit is contained in:
atharvranjan authored and GitHub committed 2026-11-24 22:24:24 -06:00
commit 10fd1cd4be
4 files changed
+685 -41

No files matched your search

+10
View File
@@ -40,6 +40,16 @@ remains unsupported.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### Added
- Added an opt-in, budgeted staged upload for RGBA8 textures (#144). `MetalRgba8Texture::upload_staged` fills a
Private-storage texture through one reused Shared staging buffer that never exceeds a `StagingBudget`. It
copies whole-row bands with a blit encoder and reuses the buffer only after the previous command buffer has
completed with status Completed. `plan_staged_upload` rejects missing, duplicate or out-of-range mip levels,
wrong mip sizes, short row pitches or byte buffers, and budgets smaller than one row, all before any Metal
object is created. A blit `read_back` returns any mip as tight RGBA8 bytes. On one Apple M4 under Metal API
validation, readback matched independently built patterns for every level of a padded 37×19, six-level
texture under four budgets, and matched the existing direct `upload`. Staging is slower than the direct path
(2048² with 12 mips, release build: 2.1 ms direct, 2.7 ms with a 4 MiB budget, 17.8 ms with 256 KiB), so
`upload` and its callers are unchanged. Not yet independently accepted.
- The gfx1030 identification benchmark fixture now runs as an ordinary integration test, so workspace tests check LLVM-derived names, families, lengths and byte boundaries without invoking a timing run.
- Added a CPU benchmark for gfx1030 metadata identification (#173). It verifies instruction boundaries on a mixed-family stream assembled with LLVM and reports first-pass and repeated-pass throughput.
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
+1
View File
@@ -33,6 +33,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [
"std",
"MTLAllocation",
"MTLArgument",
"MTLBlitCommandEncoder",
"MTLBuffer",
"MTLCommandBuffer",
"MTLCommandEncoder",
+513 -41
View File
@@ -11,8 +11,9 @@ 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,
MTLBlitCommandEncoder, MTLBuffer, MTLCommandBuffer, MTLCommandBufferStatus, MTLCommandEncoder,
MTLCommandQueue, MTLDevice, MTLOrigin, MTLPixelFormat, MTLRegion, MTLResourceOptions, MTLSize,
MTLStorageMode, MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
};
use xenora_texture::{SamplerError, TextureMetadata};
@@ -100,6 +101,9 @@ impl Rgba8TextureDesc {
pub struct MetalRgba8Texture {
texture: Retained<ProtocolObject<dyn MTLTexture>>,
desc: Rgba8TextureDesc,
/// Shared storage, which `replaceRegion` may write. Private textures are
/// filled only through `upload_staged`.
cpu_writable: bool,
}
impl MetalRgba8Texture {
@@ -108,6 +112,19 @@ impl MetalRgba8Texture {
device: &ProtocolObject<dyn MTLDevice>,
desc: Rgba8TextureDesc,
) -> Result<Self, MetalError> {
Self::allocate_with_storage(device, desc, MTLStorageMode::Shared)
}
fn allocate_with_storage(
device: &ProtocolObject<dyn MTLDevice>,
desc: Rgba8TextureDesc,
storage: MTLStorageMode,
) -> Result<Self, MetalError> {
let options = if storage == MTLStorageMode::Private {
MTLResourceOptions::StorageModePrivate
} else {
MTLResourceOptions::StorageModeShared
};
autoreleasepool(|_| {
// SAFETY: Validated non-zero dimensions within MAX_TEXTURE_PIXELS and RGBA8Unorm format.
let descriptor = unsafe {
@@ -124,8 +141,8 @@ impl MetalRgba8Texture {
descriptor.setMipmapLevelCount(desc.mips as usize);
}
}
descriptor.setStorageMode(MTLStorageMode::Shared);
descriptor.setResourceOptions(MTLResourceOptions::StorageModeShared);
descriptor.setStorageMode(storage);
descriptor.setResourceOptions(options);
descriptor.setUsage(MTLTextureUsage::ShaderRead);
let texture = device
@@ -137,51 +154,25 @@ impl MetalRgba8Texture {
)
})?;
Ok(Self { texture, desc })
Ok(Self {
texture,
desc,
cpu_writable: storage == MTLStorageMode::Shared,
})
})
}
/// Upload a single validated mip level into this texture.
///
/// Only Shared-storage textures from `allocate` or `upload` accept CPU writes.
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 {
if !self.cpu_writable {
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
),
"texture storage",
"a Private-storage texture is filled only by upload_staged",
));
}
validate_mip(&self.desc, mip)?;
autoreleasepool(|_| {
let region = MTLRegion {
@@ -227,6 +218,148 @@ impl MetalRgba8Texture {
Ok(texture)
}
/// Allocate a Private-storage RGBA8 texture and fill every mip level through
/// a reused Shared staging buffer that never exceeds `budget`.
///
/// The plan from [`plan_staged_upload`] is built, and every input checked,
/// before any Metal object is created. Each submission copies its rows into
/// the staging buffer, blits them into the texture and waits until the
/// command buffer has completed. Only a `Completed` status lets the buffer be
/// reused; any other status is returned as an error.
pub fn upload_staged(
device: &ProtocolObject<dyn MTLDevice>,
queue: &ProtocolObject<dyn MTLCommandQueue>,
desc: Rgba8TextureDesc,
mips: &[Rgba8MipLevel<'_>],
budget: StagingBudget,
) -> Result<(Self, StagedUploadReport), MetalError> {
let plan = plan_staged_upload(&desc, mips, budget)?;
let staging_len = plan.iter().map(|s| s.staging_bytes).max().unwrap_or(0);
let texture = Self::allocate_with_storage(device, desc, MTLStorageMode::Private)?;
let staging = device
.newBufferWithLength_options(staging_len, MTLResourceOptions::StorageModeShared)
.ok_or_else(|| MetalError::new("newBufferWithLength", "staging allocation failed"))?;
let mut copied = 0;
for submission in &plan {
for copy in &submission.copies {
let mip = mips
.iter()
.find(|mip| mip.level == copy.level)
.ok_or_else(|| MetalError::new("staged upload", "planned level missing"))?;
let tight = mip.width * RGBA8_TEXEL_BYTES;
for row in 0..copy.rows {
let src = &mip.bytes[(copy.first_row + row) * mip.row_pitch..][..tight];
let offset = copy.staging_offset + row * tight;
// SAFETY: The plan keeps offset + tight within staging_len, the
// buffer is Shared and CPU-visible, and the previous submission
// has completed, so the GPU no longer reads these bytes.
unsafe {
let dst = staging.contents().cast::<u8>().as_ptr().add(offset);
std::ptr::copy_nonoverlapping(src.as_ptr(), dst, tight);
}
}
copied += copy.rows * tight;
}
autoreleasepool(|_| texture.encode_staged(queue, &staging, submission))?;
}
let report = StagedUploadReport {
submissions: plan.len(),
peak_staging_bytes: staging_len,
bytes_copied: copied,
};
Ok((texture, report))
}
fn encode_staged(
&self,
queue: &ProtocolObject<dyn MTLCommandQueue>,
staging: &ProtocolObject<dyn MTLBuffer>,
submission: &StagedSubmission,
) -> Result<(), MetalError> {
let command = queue
.commandBuffer()
.ok_or_else(|| MetalError::new("commandBuffer", "command buffer creation failed"))?;
let blit = command
.blitCommandEncoder()
.ok_or_else(|| MetalError::new("blitCommandEncoder", "blit encoder creation failed"))?;
for copy in &submission.copies {
let (width, _) = self.desc.mip_extent(copy.level)?;
let pitch = width * RGBA8_TEXEL_BYTES;
// SAFETY: The plan validated the level, the row range within the mip and
// the staging range within the buffer. The command buffer retains both
// resources, and the caller waits for completion before reusing staging.
unsafe {
blit.copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(
staging,
copy.staging_offset,
pitch,
pitch * copy.rows,
MTLSize { width, height: copy.rows, depth: 1 },
&self.texture,
0,
copy.level as usize,
MTLOrigin { x: 0, y: copy.first_row, z: 0 },
);
}
}
blit.endEncoding();
command.commit();
command.waitUntilCompleted();
check_completed(&command)
}
/// Copy one mip level back into tightly packed RGBA8 bytes through a blit.
///
/// Works for Shared and Private textures and shares no code with the upload
/// paths, so tests can compare its output with independently built pixels.
pub fn read_back(
&self,
device: &ProtocolObject<dyn MTLDevice>,
queue: &ProtocolObject<dyn MTLCommandQueue>,
level: u32,
) -> Result<Vec<u8>, MetalError> {
let (width, height) = self.desc.mip_extent(level)?;
let pitch = width * RGBA8_TEXEL_BYTES;
let len = pitch * height;
autoreleasepool(|_| {
let buffer = device
.newBufferWithLength_options(len, MTLResourceOptions::StorageModeShared)
.ok_or_else(|| {
MetalError::new("newBufferWithLength", "readback allocation failed")
})?;
let command = queue.commandBuffer().ok_or_else(|| {
MetalError::new("commandBuffer", "command buffer creation failed")
})?;
let blit = command.blitCommandEncoder().ok_or_else(|| {
MetalError::new("blitCommandEncoder", "blit encoder creation failed")
})?;
// SAFETY: The level is in range, the source region is the whole mip and
// the destination buffer holds exactly pitch * height bytes.
unsafe {
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage(
&self.texture,
0,
level as usize,
MTLOrigin { x: 0, y: 0, z: 0 },
MTLSize { width, height, depth: 1 },
&buffer,
0,
pitch,
len,
);
}
blit.endEncoding();
command.commit();
command.waitUntilCompleted();
check_completed(&command)?;
// SAFETY: The command buffer completed, so the Shared buffer holds len
// initialized bytes and the GPU no longer writes it.
let bytes =
unsafe { std::slice::from_raw_parts(buffer.contents().cast::<u8>().as_ptr(), len) };
Ok(bytes.to_vec())
})
}
/// Access the underlying native Metal texture protocol object.
#[inline]
pub fn raw(&self) -> &ProtocolObject<dyn MTLTexture> {
@@ -240,6 +373,198 @@ impl MetalRgba8Texture {
}
}
/// Upper bound on the staging bytes one staged upload holds at a time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StagingBudget {
max_bytes: usize,
}
impl StagingBudget {
/// A budget of `max_bytes`, which must be a non-zero multiple of the RGBA8
/// texel size so every staged row starts on a texel boundary.
pub fn new(max_bytes: usize) -> Result<Self, MetalError> {
if max_bytes == 0 || !max_bytes.is_multiple_of(RGBA8_TEXEL_BYTES) {
return Err(MetalError::new(
"staging budget",
format!("budget {max_bytes} must be a non-zero multiple of {RGBA8_TEXEL_BYTES}"),
));
}
Ok(Self { max_bytes })
}
/// The largest staging allocation this budget allows.
#[must_use]
pub fn max_bytes(&self) -> usize {
self.max_bytes
}
}
/// One blit of whole rows of one mip level from the staging buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StagedCopy {
pub level: u32,
pub first_row: usize,
pub rows: usize,
/// Byte offset of the first row in the staging buffer. Rows are packed tightly.
pub staging_offset: usize,
}
/// The copies that share one staging fill and one command buffer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StagedSubmission {
pub copies: Vec<StagedCopy>,
/// Staging bytes this submission uses, never more than the budget.
pub staging_bytes: usize,
}
/// What a staged upload did, measured from the executed plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StagedUploadReport {
/// Command buffers committed and completed.
pub submissions: usize,
/// Size of the one staging buffer, the most staging memory held at once.
pub peak_staging_bytes: usize,
/// Texel bytes copied into the texture.
pub bytes_copied: usize,
}
/// Split a full RGBA8 upload into budget-sized submissions of whole rows.
///
/// Every level `0..desc.mips` must appear exactly once, because a Private
/// texture has no defined contents for a level nobody writes. Each mip is
/// checked like [`MetalRgba8Texture::upload_mip`] checks it. The budget must hold
/// at least one row of the widest level. Rows are packed in level order, and a
/// submission closes when the next row would exceed the budget.
pub fn plan_staged_upload(
desc: &Rgba8TextureDesc,
mips: &[Rgba8MipLevel<'_>],
budget: StagingBudget,
) -> Result<Vec<StagedSubmission>, MetalError> {
let mut by_level: Vec<Option<&Rgba8MipLevel<'_>>> = vec![None; desc.mips as usize];
for mip in mips {
validate_mip(desc, mip)?;
let slot = &mut by_level[mip.level as usize];
if slot.is_some() {
return Err(MetalError::new(
"staged upload",
format!("mip level {} appears more than once", mip.level),
));
}
*slot = Some(mip);
}
let mut plan = Vec::new();
let mut current = StagedSubmission {
copies: Vec::new(),
staging_bytes: 0,
};
for (level, mip) in by_level.iter().enumerate() {
let mip = mip.ok_or_else(|| {
MetalError::new("staged upload", format!("mip level {level} is missing"))
})?;
let pitch = mip.width * RGBA8_TEXEL_BYTES;
if pitch > budget.max_bytes {
return Err(MetalError::new(
"staging budget",
format!(
"budget {} is smaller than one {pitch}-byte row of mip level {level}",
budget.max_bytes
),
));
}
let mut row = 0;
while row < mip.height {
let fit = (budget.max_bytes - current.staging_bytes) / pitch;
if fit == 0 {
// Unreachable after the row check above, but an empty submission
// that cannot take one row must never loop.
if current.copies.is_empty() {
return Err(MetalError::new(
"staging budget",
"a row does not fit an empty staging buffer",
));
}
plan.push(std::mem::replace(
&mut current,
StagedSubmission {
copies: Vec::new(),
staging_bytes: 0,
},
));
continue;
}
let rows = fit.min(mip.height - row);
current.copies.push(StagedCopy {
level: mip.level,
first_row: row,
rows,
staging_offset: current.staging_bytes,
});
current.staging_bytes += rows * pitch;
row += rows;
}
}
if !current.copies.is_empty() {
plan.push(current);
}
Ok(plan)
}
fn check_completed(command: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
let status = command.status();
if status != MTLCommandBufferStatus::Completed {
let detail = command.error().map_or_else(
|| format!("unexpected command status {status:?}"),
|error| error.localizedDescription().to_string(),
);
return Err(MetalError::new("waitUntilCompleted", detail));
}
Ok(())
}
/// Check one mip level against the texture description and return its tight row pitch.
fn validate_mip(desc: &Rgba8TextureDesc, mip: &Rgba8MipLevel<'_>) -> Result<usize, MetalError> {
let (expected_w, expected_h) = 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
),
));
}
Ok(tight_pitch)
}
/// Resource binding indices and lifetime conventions for sampling pipelines.
///
/// In the Xenora fixture ABI and translated shader conventions:
@@ -328,3 +653,150 @@ impl BoundSampledTexture {
self.sampler_slot
}
}
#[cfg(test)]
mod tests {
use super::*;
fn copy(level: u32, first_row: usize, rows: usize, staging_offset: usize) -> StagedCopy {
StagedCopy {
level,
first_row,
rows,
staging_offset,
}
}
fn levels<'a>(desc: &Rgba8TextureDesc, bytes: &'a [u8]) -> Vec<Rgba8MipLevel<'a>> {
(0..desc.mips)
.map(|level| {
let (w, h) = desc.mip_extent(level).unwrap();
Rgba8MipLevel::new_packed(level, w, h, &bytes[..w * h * RGBA8_TEXEL_BYTES])
})
.collect()
}
fn plan(desc: Rgba8TextureDesc, budget: usize) -> Vec<StagedSubmission> {
let bytes = vec![0; desc.width * desc.height * RGBA8_TEXEL_BYTES];
plan_staged_upload(
&desc,
&levels(&desc, &bytes),
StagingBudget::new(budget).unwrap(),
)
.unwrap()
}
fn error(desc: Rgba8TextureDesc, mips: &[Rgba8MipLevel<'_>], budget: usize) -> String {
plan_staged_upload(&desc, mips, StagingBudget::new(budget).unwrap())
.unwrap_err()
.to_string()
}
#[test]
fn budget_must_be_a_non_zero_texel_multiple() {
assert!(StagingBudget::new(0).is_err());
assert!(StagingBudget::new(6).is_err());
assert_eq!(StagingBudget::new(8).unwrap().max_bytes(), 8);
}
#[test]
fn rows_split_into_budget_sized_submissions() {
// 8 texels × 4 bytes = 32 bytes per row; a 64-byte budget holds two rows.
let desc = Rgba8TextureDesc::new(8, 4, 1).unwrap();
let plan = plan(desc, 64);
assert_eq!(plan.len(), 2);
assert_eq!(plan[0].copies, [copy(0, 0, 2, 0)]);
assert_eq!(plan[1].copies, [copy(0, 2, 2, 0)]);
assert!(plan.iter().all(|s| s.staging_bytes == 64));
}
#[test]
fn one_submission_packs_every_level_when_it_fits() {
// Levels 8×4, 4×2, 2×1: 128 + 32 + 8 = 168 bytes.
let desc = Rgba8TextureDesc::new(8, 4, 3).unwrap();
let plan = plan(desc, 168);
assert_eq!(plan.len(), 1);
assert_eq!(
plan[0].copies,
[copy(0, 0, 4, 0), copy(1, 0, 2, 128), copy(2, 0, 1, 160)]
);
assert_eq!(plan[0].staging_bytes, 168);
}
#[test]
fn a_submission_closes_when_the_next_row_does_not_fit() {
// A 40-byte budget holds one 32-byte row of level 0, then two 16-byte rows of
// level 1 and the single 8-byte row of level 2 together.
let desc = Rgba8TextureDesc::new(8, 4, 3).unwrap();
let plan = plan(desc, 40);
assert_eq!(plan.len(), 5);
for (row, submission) in plan[..4].iter().enumerate() {
assert_eq!(submission.copies, [copy(0, row, 1, 0)]);
assert_eq!(submission.staging_bytes, 32);
}
assert_eq!(plan[4].copies, [copy(1, 0, 2, 0), copy(2, 0, 1, 32)]);
assert_eq!(plan[4].staging_bytes, 40);
}
#[test]
fn every_row_is_planned_once_within_budget() {
for (w, h, mips) in [(1, 1, 1), (37, 19, 6), (64, 3, 7), (5, 128, 8)] {
let desc = Rgba8TextureDesc::new(w, h, mips).unwrap();
let widest = w * RGBA8_TEXEL_BYTES;
for budget in [
widest,
widest + 4,
3 * widest,
w * h * RGBA8_TEXEL_BYTES * 2,
] {
let mut next_row = vec![0; mips as usize];
for submission in plan(desc, budget) {
assert!(submission.staging_bytes <= budget);
let mut offset = 0;
for c in &submission.copies {
let (mw, _) = desc.mip_extent(c.level).unwrap();
assert_eq!(c.first_row, next_row[c.level as usize]);
assert_eq!(c.staging_offset, offset);
assert!(c.rows > 0);
offset += c.rows * mw * RGBA8_TEXEL_BYTES;
next_row[c.level as usize] += c.rows;
}
assert_eq!(offset, submission.staging_bytes);
}
for level in 0..mips {
assert_eq!(next_row[level as usize], desc.mip_extent(level).unwrap().1);
}
}
}
}
#[test]
fn rejects_partial_and_malformed_uploads_before_planning() {
let desc = Rgba8TextureDesc::new(8, 4, 2).unwrap();
let bytes = vec![0; 8 * 4 * RGBA8_TEXEL_BYTES];
let mips = levels(&desc, &bytes);
let missing = error(desc, &mips[..1], 1024);
assert!(missing.contains("mip level 1 is missing"), "{missing}");
let duplicate = error(desc, &[mips[0], mips[1], mips[1]], 1024);
assert!(duplicate.contains("more than once"), "{duplicate}");
let out_of_range = Rgba8MipLevel::new_packed(2, 2, 1, &bytes[..8]);
let range = error(desc, &[mips[0], mips[1], out_of_range], 1024);
assert!(range.contains("out of bounds"), "{range}");
let wrong_size = Rgba8MipLevel::new_packed(1, 4, 1, &bytes[..16]);
assert!(error(desc, &[mips[0], wrong_size], 1024).contains("expected 4x2"));
let mut short_pitch = mips[0];
short_pitch.row_pitch = 28;
assert!(error(desc, &[short_pitch, mips[1]], 1024).contains("row pitch"));
let short_bytes = Rgba8MipLevel::new_packed(0, 8, 4, &bytes[..127]);
assert!(error(desc, &[short_bytes, mips[1]], 1024).contains("buffer length"));
let small = error(desc, &mips, 28);
assert!(small.contains("smaller than one 32-byte row"), "{small}");
}
}
+161
View File
@@ -1,5 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_metal::texture_pipeline::{Rgba8TextureDesc, StagingBudget, plan_staged_upload};
use xenora_metal::{MetalRgba8Texture, Rgba8MipLevel};
use xenora_texture::{Bc1Upload, Bc1UploadDesc, TiledBc1};
use super::context;
@@ -133,3 +135,162 @@ fn samples_pitched_bc1_upload_across_mips_and_layers() {
);
println!("checked 33 RGBA8 texels from pitched BC1 subresources");
}
/// Texel bytes chosen so neighbouring texels, rows and levels all differ, built
/// without any Xenora code so the readback has an independent expectation.
fn pattern_texel(level: u32, x: usize, y: usize) -> [u8; 4] {
let level = level as usize;
[
(x * 7 + level * 50) as u8,
(y * 13 + level) as u8,
((x ^ y) * 3) as u8,
(255 - level * 9) as u8,
]
}
fn tight_pattern(level: u32, width: usize, height: usize) -> Vec<u8> {
(0..height)
.flat_map(|y| (0..width).flat_map(move |x| pattern_texel(level, x, y)))
.collect()
}
/// Each row padded by `pad` bytes of 0xEE, which must never reach the texture.
fn padded_pattern(level: u32, width: usize, height: usize, pad: usize) -> Vec<u8> {
let tight = tight_pattern(level, width, height);
tight
.chunks(width * 4)
.flat_map(|row| row.iter().copied().chain(std::iter::repeat_n(0xEE, pad)))
.collect()
}
fn padded_levels(desc: Rgba8TextureDesc, pad: usize) -> Vec<(usize, usize, Vec<u8>)> {
(0..desc.mips)
.map(|level| {
let (w, h) = desc.mip_extent(level).unwrap();
(w, h, padded_pattern(level, w, h, pad))
})
.collect()
}
fn mip_views(levels: &[(usize, usize, Vec<u8>)], pad: usize) -> Vec<Rgba8MipLevel<'_>> {
levels
.iter()
.enumerate()
.map(|(level, (w, h, bytes))| Rgba8MipLevel {
level: level as u32,
width: *w,
height: *h,
row_pitch: w * 4 + pad,
bytes,
})
.collect()
}
#[test]
fn staged_upload_matches_the_source_under_every_budget() {
let gpu = context();
// 37×19 has six levels, down to 1×1, and odd sizes at every level.
let desc = Rgba8TextureDesc::new(37, 19, 6).unwrap();
let pad = 12;
let levels = padded_levels(desc, pad);
let mips = mip_views(&levels, pad);
let total: usize = levels.iter().map(|(w, h, _)| w * h * 4).sum();
let widest_row = 37 * 4;
// One submission, several bands, a single row per band, and a budget that
// leaves a remainder at every level.
for budget in [total, 3 * widest_row, widest_row, widest_row + 4] {
let budget = StagingBudget::new(budget).unwrap();
let plan = plan_staged_upload(&desc, &mips, budget).unwrap();
let (texture, report) =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget)
.unwrap();
assert_eq!(report.submissions, plan.len());
assert!(report.peak_staging_bytes <= budget.max_bytes());
assert_eq!(report.bytes_copied, total);
if budget.max_bytes() == total {
assert_eq!(report.submissions, 1);
} else {
assert!(report.submissions > 1);
}
for level in 0..desc.mips {
let (w, h) = desc.mip_extent(level).unwrap();
let actual = texture.read_back(gpu.device(), gpu.queue(), level).unwrap();
assert_eq!(
actual,
tight_pattern(level, w, h),
"budget {} level {level}",
budget.max_bytes()
);
}
}
}
#[test]
fn staged_and_direct_uploads_produce_the_same_texels() {
let gpu = context();
let desc = Rgba8TextureDesc::new(16, 9, 5).unwrap();
let levels = padded_levels(desc, 0);
let mips = mip_views(&levels, 0);
let direct = MetalRgba8Texture::upload(gpu.device(), desc, &mips).unwrap();
let budget = StagingBudget::new(16 * 4 * 2).unwrap();
let (staged, _) =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
for level in 0..desc.mips {
let (w, h) = desc.mip_extent(level).unwrap();
let expected = tight_pattern(level, w, h);
assert_eq!(
direct.read_back(gpu.device(), gpu.queue(), level).unwrap(),
expected
);
assert_eq!(
staged.read_back(gpu.device(), gpu.queue(), level).unwrap(),
expected
);
}
}
#[test]
fn staged_upload_handles_a_single_texel() {
let gpu = context();
let desc = Rgba8TextureDesc::new(1, 1, 1).unwrap();
let texel = pattern_texel(0, 0, 0);
let mips = [Rgba8MipLevel::new_packed(0, 1, 1, &texel)];
let budget = StagingBudget::new(4).unwrap();
let (texture, report) =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
assert_eq!((report.submissions, report.peak_staging_bytes), (1, 4));
assert_eq!(
texture.read_back(gpu.device(), gpu.queue(), 0).unwrap(),
texel
);
}
#[test]
fn staged_upload_rejects_bad_input_before_touching_the_gpu() {
let gpu = context();
let desc = Rgba8TextureDesc::new(8, 4, 2).unwrap();
let levels = padded_levels(desc, 0);
let mips = mip_views(&levels, 0);
let small = StagingBudget::new(28).unwrap();
let error = MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, small)
.unwrap_err();
assert!(!error.is_capability_unavailable());
assert!(
error.to_string().contains("smaller than one 32-byte row"),
"{error}"
);
let budget = StagingBudget::new(1024).unwrap();
let missing =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips[..1], budget)
.unwrap_err();
assert!(
missing.to_string().contains("mip level 1 is missing"),
"{missing}"
);
// A Private texture refuses CPU writes instead of failing inside Metal.
let (texture, _) =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
let refused = texture.upload_mip(&mips[0]).unwrap_err();
assert!(refused.to_string().contains("Private-storage"), "{refused}");
}