use crcbl_core::Handle;
use crate::{Format, HalError, Limits};
#[derive(Debug)]
pub enum Buffer {}
#[derive(Debug)]
pub enum Image {}
#[derive(Debug)]
pub enum ImageView {}
#[derive(Debug)]
pub enum Sampler {}
pub type BufferHandle = Handle<Buffer>;
pub type ImageHandle = Handle<Image>;
pub type ImageViewHandle = Handle<ImageView>;
pub type SamplerHandle = Handle<Sampler>;
bitflags::bitflags! {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BufferUsage: u32 {
const TRANSFER_SRC = 1 << 0;
const TRANSFER_DST = 1 << 1;
const UNIFORM = 1 << 2;
const STORAGE = 1 << 3;
const INDEX = 1 << 4;
const INDIRECT = 1 << 5;
const DEVICE_ADDRESS = 1 << 6;
const QUERY_RESOLVE = 1 << 7;
}
}
bitflags::bitflags! {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ImageUsage: u32 {
const TRANSFER_SRC = 1 << 0;
const TRANSFER_DST = 1 << 1;
const SAMPLED = 1 << 2;
const STORAGE = 1 << 3;
const COLOR_ATTACHMENT = 1 << 4;
const DEPTH_STENCIL_ATTACHMENT = 1 << 5;
const PRESENT = 1 << 6;
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MemoryLocation {
DeviceLocal,
HostUpload,
HostReadback,
}
impl MemoryLocation {
#[must_use]
pub const fn is_mappable(self) -> bool {
matches!(self, Self::HostUpload | Self::HostReadback)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BufferDesc<'a> {
pub label: Option<&'a str>,
pub size: u64,
pub usage: BufferUsage,
pub memory: MemoryLocation,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ImageType {
D1,
D2,
D3,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Extent3d {
pub width: u32,
pub height: u32,
pub depth_or_layers: u32,
}
impl Extent3d {
#[must_use]
pub const fn d2(width: u32, height: u32) -> Self {
Self {
width,
height,
depth_or_layers: 1,
}
}
#[must_use]
pub const fn full_mip_levels(self, image_type: ImageType) -> u32 {
let mut longest = if self.width > self.height {
self.width
} else {
self.height
};
if matches!(image_type, ImageType::D3) && self.depth_or_layers > longest {
longest = self.depth_or_layers;
}
if longest == 0 {
1
} else {
u32::BITS - longest.leading_zeros()
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Offset3d {
pub x: i32,
pub y: i32,
pub z: i32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Rect2d {
pub x: i32,
pub y: i32,
pub width: u32,
pub height: u32,
}
impl Rect2d {
#[must_use]
pub const fn from_size(width: u32, height: u32) -> Self {
Self {
x: 0,
y: 0,
width,
height,
}
}
}
bitflags::bitflags! {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ImageAspect: u32 {
const COLOR = 1 << 0;
const DEPTH = 1 << 1;
const STENCIL = 1 << 2;
}
}
impl ImageAspect {
#[must_use]
pub const fn of(format: Format) -> Self {
if format.is_depth_stencil() {
let mut aspect = Self::empty();
if format.has_depth() {
aspect = aspect.union(Self::DEPTH);
}
if format.has_stencil() {
aspect = aspect.union(Self::STENCIL);
}
aspect
} else {
Self::COLOR
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ImageSubresourceRange {
pub aspect: ImageAspect,
pub base_mip: u32,
pub mip_count: u32,
pub base_layer: u32,
pub layer_count: u32,
}
impl ImageSubresourceRange {
pub const ALL: u32 = u32::MAX;
#[must_use]
pub const fn all(format: Format) -> Self {
Self {
aspect: ImageAspect::of(format),
base_mip: 0,
mip_count: Self::ALL,
base_layer: 0,
layer_count: Self::ALL,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ImageSubresourceLayers {
pub aspect: ImageAspect,
pub mip: u32,
pub base_layer: u32,
pub layer_count: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ImageDesc<'a> {
pub label: Option<&'a str>,
pub image_type: ImageType,
pub extent: Extent3d,
pub format: Format,
pub mip_levels: u32,
pub samples: u32,
pub usage: ImageUsage,
}
impl ImageDesc<'_> {
pub fn check(&self, limits: &Limits) -> Result<(), HalError> {
let extent = self.extent;
if extent.width == 0 || extent.height == 0 || extent.depth_or_layers == 0 {
return Err(HalError::InvalidDescriptor(
"image extent must be non-zero in every dimension".to_string(),
));
}
if self.image_type == ImageType::D1 && extent.height != 1 {
return Err(HalError::InvalidDescriptor(format!(
"a D1 image is {} texels high, and a 1D image has a height of 1",
extent.height
)));
}
if self.image_type == ImageType::D3 {
let longest = extent.width.max(extent.height).max(extent.depth_or_layers);
if longest > limits.max_image_3d {
return Err(HalError::InvalidDescriptor(format!(
"3D image extent {extent:?} exceeds max_image_3d {}",
limits.max_image_3d
)));
}
} else {
let longest = extent.width.max(extent.height);
if longest > limits.max_image_2d {
return Err(HalError::InvalidDescriptor(format!(
"image extent {longest} exceeds max_image_2d {}",
limits.max_image_2d
)));
}
if extent.depth_or_layers > limits.max_image_array_layers {
return Err(HalError::InvalidDescriptor(format!(
"{} array layers exceeds max_image_array_layers {}",
extent.depth_or_layers, limits.max_image_array_layers
)));
}
}
if self.mip_levels == 0 {
return Err(HalError::InvalidDescriptor(
"image must have at least one mip level".to_string(),
));
}
let full_chain = extent.full_mip_levels(self.image_type);
if self.mip_levels > full_chain {
return Err(HalError::InvalidDescriptor(format!(
"{} mip levels exceeds the {full_chain} a {extent:?} {:?} image can have",
self.mip_levels, self.image_type
)));
}
if !self.samples.is_power_of_two() || self.samples > limits.max_sample_count {
return Err(HalError::InvalidDescriptor(format!(
"{} samples is not a power of two in 1..={}",
self.samples, limits.max_sample_count
)));
}
if self.samples > 1 {
if self.image_type != ImageType::D2 {
return Err(HalError::InvalidDescriptor(format!(
"a {:?} image asks for {} samples, and only a D2 image is multisampled",
self.image_type, self.samples
)));
}
if self.mip_levels != 1 {
return Err(HalError::InvalidDescriptor(format!(
"a {}-sample image asks for {} mip levels, and a multisampled image has one",
self.samples, self.mip_levels
)));
}
}
if self.usage.is_empty() {
return Err(HalError::InvalidDescriptor(
"an image with no usage flags can never be used".to_string(),
));
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ImageViewType {
D1,
D2,
D2Array,
Cube,
CubeArray,
D3,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ImageViewDesc<'a> {
pub label: Option<&'a str>,
pub image: ImageHandle,
pub view_type: ImageViewType,
pub format: Format,
pub range: ImageSubresourceRange,
}
impl ImageViewDesc<'_> {
pub fn check(
&self,
image_format: Format,
image_mip_levels: u32,
image_layers: u32,
) -> Result<(), HalError> {
if self.format != image_format {
return Err(HalError::InvalidDescriptor(format!(
"a view of a {image_format:?} image cannot be created as {:?}: this seam offers \
no format reinterpretation, because D3D12 needs a typeless resource for it and \
Metal a usage flag neither backend asks for",
self.format
)));
}
let range = self.range;
if range.base_mip >= image_mip_levels || range.base_layer >= image_layers {
return Err(HalError::InvalidDescriptor(format!(
"view starts at mip {} layer {}, and the image has {image_mip_levels} mips and \
{image_layers} layers",
range.base_mip, range.base_layer
)));
}
let mip_count = resolve_count(range.mip_count, range.base_mip, image_mip_levels);
let layer_count = resolve_count(range.layer_count, range.base_layer, image_layers);
if mip_count == 0 || layer_count == 0 {
return Err(HalError::InvalidDescriptor(
"an image view covering no mip levels or no layers is not a view".to_string(),
));
}
if range
.base_mip
.checked_add(mip_count)
.is_none_or(|end| end > image_mip_levels)
{
return Err(HalError::InvalidDescriptor(format!(
"a view of {mip_count} mips from mip {} runs past the {image_mip_levels} mips \
the image has",
range.base_mip
)));
}
if range
.base_layer
.checked_add(layer_count)
.is_none_or(|end| end > image_layers)
{
return Err(HalError::InvalidDescriptor(format!(
"a view of {layer_count} layers from layer {} runs past the {image_layers} \
layers the image has",
range.base_layer
)));
}
Ok(())
}
}
const fn resolve_count(requested: u32, base: u32, total: u32) -> u32 {
if requested == ImageSubresourceRange::ALL {
total.saturating_sub(base)
} else {
requested
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FilterMode {
Nearest,
Linear,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SamplerAddressMode {
Repeat,
MirrorRepeat,
ClampToEdge,
ClampToBorder,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SamplerDesc<'a> {
pub label: Option<&'a str>,
pub mag_filter: FilterMode,
pub min_filter: FilterMode,
pub mip_filter: FilterMode,
pub address_mode: [SamplerAddressMode; 3],
pub lod_min: f32,
pub lod_max: f32,
pub anisotropy: f32,
pub compare: Option<crate::CompareOp>,
}
impl Default for SamplerDesc<'_> {
fn default() -> Self {
Self {
label: None,
mag_filter: FilterMode::Linear,
min_filter: FilterMode::Linear,
mip_filter: FilterMode::Linear,
address_mode: [SamplerAddressMode::Repeat; 3],
lod_min: 0.0,
lod_max: f32::MAX,
anisotropy: 1.0,
compare: None,
}
}
}
impl SamplerDesc<'_> {
pub fn check_anisotropy_floor(&self) -> Result<(), HalError> {
if self.anisotropy.is_nan() || self.anisotropy < 1.0 {
return Err(HalError::InvalidDescriptor(format!(
"anisotropy {} is below 1.0, which is the value that disables it",
self.anisotropy
)));
}
Ok(())
}
pub fn check_anisotropy_ceiling(&self, limits: &Limits) -> Result<(), HalError> {
if self.anisotropy > limits.max_sampler_anisotropy {
return Err(HalError::InvalidDescriptor(format!(
"anisotropy {} exceeds max_sampler_anisotropy {}",
self.anisotropy, limits.max_sampler_anisotropy
)));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_one_dimensional_or_multisampled_image_is_held_to_its_shape() {
let limits = Limits::minimum();
let image = |image_type, extent, mip_levels, samples| ImageDesc {
label: None,
image_type,
extent,
format: Format::Rgba8Unorm,
mip_levels,
samples,
usage: ImageUsage::SAMPLED,
};
let line = Extent3d {
width: 64,
height: 1,
depth_or_layers: 1,
};
let square = Extent3d::d2(64, 64);
image(ImageType::D1, line, 1, 1)
.check(&limits)
.expect("a 1D image one texel high is the shape the field describes");
image(ImageType::D2, square, 1, 4)
.check(&limits)
.expect("a four-sample 2D image with one mip is what MSAA is");
image(ImageType::D2, square, 7, 1)
.check(&limits)
.expect("a single-sampled image may carry its whole chain");
for (desc, what) in [
(
image(ImageType::D1, square, 1, 1),
"a 1D image 64 texels high",
),
(
image(ImageType::D3, square, 1, 4),
"a multisampled 3D image",
),
(
image(ImageType::D2, square, 7, 4),
"a multisampled image with a mip chain",
),
] {
let error = desc
.check(&limits)
.expect_err(&format!("{what} must be refused"));
assert!(
matches!(error, HalError::InvalidDescriptor(_)),
"{what}: {error:?}"
);
}
}
#[test]
fn a_view_may_only_name_subresources_its_image_has() {
const MIPS: u32 = 4;
const LAYERS: u32 = 3;
const VIEW_FORMAT: Format = Format::Rgba8Unorm;
let view = |base_mip, mip_count, base_layer, layer_count| ImageViewDesc {
label: None,
image: Handle::from_bits(1 << 32).expect("a non-zero generation"),
view_type: ImageViewType::D2Array,
format: Format::Rgba8Unorm,
range: ImageSubresourceRange {
aspect: ImageAspect::COLOR,
base_mip,
mip_count,
base_layer,
layer_count,
},
};
let all = ImageSubresourceRange::ALL;
view(0, all, 0, all)
.check(VIEW_FORMAT, MIPS, LAYERS)
.expect("both sentinels resolve to the whole image, which is a view of all of it");
view(3, all, 2, all)
.check(VIEW_FORMAT, MIPS, LAYERS)
.expect("the sentinel from the last mip and last layer is one of each, not none");
view(0, MIPS, 0, LAYERS)
.check(VIEW_FORMAT, MIPS, LAYERS)
.expect("the whole image named explicitly is the same view");
view(1, 2, 1, 2)
.check(VIEW_FORMAT, MIPS, LAYERS)
.expect("a subrange ending exactly at the end is inside the image");
for (desc, what) in [
(view(MIPS, all, 0, all), "a view starting past the last mip"),
(
view(0, all, LAYERS, all),
"a view starting past the last layer",
),
] {
let error = desc
.check(VIEW_FORMAT, MIPS, LAYERS)
.expect_err(&format!("{what} must be refused"));
let HalError::InvalidDescriptor(message) = &error else {
panic!("{what} is a bad descriptor, not {error:?}");
};
assert!(
message.starts_with("view starts at mip"),
"{what} must be refused for its base rather than for what its \
count resolved to: {message}"
);
}
for (desc, what) in [
(view(0, 0, 0, all), "a view of no mip levels"),
(view(0, all, 0, 0), "a view of no layers"),
(view(2, 3, 0, all), "a mip range running past the last mip"),
(
view(0, all, 1, 3),
"a layer range running past the last layer",
),
(
view(2, u32::MAX - 1, 0, all),
"a mip count whose sum with its base overflows a u32",
),
(
view(0, all, 2, u32::MAX - 1),
"a layer count whose sum with its base overflows a u32",
),
] {
let error = desc
.check(VIEW_FORMAT, MIPS, LAYERS)
.expect_err(&format!("{what} must be refused"));
assert!(
matches!(error, HalError::InvalidDescriptor(_)),
"{what}: {error:?}"
);
}
}
#[test]
fn a_view_may_not_reinterpret_its_image_s_format() {
let view = |format| ImageViewDesc {
label: None,
image: Handle::from_bits(1 << 32).expect("a non-zero generation"),
view_type: ImageViewType::D2,
format,
range: ImageSubresourceRange::all(Format::Rgba8Unorm),
};
view(Format::Rgba8Unorm)
.check(Format::Rgba8Unorm, 1, 1)
.expect("the image's own format is what a view asks for");
let error = view(Format::Rgba8UnormSrgb)
.check(Format::Rgba8Unorm, 1, 1)
.expect_err("sRGB reinterpretation is the case this seam does not offer");
let HalError::InvalidDescriptor(text) = error else {
panic!("a caller bug is named in the descriptor");
};
assert!(
text.contains("Rgba8Unorm") && text.contains("Rgba8UnormSrgb"),
"the refusal names both formats: {text}"
);
}
#[test]
fn mip_chain_length_matches_the_textbook_formula() {
for (width, height, expected) in [
(1u32, 1u32, 1u32),
(2, 1, 2),
(2, 2, 2),
(4, 4, 3),
(5, 5, 3),
(256, 256, 9),
(1024, 512, 11),
(4096, 4096, 13),
] {
assert_eq!(
Extent3d::d2(width, height).full_mip_levels(ImageType::D2),
expected,
"{width}x{height}"
);
}
assert_eq!(Extent3d::d2(0, 0).full_mip_levels(ImageType::D2), 1);
}
#[test]
fn a_volumes_depth_joins_the_mip_chain_but_array_layers_do_not() {
let extent = Extent3d {
width: 4,
height: 4,
depth_or_layers: 64,
};
assert_eq!(extent.full_mip_levels(ImageType::D3), 7, "4x4x64 volume");
assert_eq!(
extent.full_mip_levels(ImageType::D2),
3,
"64 array layers do not mip"
);
assert_eq!(extent.full_mip_levels(ImageType::D1), 3);
}
#[test]
fn aspects_follow_the_format() {
assert_eq!(ImageAspect::of(Format::Rgba16Float), ImageAspect::COLOR);
assert_eq!(ImageAspect::of(Format::D32Float), ImageAspect::DEPTH);
assert_eq!(
ImageAspect::of(Format::D32FloatS8Uint),
ImageAspect::DEPTH | ImageAspect::STENCIL
);
assert!(!ImageAspect::of(Format::D32Float).contains(ImageAspect::COLOR));
}
#[test]
fn whole_image_range_uses_the_sentinel() {
let range = ImageSubresourceRange::all(Format::D32Float);
assert_eq!(range.aspect, ImageAspect::DEPTH);
assert_eq!(range.mip_count, ImageSubresourceRange::ALL);
assert_eq!(range.layer_count, ImageSubresourceRange::ALL);
assert_eq!(range.base_mip, 0);
}
#[test]
fn only_the_host_visible_memory_locations_report_themselves_as_mappable() {
assert!(!MemoryLocation::DeviceLocal.is_mappable());
assert!(MemoryLocation::HostUpload.is_mappable());
assert!(MemoryLocation::HostReadback.is_mappable());
}
#[test]
fn default_sampler_is_trilinear_repeat_without_comparison() {
let sampler = SamplerDesc::default();
assert_eq!(sampler.mip_filter, FilterMode::Linear);
assert_eq!(sampler.address_mode, [SamplerAddressMode::Repeat; 3]);
assert_eq!(sampler.anisotropy, 1.0);
assert!(
sampler.compare.is_none(),
"a comparison sampler must be asked for explicitly; a silent default \
would be wrong under reversed-Z in one direction or the other"
);
}
#[test]
fn anisotropy_is_held_to_the_seams_floor_and_the_devices_ceiling() {
let limits = Limits::desktop();
let ceiling = limits.max_sampler_anisotropy;
let sampler = |anisotropy| SamplerDesc {
anisotropy,
..SamplerDesc::default()
};
for (case, anisotropy) in [("the floor exactly", 1.0), ("the ceiling exactly", ceiling)] {
sampler(anisotropy)
.check_anisotropy_floor()
.unwrap_or_else(|error| panic!("{case} is a value a sampler may ask for: {error}"));
sampler(anisotropy)
.check_anisotropy_ceiling(&limits)
.unwrap_or_else(|error| panic!("{case} is a value a sampler may ask for: {error}"));
}
for (case, anisotropy) in [("below the floor", 0.5), ("a NaN", f32::NAN)] {
let error = sampler(anisotropy)
.check_anisotropy_floor()
.expect_err(&format!("{case} must be refused"));
assert!(
matches!(error, HalError::InvalidDescriptor(_)),
"{case}: {error:?}"
);
sampler(anisotropy)
.check_anisotropy_ceiling(&limits)
.unwrap_or_else(|error| {
panic!("{case} is under the ceiling, not over it: {error}")
});
}
let error = sampler(ceiling + 1.0)
.check_anisotropy_ceiling(&limits)
.expect_err("past the device's ceiling must be refused");
assert!(
matches!(error, HalError::InvalidDescriptor(_)),
"past the ceiling: {error:?}"
);
sampler(ceiling + 1.0)
.check_anisotropy_floor()
.expect("past the ceiling is still above the floor");
}
#[test]
fn rect_from_size_is_at_the_origin() {
let rect = Rect2d::from_size(1920, 1080);
assert_eq!((rect.x, rect.y), (0, 0));
assert_eq!((rect.width, rect.height), (1920, 1080));
}
}