1use std::sync::atomic::{AtomicU64, Ordering};
7
8use mln_gfx::gfx_types::AttributeDataType;
9use mln_gfx::gpu::{BufferUsage, Gpu, GpuError};
10use mln_gfx::shaders::bindings::MAX_ATTRIBUTES;
11
12use crate::draw::buffer::Buffer;
13use crate::draw::context::Context;
14use crate::draw::upload::{AttributeBinding, AttributeDescriptor};
15use crate::draw::vertices::{SharedVertices, Vertices};
16
17#[derive(Clone)]
21pub struct SharedAttribute {
22 pub vertices: SharedVertices,
23 pub(crate) data_type: AttributeDataType,
24 pub offset: u32,
25 pub(crate) vertex_offset: u32,
26 pub stride: u32,
27}
28
29impl SharedAttribute {
30 #[must_use]
33 pub fn new(vertices: SharedVertices, data_type: AttributeDataType, offset: u32, stride: u32) -> Self {
34 SharedAttribute { vertices, data_type, offset, vertex_offset: 0, stride }
35 }
36
37 #[must_use]
39 pub fn starting_at(self, vertex_offset: u32) -> Self {
40 SharedAttribute { vertex_offset, ..self }
41 }
42}
43
44pub(crate) enum OwnValues {
47 Bytes(Vec<u8>),
48 Buffer(Buffer),
49}
50
51pub(crate) enum VertexAttribute {
53 Own { data_type: AttributeDataType, count: usize, values: OwnValues },
55 Shared(SharedAttribute),
57}
58
59impl VertexAttribute {
60 pub(crate) fn count(&self) -> usize {
62 match self {
63 VertexAttribute::Own { count, .. } => *count,
64 VertexAttribute::Shared(shared) => shared.vertices.count(),
65 }
66 }
67
68 pub(crate) fn shared(&self) -> Option<&SharedAttribute> {
71 match self {
72 VertexAttribute::Shared(shared) => Some(shared),
73 VertexAttribute::Own { .. } => None,
74 }
75 }
76
77 pub(crate) fn needs_upload(&self, context: &Context) -> bool {
81 match self {
82 VertexAttribute::Own { values, .. } => matches!(values, OwnValues::Bytes(_)),
83 VertexAttribute::Shared(shared) => context.vertices(&shared.vertices).is_some_and(Vertices::needs_upload),
84 }
85 }
86
87 pub(crate) fn binding(
91 &mut self,
92 gpu: &mut dyn Gpu,
93 context: &mut Context,
94 ) -> Result<Option<AttributeBinding>, GpuError> {
95 match self {
96 VertexAttribute::Own { data_type, values, .. } => {
97 let buffer = match values {
98 OwnValues::Buffer(buffer) => buffer.id(),
99 OwnValues::Bytes(bytes) => {
100 let buffer = context.device().buffer(gpu, BufferUsage::Vertex, bytes)?;
101 let id = buffer.id();
102 *values = OwnValues::Buffer(buffer);
103 id
104 }
105 };
106 Ok(Some(AttributeBinding {
107 attribute: AttributeDescriptor { data_type: *data_type, offset: 0 },
108 vertex_stride: data_type.stride() as u32,
109 buffer,
110 vertex_offset: 0,
111 held: None,
112 }))
113 }
114 VertexAttribute::Shared(shared) => {
115 let Some(buffer) = context.upload_vertices(gpu, &shared.vertices)? else {
116 return Ok(None);
117 };
118 debug_assert!(
119 context
120 .vertices(&shared.vertices)
121 .is_none_or(|vertices| (shared.stride as usize) * (shared.vertex_offset as usize)
122 < vertices.vertex_size() * vertices.count())
123 );
124 Ok(Some(AttributeBinding {
125 attribute: AttributeDescriptor { data_type: shared.data_type, offset: shared.offset },
126 vertex_stride: shared.stride,
127 buffer,
128 vertex_offset: shared.vertex_offset,
129 held: Some(shared.vertices.held()),
130 }))
131 }
132 }
133 }
134}
135
136#[derive(Clone, Copy, Debug, Default)]
138pub struct Uniforms {
139 names: [&'static str; MAX_ATTRIBUTES],
140 len: usize,
141}
142
143impl Uniforms {
144 pub(crate) fn insert(&mut self, name: &'static str) {
145 if self.contains(name) {
146 return;
147 }
148 debug_assert!(self.len < self.names.len(), "more uniforms than attributes");
149 if let Some(slot) = self.names.get_mut(self.len) {
150 *slot = name;
151 self.len += 1;
152 }
153 }
154
155 #[must_use]
156 pub(crate) fn contains(&self, name: &str) -> bool {
157 self.names[..self.len].contains(&name)
158 }
159}
160
161impl FromIterator<&'static str> for Uniforms {
162 fn from_iter<I: IntoIterator<Item = &'static str>>(names: I) -> Uniforms {
163 let mut uniforms = Uniforms::default();
164 for name in names {
165 uniforms.insert(name);
166 }
167 uniforms
168 }
169}
170
171#[derive(Default)]
174pub struct VertexAttributeArray {
175 attrs: [Option<Box<(&'static str, VertexAttribute)>>; MAX_ATTRIBUTES],
176 layout: u64,
178}
179
180fn new_layout() -> u64 {
182 static NEXT: AtomicU64 = AtomicU64::new(1);
183 NEXT.fetch_add(1, Ordering::Relaxed)
184}
185
186impl VertexAttributeArray {
187 #[must_use]
189 pub fn new() -> Self {
190 Self::default()
191 }
192
193 #[must_use]
196 pub(crate) fn min_count(&self) -> usize {
197 self.iter().map(|(_, attr)| attr.count()).min().unwrap_or(usize::MAX)
198 }
199
200 #[must_use]
202 pub(crate) fn slot_of(&self, name: &str) -> Option<usize> {
203 self.attrs.iter().position(|attr| attr.as_ref().is_some_and(|attr| attr.0 == name))
204 }
205
206 #[must_use]
207 pub(crate) fn get(&self, name: &str) -> Option<&VertexAttribute> {
208 self.at(self.slot_of(name)?)
209 }
210
211 #[must_use]
214 pub fn shared(&self, name: &str) -> Option<&SharedAttribute> {
215 self.get(name)?.shared()
216 }
217
218 #[must_use]
220 pub(crate) fn at(&self, slot: usize) -> Option<&VertexAttribute> {
221 self.attrs.get(slot)?.as_ref().map(|attr| &attr.1)
222 }
223
224 pub(crate) fn at_mut(&mut self, slot: usize) -> Option<&mut VertexAttribute> {
226 self.attrs.get_mut(slot)?.as_mut().map(|attr| &mut attr.1)
227 }
228
229 #[must_use]
234 pub(crate) fn layout(&self) -> u64 {
235 self.layout
236 }
237
238 pub(crate) fn set_own(&mut self, name: &'static str, data_type: AttributeDataType, bytes: Vec<u8>) {
241 let count = bytes.len().checked_div(data_type.stride()).unwrap_or(0);
242 self.set(name, VertexAttribute::Own { data_type, count, values: OwnValues::Bytes(bytes) });
243 }
244
245 pub fn set_shared(&mut self, name: &'static str, shared: SharedAttribute) {
248 self.set(name, VertexAttribute::Shared(shared));
249 }
250
251 fn set(&mut self, name: &'static str, attribute: VertexAttribute) {
254 if let Some(slot) = self.slot_of(name).and_then(|slot| self.attrs.get_mut(slot)) {
255 *slot = Some(Box::new((name, attribute)));
256 return;
257 }
258 let slot = self.attrs.iter_mut().find(|slot| slot.is_none());
259 debug_assert!(slot.is_some(), "more attributes than a shader has");
260 if let Some(slot) = slot {
261 *slot = Some(Box::new((name, attribute)));
262 self.layout = new_layout();
263 }
264 }
265
266 pub fn shared_mut(&mut self) -> impl Iterator<Item = &mut SharedAttribute> {
269 self.attrs.iter_mut().filter_map(|attr| match &mut attr.as_mut()?.1 {
270 VertexAttribute::Shared(shared) => Some(shared),
271 VertexAttribute::Own { .. } => None,
272 })
273 }
274
275 pub(crate) fn has_own(&self) -> bool {
278 self.iter().any(|(_, attr)| matches!(attr, VertexAttribute::Own { .. }))
279 }
280
281 pub(crate) fn iter(&self) -> impl Iterator<Item = (&'static str, &VertexAttribute)> {
283 self.attrs.iter().filter_map(|attr| attr.as_ref().map(|attr| (attr.0, &attr.1)))
284 }
285}