Skip to main content

crcbl_frame/
texture.rs

1//! One texture upload, for every format and every caller.
2//!
3//! ```text
4//! pixels ──pad rows to the device's copy alignment──▶ staging buffer
5//!            │
6//!            └──barrier ▸ copy_buffer_to_image ▸ barrier──▶ sampled image + view
7//! ```
8//!
9//! # One layer or several, one level or a chain
10//!
11//! [`upload_texture`] uploads a single-layer `D2` image, which is what a sprite
12//! sheet and a glyph atlas are. [`upload_texture_layers`] uploads several layers
13//! of the same size into one `D2Array` image, which is
14//! topic 03 §3.2's
15//! [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) page: one image, one
16//! descriptor, and a layer index in the material row selecting between them.
17//! [`upload_texture_mip_layers`] is the same page with every layer's mip chain
18//! behind it — topic 43's filtering rung, whose chain
19//! [`crate::mip`] builds on the host.
20//!
21//! All three go through the same body, and it records **one copy per level of
22//! every layer** rather than one covering all of them. That is not caution: a
23//! copy region's extent is a 2D extent on every backend here — `crcbl-dx12`
24//! refuses a `depth_or_layers` other than 1 by name, because
25//! `CopyTextureRegion` addresses one subresource — so the layer travels in
26//! [`ImageSubresourceLayers::base_layer`], the level in
27//! [`ImageSubresourceLayers::mip`], and the buffer offset says where that
28//! subresource's rows start.
29//!
30//! # A page that starts empty
31//!
32//! [`upload_cleared_texture`] is the same copy for an image that is mostly
33//! zeroes — an atlas when it is created. The zeroes are written by a
34//! [`clear_buffer`](crcbl_hal::CommandEncoder::clear_buffer) on the GPU and
35//! copied into every layer, and only the rectangles written over them are
36//! staged from the host. See that function for why the difference is the wasm
37//! heap's.
38//!
39//! This is a **startup** path, not a frame path: it records its own barriers
40//! and blocks on [`Device::wait_idle`], which is only legal because no graph
41//! is being recorded while it runs. See this crate's docs on the one rule — the
42//! two staging uploads (`crcbl_render::forward`'s cube and this) are its named
43//! exceptions. Its barriers name only the image it creates, so a caller between
44//! two frames — `ForwardRenderer::replace_page`
45//! reloading a page — touches nothing a frame in flight reads, and the wait
46//! means no frame can bind the image before its copy has landed.
47//!
48//! # Why it is not in `ui_pass`
49//!
50//! It was, and it was `R8_UNORM` only, with the glyph atlas's labels baked in.
51//! The interesting part is that the old code was *right by coincidence*: it
52//! computed a row pitch from `width`, called it `row_texels`, and handed it to
53//! [`BufferImageCopy::buffer_row_length`] — which really is in texels, and
54//! really did equal the byte count, because `R8Unorm` is one byte per texel.
55//! For `Rgba8Unorm` the two differ by four, so the pitch here is computed in
56//! **bytes** and converted back to texels exactly once, at the copy.
57
58use crcbl_hal::{
59    BufferDesc, BufferImageCopy, BufferUsage, CommandEncoder, CommandEncoderDesc, Device, Extent3d,
60    Format, HalError, ImageAspect, ImageDesc, ImageHandle, ImageSubresourceLayers,
61    ImageSubresourceRange, ImageType, ImageUsage, ImageViewDesc, ImageViewHandle, ImageViewType,
62    MemoryLocation, Offset3d, QueueHandle, ResourceState, SubmitInfo,
63};
64
65use crate::mip::level_extent;
66
67/// A texture that has been uploaded: the image, and the view callers bind.
68///
69/// The two travel together because they die together, and every caller that
70/// kept them as two loose handles has had to remember that on both its failure
71/// path and its teardown path. [`UploadedTexture::destroy`] is the one place
72/// the order lives.
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub struct UploadedTexture {
75    /// The device-local image the copy filled.
76    pub image: ImageHandle,
77    /// A full-subresource colour view of [`UploadedTexture::image`]: `D2` from
78    /// [`upload_texture`], `D2Array` from [`upload_texture_layers`] and
79    /// [`upload_texture_mip_layers`].
80    pub view: ImageViewHandle,
81}
82
83impl UploadedTexture {
84    /// Releases the view and then the image. The device must be idle.
85    pub fn destroy(&self, device: &dyn Device) {
86        device.destroy_image_view(self.view);
87        device.destroy_image(self.image);
88    }
89}
90
91/// Uploads a 2D colour texture via a staging-buffer copy, and returns the image
92/// and a view onto it.
93///
94/// `label` names the image and the view, and is the stem of the staging
95/// buffer's and the encoder's names, so a capture shows which texture an
96/// upload belonged to.
97///
98/// `pixels` must be exactly `width * height * texel_size` bytes, tightly
99/// packed; the row padding the device's copy alignment wants is added here.
100/// Padding rather than packing is what makes one upload path work on both
101/// backends: Vulkan takes either, WebGPU requires a 256-byte row pitch and says
102/// so through
103/// [`optimal_buffer_copy_offset_alignment`](crcbl_hal::Limits::optimal_buffer_copy_offset_alignment).
104///
105/// Every object this creates is released on every path out, including the
106/// failing ones: a `?` that dropped the staging buffer on the floor would leak
107/// one per failed startup, and the recorder's leak assertions would only notice
108/// once something actually failed.
109///
110/// # Errors
111///
112/// [`HalError::InvalidDescriptor`] if `format` has no single colour plane, if
113/// either extent is zero, or if `pixels` is not exactly the size the extent and
114/// the format imply — the last of which used to be a `copy_from_slice` panic
115/// naming neither number. [`HalError`] from any seam call otherwise; an extent
116/// past the device's `max_image_2d` is the device's to refuse, not this
117/// function's.
118pub fn upload_texture(
119    device: &dyn Device,
120    queue: QueueHandle,
121    label: &str,
122    format: Format,
123    width: u32,
124    height: u32,
125    pixels: &[u8],
126) -> Result<UploadedTexture, HalError> {
127    upload(
128        device,
129        queue,
130        label,
131        format,
132        (width, height),
133        &[&[pixels]],
134        ImageViewType::D2,
135    )
136}
137
138/// Uploads several equally-sized layers into one `D2Array` colour image, and
139/// returns it with an array view onto every layer.
140///
141/// §3.2's [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) page: the index a
142/// material row carries is a layer of the image this returns. One image rather
143/// than one descriptor per texture is what makes the lookup need no
144/// [`Features::DESCRIPTOR_INDEXING`](crcbl_hal::Features::DESCRIPTOR_INDEXING),
145/// and therefore run on every backend the engine has — see
146/// `crcbl_render::forward`, which builds the page this crate's only caller binds.
147///
148/// Every slice in `layers` must be exactly one tightly packed
149/// `width * height * texel_size` image, and they become layers 0, 1, … in the
150/// order given. [`upload_texture`]'s account of the label, the row padding and
151/// the release-on-every-path rule applies here unchanged. The image has one
152/// mip level; [`upload_texture_mip_layers`] is the form that carries a chain.
153///
154/// # Errors
155///
156/// [`upload_texture`]'s errors, plus [`HalError::InvalidDescriptor`] when
157/// `layers` is empty — a zero-layer image is not a page, and it reaches the
158/// device as a zero extent whose complaint names a different thing. A layer
159/// count past the device's `max_image_array_layers` is the device's to refuse.
160pub fn upload_texture_layers(
161    device: &dyn Device,
162    queue: QueueHandle,
163    label: &str,
164    format: Format,
165    width: u32,
166    height: u32,
167    layers: &[&[u8]],
168) -> Result<UploadedTexture, HalError> {
169    let chains: Vec<[&[u8]; 1]> = layers.iter().map(|pixels| [*pixels]).collect();
170    let layers: Vec<&[&[u8]]> = chains.iter().map(|chain| &chain[..]).collect();
171    upload(
172        device,
173        queue,
174        label,
175        format,
176        (width, height),
177        &layers,
178        ImageViewType::D2Array,
179    )
180}
181
182/// [`upload_texture_layers`] with a mip chain behind every layer: one
183/// `D2Array` image whose level count is the chain's length, and an array view
184/// onto every level of every layer.
185///
186/// `layers[layer][level]` is level `level` of layer `layer`, tightly packed at
187/// that level's extent — `width` and `height` each halved per level and never
188/// below one texel, which is [`crate::mip::level_extent`] and every backend's
189/// own definition. Every layer carries the same number of levels, at least one
190/// and at most the full chain
191/// [`Extent3d::full_mip_levels`](crcbl_hal::Extent3d::full_mip_levels) counts;
192/// a shorter chain is legal and leaves the sampler's `lod_max` to the caller.
193///
194/// # Errors
195///
196/// [`upload_texture_layers`]'s errors, plus [`HalError::InvalidDescriptor`]
197/// when a layer has no levels, when two layers disagree on how many, when the
198/// count exceeds the full chain, or when a level is not exactly its own
199/// extent's worth of texels — each naming the layer and the level.
200pub fn upload_texture_mip_layers(
201    device: &dyn Device,
202    queue: QueueHandle,
203    label: &str,
204    format: Format,
205    width: u32,
206    height: u32,
207    layers: &[&[&[u8]]],
208) -> Result<UploadedTexture, HalError> {
209    upload(
210        device,
211        queue,
212        label,
213        format,
214        (width, height),
215        layers,
216        ImageViewType::D2Array,
217    )
218}
219
220/// Texels written over an [`upload_cleared_texture`] image as it is created: a
221/// `width` by `height` rectangle of layer `layer`, its top-left texel at `x`,
222/// `y`.
223#[derive(Clone, Copy, Debug)]
224pub struct TexturePatch<'a> {
225    /// The array layer the rectangle is written to.
226    pub layer: u32,
227    /// The rectangle's left column.
228    pub x: u32,
229    /// The rectangle's top row.
230    pub y: u32,
231    /// Its width in texels.
232    pub width: u32,
233    /// Its height in texels.
234    pub height: u32,
235    /// Exactly `width * height * texel_size` bytes, tightly packed, rows top to
236    /// bottom.
237    pub pixels: &'a [u8],
238}
239
240/// The image [`upload_cleared_texture`] creates, and what goes on it.
241#[derive(Clone, Copy, Debug)]
242pub struct ClearedTextureDesc<'a> {
243    /// Names the image and the view, and is the stem of the buffers' and the
244    /// encoder's names, as in [`upload_texture`].
245    pub label: &'a str,
246    /// An uncompressed format with a single colour plane.
247    pub format: Format,
248    /// Width of every layer, in texels.
249    pub width: u32,
250    /// Height of every layer, in texels.
251    pub height: u32,
252    /// Array layers in the image; at least one.
253    pub layers: u32,
254    /// `D2` or `D2Array`: the shader's declaration decides, not `layers`.
255    pub view_type: ImageViewType,
256    /// Rectangles written over the zeroes, in order.
257    pub patches: &'a [TexturePatch<'a>],
258}
259
260/// Creates a sampled colour image whose every texel is zero, with `patches`
261/// written over it, and returns it with a full view.
262///
263/// **For a page that is mostly empty**, which is what an atlas is when it is
264/// created: [`crate::ui_pass`]'s image atlas and glyph pages. Staging such a
265/// page through [`upload_texture`] builds every zero texel on the host, pads a
266/// second copy of it, and writes it into a staging buffer — and on
267/// `crcbl-webgpu` that write is bytes on the command stream, which lives in the
268/// wasm heap, grows to hold the whole start-up frame and never gives the
269/// address space back. Here the zeroes never exist on the host: one
270/// device-local buffer a layer in size is zeroed by
271/// [`clear_buffer`](crcbl_hal::CommandEncoder::clear_buffer) and copied into
272/// every layer, and only the patches are staged and written. The page is
273/// transparent black where nothing was patched, on every backend, rather than
274/// whatever an uninitialised image held.
275///
276/// One mip level. The same startup rules as [`upload_texture`]: it records its
277/// own barriers, blocks on [`Device::wait_idle`], and releases every buffer it
278/// created on every path out.
279///
280/// # Errors
281///
282/// [`upload_texture`]'s format and extent errors;
283/// [`HalError::InvalidDescriptor`] for zero layers, and for a patch that is
284/// empty, is not on a layer or inside the extent, or whose `pixels` is not its
285/// own size — naming the patch. [`HalError`] from any seam call otherwise.
286pub fn upload_cleared_texture(
287    device: &dyn Device,
288    queue: QueueHandle,
289    desc: &ClearedTextureDesc<'_>,
290) -> Result<UploadedTexture, HalError> {
291    let mut batch = UploadBatch::new(device, queue, desc.label);
292    let texture = batch.cleared_texture(desc)?;
293    batch.submit_one(texture)
294}
295
296/// [`upload_cleared_texture`]'s validation and staging, recorded into
297/// `batch`.
298fn stage_cleared_texture(
299    batch: &mut UploadBatch<'_>,
300    desc: &ClearedTextureDesc<'_>,
301) -> Result<UploadedTexture, HalError> {
302    let device = batch.device;
303    let label = desc.label;
304    let texel = image_texel(label, desc.format, (desc.width, desc.height))?;
305    if desc.layers == 0 {
306        return Err(HalError::InvalidDescriptor(format!(
307            "{label}: a texture needs at least one layer"
308        )));
309    }
310    let alignment = device
311        .caps()
312        .limits
313        .optimal_buffer_copy_offset_alignment
314        .max(1);
315    let full = u64::from(desc.width) * u64::from(texel);
316    let full_pitch = padded_row_pitch(full, texel, alignment);
317    // Whole words: `vkCmdFillBuffer` and `crcbl-dx12`'s clear refuse a size that
318    // is not a multiple of four.
319    let cleared = (full_pitch * u64::from(desc.height)).next_multiple_of(CLEAR_WORD_BYTES);
320    let mut patched = Vec::new();
321    let mut patch_regions = Vec::with_capacity(desc.patches.len());
322    for (index, patch) in desc.patches.iter().enumerate() {
323        let inside = patch
324            .x
325            .checked_add(patch.width)
326            .is_some_and(|right| right <= desc.width)
327            && patch
328                .y
329                .checked_add(patch.height)
330                .is_some_and(|bottom| bottom <= desc.height);
331        if patch.width == 0 || patch.height == 0 || patch.layer >= desc.layers || !inside {
332            return Err(HalError::InvalidDescriptor(format!(
333                "{label}: patch {index} is {}x{} at {},{} on layer {}, which is not a non-empty \
334                 rectangle inside a {}x{} image of {} layer(s)",
335                patch.width,
336                patch.height,
337                patch.x,
338                patch.y,
339                patch.layer,
340                desc.width,
341                desc.height,
342                desc.layers
343            )));
344        }
345        if let Some(other) = desc.patches[..index]
346            .iter()
347            .position(|earlier| earlier.layer == patch.layer && overlaps(earlier, patch))
348        {
349            return Err(HalError::InvalidDescriptor(format!(
350                "{label}: patch {index} overlaps patch {other} on layer {}, and a texel written \
351                 twice in one upload is a synchronisation hazard",
352                patch.layer
353            )));
354        }
355        let row_bytes = u64::from(patch.width) * u64::from(texel);
356        let expected = row_bytes * u64::from(patch.height);
357        if patch.pixels.len() as u64 != expected {
358            return Err(HalError::InvalidDescriptor(format!(
359                "{label}: patch {index} is {}x{} {:?}, {expected} bytes, got {}",
360                patch.width,
361                patch.height,
362                desc.format,
363                patch.pixels.len()
364            )));
365        }
366        let row_pitch = padded_row_pitch(row_bytes, texel, alignment);
367        let staged =
368            stage_rows(row_bytes, patch.height, row_pitch, patch.pixels).ok_or_else(|| {
369                HalError::InvalidDescriptor(format!(
370                    "{label}: patch {index} does not fit in this host's address space"
371                ))
372            })?;
373        patch_regions.push(StagedRegion {
374            buffer_offset: patched.len() as u64,
375            row_texels: u32::try_from(row_pitch / u64::from(texel)).unwrap_or(u32::MAX),
376            extent: Extent3d::d2(patch.width, patch.height),
377            layer: patch.layer,
378            mip: 0,
379            image_offset: Offset3d {
380                x: i32::try_from(patch.x).unwrap_or(i32::MAX),
381                y: i32::try_from(patch.y).unwrap_or(i32::MAX),
382                z: 0,
383            },
384        });
385        patched.extend_from_slice(&staged);
386    }
387
388    // The zeroes go only where no patch does, so no texel is written twice: two
389    // unbarriered writes to one subresource in one command buffer are a
390    // synchronisation hazard Vulkan's sync validation reports.
391    let row_texels = u32::try_from(full_pitch / u64::from(texel)).unwrap_or(u32::MAX);
392    let layer_regions: Vec<StagedRegion> = (0..desc.layers)
393        .flat_map(|layer| {
394            let covered: Vec<&TexturePatch<'_>> = desc
395                .patches
396                .iter()
397                .filter(|patch| patch.layer == layer)
398                .collect();
399            uncovered(desc.width, desc.height, &covered)
400                .into_iter()
401                .map(move |(x, y, width, height)| StagedRegion {
402                    buffer_offset: 0,
403                    row_texels,
404                    extent: Extent3d::d2(width, height),
405                    layer,
406                    mip: 0,
407                    image_offset: Offset3d {
408                        x: i32::try_from(x).unwrap_or(i32::MAX),
409                        y: i32::try_from(y).unwrap_or(i32::MAX),
410                        z: 0,
411                    },
412                })
413        })
414        .collect();
415
416    // Device-local, because a clear writes into the buffer on the GPU: a
417    // `crcbl-dx12` upload-heap buffer can never be a copy destination.
418    let zero_label = format!("{label} zero");
419    let zero = device.create_buffer(&BufferDesc {
420        label: Some(&zero_label),
421        size: cleared,
422        usage: BufferUsage::TRANSFER_SRC | BufferUsage::TRANSFER_DST,
423        memory: MemoryLocation::DeviceLocal,
424    })?;
425    batch.buffers.push(zero);
426    let staging = if patched.is_empty() {
427        None
428    } else {
429        let staging = create_staging(device, label, &patched)?;
430        batch.buffers.push(staging);
431        Some(staging)
432    };
433    let zero_source = CopySource {
434        buffer: zero,
435        regions: &layer_regions,
436    };
437    let sources: Vec<CopySource<'_>> = core::iter::once(zero_source)
438        .chain(staging.map(|buffer| CopySource {
439            buffer,
440            regions: &patch_regions,
441        }))
442        .collect();
443    batch.record(&UploadArgs {
444        label,
445        format: desc.format,
446        width: desc.width,
447        height: desc.height,
448        layer_count: desc.layers,
449        mip_levels: 1,
450        view_type: desc.view_type,
451        cleared: Some((zero, cleared)),
452        sources: &sources,
453    })
454}
455
456/// Whether two patches share a texel.
457fn overlaps(a: &TexturePatch<'_>, b: &TexturePatch<'_>) -> bool {
458    a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height
459}
460
461/// The rectangles of a `width` by `height` layer that no patch in `covered`
462/// touches, as `(x, y, width, height)`: the layer cut into horizontal bands at
463/// every patch's top and bottom edge, and each band's gaps between patches.
464/// The patches must not overlap and must lie inside the layer.
465fn uncovered(width: u32, height: u32, covered: &[&TexturePatch<'_>]) -> Vec<(u32, u32, u32, u32)> {
466    let mut edges: Vec<u32> = covered
467        .iter()
468        .flat_map(|patch| [patch.y, patch.y + patch.height])
469        .chain([0, height])
470        .collect();
471    edges.sort_unstable();
472    edges.dedup();
473    let mut gaps = Vec::new();
474    for band in edges.windows(2) {
475        let (top, bottom) = (band[0], band[1]);
476        let mut spans: Vec<(u32, u32)> = covered
477            .iter()
478            .filter(|patch| patch.y < bottom && top < patch.y + patch.height)
479            .map(|patch| (patch.x, patch.x + patch.width))
480            .collect();
481        spans.sort_unstable();
482        let mut x = 0;
483        for (left, right) in spans.into_iter().chain([(width, width)]) {
484            if left > x {
485                gaps.push((x, top, left - x, bottom - top));
486            }
487            x = x.max(right);
488        }
489    }
490    gaps
491}
492
493/// The word [`clear_buffer`](crcbl_hal::CommandEncoder::clear_buffer) zeroes in
494/// on the backends that fill `u32`s, and so the unit its size is rounded to.
495const CLEAR_WORD_BYTES: u64 = 4;
496
497/// The body the public uploads share, as a batch of one.
498///
499/// `extent` is `(width, height)` as one argument rather than two, which is what
500/// keeps this inside the argument count the public wrappers already sit at.
501fn upload(
502    device: &dyn Device,
503    queue: QueueHandle,
504    label: &str,
505    format: Format,
506    extent: (u32, u32),
507    layers: &[&[&[u8]]],
508    view_type: ImageViewType,
509) -> Result<UploadedTexture, HalError> {
510    let mut batch = UploadBatch::new(device, queue, label);
511    let texture = batch.texture(label, format, extent, layers, view_type)?;
512    batch.submit_one(texture)
513}
514
515/// Validates `layers`, stages every level of every layer into one buffer, and
516/// records the copies into `batch`.
517fn stage_texture(
518    batch: &mut UploadBatch<'_>,
519    label: &str,
520    format: Format,
521    extent: (u32, u32),
522    layers: &[&[&[u8]]],
523    view_type: ImageViewType,
524) -> Result<UploadedTexture, HalError> {
525    let device = batch.device;
526    let (width, height) = extent;
527    let texel = image_texel(label, format, extent)?;
528    let layer_count = u32::try_from(layers.len()).unwrap_or(u32::MAX);
529    if layer_count == 0 {
530        return Err(HalError::InvalidDescriptor(format!(
531            "{label}: a texture needs at least one layer of pixels"
532        )));
533    }
534    let mip_levels = u32::try_from(layers[0].len()).unwrap_or(u32::MAX);
535    let full_chain = Extent3d::d2(width, height).full_mip_levels(ImageType::D2);
536    if mip_levels == 0 {
537        return Err(HalError::InvalidDescriptor(format!(
538            "{label}: layer 0 has no mip levels; a layer needs at least its own texels"
539        )));
540    }
541    if mip_levels > full_chain {
542        return Err(HalError::InvalidDescriptor(format!(
543            "{label}: {mip_levels} mip levels for a {width}x{height} image, whose full chain \
544             is {full_chain}"
545        )));
546    }
547
548    let alignment = device
549        .caps()
550        .limits
551        .optimal_buffer_copy_offset_alignment
552        .max(1);
553
554    // Every level of every layer is validated and staged in the order the
555    // copies below read them: layer-major, level-minor. Each level's rows are a
556    // multiple of the alignment, so stacking them puts every subresource's own
557    // offset on it too — which is what lets each copy name one buffer offset.
558    let mut padded = Vec::new();
559    let mut regions = Vec::with_capacity(layers.len() * mip_levels as usize);
560    for (layer, chain) in layers.iter().enumerate() {
561        if chain.len() as u32 != mip_levels {
562            return Err(HalError::InvalidDescriptor(format!(
563                "{label}: layer {layer} carries {} mip levels and layer 0 carries {mip_levels}; \
564                 every layer of one image has the same chain",
565                chain.len()
566            )));
567        }
568        for (level, pixels) in chain.iter().enumerate() {
569            let level_width = level_extent(width, level as u32);
570            let level_height = level_extent(height, level as u32);
571            let row_bytes = u64::from(level_width) * u64::from(texel);
572            let expected = row_bytes * u64::from(level_height);
573            if pixels.len() as u64 != expected {
574                return Err(HalError::InvalidDescriptor(format!(
575                    "{label}: layer {layer} level {level} of a {width}x{height} {format:?} image \
576                     is {level_width}x{level_height}, {expected} bytes ({texel} per texel), got {}",
577                    pixels.len()
578                )));
579            }
580            let row_pitch = padded_row_pitch(row_bytes, texel, alignment);
581            let staged =
582                stage_rows(row_bytes, level_height, row_pitch, pixels).ok_or_else(|| {
583                    HalError::InvalidDescriptor(format!(
584                        "{label}: a staging image of {} bytes and more does not fit in this \
585                         host's address space",
586                        padded.len()
587                    ))
588                })?;
589            regions.push(StagedRegion {
590                buffer_offset: padded.len() as u64,
591                // The copy is in texels; the pitch above is in bytes.
592                // `padded_row_pitch` guarantees the division is exact.
593                row_texels: u32::try_from(row_pitch / u64::from(texel)).unwrap_or(u32::MAX),
594                extent: Extent3d::d2(level_width, level_height),
595                layer: layer as u32,
596                mip: level as u32,
597                image_offset: Offset3d { x: 0, y: 0, z: 0 },
598            });
599            padded.extend_from_slice(&staged);
600        }
601    }
602
603    let staging = create_staging(device, label, &padded)?;
604    batch.buffers.push(staging);
605    batch.record(&UploadArgs {
606        label,
607        format,
608        width,
609        height,
610        layer_count,
611        mip_levels,
612        view_type,
613        cleared: None,
614        sources: &[CopySource {
615            buffer: staging,
616            regions: &regions,
617        }],
618    })
619}
620
621/// The bytes one texel of `format` occupies, once `format` and `extent` are
622/// known to describe an image this module can stage.
623///
624/// # Errors
625///
626/// [`HalError::InvalidDescriptor`] for a format with no single colour plane, a
627/// block-compressed format, or a zero extent, each naming `label`.
628fn image_texel(label: &str, format: Format, (width, height): (u32, u32)) -> Result<u32, HalError> {
629    // `texel_size`, not `block_size`: it is the number a `BufferImageCopy` is
630    // sized against, and it is `None` for exactly the formats this path cannot
631    // describe — a combined depth/stencil format, whose two planes need two
632    // copies and neither of which is a `COLOR` aspect.
633    let texel = format.texel_size(ImageAspect::COLOR).ok_or_else(|| {
634        HalError::InvalidDescriptor(format!(
635            "{label}: {format:?} has no single colour plane, so it cannot be uploaded as one \
636             colour-aspect copy"
637        ))
638    })?;
639    // A compressed format's `block_size` covers a 4×4 block, not one texel, so
640    // the per-texel sizing below would be wrong by a factor of four: a BC1 row
641    // is `ceil(width / 4) × 8` bytes, not `width × 8`. No caller uploads one
642    // today; refuse rather than corrupt.
643    if format.is_compressed() {
644        return Err(HalError::InvalidDescriptor(format!(
645            "{label}: {format:?} is block-compressed and this path sizes per texel; \
646             it cannot be uploaded as a colour-aspect copy"
647        )));
648    }
649    if width == 0 || height == 0 {
650        return Err(HalError::InvalidDescriptor(format!(
651            "{label}: texture extent {width}x{height} must be non-zero in both dimensions"
652        )));
653    }
654    Ok(texel)
655}
656
657/// A host-visible `TRANSFER_SRC` buffer labelled `"{label} staging"` holding
658/// `bytes`, destroyed again if the write fails.
659fn create_staging(
660    device: &dyn Device,
661    label: &str,
662    bytes: &[u8],
663) -> Result<crcbl_hal::BufferHandle, HalError> {
664    let staging_label = format!("{label} staging");
665    let staging = device.create_buffer(&BufferDesc {
666        label: Some(&staging_label),
667        size: bytes.len() as u64,
668        usage: BufferUsage::TRANSFER_SRC,
669        memory: MemoryLocation::HostUpload,
670    })?;
671    if let Err(error) = device.write_buffer(staging, 0, bytes) {
672        device.destroy_buffer(staging);
673        return Err(error);
674    }
675    Ok(staging)
676}
677
678/// A tightly packed region of `format` texels staged for an in-frame copy: a
679/// host-visible `TRANSFER_SRC` buffer holding `pixels` with its rows padded to
680/// the device's copy alignment, and the row pitch in texels a
681/// [`BufferImageCopy`] reading it names.
682///
683/// The frame-time half of what [`upload_texture`] does at start-up, without the
684/// image, the barriers or the wait: the caller records the copy inside a
685/// [`RenderGraph`](crate::graph::RenderGraph) copy pass, which is where a
686/// barrier recorded during a frame belongs. [`ui_pass`](crate::ui_pass)'s image
687/// atlas and `crcbl_render`'s sprite atlas are the callers, and each owns the
688/// buffer's lifetime.
689///
690/// # Errors
691///
692/// [`HalError::InvalidDescriptor`] if `format` has no single colour plane, if
693/// the region is empty or if `pixels` is not exactly `width * height` texels;
694/// [`HalError`] from creating or writing the buffer, which is destroyed again
695/// if the write fails.
696pub fn stage_region(
697    device: &dyn Device,
698    label: &str,
699    format: Format,
700    (width, height): (u32, u32),
701    pixels: &[u8],
702) -> Result<(crcbl_hal::BufferHandle, u32), HalError> {
703    let texel = format.texel_size(ImageAspect::COLOR).ok_or_else(|| {
704        HalError::InvalidDescriptor(format!("{label}: {format:?} has no single colour plane"))
705    })?;
706    let row_bytes = u64::from(width) * u64::from(texel);
707    if width == 0 || height == 0 || pixels.len() as u64 != row_bytes * u64::from(height) {
708        return Err(HalError::InvalidDescriptor(format!(
709            "{label}: a {width}x{height} {format:?} region is {} bytes, got {}",
710            row_bytes * u64::from(height),
711            pixels.len()
712        )));
713    }
714    let alignment = device
715        .caps()
716        .limits
717        .optimal_buffer_copy_offset_alignment
718        .max(1);
719    let row_pitch = padded_row_pitch(row_bytes, texel, alignment);
720    let staged = stage_rows(row_bytes, height, row_pitch, pixels).ok_or_else(|| {
721        HalError::InvalidDescriptor(format!(
722            "{label}: the staged region does not fit in this host's address space"
723        ))
724    })?;
725    let buffer = device.create_buffer(&BufferDesc {
726        label: Some(label),
727        size: staged.len() as u64,
728        usage: BufferUsage::TRANSFER_SRC,
729        memory: MemoryLocation::HostUpload,
730    })?;
731    if let Err(error) = device.write_buffer(buffer, 0, &staged) {
732        device.destroy_buffer(buffer);
733        return Err(error);
734    }
735    // `padded_row_pitch` returns a whole number of texels, so this is exact.
736    let row_texels = u32::try_from(row_pitch / u64::from(texel)).unwrap_or(u32::MAX);
737    Ok((buffer, row_texels))
738}
739
740/// The row pitch in **bytes**: at least `row_bytes`, a multiple of `alignment`,
741/// and a whole number of texels.
742///
743/// The last of those is why this is not one `next_multiple_of` call. The copy
744/// expresses its pitch in texels, so a byte pitch that is not divisible by the
745/// texel size cannot be expressed at all. Every real device's alignment is a
746/// power of two at least as large as any uncompressed texel, so in practice the
747/// lcm *is* the alignment — this costs nothing and removes the assumption.
748fn padded_row_pitch(row_bytes: u64, texel: u32, alignment: u64) -> u64 {
749    let texel = u64::from(texel);
750    let step = texel / gcd(texel, alignment) * alignment;
751    row_bytes.next_multiple_of(step)
752}
753
754/// Greatest common divisor, for [`padded_row_pitch`]'s lcm.
755fn gcd(mut a: u64, mut b: u64) -> u64 {
756    while b != 0 {
757        (a, b) = (b, a % b);
758    }
759    a
760}
761
762/// Copies `height` tightly-packed rows of `row_bytes` into a buffer whose rows
763/// are `row_pitch` bytes apart, zero-filling the padding.
764///
765/// `None` only when the padded image does not fit in a `usize`, which on a
766/// 64-bit host means the caller asked for more than the address space.
767fn stage_rows(row_bytes: u64, height: u32, row_pitch: u64, pixels: &[u8]) -> Option<Vec<u8>> {
768    let size = usize::try_from(row_pitch * u64::from(height)).ok()?;
769    let row_bytes = usize::try_from(row_bytes).ok()?;
770    let row_pitch = usize::try_from(row_pitch).ok()?;
771    let mut padded = vec![0u8; size];
772    for row in 0..height as usize {
773        let src = row * row_bytes;
774        let dst = row * row_pitch;
775        padded[dst..dst + row_bytes].copy_from_slice(&pixels[src..src + row_bytes]);
776    }
777    Some(padded)
778}
779
780/// One subresource's place in the staging buffer: what its
781/// [`BufferImageCopy`] names besides the buffer and the image.
782struct StagedRegion {
783    /// Where this subresource's first row starts, on the copy alignment.
784    buffer_offset: u64,
785    /// The padded row pitch, in texels — the unit
786    /// [`BufferImageCopy::buffer_row_length`] documents.
787    row_texels: u32,
788    /// This level's own extent, halved from the image's per level.
789    extent: Extent3d,
790    layer: u32,
791    mip: u32,
792    /// Where in that subresource the rows land: the origin for a whole level,
793    /// the rectangle's corner for a [`TexturePatch`].
794    image_offset: Offset3d,
795}
796
797/// One buffer the copies read, and the regions they read from it.
798struct CopySource<'a> {
799    buffer: crcbl_hal::BufferHandle,
800    regions: &'a [StagedRegion],
801}
802
803/// Everything [`UploadBatch::record`] needs that is not the device, the queue
804/// or the bytes — one struct rather than seven positional arguments, which is what
805/// `clippy::too_many_arguments` is objecting to and also what makes the two
806/// `u32`s impossible to swap at the call site.
807struct UploadArgs<'a> {
808    label: &'a str,
809    format: Format,
810    width: u32,
811    height: u32,
812    /// Array layers in the image.
813    layer_count: u32,
814    /// Mip levels in the image, and in every layer's chain.
815    mip_levels: u32,
816    /// `D2` for one layer, `D2Array` for a page. Not derived from
817    /// `layer_count`: a one-layer array view is a legitimate thing to want, and
818    /// the shader's declaration is what decides which it is.
819    view_type: ImageViewType,
820    /// A buffer the copies zero first, and how many bytes of it, for
821    /// [`upload_cleared_texture`].
822    cleared: Option<(crcbl_hal::BufferHandle, u64)>,
823    /// Every copy, in the order they are recorded.
824    sources: &'a [CopySource<'a>],
825}
826
827/// Startup uploads recorded into one command buffer and submitted with one
828/// wait.
829///
830/// Each texture added is created at once, and its copies are recorded behind
831/// the ones before it; nothing reaches the device until
832/// [`submit`](Self::submit). One submission rather than one per texture is the
833/// point: on Mesa's ANV a submit and its [`Device::wait_idle`] cost more than
834/// the copies of an empty page, and [`crate::ui_pass`]'s renderer uploads
835/// several pages before its first frame.
836///
837/// The textures are the caller's from the moment they are returned, and must
838/// not be sampled until `submit` has returned `Ok`. The staging and zero
839/// buffers are the batch's, released when it drops: after the wait if it was
840/// submitted, and before any submission if an add or the caller failed first.
841pub(crate) struct UploadBatch<'a> {
842    device: &'a dyn Device,
843    queue: QueueHandle,
844    encoder: Option<Box<dyn CommandEncoder>>,
845    buffers: Vec<crcbl_hal::BufferHandle>,
846}
847
848impl<'a> UploadBatch<'a> {
849    /// An empty batch; `label` is the stem of its encoder's name.
850    pub(crate) fn new(device: &'a dyn Device, queue: QueueHandle, label: &str) -> Self {
851        let encoder_label = format!("{label} upload");
852        let encoder = device.create_command_encoder(&CommandEncoderDesc {
853            label: Some(&encoder_label),
854            queue,
855        });
856        Self {
857            device,
858            queue,
859            encoder: Some(encoder),
860            buffers: Vec::new(),
861        }
862    }
863
864    /// [`upload_texture_mip_layers`], recorded into this batch.
865    ///
866    /// # Errors
867    ///
868    /// As [`upload_texture_mip_layers`], before anything is recorded.
869    pub(crate) fn texture(
870        &mut self,
871        label: &str,
872        format: Format,
873        extent: (u32, u32),
874        layers: &[&[&[u8]]],
875        view_type: ImageViewType,
876    ) -> Result<UploadedTexture, HalError> {
877        stage_texture(self, label, format, extent, layers, view_type)
878    }
879
880    /// [`upload_cleared_texture`], recorded into this batch.
881    ///
882    /// # Errors
883    ///
884    /// As [`upload_cleared_texture`], before anything is recorded.
885    pub(crate) fn cleared_texture(
886        &mut self,
887        desc: &ClearedTextureDesc<'_>,
888    ) -> Result<UploadedTexture, HalError> {
889        stage_cleared_texture(self, desc)
890    }
891
892    /// Submits every recorded copy and waits for the device, leaving every
893    /// texture in [`ResourceState::ShaderRead`].
894    ///
895    /// # Errors
896    ///
897    /// [`HalError`] from finishing, submitting or waiting. The textures stay
898    /// the caller's to destroy.
899    pub(crate) fn submit(mut self) -> Result<(), HalError> {
900        let Some(encoder) = self.encoder.take() else {
901            return Ok(());
902        };
903        let commands = encoder.finish()?;
904        let submitted = self
905            .device
906            .submit(self.queue, &SubmitInfo::new(&[commands]))
907            .and_then(|()| self.device.wait_idle());
908        self.device.destroy_command_buffer(commands);
909        submitted
910    }
911
912    /// [`submit`](Self::submit) for a batch of the one `texture`, which is
913    /// destroyed if the submission fails.
914    fn submit_one(self, texture: UploadedTexture) -> Result<UploadedTexture, HalError> {
915        let device = self.device;
916        match self.submit() {
917            Ok(()) => Ok(texture),
918            Err(error) => {
919                texture.destroy(device);
920                Err(error)
921            }
922        }
923    }
924
925    /// Creates the image and the view `args` describe and records its copies,
926    /// leaving it in [`ResourceState::ShaderRead`] once submitted.
927    fn record(&mut self, args: &UploadArgs<'_>) -> Result<UploadedTexture, HalError> {
928        let device = self.device;
929        let image = device.create_image(&ImageDesc {
930            label: Some(args.label),
931            image_type: ImageType::D2,
932            format: args.format,
933            extent: Extent3d {
934                width: args.width,
935                height: args.height,
936                // A `D2` image's `depth_or_layers` is its array length, which
937                // the seam says on the field itself.
938                depth_or_layers: args.layer_count,
939            },
940            mip_levels: args.mip_levels,
941            samples: 1,
942            // `TRANSFER_SRC` as well as the copy's `TRANSFER_DST`, so a test or
943            // a capture can copy a level back out — `tests/forward_e2e/page.rs`
944            // reads the page's chain that way. Free on every backend: a sampled
945            // image that is also a copy source costs no layout, no memory and
946            // no decompression it would not already pay.
947            usage: ImageUsage::TRANSFER_SRC | ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED,
948        })?;
949        let view = match device.create_image_view(&ImageViewDesc {
950            label: Some(args.label),
951            image,
952            view_type: args.view_type,
953            format: args.format,
954            range: color_range(args.mip_levels, args.layer_count),
955        }) {
956            Ok(view) => view,
957            Err(error) => {
958                device.destroy_image(image);
959                return Err(error);
960            }
961        };
962        let encoder = self
963            .encoder
964            .as_deref_mut()
965            .expect("a batch records until it is submitted, which consumes it");
966        record_copies(encoder, args, image);
967        Ok(UploadedTexture { image, view })
968    }
969}
970
971impl Drop for UploadBatch<'_> {
972    fn drop(&mut self) {
973        for buffer in self.buffers.drain(..) {
974            self.device.destroy_buffer(buffer);
975        }
976    }
977}
978
979/// The whole of a colour image `mips` levels deep and `layers` layers deep.
980const fn color_range(mips: u32, layers: u32) -> ImageSubresourceRange {
981    ImageSubresourceRange {
982        aspect: ImageAspect::COLOR,
983        base_mip: 0,
984        mip_count: mips,
985        base_layer: 0,
986        layer_count: layers,
987    }
988}
989
990/// Records `image`'s barriers and copies, leaving it in
991/// [`ResourceState::ShaderRead`]. Its barriers name only `image` and its own
992/// zero buffer, so a batch's uploads do not wait on one another.
993fn record_copies(encoder: &mut dyn CommandEncoder, args: &UploadArgs<'_>, image: ImageHandle) {
994    let range = color_range(args.mip_levels, args.layer_count);
995    // Undefined → TransferDst: the image has never held anything, so its old
996    // contents are explicitly discarded rather than transitioned. The range
997    // covers every level of every layer, so one barrier serves all the copies
998    // below.
999    encoder.pipeline_barrier(&crcbl_hal::Barriers {
1000        images: &[crcbl_hal::ImageBarrier::new(
1001            image,
1002            range,
1003            ResourceState::Undefined,
1004            ResourceState::TransferDst,
1005        )],
1006        ..Default::default()
1007    });
1008
1009    // Outside any pass, and before the copies that read it: a clear is recorded
1010    // into the same command buffer, so it runs first on every backend. The
1011    // buffer is then moved to a copy source explicitly, because the clear left
1012    // it a copy destination: D3D12 promotes a buffer implicitly only out of
1013    // `COMMON`, which a fresh one is in and this one no longer is.
1014    if let Some((buffer, size)) = args.cleared {
1015        encoder.clear_buffer(buffer, 0, size);
1016        encoder.pipeline_barrier(&crcbl_hal::Barriers {
1017            buffers: &[crcbl_hal::BufferBarrier::new(
1018                buffer,
1019                ResourceState::TransferDst,
1020                ResourceState::TransferSrc,
1021            )],
1022            ..Default::default()
1023        });
1024    }
1025
1026    // One copy per subresource. A region's `image_extent` is a 2D extent
1027    // whatever the image is — `crcbl-dx12` refuses anything else by name,
1028    // because `CopyTextureRegion` addresses one subresource — so the layer and
1029    // the level are named by `base_layer` and `mip`, and the buffer offset says
1030    // where that subresource's rows start.
1031    for (source, region) in args
1032        .sources
1033        .iter()
1034        .flat_map(|source| source.regions.iter().map(move |region| (source, region)))
1035    {
1036        encoder.copy_buffer_to_image(&BufferImageCopy {
1037            buffer: source.buffer,
1038            buffer_offset: region.buffer_offset,
1039            buffer_row_length: region.row_texels,
1040            buffer_image_height: region.extent.height,
1041            image,
1042            image_subresource: ImageSubresourceLayers {
1043                aspect: ImageAspect::COLOR,
1044                mip: region.mip,
1045                base_layer: region.layer,
1046                layer_count: 1,
1047            },
1048            image_offset: region.image_offset,
1049            image_extent: region.extent,
1050        });
1051    }
1052
1053    encoder.pipeline_barrier(&crcbl_hal::Barriers {
1054        images: &[crcbl_hal::ImageBarrier::new(
1055            image,
1056            range,
1057            ResourceState::TransferDst,
1058            ResourceState::ShaderRead,
1059        )],
1060        ..Default::default()
1061    });
1062}
1063
1064// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
1065#[cfg(all(test, not(target_arch = "wasm32")))]
1066mod tests {
1067    use super::*;
1068    use crcbl_hal::null::{Command, Event, NullInstance, Recorder};
1069    use crcbl_hal::{DeviceDesc, Features, Instance, QueueKind};
1070
1071    /// Tier B, because its `optimal_buffer_copy_offset_alignment` is 256 —
1072    /// WebGPU's — and Tier A's is 4, which an `Rgba8Unorm` row satisfies for
1073    /// free. Padding is only exercised on the tier that asks for it.
1074    fn open_tier_b(recorder: &Recorder) -> (Box<dyn Device>, QueueHandle) {
1075        let instance = NullInstance::portable().with_recorder(recorder.clone());
1076        let adapter = instance.adapters().remove(0);
1077        let device = instance
1078            .create_device(&DeviceDesc {
1079                label: None,
1080                adapter: adapter.id,
1081                required_features: Features::COMPUTE,
1082                optional_features: Features::empty(),
1083                compatible_surface: None,
1084            })
1085            .expect("the tier B null adapter opens");
1086        let queue = device.queue(QueueKind::Graphics).expect("always present");
1087        (device, queue)
1088    }
1089
1090    fn open_tier_a(recorder: &Recorder) -> (Box<dyn Device>, QueueHandle) {
1091        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
1092        let adapter = instance.adapters().remove(0);
1093        let device = instance
1094            .create_device(&DeviceDesc {
1095                label: None,
1096                adapter: adapter.id,
1097                required_features: Features::GPU_DRIVEN,
1098                optional_features: Features::empty(),
1099                compatible_surface: None,
1100            })
1101            .expect("the null backend always opens");
1102        let queue = device.queue(QueueKind::Graphics).expect("always present");
1103        (device, queue)
1104    }
1105
1106    fn the_copies(recorder: &Recorder) -> Vec<BufferImageCopy> {
1107        recorder
1108            .commands()
1109            .into_iter()
1110            .filter_map(|command| match command {
1111                Command::CopyBufferToImage(copy) => Some(copy),
1112                _ => None,
1113            })
1114            .collect()
1115    }
1116
1117    fn the_copy(recorder: &Recorder) -> BufferImageCopy {
1118        let copies = the_copies(recorder);
1119        assert_eq!(
1120            copies.len(),
1121            1,
1122            "a single-layer upload records exactly one buffer-to-image copy"
1123        );
1124        copies[0]
1125    }
1126
1127    fn bytes_written(recorder: &Recorder) -> usize {
1128        recorder
1129            .events()
1130            .into_iter()
1131            .find_map(|event| match event {
1132                Event::BufferWritten { len, .. } => Some(len),
1133                _ => None,
1134            })
1135            .expect("an upload writes its staging buffer once")
1136    }
1137
1138    /// A 100-texel RGBA row: 400 bytes, which Tier B's 256-byte alignment pads
1139    /// to 512. Every number here is different from the one the old
1140    /// texels-as-bytes arithmetic would produce — that pitched 100 up to 256 —
1141    /// so this is what fails if a pitch is ever computed from `width` rather
1142    /// than `width * texel_size` again.
1143    const WIDTH: u32 = 100;
1144    const HEIGHT: u32 = 3;
1145    const ROW_BYTES: usize = 400;
1146    const PITCH: usize = 512;
1147
1148    fn ramp(len: usize) -> Vec<u8> {
1149        // Coprime with 256, so no two bytes 256 apart are equal and a row
1150        // written at the wrong offset cannot compare equal by accident.
1151        (0..len).map(|index| (index % 251) as u8).collect()
1152    }
1153
1154    /// The row pitch is in **bytes**, and each source row lands at its padded
1155    /// byte offset with zeroes after it.
1156    #[test]
1157    fn each_source_row_lands_at_its_padded_byte_offset() {
1158        let texel = Format::Rgba8Unorm
1159            .texel_size(ImageAspect::COLOR)
1160            .expect("rgba8 is a colour format");
1161        assert_eq!(texel, 4);
1162
1163        let row_bytes = u64::from(WIDTH) * u64::from(texel);
1164        assert_eq!(row_bytes as usize, ROW_BYTES);
1165        let pitch = padded_row_pitch(row_bytes, texel, 256);
1166        assert_eq!(
1167            pitch as usize, PITCH,
1168            "400 bytes padded up to the 256-byte alignment is 512, not 256"
1169        );
1170
1171        let pixels = ramp(ROW_BYTES * HEIGHT as usize);
1172        let padded = stage_rows(row_bytes, HEIGHT, pitch, &pixels).expect("fits");
1173        assert_eq!(padded.len(), PITCH * HEIGHT as usize);
1174        for row in 0..HEIGHT as usize {
1175            let start = row * PITCH;
1176            assert_eq!(
1177                &padded[start..start + ROW_BYTES],
1178                &pixels[row * ROW_BYTES..(row + 1) * ROW_BYTES],
1179                "row {row} must sit at byte {start}"
1180            );
1181            assert!(
1182                padded[start + ROW_BYTES..start + PITCH]
1183                    .iter()
1184                    .all(|&byte| byte == 0),
1185                "row {row}'s padding must be zero, not the next row"
1186            );
1187        }
1188    }
1189
1190    /// And the copy is told that pitch in *texels*, which is the unit
1191    /// [`BufferImageCopy::buffer_row_length`] documents.
1192    #[test]
1193    fn an_rgba_upload_records_its_pitch_in_texels() {
1194        let recorder = Recorder::new();
1195        let (device, queue) = open_tier_b(&recorder);
1196        assert_eq!(
1197            device.caps().limits.optimal_buffer_copy_offset_alignment,
1198            256,
1199            "the padding this test exercises only exists on the tier that asks for it"
1200        );
1201        let pixels = ramp(ROW_BYTES * HEIGHT as usize);
1202
1203        let texture = upload_texture(
1204            device.as_ref(),
1205            queue,
1206            "sprite atlas",
1207            Format::Rgba8Unorm,
1208            WIDTH,
1209            HEIGHT,
1210            &pixels,
1211        )
1212        .expect("the null backend accepts this");
1213
1214        assert_eq!(
1215            bytes_written(&recorder),
1216            PITCH * HEIGHT as usize,
1217            "the staging write is the padded image, not the packed one"
1218        );
1219        let copy = the_copy(&recorder);
1220        assert_eq!(
1221            copy.buffer_row_length, 128,
1222            "512 bytes of pitch is 128 rgba texels, not 512"
1223        );
1224        assert_eq!(copy.buffer_image_height, HEIGHT);
1225        assert_eq!(copy.image_extent, Extent3d::d2(WIDTH, HEIGHT));
1226        assert_eq!(copy.image_offset, Offset3d { x: 0, y: 0, z: 0 });
1227
1228        texture.destroy(device.as_ref());
1229        recorder.assert_valid();
1230    }
1231
1232    /// A device whose alignment an `Rgba8Unorm` row already satisfies pads
1233    /// nothing, and the copy's pitch is then simply the width.
1234    #[test]
1235    fn an_aligned_row_is_not_padded() {
1236        let recorder = Recorder::new();
1237        let (device, queue) = open_tier_a(&recorder);
1238        assert_eq!(device.caps().limits.optimal_buffer_copy_offset_alignment, 4);
1239        let pixels = vec![0u8; 5 * 3 * 4];
1240        let texture = upload_texture(
1241            device.as_ref(),
1242            queue,
1243            "tight",
1244            Format::Rgba8Unorm,
1245            5,
1246            3,
1247            &pixels,
1248        )
1249        .expect("accepted");
1250        assert_eq!(bytes_written(&recorder), 5 * 3 * 4);
1251        assert_eq!(the_copy(&recorder).buffer_row_length, 5);
1252        texture.destroy(device.as_ref());
1253        recorder.assert_valid();
1254    }
1255
1256    /// The pitch satisfies the alignment *and* stays a whole number of texels,
1257    /// including when the two do not divide each other — a byte pitch the copy
1258    /// cannot express in texels is not a pitch.
1259    #[test]
1260    fn a_row_pitch_is_aligned_and_a_whole_number_of_texels() {
1261        // The ordinary cases: alignment already a multiple of the texel.
1262        assert_eq!(padded_row_pitch(20, 4, 256), 256);
1263        assert_eq!(padded_row_pitch(20, 4, 4), 20);
1264        assert_eq!(padded_row_pitch(5, 1, 4), 8);
1265        assert_eq!(padded_row_pitch(1024, 4, 256), 1024);
1266        // The awkward one: 6-byte alignment, 4-byte texel. 4 is not enough (it
1267        // is not a multiple of 6) and 6 is not enough (it is not a whole texel);
1268        // 12 is the first that is both.
1269        let pitch = padded_row_pitch(4, 4, 6);
1270        assert_eq!(pitch, 12);
1271        assert_eq!(pitch % 6, 0, "must satisfy the alignment");
1272        assert_eq!(pitch % 4, 0, "must be a whole number of texels");
1273    }
1274
1275    /// **A page is one image whose layers each get their own copy**, and each
1276    /// copy reads the layer's own slice of the staging buffer.
1277    ///
1278    /// The offsets are what this is for. Every layer's rows are padded, so a
1279    /// second layer read at `width * height * texel` — the *unpadded* size —
1280    /// would take the tail of the first layer plus part of the second and put
1281    /// a plausible smear in the page. Tier B is used because its 256-byte
1282    /// alignment is what makes the padded and unpadded strides differ.
1283    #[test]
1284    fn a_page_copies_each_layer_from_its_own_padded_offset() {
1285        let recorder = Recorder::new();
1286        let (device, queue) = open_tier_b(&recorder);
1287        let layers: Vec<Vec<u8>> = (0..3).map(|_| ramp(ROW_BYTES * HEIGHT as usize)).collect();
1288        let refs: Vec<&[u8]> = layers.iter().map(Vec::as_slice).collect();
1289
1290        let page = upload_texture_layers(
1291            device.as_ref(),
1292            queue,
1293            "material page",
1294            Format::Rgba8Unorm,
1295            WIDTH,
1296            HEIGHT,
1297            &refs,
1298        )
1299        .expect("the null backend accepts this");
1300
1301        let layer_bytes = PITCH * HEIGHT as usize;
1302        assert_eq!(
1303            bytes_written(&recorder),
1304            layer_bytes * layers.len(),
1305            "the staging write is every layer, padded"
1306        );
1307        let copies = the_copies(&recorder);
1308        assert_eq!(
1309            copies.len(),
1310            layers.len(),
1311            "one copy per layer, because a region's extent is 2D on every backend"
1312        );
1313        for (layer, copy) in copies.iter().enumerate() {
1314            assert_eq!(
1315                copy.buffer_offset,
1316                (layer * layer_bytes) as u64,
1317                "layer {layer} must read from its own slice of the staging buffer"
1318            );
1319            assert_eq!(
1320                copy.image_subresource.base_layer, layer as u32,
1321                "layer {layer} must be written to layer {layer} of the image"
1322            );
1323            assert_eq!(copy.image_subresource.layer_count, 1);
1324            assert_eq!(copy.buffer_row_length, 128);
1325            assert_eq!(
1326                copy.image_extent,
1327                Extent3d::d2(WIDTH, HEIGHT),
1328                "a copy region's extent stays 2D"
1329            );
1330        }
1331
1332        page.destroy(device.as_ref());
1333        recorder.assert_valid();
1334    }
1335
1336    /// A page with no layers is refused here, by name.
1337    ///
1338    /// Without the guard it reaches the device as an image whose
1339    /// `depth_or_layers` is zero, whose complaint is about an *extent* — a
1340    /// different object and a message that does not say what the caller did.
1341    #[test]
1342    fn a_page_with_no_layers_is_rejected() {
1343        let recorder = Recorder::new();
1344        let (device, queue) = open_tier_a(&recorder);
1345        let error = upload_texture_layers(
1346            device.as_ref(),
1347            queue,
1348            "empty page",
1349            Format::Rgba8Unorm,
1350            4,
1351            4,
1352            &[],
1353        )
1354        .expect_err("a page needs a layer");
1355        assert!(
1356            error.to_string().contains("at least one layer"),
1357            "got: {error}"
1358        );
1359        assert_eq!(recorder.total_live_objects(), 0);
1360    }
1361
1362    /// A short or long slice is an error naming both numbers, not a
1363    /// `copy_from_slice` panic naming neither — and nothing is created before
1364    /// it is noticed.
1365    #[test]
1366    fn a_wrong_sized_pixel_slice_is_rejected() {
1367        let recorder = Recorder::new();
1368        let (device, queue) = open_tier_a(&recorder);
1369        let before = recorder.total_live_objects();
1370
1371        let short = vec![0u8; 5 * 3 * 4 - 1];
1372        let error = upload_texture(
1373            device.as_ref(),
1374            queue,
1375            "short",
1376            Format::Rgba8Unorm,
1377            5,
1378            3,
1379            &short,
1380        )
1381        .expect_err("a 59-byte slice is not a 5x3 rgba image");
1382        let message = error.to_string();
1383        assert!(
1384            message.contains("60") && message.contains("59"),
1385            "the error must name both sizes, got: {message}"
1386        );
1387
1388        let long = vec![0u8; 5 * 3 * 4 + 1];
1389        upload_texture(
1390            device.as_ref(),
1391            queue,
1392            "long",
1393            Format::Rgba8Unorm,
1394            5,
1395            3,
1396            &long,
1397        )
1398        .expect_err("a 61-byte slice is not one either");
1399
1400        assert_eq!(
1401            recorder.total_live_objects(),
1402            before,
1403            "a rejected upload creates nothing"
1404        );
1405    }
1406
1407    /// A zero extent is refused here rather than reaching the device as a
1408    /// zero-sized staging buffer, which is a different error about a different
1409    /// object.
1410    #[test]
1411    fn a_zero_extent_is_rejected() {
1412        let recorder = Recorder::new();
1413        let (device, queue) = open_tier_a(&recorder);
1414        for (width, height) in [(0u32, 4u32), (4, 0)] {
1415            let error = upload_texture(
1416                device.as_ref(),
1417                queue,
1418                "empty",
1419                Format::Rgba8Unorm,
1420                width,
1421                height,
1422                &[],
1423            )
1424            .expect_err("a zero extent is not a texture");
1425            // "texture extent", not merely "non-zero": without the guard above
1426            // this reaches the device as a zero-sized *buffer*, whose own error
1427            // also says "non-zero" and would have made this test pass while
1428            // naming the wrong object.
1429            assert!(
1430                error.to_string().contains("texture extent"),
1431                "got: {error}, which is not the extent complaint"
1432            );
1433        }
1434        assert_eq!(recorder.total_live_objects(), 0);
1435    }
1436
1437    /// A combined depth/stencil format has two planes and no colour aspect, so
1438    /// there is no single `texel_size` to pitch against. Refused by name rather
1439    /// than silently pitched against `block_size`, which would be 8.
1440    #[test]
1441    fn a_depth_stencil_format_is_rejected() {
1442        let recorder = Recorder::new();
1443        let (device, queue) = open_tier_a(&recorder);
1444        let error = upload_texture(
1445            device.as_ref(),
1446            queue,
1447            "depth",
1448            Format::D32FloatS8Uint,
1449            4,
1450            4,
1451            &[0u8; 128],
1452        )
1453        .expect_err("a depth/stencil upload needs one copy per plane");
1454        assert!(error.to_string().contains("colour plane"), "got: {error}");
1455        assert_eq!(recorder.total_live_objects(), 0);
1456    }
1457
1458    /// A compressed format's `block_size` covers a 4×4 block, not one texel, so
1459    /// the per-texel sizing here would be wrong by a factor of four — and there
1460    /// is no caller that needs one. Refused by name rather than silently
1461    /// pitched against the block size, before any device call.
1462    #[test]
1463    fn a_compressed_format_is_rejected() {
1464        let recorder = Recorder::new();
1465        let (device, queue) = open_tier_a(&recorder);
1466        // 8x8 BC1 is 2x2 blocks of 8 bytes: the *correct* compressed size, so a
1467        // regression that accepted compressed uploads would pass the size check
1468        // and fail only here.
1469        let error = upload_texture(
1470            device.as_ref(),
1471            queue,
1472            "compressed",
1473            Format::Bc1RgbaUnorm,
1474            8,
1475            8,
1476            &[0u8; 2 * 2 * 8],
1477        )
1478        .expect_err("a BC1 upload is sized per block, not per texel");
1479        assert!(
1480            error.to_string().contains("block-compressed"),
1481            "got: {error}"
1482        );
1483        assert_eq!(recorder.total_live_objects(), 0);
1484    }
1485
1486    /// A failure after the staging buffer exists releases it. `create_image`
1487    /// is what fails: Tier A's `max_image_2d` is 16384, and a 16385x1 R8 image
1488    /// is one byte per texel, so the staging allocation this must clean up is
1489    /// 16 KiB rather than something that would fail for its own reasons first.
1490    #[test]
1491    fn a_failed_upload_leaks_nothing() {
1492        let recorder = Recorder::new();
1493        let (device, queue) = open_tier_a(&recorder);
1494        let limit = device.caps().limits.max_image_2d;
1495        assert_eq!(limit, 16384);
1496        let before = recorder.total_live_objects();
1497
1498        let width = limit + 1;
1499        let pixels = vec![0u8; width as usize];
1500        let error = upload_texture(
1501            device.as_ref(),
1502            queue,
1503            "too wide",
1504            Format::R8Unorm,
1505            width,
1506            1,
1507            &pixels,
1508        )
1509        .expect_err("the device refuses an image past max_image_2d");
1510        assert!(
1511            error.to_string().contains("max_image_2d"),
1512            "the failure must be the image, not something earlier: {error}"
1513        );
1514
1515        assert_eq!(
1516            recorder.total_live_objects(),
1517            before,
1518            "the staging buffer created before the failure must be destroyed"
1519        );
1520        assert!(
1521            recorder
1522                .events()
1523                .iter()
1524                .any(|event| matches!(event, Event::BufferWritten { .. })),
1525            "the test is only meaningful if the staging buffer really was created \
1526             and written before the failure"
1527        );
1528    }
1529
1530    /// **A chain is one copy per level of every layer**, each into its own mip
1531    /// and each from its own padded offset — level-minor, so a layer's whole
1532    /// chain sits together in the staging buffer.
1533    ///
1534    /// Tier B again, for the padded-versus-unpadded reason above, and a width
1535    /// that halves onto rows of three different pitches: 100 texels pad to 512
1536    /// bytes, 50 to 256, 25 to 256. A level offset computed from level 0's
1537    /// pitch would land the second level's rows inside the first's tail.
1538    #[test]
1539    fn a_chain_copies_each_level_into_its_own_mip_from_its_own_offset() {
1540        let recorder = Recorder::new();
1541        let (device, queue) = open_tier_b(&recorder);
1542        // Three of the seven levels a 100-wide image has: a partial chain is
1543        // legal, and each level is its own extent's worth of texels.
1544        let level_extents = [(WIDTH, HEIGHT), (50, 1), (25, 1)];
1545        let chains: Vec<Vec<Vec<u8>>> = (0..2)
1546            .map(|_| {
1547                level_extents
1548                    .iter()
1549                    .map(|&(width, height)| ramp((width * height * 4) as usize))
1550                    .collect()
1551            })
1552            .collect();
1553        let levels: Vec<Vec<&[u8]>> = chains
1554            .iter()
1555            .map(|chain| chain.iter().map(Vec::as_slice).collect())
1556            .collect();
1557        let layers: Vec<&[&[u8]]> = levels.iter().map(Vec::as_slice).collect();
1558
1559        let page = upload_texture_mip_layers(
1560            device.as_ref(),
1561            queue,
1562            "mipped page",
1563            Format::Rgba8Unorm,
1564            WIDTH,
1565            HEIGHT,
1566            &layers,
1567        )
1568        .expect("the null backend accepts a partial chain");
1569
1570        let level_bytes = [PITCH * HEIGHT as usize, 256, 256];
1571        let layer_bytes: usize = level_bytes.iter().sum();
1572        assert_eq!(
1573            bytes_written(&recorder),
1574            layer_bytes * chains.len(),
1575            "the staging write is every level of every layer, each padded to its own pitch"
1576        );
1577        let copies = the_copies(&recorder);
1578        assert_eq!(copies.len(), chains.len() * level_extents.len());
1579        let mut expected_offset = 0u64;
1580        for (index, copy) in copies.iter().enumerate() {
1581            let layer = index / level_extents.len();
1582            let level = index % level_extents.len();
1583            let (width, height) = level_extents[level];
1584            assert_eq!(
1585                (
1586                    copy.image_subresource.base_layer,
1587                    copy.image_subresource.mip
1588                ),
1589                (layer as u32, level as u32),
1590                "copy {index} is layer {layer}'s level {level}"
1591            );
1592            assert_eq!(copy.image_subresource.layer_count, 1);
1593            assert_eq!(
1594                copy.buffer_offset, expected_offset,
1595                "layer {layer} level {level} reads from its own slice of the staging buffer"
1596            );
1597            assert_eq!(
1598                copy.image_extent,
1599                Extent3d::d2(width, height),
1600                "level {level} is copied at its own extent"
1601            );
1602            assert_eq!(copy.buffer_image_height, height);
1603            assert_eq!(
1604                copy.buffer_row_length as usize * 4,
1605                level_bytes[level] / height as usize,
1606                "level {level}'s pitch is its own row padded, in texels"
1607            );
1608            expected_offset += level_bytes[level] as u64;
1609        }
1610
1611        page.destroy(device.as_ref());
1612        recorder.assert_valid();
1613    }
1614
1615    /// The single-level form is the chain form with one level, so the image it
1616    /// creates has one mip and the copies name it — a `mip_levels` that
1617    /// followed the chain length would otherwise be off by one somewhere.
1618    #[test]
1619    fn a_single_level_page_is_a_chain_of_one() {
1620        let recorder = Recorder::new();
1621        let (device, queue) = open_tier_a(&recorder);
1622        let pixels = vec![0u8; 4 * 4 * 4];
1623        let page = upload_texture_layers(
1624            device.as_ref(),
1625            queue,
1626            "flat page",
1627            Format::Rgba8Unorm,
1628            4,
1629            4,
1630            &[&pixels],
1631        )
1632        .expect("accepted");
1633        let copy = the_copy(&recorder);
1634        assert_eq!(copy.image_subresource.mip, 0);
1635        page.destroy(device.as_ref());
1636        recorder.assert_valid();
1637    }
1638
1639    /// A chain that is ragged, too long, empty, or has a level of the wrong
1640    /// size is refused by name before anything is created.
1641    #[test]
1642    fn a_malformed_chain_is_rejected_naming_the_layer_and_the_level() {
1643        let recorder = Recorder::new();
1644        let (device, queue) = open_tier_a(&recorder);
1645        let before = recorder.total_live_objects();
1646        let level0 = vec![0u8; 4 * 4 * 4];
1647        let level1 = vec![0u8; 2 * 2 * 4];
1648        let level2 = vec![0u8; 4];
1649        let upload = |layers: &[&[&[u8]]]| {
1650            upload_texture_mip_layers(
1651                device.as_ref(),
1652                queue,
1653                "chain",
1654                Format::Rgba8Unorm,
1655                4,
1656                4,
1657                layers,
1658            )
1659            .expect_err("a malformed chain is not a page")
1660            .to_string()
1661        };
1662
1663        let ragged = upload(&[&[&level0, &level1], &[&level0]]);
1664        assert!(
1665            ragged.contains("layer 1 carries 1 mip levels and layer 0 carries 2"),
1666            "got: {ragged}"
1667        );
1668        let long = upload(&[&[&level0, &level1, &level2, &level2]]);
1669        assert!(
1670            long.contains("4 mip levels") && long.contains("full chain is 3"),
1671            "got: {long}"
1672        );
1673        let empty = upload(&[&[]]);
1674        assert!(empty.contains("no mip levels"), "got: {empty}");
1675        let wrong = upload(&[&[&level0, &level0]]);
1676        assert!(
1677            wrong.contains("layer 0 level 1") && wrong.contains("is 2x2, 16 bytes"),
1678            "got: {wrong}"
1679        );
1680
1681        assert_eq!(
1682            recorder.total_live_objects(),
1683            before,
1684            "a rejected chain creates nothing"
1685        );
1686    }
1687
1688    /// **A cleared page is zeroed on the GPU and copied into every layer, and
1689    /// only its patches cross from the host** — each into its own layer at its
1690    /// own corner, after the zeroes it overwrites.
1691    ///
1692    /// Tier B, so the page and the patch pitch to different strides: a 100-texel
1693    /// RGBA row pads to 512 bytes, the 5-texel patch row to 256.
1694    #[test]
1695    fn a_cleared_page_zeroes_every_layer_and_stages_only_its_patches() {
1696        let recorder = Recorder::new();
1697        let (device, queue) = open_tier_b(&recorder);
1698        let before = recorder.total_live_objects();
1699        let pixels = ramp(5 * 2 * 4);
1700
1701        let page = upload_cleared_texture(
1702            device.as_ref(),
1703            queue,
1704            &ClearedTextureDesc {
1705                label: "cleared page",
1706                format: Format::Rgba8Unorm,
1707                width: WIDTH,
1708                height: HEIGHT,
1709                layers: 3,
1710                view_type: ImageViewType::D2Array,
1711                patches: &[TexturePatch {
1712                    layer: 2,
1713                    x: 7,
1714                    y: 1,
1715                    width: 5,
1716                    height: 2,
1717                    pixels: &pixels,
1718                }],
1719            },
1720        )
1721        .expect("the null backend accepts this");
1722
1723        let commands = recorder.commands();
1724        let clears: Vec<(crcbl_hal::BufferHandle, u64, u64)> = commands
1725            .iter()
1726            .filter_map(|command| match command {
1727                Command::ClearBuffer {
1728                    buffer,
1729                    offset,
1730                    size,
1731                } => Some((*buffer, *offset, *size)),
1732                _ => None,
1733            })
1734            .collect();
1735        let [(zero, 0, size)] = clears[..] else {
1736            panic!("expected one clear from the start of one buffer, got {clears:?}");
1737        };
1738        assert_eq!(size as usize, PITCH * HEIGHT as usize, "one padded layer");
1739        let first_copy = commands
1740            .iter()
1741            .position(|command| matches!(command, Command::CopyBufferToImage(_)));
1742        let clear_at = commands
1743            .iter()
1744            .position(|command| matches!(command, Command::ClearBuffer { .. }));
1745        assert!(
1746            clear_at < first_copy,
1747            "the clear must be recorded before the copies that read it"
1748        );
1749
1750        let copies = the_copies(&recorder);
1751        // **Every texel of every layer is written exactly once**: by a zero
1752        // copy, or by the patch — never both, which sync validation reports.
1753        let mut writes = vec![0u8; 3 * (WIDTH * HEIGHT) as usize];
1754        for copy in &copies {
1755            let Offset3d { x, y, .. } = copy.image_offset;
1756            let layer = copy.image_subresource.base_layer;
1757            for row in 0..copy.image_extent.height {
1758                for column in 0..copy.image_extent.width {
1759                    let texel = (layer * WIDTH * HEIGHT
1760                        + (y as u32 + row) * WIDTH
1761                        + (x as u32 + column)) as usize;
1762                    writes[texel] += 1;
1763                }
1764            }
1765            if copy.buffer == zero {
1766                assert_eq!(copy.buffer_offset, 0);
1767                assert_eq!(copy.buffer_row_length, 128);
1768            }
1769        }
1770        assert!(
1771            writes.iter().all(|&count| count == 1),
1772            "a texel was written {} times, or not at all: {copies:?}",
1773            writes
1774                .iter()
1775                .copied()
1776                .find(|&count| count != 1)
1777                .unwrap_or(1)
1778        );
1779        let zeroes: Vec<_> = copies.iter().filter(|copy| copy.buffer == zero).collect();
1780        assert_eq!(
1781            zeroes.len(),
1782            2 + 3,
1783            "one copy for each unpatched layer, and the patched layer as the row \
1784             above its patch and the two spans beside it: {copies:?}"
1785        );
1786        let [patch] = copies
1787            .iter()
1788            .filter(|copy| copy.buffer != zero)
1789            .collect::<Vec<_>>()[..]
1790        else {
1791            panic!("expected one staged patch copy: {copies:?}");
1792        };
1793        let patch = *patch;
1794        assert_ne!(patch.buffer, zero, "a patch is staged, not cleared");
1795        assert_eq!(patch.buffer_offset, 0);
1796        assert_eq!(
1797            patch.buffer_row_length, 64,
1798            "256 bytes of pitch is 64 texels"
1799        );
1800        assert_eq!(patch.image_subresource.base_layer, 2);
1801        assert_eq!(patch.image_extent, Extent3d::d2(5, 2));
1802        assert_eq!(patch.image_offset, Offset3d { x: 7, y: 1, z: 0 });
1803
1804        let writes: Vec<(crcbl_hal::BufferHandle, usize)> = recorder
1805            .events()
1806            .into_iter()
1807            .filter_map(|event| match event {
1808                Event::BufferWritten { buffer, len, .. } => Some((buffer, len)),
1809                _ => None,
1810            })
1811            .collect();
1812        assert_eq!(
1813            writes,
1814            [(patch.buffer, 256 * 2)],
1815            "the host writes the padded patch and nothing of the page"
1816        );
1817
1818        page.destroy(device.as_ref());
1819        assert_eq!(
1820            recorder.total_live_objects(),
1821            before,
1822            "both buffers are released once the copies are submitted"
1823        );
1824        recorder.assert_valid();
1825    }
1826
1827    /// A page with nothing patched creates no staging buffer and writes nothing.
1828    #[test]
1829    fn a_cleared_page_with_no_patches_writes_nothing() {
1830        let recorder = Recorder::new();
1831        let (device, queue) = open_tier_a(&recorder);
1832        let page = upload_cleared_texture(
1833            device.as_ref(),
1834            queue,
1835            &ClearedTextureDesc {
1836                label: "empty page",
1837                format: Format::R8Unorm,
1838                width: 16,
1839                height: 16,
1840                layers: 2,
1841                view_type: ImageViewType::D2Array,
1842                patches: &[],
1843            },
1844        )
1845        .expect("accepted");
1846        assert!(
1847            !recorder
1848                .events()
1849                .iter()
1850                .any(|event| matches!(event, Event::BufferWritten { .. })),
1851            "an unpatched page is all zeroes, and zeroes are the GPU's to write"
1852        );
1853        assert_eq!(the_copies(&recorder).len(), 2, "one copy a layer");
1854        page.destroy(device.as_ref());
1855        recorder.assert_valid();
1856    }
1857
1858    /// A patch off its layer, outside the extent, empty, or not its own size is
1859    /// refused naming the patch — and so is a page with no layers — before
1860    /// anything is created.
1861    #[test]
1862    fn a_malformed_cleared_page_is_rejected_naming_the_patch() {
1863        let recorder = Recorder::new();
1864        let (device, queue) = open_tier_a(&recorder);
1865        let before = recorder.total_live_objects();
1866        let four = [0u8; 4];
1867        let upload = |layers: u32, patch: TexturePatch<'_>| {
1868            upload_cleared_texture(
1869                device.as_ref(),
1870                queue,
1871                &ClearedTextureDesc {
1872                    label: "atlas",
1873                    format: Format::Rgba8Unorm,
1874                    width: 8,
1875                    height: 8,
1876                    layers,
1877                    view_type: ImageViewType::D2,
1878                    patches: &[patch],
1879                },
1880            )
1881            .expect_err("a malformed page is not a texture")
1882            .to_string()
1883        };
1884        let texel = TexturePatch {
1885            layer: 0,
1886            x: 0,
1887            y: 0,
1888            width: 1,
1889            height: 1,
1890            pixels: &four,
1891        };
1892
1893        let no_layers = upload(0, texel);
1894        assert!(no_layers.contains("at least one layer"), "got: {no_layers}");
1895        for (patch, why) in [
1896            (TexturePatch { layer: 1, ..texel }, "off the only layer"),
1897            (TexturePatch { x: 8, ..texel }, "right of the extent"),
1898            (
1899                TexturePatch {
1900                    y: u32::MAX,
1901                    ..texel
1902                },
1903                "overflowing the extent",
1904            ),
1905            (TexturePatch { width: 0, ..texel }, "empty"),
1906        ] {
1907            let message = upload(1, patch);
1908            assert!(
1909                message.contains("patch 0") && message.contains("inside a 8x8 image"),
1910                "a patch {why} got: {message}"
1911            );
1912        }
1913        let overlapping = upload_cleared_texture(
1914            device.as_ref(),
1915            queue,
1916            &ClearedTextureDesc {
1917                label: "atlas",
1918                format: Format::Rgba8Unorm,
1919                width: 8,
1920                height: 8,
1921                layers: 1,
1922                view_type: ImageViewType::D2,
1923                patches: &[texel, texel],
1924            },
1925        )
1926        .expect_err("two patches on one texel are refused")
1927        .to_string();
1928        assert!(
1929            overlapping.contains("patch 1 overlaps patch 0"),
1930            "got: {overlapping}"
1931        );
1932        let short = upload(1, TexturePatch { width: 2, ..texel });
1933        assert!(
1934            short.contains("patch 0") && short.contains("8 bytes, got 4"),
1935            "got: {short}"
1936        );
1937
1938        assert_eq!(
1939            recorder.total_live_objects(),
1940            before,
1941            "a rejected page creates nothing"
1942        );
1943    }
1944
1945    /// A failure after both buffers exist releases both: the image is what
1946    /// fails, one texel past Tier A's `max_image_2d`.
1947    #[test]
1948    fn a_failed_cleared_page_leaks_nothing() {
1949        let recorder = Recorder::new();
1950        let (device, queue) = open_tier_a(&recorder);
1951        let limit = device.caps().limits.max_image_2d;
1952        let before = recorder.total_live_objects();
1953        let four = [0u8; 4];
1954
1955        let error = upload_cleared_texture(
1956            device.as_ref(),
1957            queue,
1958            &ClearedTextureDesc {
1959                label: "too wide",
1960                format: Format::R8Unorm,
1961                width: limit + 1,
1962                height: 1,
1963                layers: 1,
1964                view_type: ImageViewType::D2,
1965                patches: &[TexturePatch {
1966                    layer: 0,
1967                    x: 0,
1968                    y: 0,
1969                    width: 4,
1970                    height: 1,
1971                    pixels: &four,
1972                }],
1973            },
1974        )
1975        .expect_err("the device refuses an image past max_image_2d");
1976        assert!(
1977            error.to_string().contains("max_image_2d"),
1978            "the failure must be the image, not something earlier: {error}"
1979        );
1980        assert!(
1981            recorder
1982                .events()
1983                .iter()
1984                .any(|event| matches!(event, Event::BufferWritten { .. })),
1985            "only meaningful if the staging buffer really was created and written"
1986        );
1987        assert_eq!(
1988            recorder.total_live_objects(),
1989            before,
1990            "the zeroed and the staging buffer must both be destroyed"
1991        );
1992    }
1993}