use alloc::vec::Vec;
use core::mem::{align_of, size_of};
use crate::{Attributes, ByteOrder, Positions};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum VertexLayoutError {
InvalidStride,
MisalignedField,
InvalidFieldSize,
InvalidPositionSize,
FieldOffsetMismatch,
SizeOverflow,
AllocationFailed,
}
impl core::fmt::Display for VertexLayoutError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(match self {
Self::InvalidStride => "unsupported vertex stride",
Self::MisalignedField => "misaligned float field",
Self::InvalidFieldSize => "unsupported field size",
Self::InvalidPositionSize => "positions require three float components",
Self::FieldOffsetMismatch => "field selector does not match offset",
Self::SizeOverflow => "vertex snapshot size overflow",
Self::AllocationFailed => "vertex snapshot allocation failed",
})
}
}
#[cfg(feature = "std")]
impl std::error::Error for VertexLayoutError {}
pub struct VertexLayout<V, const N: usize, F> {
offset: usize,
field: F,
marker: core::marker::PhantomData<fn(&V) -> &[f32; N]>,
}
impl<V, const N: usize, F: Clone> Clone for VertexLayout<V, N, F> {
fn clone(&self) -> Self {
Self {
offset: self.offset,
field: self.field.clone(),
marker: core::marker::PhantomData,
}
}
}
impl<V, const N: usize, F: Copy> Copy for VertexLayout<V, N, F> {}
impl<V, const N: usize, F> core::fmt::Debug for VertexLayout<V, N, F> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("VertexLayout")
.field("stride", &self.stride())
.field("offset", &self.offset)
.field("components", &N)
.finish()
}
}
impl<V, const N: usize, F> VertexLayout<V, N, F> {
pub const fn stride(&self) -> usize {
size_of::<V>()
}
pub const fn offset(&self) -> usize {
self.offset
}
}
impl<V, const N: usize, F: Fn(&V) -> &[f32; N]> VertexLayout<V, N, F> {
pub fn new(offset: usize, field: F) -> Result<Self, VertexLayoutError> {
let stride = size_of::<V>();
if stride == 0 || stride > 256 || !stride.is_multiple_of(4) {
return Err(VertexLayoutError::InvalidStride);
}
if align_of::<V>() < align_of::<f32>() || !offset.is_multiple_of(align_of::<f32>()) {
return Err(VertexLayoutError::MisalignedField);
}
if N == 0 || N > 32 || offset.checked_add(N * 4).is_none_or(|end| end > stride) {
return Err(VertexLayoutError::InvalidFieldSize);
}
Ok(Self {
offset,
field,
marker: core::marker::PhantomData,
})
}
pub fn copy_from(&self, vertices: &[V]) -> Result<VertexFieldSnapshot<N>, VertexLayoutError> {
let len = vertices
.len()
.checked_mul(self.stride())
.filter(|&len| len <= isize::MAX as usize)
.ok_or(VertexLayoutError::SizeOverflow)?;
let mut bytes = Vec::new();
bytes
.try_reserve_exact(len)
.map_err(|_| VertexLayoutError::AllocationFailed)?;
bytes.resize(len, 0);
for (vertex, record) in vertices.iter().zip(bytes.chunks_exact_mut(self.stride())) {
let field = (self.field)(vertex);
if (field.as_ptr() as usize).checked_sub(vertex as *const V as usize)
!= Some(self.offset)
{
return Err(VertexLayoutError::FieldOffsetMismatch);
}
for (component, value) in field.iter().enumerate() {
let start = self.offset + component * 4;
record[start..start + 4].copy_from_slice(&value.to_le_bytes());
}
}
Ok(VertexFieldSnapshot {
bytes,
count: vertices.len(),
stride: self.stride(),
offset: self.offset,
})
}
}
#[derive(Debug)]
pub struct VertexFieldSnapshot<const N: usize> {
bytes: Vec<u8>,
count: usize,
stride: usize,
offset: usize,
}
impl<const N: usize> VertexFieldSnapshot<N> {
pub fn from_vertices<V>(
vertices: &[V],
offset: usize,
field: impl Fn(&V) -> &[f32; N],
) -> Result<Self, VertexLayoutError> {
VertexLayout::new(offset, field)?.copy_from(vertices)
}
pub fn positions(&self) -> Result<Positions<'_>, VertexLayoutError> {
if N != 3 {
return Err(VertexLayoutError::InvalidPositionSize);
}
Positions::from_bytes(
&self.bytes,
self.count,
self.stride,
if self.count == 0 { 0 } else { self.offset },
ByteOrder::LittleEndian,
)
.map_err(|_| VertexLayoutError::InvalidFieldSize)
}
pub fn attributes(&self) -> Result<Attributes<'_>, VertexLayoutError> {
Attributes::from_bytes(
&self.bytes,
self.count,
N,
self.stride,
if self.count == 0 { 0 } else { self.offset },
ByteOrder::LittleEndian,
)
.map_err(|_| VertexLayoutError::InvalidFieldSize)
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
pub const fn stride(&self) -> usize {
self.stride
}
pub const fn offset(&self) -> usize {
self.offset
}
}