Skip to main content

crcbl_hal/
format.rs

1//! Pixel and index formats.
2//!
3//! # Exhaustiveness
4//!
5//! [`Format`] is deliberately **not** `#[non_exhaustive]`. The whole engine is
6//! one workspace, so adding a format *should* break every backend's `match` at
7//! compile time. A format silently falling into a `_ => unsupported` arm is a
8//! runtime bug three backends deep; a compile error is a five-line patch.
9//!
10//! # HDR
11//!
12//! [`Format::Rgba16Float`] and [`Format::R11g11b10Float`] exist from P0 because
13//! the renderer targets `RGBA16F` + tonemap from the first lit mesh
14//! (a stage-2 rule), so P7's real HDR stack does not force a
15//! wholesale re-bless of the golden images.
16
17/// A texel format.
18///
19/// The set is the intersection of what Vulkan, Metal, DX12 and WebGPU all
20/// support without optional features, plus the depth formats the engine
21/// actually asks for. Anything that is not universally available (BC on mobile,
22/// `D24UnormS8Uint` on some drivers) is reported through
23/// [`Features`](crate::Features) or refused at surface/image creation, never
24/// silently substituted.
25#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
26pub enum Format {
27    // --- 8-bit ---
28    /// Single-channel 8-bit unsigned normalised.
29    R8Unorm,
30    /// Two-channel 8-bit unsigned normalised.
31    Rg8Unorm,
32    /// Four-channel 8-bit unsigned normalised, linear.
33    Rgba8Unorm,
34    /// Four-channel 8-bit unsigned normalised, sRGB-encoded.
35    Rgba8UnormSrgb,
36    /// Swapchain-native byte order on most desktop platforms, linear.
37    Bgra8Unorm,
38    /// Swapchain-native byte order on most desktop platforms, sRGB-encoded.
39    Bgra8UnormSrgb,
40    // --- packed ---
41    /// Packed 10/10/10/2 unsigned normalised — the usual normal-buffer format.
42    Rgb10a2Unorm,
43    /// Packed 11/11/10 float — half the bandwidth of `Rgba16Float` for
44    /// non-alpha HDR intermediates (bloom chains, light accumulation).
45    R11g11b10Float,
46    // --- 16-bit float ---
47    /// Single-channel half float.
48    R16Float,
49    /// Two-channel half float — motion vectors, packed BRDF LUTs.
50    Rg16Float,
51    /// **The engine's HDR render-target format.** Four-channel half float.
52    Rgba16Float,
53    // --- 32-bit ---
54    /// Single-channel 32-bit float.
55    R32Float,
56    /// Two-channel 32-bit float.
57    Rg32Float,
58    /// Four-channel 32-bit float — readback and reference targets, not a
59    /// steady-state render target.
60    Rgba32Float,
61    /// Single-channel 32-bit unsigned integer — visibility/ID buffers.
62    R32Uint,
63    /// Two-channel 32-bit unsigned integer.
64    Rg32Uint,
65    // --- depth/stencil ---
66    /// **The engine's depth format.** 32-bit float depth, reversed-Z.
67    D32Float,
68    /// 32-bit float depth plus 8-bit stencil (padded).
69    D32FloatS8Uint,
70    /// 24-bit unorm depth plus 8-bit stencil. Present on most desktop GPUs but
71    /// not guaranteed; prefer [`Format::D32Float`].
72    D24UnormS8Uint,
73    /// 16-bit unorm depth — shadow maps where precision allows.
74    D16Unorm,
75    // --- block compressed (BC / DXT) ---
76    /// BC1 (DXT1) RGB(A1), linear.
77    Bc1RgbaUnorm,
78    /// BC1 (DXT1) RGB(A1), sRGB.
79    Bc1RgbaUnormSrgb,
80    /// BC3 (DXT5) RGBA, linear.
81    Bc3RgbaUnorm,
82    /// BC3 (DXT5) RGBA, sRGB.
83    Bc3RgbaUnormSrgb,
84    /// BC4 single-channel — roughness/metallic/AO atlases.
85    Bc4RUnorm,
86    /// BC5 two-channel — tangent-space normal maps.
87    Bc5RgUnorm,
88    /// BC6H unsigned half float — compressed HDR (environment maps).
89    Bc6hRgbUfloat,
90    /// BC7 RGBA, linear.
91    Bc7RgbaUnorm,
92    /// BC7 RGBA, sRGB — the default albedo format.
93    Bc7RgbaUnormSrgb,
94}
95
96impl Format {
97    /// Every variant, in declaration order.
98    ///
99    /// The seam owns this list so a backend does not keep a second copy of it.
100    /// That mattered: `crcbl-vk`'s reverse mapping ends in `_ => None`, so a
101    /// format added forward and forgotten in reverse is not a compile error —
102    /// it is a format its `surface_caps` silently drops — and the round-trip
103    /// test that would have caught it was iterating the backend's *own* copy of
104    /// this list, which had the same omission. Iterating `ALL` ties the two
105    /// together.
106    ///
107    /// **Add a variant above, add it here.** Nothing on stable Rust can count
108    /// an enum's variants, so this list is hand-maintained; the closest guard
109    /// is this module's `the_format_table_is_in_declaration_order` test, which
110    /// catches an entry inserted anywhere but the very end.
111    pub const ALL: &'static [Self] = &[
112        Self::R8Unorm,
113        Self::Rg8Unorm,
114        Self::Rgba8Unorm,
115        Self::Rgba8UnormSrgb,
116        Self::Bgra8Unorm,
117        Self::Bgra8UnormSrgb,
118        Self::Rgb10a2Unorm,
119        Self::R11g11b10Float,
120        Self::R16Float,
121        Self::Rg16Float,
122        Self::Rgba16Float,
123        Self::R32Float,
124        Self::Rg32Float,
125        Self::Rgba32Float,
126        Self::R32Uint,
127        Self::Rg32Uint,
128        Self::D32Float,
129        Self::D32FloatS8Uint,
130        Self::D24UnormS8Uint,
131        Self::D16Unorm,
132        Self::Bc1RgbaUnorm,
133        Self::Bc1RgbaUnormSrgb,
134        Self::Bc3RgbaUnorm,
135        Self::Bc3RgbaUnormSrgb,
136        Self::Bc4RUnorm,
137        Self::Bc5RgUnorm,
138        Self::Bc6hRgbUfloat,
139        Self::Bc7RgbaUnorm,
140        Self::Bc7RgbaUnormSrgb,
141    ];
142
143    /// Bytes per block. For uncompressed formats a "block" is one texel.
144    ///
145    /// # Not the copy footprint of a depth/stencil format
146    ///
147    /// A combined depth+stencil format has **two planes**, and a copy names one
148    /// of them: `D32FloatS8Uint` reports `8` here (its in-memory element size)
149    /// while a depth-aspect copy moves 4 bytes per texel and a stencil-aspect
150    /// copy moves 1. `D24UnormS8Uint` reports `4` while its stencil aspect is
151    /// again 1 byte and its depth aspect is, on every API that permits the copy
152    /// at all, a 4-byte element. Use [`Format::texel_size`] when sizing a
153    /// [`BufferImageCopy`](crate::BufferImageCopy); `block_size` answers "how
154    /// wide is one element of this format", which is the right question for a
155    /// colour format and only that.
156    #[must_use]
157    pub const fn block_size(self) -> u32 {
158        match self {
159            Self::R8Unorm => 1,
160            Self::Rg8Unorm | Self::R16Float | Self::D16Unorm => 2,
161            Self::Rgba8Unorm
162            | Self::Rgba8UnormSrgb
163            | Self::Bgra8Unorm
164            | Self::Bgra8UnormSrgb
165            | Self::Rgb10a2Unorm
166            | Self::R11g11b10Float
167            | Self::Rg16Float
168            | Self::R32Float
169            | Self::R32Uint
170            | Self::D32Float
171            | Self::D24UnormS8Uint => 4,
172            Self::Rgba16Float | Self::Rg32Float | Self::Rg32Uint | Self::D32FloatS8Uint => 8,
173            Self::Rgba32Float => 16,
174            Self::Bc1RgbaUnorm | Self::Bc1RgbaUnormSrgb | Self::Bc4RUnorm => 8,
175            Self::Bc3RgbaUnorm
176            | Self::Bc3RgbaUnormSrgb
177            | Self::Bc5RgUnorm
178            | Self::Bc6hRgbUfloat
179            | Self::Bc7RgbaUnorm
180            | Self::Bc7RgbaUnormSrgb => 16,
181        }
182    }
183
184    /// Bytes one block of `aspect` occupies in a buffer during a copy.
185    ///
186    /// This is the number a [`BufferImageCopy`](crate::BufferImageCopy) is
187    /// sized against, and it is **not** [`Format::block_size`] for a combined
188    /// depth/stencil format — see that method for why. `None` means the format
189    /// does not have that aspect, or the aspect set names more than one plane,
190    /// neither of which a single copy region can describe.
191    ///
192    /// ```
193    /// use crcbl_hal::{Format, ImageAspect};
194    ///
195    /// assert_eq!(Format::D32FloatS8Uint.block_size(), 8);
196    /// assert_eq!(Format::D32FloatS8Uint.texel_size(ImageAspect::DEPTH), Some(4));
197    /// assert_eq!(Format::D32FloatS8Uint.texel_size(ImageAspect::STENCIL), Some(1));
198    /// assert_eq!(Format::D32FloatS8Uint.texel_size(ImageAspect::COLOR), None);
199    /// assert_eq!(Format::Rgba8Unorm.texel_size(ImageAspect::COLOR), Some(4));
200    /// ```
201    #[must_use]
202    pub const fn texel_size(self, aspect: crate::ImageAspect) -> Option<u32> {
203        use crate::ImageAspect as A;
204        // Exactly one plane, or the question has no single answer.
205        if aspect.bits().count_ones() != 1 {
206            return None;
207        }
208        if aspect.contains(A::COLOR) {
209            return if self.is_depth_stencil() {
210                None
211            } else {
212                Some(self.block_size())
213            };
214        }
215        if aspect.contains(A::STENCIL) {
216            return if self.has_stencil() { Some(1) } else { None };
217        }
218        // Depth.
219        match self {
220            Self::D16Unorm => Some(2),
221            // The 24-bit plane is addressed as a 32-bit element by every API
222            // that permits copying it at all.
223            Self::D32Float | Self::D32FloatS8Uint | Self::D24UnormS8Uint => Some(4),
224            _ => None,
225        }
226    }
227
228    /// Block footprint in texels — `(1, 1)` unless the format is block
229    /// compressed, in which case `(4, 4)`.
230    #[must_use]
231    pub const fn block_extent(self) -> (u32, u32) {
232        if self.is_compressed() { (4, 4) } else { (1, 1) }
233    }
234
235    /// Whether this is a BC-compressed format.
236    #[must_use]
237    pub const fn is_compressed(self) -> bool {
238        matches!(
239            self,
240            Self::Bc1RgbaUnorm
241                | Self::Bc1RgbaUnormSrgb
242                | Self::Bc3RgbaUnorm
243                | Self::Bc3RgbaUnormSrgb
244                | Self::Bc4RUnorm
245                | Self::Bc5RgUnorm
246                | Self::Bc6hRgbUfloat
247                | Self::Bc7RgbaUnorm
248                | Self::Bc7RgbaUnormSrgb
249        )
250    }
251
252    /// Whether the format carries a depth channel.
253    #[must_use]
254    pub const fn has_depth(self) -> bool {
255        matches!(
256            self,
257            Self::D32Float | Self::D32FloatS8Uint | Self::D24UnormS8Uint | Self::D16Unorm
258        )
259    }
260
261    /// Whether the format carries a stencil channel.
262    #[must_use]
263    pub const fn has_stencil(self) -> bool {
264        matches!(self, Self::D32FloatS8Uint | Self::D24UnormS8Uint)
265    }
266
267    /// Whether the format may be used as a depth/stencil attachment rather than
268    /// a colour one.
269    #[must_use]
270    pub const fn is_depth_stencil(self) -> bool {
271        self.has_depth() || self.has_stencil()
272    }
273
274    /// Whether sampling this format applies sRGB→linear decode in hardware.
275    #[must_use]
276    pub const fn is_srgb(self) -> bool {
277        matches!(
278            self,
279            Self::Rgba8UnormSrgb
280                | Self::Bgra8UnormSrgb
281                | Self::Bc1RgbaUnormSrgb
282                | Self::Bc3RgbaUnormSrgb
283                | Self::Bc7RgbaUnormSrgb
284        )
285    }
286
287    /// Whether the format stores floating-point components wider than 8 bits —
288    /// i.e. whether it can hold values outside `[0, 1]` and is therefore usable
289    /// as an HDR intermediate.
290    #[must_use]
291    pub const fn is_hdr_capable(self) -> bool {
292        matches!(
293            self,
294            Self::R11g11b10Float
295                | Self::R16Float
296                | Self::Rg16Float
297                | Self::Rgba16Float
298                | Self::R32Float
299                | Self::Rg32Float
300                | Self::Rgba32Float
301                | Self::Bc6hRgbUfloat
302        )
303    }
304}
305
306/// Index buffer element width.
307#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
308pub enum IndexFormat {
309    /// 16-bit indices — half the bandwidth, capped at 65 535 vertices per
310    /// index-buffer range.
311    Uint16,
312    /// 32-bit indices.
313    Uint32,
314}
315
316impl IndexFormat {
317    /// Size of one index in bytes.
318    #[must_use]
319    pub const fn size(self) -> u64 {
320        match self {
321            Self::Uint16 => 2,
322            Self::Uint32 => 4,
323        }
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    /// [`Format::ALL`] must list every variant exactly once, in declaration
332    /// order — that is what lets every consumer of it, this module and
333    /// `crcbl-vk` alike, treat "iterated `ALL`" as "covered every format".
334    ///
335    /// Casting a variant to its discriminant is what makes it checkable at all,
336    /// and it only works because `Format` is fieldless. An entry inserted or
337    /// duplicated anywhere shifts every index after it and fails here; a
338    /// variant *appended* to the enum and not appended here does not, and
339    /// nothing on stable Rust can see it. That gap is the reason `ALL` carries
340    /// the instruction it does.
341    #[test]
342    fn the_format_table_is_in_declaration_order() {
343        for (index, format) in Format::ALL.iter().enumerate() {
344            assert_eq!(*format as usize, index, "{format:?} is out of place");
345        }
346    }
347
348    #[test]
349    fn every_format_has_a_nonzero_block_size() {
350        for format in Format::ALL {
351            assert!(format.block_size() > 0, "{format:?}");
352        }
353    }
354
355    #[test]
356    fn compressed_formats_use_four_by_four_blocks() {
357        for format in Format::ALL {
358            let expected = if format.is_compressed() {
359                (4, 4)
360            } else {
361                (1, 1)
362            };
363            assert_eq!(format.block_extent(), expected, "{format:?}");
364        }
365    }
366
367    #[test]
368    fn depth_formats_are_classified_consistently() {
369        assert!(Format::D32Float.has_depth());
370        assert!(!Format::D32Float.has_stencil());
371        assert!(Format::D32FloatS8Uint.has_stencil());
372        assert!(Format::D24UnormS8Uint.has_stencil());
373        for format in Format::ALL {
374            assert_eq!(
375                format.is_depth_stencil(),
376                format.has_depth() || format.has_stencil(),
377                "{format:?}"
378            );
379            if format.has_stencil() {
380                assert!(
381                    format.has_depth(),
382                    "no stencil-only formats exist: {format:?}"
383                );
384            }
385        }
386    }
387
388    /// The HDR pipeline is specified in terms of `Rgba16Float`; if it ever
389    /// stops being classified as HDR-capable the P1 target selection is broken.
390    #[test]
391    fn hdr_target_format_is_available_and_classified() {
392        assert!(Format::Rgba16Float.is_hdr_capable());
393        assert!(Format::R11g11b10Float.is_hdr_capable());
394        assert!(!Format::Rgba8Unorm.is_hdr_capable());
395        assert!(!Format::Rgba8UnormSrgb.is_hdr_capable());
396    }
397
398    #[test]
399    fn srgb_variants_are_marked_and_pair_with_a_linear_one() {
400        assert!(Format::Bgra8UnormSrgb.is_srgb());
401        assert!(!Format::Bgra8Unorm.is_srgb());
402        // sRGB is a decode rule, not a layout change: paired formats must agree
403        // on size.
404        assert_eq!(
405            Format::Rgba8Unorm.block_size(),
406            Format::Rgba8UnormSrgb.block_size()
407        );
408        assert_eq!(
409            Format::Bc7RgbaUnorm.block_size(),
410            Format::Bc7RgbaUnormSrgb.block_size()
411        );
412    }
413
414    /// The gap `block_size` cannot express: a combined format's two planes have
415    /// different copy footprints, and neither is the element size.
416    #[test]
417    fn depth_stencil_aspects_have_their_own_copy_footprint() {
418        use crate::ImageAspect as A;
419
420        assert_eq!(Format::D32FloatS8Uint.block_size(), 8);
421        assert_eq!(Format::D32FloatS8Uint.texel_size(A::DEPTH), Some(4));
422        assert_eq!(Format::D32FloatS8Uint.texel_size(A::STENCIL), Some(1));
423        assert_eq!(Format::D24UnormS8Uint.texel_size(A::STENCIL), Some(1));
424        assert_eq!(Format::D16Unorm.texel_size(A::DEPTH), Some(2));
425
426        for format in Format::ALL {
427            // A colour format has exactly one plane, and it is the block size.
428            if !format.is_depth_stencil() {
429                assert_eq!(format.texel_size(A::COLOR), Some(format.block_size()));
430                assert_eq!(format.texel_size(A::DEPTH), None, "{format:?}");
431                assert_eq!(format.texel_size(A::STENCIL), None, "{format:?}");
432            } else {
433                assert_eq!(format.texel_size(A::COLOR), None, "{format:?}");
434                assert!(format.texel_size(A::DEPTH).is_some(), "{format:?}");
435                assert_eq!(
436                    format.texel_size(A::STENCIL).is_some(),
437                    format.has_stencil(),
438                    "{format:?}"
439                );
440            }
441            // More than one plane, or none, is not a copy region.
442            assert_eq!(format.texel_size(A::DEPTH | A::STENCIL), None, "{format:?}");
443            assert_eq!(format.texel_size(A::empty()), None, "{format:?}");
444        }
445    }
446
447    #[test]
448    fn each_index_format_reports_the_byte_size_its_name_promises() {
449        assert_eq!(IndexFormat::Uint16.size(), 2);
450        assert_eq!(IndexFormat::Uint32.size(), 4);
451    }
452}