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::{VertexBuffer, Vertices};
16
17#[derive(Clone)]
21pub(crate) struct SharedAttribute {
22 pub(crate) vertices: VertexBuffer,
23 pub(crate) data_type: AttributeDataType,
24 pub(crate) offset: u32,
25 pub(crate) vertex_offset: u32,
26 pub(crate) stride: u32,
27}
28
29impl SharedAttribute {
30 #[must_use]
33 pub(crate) fn new(vertices: VertexBuffer, 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(crate) 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 AttributeSource {
53 Own { data_type: AttributeDataType, count: usize, values: OwnValues },
55 Shared(SharedAttribute),
57}
58
59impl AttributeSource {
60 pub(crate) fn count(&self) -> usize {
62 match self {
63 AttributeSource::Own { count, .. } => *count,
64 AttributeSource::Shared(shared) => shared.vertices.count(),
65 }
66 }
67
68 pub(crate) fn needs_upload(&self, context: &Context) -> bool {
72 match self {
73 AttributeSource::Own { values, .. } => matches!(values, OwnValues::Bytes(_)),
74 AttributeSource::Shared(shared) => context.vertices(&shared.vertices).is_some_and(Vertices::needs_upload),
75 }
76 }
77
78 pub(crate) fn binding(
82 &mut self,
83 gpu: &mut dyn Gpu,
84 context: &mut Context,
85 ) -> Result<Option<AttributeBinding>, GpuError> {
86 match self {
87 AttributeSource::Own { data_type, values, .. } => {
88 let buffer = match values {
89 OwnValues::Buffer(buffer) => buffer.id(),
90 OwnValues::Bytes(bytes) => {
91 let buffer = context.device().buffer(gpu, BufferUsage::Vertex, bytes)?;
92 let id = buffer.id();
93 *values = OwnValues::Buffer(buffer);
94 id
95 }
96 };
97 Ok(Some(AttributeBinding {
98 attribute: AttributeDescriptor { data_type: *data_type, offset: 0 },
99 vertex_stride: data_type.stride() as u32,
100 buffer,
101 vertex_offset: 0,
102 held: None,
103 }))
104 }
105 AttributeSource::Shared(shared) => {
106 let Some(buffer) = context.upload_vertices(gpu, &shared.vertices)? else {
107 return Ok(None);
108 };
109 debug_assert!(
110 context
111 .vertices(&shared.vertices)
112 .is_none_or(|vertices| (shared.stride as usize) * (shared.vertex_offset as usize)
113 < vertices.vertex_size() * vertices.count())
114 );
115 Ok(Some(AttributeBinding {
116 attribute: AttributeDescriptor { data_type: shared.data_type, offset: shared.offset },
117 vertex_stride: shared.stride,
118 buffer,
119 vertex_offset: shared.vertex_offset,
120 held: Some(shared.vertices.held()),
121 }))
122 }
123 }
124 }
125}
126
127#[derive(Clone, Copy, Debug, Default)]
129pub struct Uniforms {
130 names: [&'static str; MAX_ATTRIBUTES],
131 len: usize,
132}
133
134impl Uniforms {
135 pub(crate) fn insert(&mut self, name: &'static str) {
136 if self.contains(name) {
137 return;
138 }
139 debug_assert!(self.len < self.names.len(), "more uniforms than attributes");
140 if let Some(slot) = self.names.get_mut(self.len) {
141 *slot = name;
142 self.len += 1;
143 }
144 }
145
146 #[must_use]
147 pub(crate) fn contains(&self, name: &str) -> bool {
148 self.names[..self.len].contains(&name)
149 }
150}
151
152impl FromIterator<&'static str> for Uniforms {
153 fn from_iter<I: IntoIterator<Item = &'static str>>(names: I) -> Uniforms {
154 let mut uniforms = Uniforms::default();
155 for name in names {
156 uniforms.insert(name);
157 }
158 uniforms
159 }
160}
161
162#[derive(Default)]
165pub(crate) struct VertexAttributeArray {
166 attrs: [Option<Box<(&'static str, AttributeSource)>>; MAX_ATTRIBUTES],
167 layout: u64,
169}
170
171fn new_layout() -> u64 {
173 static NEXT: AtomicU64 = AtomicU64::new(1);
174 NEXT.fetch_add(1, Ordering::Relaxed)
175}
176
177impl VertexAttributeArray {
178 #[must_use]
180 pub(crate) fn new() -> Self {
181 Self::default()
182 }
183
184 #[must_use]
187 pub(crate) fn min_count(&self) -> usize {
188 self.iter().map(|(_, attr)| attr.count()).min().unwrap_or(usize::MAX)
189 }
190
191 #[must_use]
193 pub(crate) fn slot_of(&self, name: &str) -> Option<usize> {
194 self.attrs.iter().position(|attr| attr.as_ref().is_some_and(|attr| attr.0 == name))
195 }
196
197 #[must_use]
199 pub(crate) fn at(&self, slot: usize) -> Option<&AttributeSource> {
200 self.attrs.get(slot)?.as_ref().map(|attr| &attr.1)
201 }
202
203 pub(crate) fn at_mut(&mut self, slot: usize) -> Option<&mut AttributeSource> {
205 self.attrs.get_mut(slot)?.as_mut().map(|attr| &mut attr.1)
206 }
207
208 #[must_use]
213 pub(crate) fn layout(&self) -> u64 {
214 self.layout
215 }
216
217 pub(crate) fn set_own(&mut self, name: &'static str, data_type: AttributeDataType, bytes: Vec<u8>) {
220 let count = bytes.len().checked_div(data_type.stride()).unwrap_or(0);
221 self.set(name, AttributeSource::Own { data_type, count, values: OwnValues::Bytes(bytes) });
222 }
223
224 pub(crate) fn set_shared(&mut self, name: &'static str, shared: SharedAttribute) {
227 let _slot = self.set(name, AttributeSource::Shared(shared));
228 }
229
230 fn set(&mut self, name: &'static str, attribute: AttributeSource) -> Option<usize> {
233 if let Some(slot) = self.slot_of(name) {
234 if let Some(Some(held)) = self.attrs.get_mut(slot) {
235 held.1 = attribute;
236 }
237 return Some(slot);
238 }
239 let slot = self.attrs.iter().position(Option::is_none);
240 debug_assert!(slot.is_some(), "more attributes than a shader has");
241 let slot = slot?;
242 self.attrs[slot] = Some(Box::new((name, attribute)));
243 self.layout = new_layout();
244 Some(slot)
245 }
246
247 pub(crate) fn replace(&mut self, attributes: impl IntoIterator<Item = (&'static str, SharedAttribute)>) {
250 let mut kept = [false; MAX_ATTRIBUTES];
251 for (name, shared) in attributes {
252 if let Some(slot) = self.set(name, AttributeSource::Shared(shared)) {
253 kept[slot] = true;
254 }
255 }
256 for (slot, kept) in self.attrs.iter_mut().zip(kept) {
257 if !kept && slot.take().is_some() {
258 self.layout = new_layout();
259 }
260 }
261 }
262
263 pub(crate) fn has_own(&self) -> bool {
266 self.iter().any(|(_, attr)| matches!(attr, AttributeSource::Own { .. }))
267 }
268
269 pub(crate) fn iter(&self) -> impl Iterator<Item = (&'static str, &AttributeSource)> {
271 self.attrs.iter().filter_map(|attr| attr.as_ref().map(|attr| (attr.0, &attr.1)))
272 }
273}