Skip to main content

mln_engine/draw/
vertex.rs

1//! How a mesh reads its vertices: each of its [`VertexBinding`]s reads one
2//! [`VertexBuffer`] as the attributes of a layout, which a vertex type
3//! declares ([`Vertex`], [`vertex_attributes!`](crate::vertex_attributes))
4//! or a layer makes, as the paint attributes are.
5
6use std::borrow::Cow;
7
8use mln_gfx::gfx_types::AttributeDataType;
9
10use crate::draw::vertex_attribute::{SharedAttribute, VertexAttributeArray};
11use crate::draw::vertices::VertexBuffer;
12
13/// An attribute of a vertex layout: the program attribute `name`, read as
14/// `format` at `offset` bytes into each vertex.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub struct VertexAttribute {
17    pub name: &'static str,
18    pub format: AttributeDataType,
19    pub offset: u32,
20}
21
22/// A `#[repr(C)]` vertex type, and the attributes a program reads of it.
23/// [`vertex_attributes!`](crate::vertex_attributes) declares them.
24pub trait Vertex: bytemuck::Pod {
25    const ATTRIBUTES: &'static [VertexAttribute];
26}
27
28/// Declares the attributes of a `#[repr(C)]` vertex type: each field, the
29/// program attribute it binds to and the format the program reads it as.
30///
31/// ```ignore
32/// #[repr(C)]
33/// #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
34/// struct LineVertex {
35///     pos_normal: [i16; 2],
36///     data: [u8; 4],
37/// }
38/// mln_engine::vertex_attributes!(LineVertex { pos_normal => "pos_normal": Short2, data => "data": UByte4 });
39/// ```
40#[macro_export]
41macro_rules! vertex_attributes {
42    ($vertex:ty { $($field:ident => $name:literal: $format:ident),+ $(,)? }) => {
43        impl $crate::draw::Vertex for $vertex {
44            const ATTRIBUTES: &'static [$crate::draw::VertexAttribute] = &[$(
45                $crate::draw::VertexAttribute {
46                    name: $name,
47                    format: $crate::__private::mln_gfx::gfx_types::AttributeDataType::$format,
48                    offset: ::core::mem::offset_of!($vertex, $field) as u32,
49                },
50            )+];
51        }
52    };
53}
54
55/// A vertex buffer a mesh reads, and how: its vertices of `stride` bytes,
56/// from the vertex `first_vertex` on, as `attributes`. Clones read the same
57/// buffer, which meshes share.
58#[derive(Clone, Debug)]
59pub struct VertexBinding {
60    pub buffer: VertexBuffer,
61    pub stride: u32,
62    pub first_vertex: u32,
63    pub attributes: Cow<'static, [VertexAttribute]>,
64}
65
66impl VertexBinding {
67    /// `buffer`, of `stride`-byte vertices, read as `attributes`.
68    #[must_use]
69    pub fn new(buffer: &VertexBuffer, stride: u32, attributes: impl Into<Cow<'static, [VertexAttribute]>>) -> Self {
70        VertexBinding { buffer: buffer.clone(), stride, first_vertex: 0, attributes: attributes.into() }
71    }
72
73    /// `buffer`, of vertices of the type `V`, read as its attributes.
74    #[must_use]
75    pub fn of<V: Vertex>(buffer: &VertexBuffer) -> Self {
76        VertexBinding::new(buffer, size_of::<V>() as u32, V::ATTRIBUTES)
77    }
78
79    /// The binding, read from the vertex `first_vertex` on.
80    #[must_use]
81    pub fn starting_at(self, first_vertex: u32) -> Self {
82        VertexBinding { first_vertex, ..self }
83    }
84
85    /// The binding, read from `buffer`, in its layout.
86    #[must_use]
87    pub fn with_buffer(self, buffer: &VertexBuffer) -> Self {
88        VertexBinding { buffer: buffer.clone(), ..self }
89    }
90
91    /// The attribute named `name`, if the binding has it.
92    #[must_use]
93    pub fn attribute(&self, name: &str) -> Option<&VertexAttribute> {
94        self.attributes.iter().find(|attribute| attribute.name == name)
95    }
96
97    /// Binds the attributes in `attrs`, in place of those of their names.
98    pub(crate) fn bind(&self, attrs: &mut VertexAttributeArray) {
99        for (name, shared) in self.shared() {
100            attrs.set_shared(name, shared);
101        }
102    }
103
104    /// The attributes, as an attribute array holds them.
105    fn shared(&self) -> impl Iterator<Item = (&'static str, SharedAttribute)> + '_ {
106        self.attributes.iter().map(|attribute| {
107            let shared = SharedAttribute::new(self.buffer.clone(), attribute.format, attribute.offset, self.stride)
108                .starting_at(self.first_vertex);
109            (attribute.name, shared)
110        })
111    }
112}
113
114/// Makes the attributes of `bindings` those of `attrs`, in place of what it
115/// had.
116pub(crate) fn replace_attributes<'b>(
117    attrs: &mut VertexAttributeArray,
118    bindings: impl IntoIterator<Item = &'b VertexBinding>,
119) {
120    attrs.replace(bindings.into_iter().flat_map(VertexBinding::shared));
121}
122
123/// The attributes of `bindings`.
124pub(crate) fn attributes_of(bindings: &[VertexBinding]) -> VertexAttributeArray {
125    let mut attrs = VertexAttributeArray::new();
126    for binding in bindings {
127        binding.bind(&mut attrs);
128    }
129    attrs
130}