1use mln_gfx::color_mode::ColorMode;
17use mln_gfx::cull_face_mode::CullFaceMode;
18use mln_gfx::depth_mode::DepthMode;
19use mln_gfx::draw_mode::DrawMode;
20use mln_gfx::gfx_types::{AttributeDataType, DrawModeType, PrimitiveType};
21use mln_gfx::gpu::{
22 BindGroupEntry, BindingsDesc, BindingsId, BufferId, DepthState, Draw, DynamicState, FixedState, GeometryDesc,
23 GeometryId, Gpu, GpuError, MAX_BASE_VERTEX, PipelineId, PipelineKey, SamplerId, Scissor, ShaderId, ShaderKey,
24 StencilState, TargetFormats, TextureId, VertexAttribute as GpuVertexAttribute, VertexBufferLayout, VertexStep,
25};
26use mln_gfx::shaders::bindings::{BUFFER_IDS, MAX_TEXTURES};
27use mln_gfx::shaders::program::Program;
28use mln_gfx::stencil_mode::StencilMode;
29use mln_gfx::texture2d::SamplerState;
30use mln_style::hash::HashMap;
31use smallvec::SmallVec;
32
33use crate::draw::buffer::Buffer;
34use crate::draw::context::Context;
35use crate::draw::identity::SimpleIdentity;
36use crate::draw::indexes::DrawIndexes;
37use crate::draw::owned::{Held, Owned};
38use crate::draw::range::DrawRange;
39use crate::draw::resources::{Device, Resources};
40use crate::draw::store::{IndexBuffer, MeshKey, Shared, Texture, WeakShared};
41use crate::draw::uniform_buffer::UniformBufferArray;
42use crate::draw::upload::{self, AttributeBindingArray, AttributeSlots};
43use crate::draw::vertex::{VertexBinding, attributes_of, replace_attributes};
44use crate::draw::vertex_attribute::VertexAttributeArray;
45use crate::draw::vertices::VertexBuffer;
46use crate::log_target;
47use crate::render::paint_parameters::{DrawTarget, PaintParameters};
48
49pub type Textures = [Option<Texture>; MAX_TEXTURES];
51
52const MAX_VERTEX_BUFFERS: usize = 8;
54
55pub(crate) struct DrawGeometry {
58 pub(crate) vertices: VertexAttributeArray,
60 pub(crate) vertex_count: usize,
63 pub(crate) mode: DrawMode,
65 pub(crate) indexes: DrawIndexes,
66 pub(crate) ranges: Vec<DrawRange>,
68 pub(crate) instances: Option<VertexAttributeArray>,
70}
71
72#[must_use]
75pub(crate) fn raw_vertices(
76 name: &'static str,
77 data: Vec<u8>,
78 count: usize,
79 data_type: AttributeDataType,
80) -> VertexAttributeArray {
81 let mut attributes = VertexAttributeArray::new();
82 if count == 0 || data.is_empty() {
83 return attributes;
84 }
85 attributes.set_own(name, data_type, data);
86 attributes
87}
88
89const MAX_STORAGE_VERTICES: usize = 3;
91
92const MAX_ENTRIES: usize = BUFFER_IDS + MAX_STORAGE_VERTICES + MAX_TEXTURES;
94
95pub(crate) struct Entries {
99 entries: [BindGroupEntry; MAX_ENTRIES],
100 len: usize,
101}
102
103impl Entries {
104 pub(crate) fn new() -> Entries {
105 let none = BindGroupEntry::Texture { slot: 0, texture: TextureId::default(), sampler: SamplerId::default() };
106 Entries { entries: [none; MAX_ENTRIES], len: 0 }
107 }
108
109 pub(crate) fn push(&mut self, entry: BindGroupEntry) {
110 self.entries[self.len] = entry;
111 self.len += 1;
112 }
113
114 pub(crate) fn as_slice(&self) -> &[BindGroupEntry] {
115 &self.entries[..self.len]
116 }
117}
118
119type SegmentGeometry = (usize, Owned<GeometryId>);
125
126struct GeometryParts<'a> {
129 shader: ShaderId,
130 layouts: &'a [VertexBufferLayout],
131 slots: &'a [VertexSlot],
132 index_buffer: BufferId,
133 index_held: Option<Held>,
134}
135
136fn segment_geometry(
139 gpu: &mut dyn Gpu,
140 context: &Context,
141 parts: GeometryParts<'_>,
142 start: usize,
143) -> Result<Owned<GeometryId>, GpuError> {
144 let GeometryParts { shader, layouts, slots, index_buffer, index_held } = parts;
145 let mut buffers = [(BufferId::default(), 0); MAX_VERTEX_BUFFERS];
147 for (buffer, slot) in buffers.iter_mut().zip(slots) {
148 let skipped = match slot.layout.step {
149 VertexStep::Vertex => start as u64 * u64::from(slot.layout.stride),
150 VertexStep::Instance => 0,
151 };
152 *buffer = (slot.buffer, slot.offset + skipped);
153 }
154 let geometry =
155 gpu.create_geometry(&GeometryDesc { shader, layouts, vertex_buffers: &buffers[..slots.len()], index_buffer })?;
156 let len = slots.iter().filter(|slot| slot.held.is_some()).count() + usize::from(index_held.is_some());
158 let mut held = Vec::with_capacity(len);
159 held.extend(slots.iter().filter_map(|slot| slot.held.clone()).chain(index_held));
160 Ok(context.own(geometry, held))
161}
162
163struct VertexSlot {
166 buffer: BufferId,
167 held: Option<Held>,
168 offset: u64,
169 layout: VertexBufferLayout,
170}
171
172#[derive(Clone, Copy, PartialEq)]
177struct BindingsStamp {
178 global: u64,
179 storage: u64,
180 textures: [Option<(TextureId, SamplerId)>; MAX_TEXTURES],
181}
182
183struct MeshBindings {
185 mesh: WeakShared<MeshKey>,
186 bindings: Owned<BindingsId>,
187 stamp: BindingsStamp,
188}
189
190#[derive(Default)]
197pub(crate) struct DrawBuffers {
198 buffers: UniformBufferArray,
199 bindings: HashMap<SimpleIdentity, MeshBindings>,
200}
201
202impl DrawBuffers {
203 pub(crate) fn get(&self, id: usize) -> Option<&Buffer> {
205 self.buffers.get(id)
206 }
207
208 pub(crate) fn write_pod<T: bytemuck::Pod>(&mut self, gpu: &mut dyn Gpu, id: usize, value: &T, device: &mut Device) {
211 let epoch = self.buffers.epoch();
212 let _replaced = self.buffers.write_pod(gpu, id, value, device);
213 self.made(epoch);
214 }
215
216 pub(crate) fn write_uniform(&mut self, gpu: &mut dyn Gpu, id: usize, data: &[u8], device: &mut Device) {
219 let epoch = self.buffers.epoch();
220 let _replaced = self.buffers.write_uniform(gpu, id, data, device);
221 self.made(epoch);
222 }
223
224 pub(crate) fn write_storage(&mut self, gpu: &mut dyn Gpu, id: usize, data: &[u8], device: &mut Device) {
227 let epoch = self.buffers.epoch();
228 let _replaced = self.buffers.write_storage(gpu, id, data, device);
229 self.made(epoch);
230 }
231
232 fn made(&mut self, epoch: u64) {
235 if self.buffers.epoch() != epoch {
236 self.bindings.clear();
237 }
238 }
239
240 pub(crate) fn sweep(&mut self) {
242 self.bindings.retain(|_, made| made.mesh.is_held());
243 }
244
245 fn bindings(
250 &mut self,
251 gpu: &mut dyn Gpu,
252 context: &mut Context,
253 mesh: &DrawObjects,
254 shader_id: ShaderId,
255 ) -> Result<BindingsId, GpuError> {
256 let program = mesh.shader.program();
257 let mut textures = [None; MAX_TEXTURES];
258 for slot in sampled_slots(program) {
259 if let Some(texture) = mesh.textures.get(slot).and_then(Option::as_ref) {
260 textures[slot] = Some(context.texture_binding(gpu, texture, mesh.samplers[slot])?);
261 }
262 }
263 let global = context.global_uniform_buffers();
264 let stamp = BindingsStamp { global: global.epoch(), storage: mesh.storage_epoch, textures };
265 if let Some(made) = self.bindings.get(&mesh.id)
266 && made.stamp == stamp
267 {
268 return Ok(made.bindings.id());
269 }
270 self.bindings.remove(&mesh.id);
271 let mut entries = Entries::new();
272 for id in 0..BUFFER_IDS {
273 let buffer = self.buffers.get(id).or_else(|| global.get(id));
275 if let Some(buffer) = buffer {
276 entries.push(BindGroupEntry::Buffer {
277 id: id as u32,
278 buffer: buffer.id(),
279 offset: 0,
280 size: buffer.size() as u64,
281 });
282 }
283 }
284 let mut held = Vec::new();
285 for (id, vertices, buffer) in &mesh.storage_vertices {
286 let size = context.vertices(vertices).map_or(0, |stored| stored.count() * stored.vertex_size());
287 if let Some(buffer) = buffer.filter(|_| size > 0) {
288 entries.push(BindGroupEntry::Buffer { id: *id as u32, buffer, offset: 0, size: size as u64 });
289 held.push(vertices.held());
290 }
291 }
292 for (slot, binding) in textures.iter().enumerate() {
293 if let Some((texture, sampler)) = *binding {
294 entries.push(BindGroupEntry::Texture { slot: slot as u32, texture, sampler });
295 }
296 }
297 held.extend(
298 sampled_slots(program)
299 .filter_map(|slot| context.gpu_texture(mesh.textures.get(slot)?.as_ref()?).cloned().map(Held::Texture)),
300 );
301 let bindings =
302 gpu.create_bindings(&BindingsDesc { label: program.name, shader: shader_id, entries: entries.as_slice() })?;
303 let made = MeshBindings { mesh: mesh.handle.clone(), bindings: context.own(bindings, held), stamp };
304 self.bindings.insert(mesh.id, made);
305 Ok(bindings)
306 }
307
308 #[cfg(test)]
310 pub(crate) fn bind(
311 &mut self,
312 gpu: &mut dyn Gpu,
313 context: &mut Context,
314 mesh: &Mesh,
315 ) -> Result<BindingsId, GpuError> {
316 let objects = context.take_mesh(mesh).ok_or(GpuError::UnknownId("mesh"))?;
317 let bound =
318 context.shader(gpu, &objects.shader).and_then(|shader| self.bindings(gpu, context, &objects, shader));
319 context.put_mesh(mesh, objects);
320 bound
321 }
322
323 #[cfg(test)]
325 pub(crate) fn bound_meshes(&self) -> usize {
326 self.bindings.len()
327 }
328}
329
330#[derive(Clone, Copy, PartialEq)]
332struct PipelineVariant {
333 primitive: DrawModeType,
334 depth: DepthState,
335 stencil: StencilState,
336 targets: TargetFormats,
337}
338
339pub(crate) struct DrawObjects {
346 id: SimpleIdentity,
349 handle: WeakShared<MeshKey>,
352 shader: ShaderKey,
353 vertex_attributes: VertexAttributeArray,
354 instance_attributes: Option<VertexAttributeArray>,
356 vertex_attributes_changed: bool,
359 instance_attributes_changed: bool,
362 vertex_slots_of: AttributeSlots,
365 instance_slots_of: AttributeSlots,
366 textures: Textures,
368 samplers: [Option<SamplerState>; MAX_TEXTURES],
371 storage_vertices: Vec<(usize, VertexBuffer, Option<BufferId>)>,
375 storage_epoch: u64,
377 color_mode: ColorMode,
378 cull_face_mode: CullFaceMode,
379
380 mode: DrawMode,
381 ranges: Vec<DrawRange>,
382 indexes: DrawIndexes,
383 vertex_count: usize,
384 attribute_bindings: AttributeBindingArray,
385 instance_bindings: AttributeBindingArray,
386 vertex_slots: Option<Vec<VertexSlot>>,
389 shader_id: Option<ShaderId>,
391 pipelines: Vec<(PipelineVariant, PipelineId)>,
394 pipeline_layouts: Vec<VertexBufferLayout>,
397 geometry: Option<(BufferId, SmallVec<[SegmentGeometry; 1]>)>,
402}
403
404impl DrawObjects {
405 #[must_use]
408 pub(crate) fn new(
409 shader: ShaderKey,
410 color_mode: ColorMode,
411 cull_face_mode: CullFaceMode,
412 geometry: DrawGeometry,
413 textures: Textures,
414 ) -> Self {
415 let DrawGeometry { vertices, vertex_count, mode, indexes, ranges, instances } = geometry;
416 DrawObjects {
417 id: SimpleIdentity::new(),
418 handle: WeakShared::default(),
419 shader,
420 vertex_attributes: vertices,
421 instance_attributes: instances,
422 vertex_attributes_changed: true,
423 instance_attributes_changed: true,
424 vertex_slots_of: AttributeSlots::default(),
425 instance_slots_of: AttributeSlots::default(),
426 textures,
427 samplers: [None; MAX_TEXTURES],
428 storage_vertices: Vec::new(),
429 storage_epoch: 0,
430 color_mode,
431 cull_face_mode,
432 mode,
433 ranges,
434 indexes,
435 vertex_count,
436 attribute_bindings: Vec::new(),
437 instance_bindings: Vec::new(),
438 vertex_slots: None,
439 shader_id: None,
440 pipelines: Vec::new(),
441 pipeline_layouts: Vec::new(),
442 geometry: None,
443 }
444 }
445
446 pub(crate) fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context) {
449 if let Err(error) = self.upload_in(gpu, context) {
450 context.fail(format!("Uploading {} failed: {error}", self.shader.program().name));
451 }
452 }
453
454 fn upload_in(&mut self, gpu: &mut dyn Gpu, context: &mut Context) -> Result<(), GpuError> {
455 let program = self.shader.program();
456 if self.indexes.buffer(context).is_none() && self.indexes.len(context) == 0 {
457 debug_assert!(false, "a draw of {} has no index data", program.name);
458 return Ok(());
459 }
460 self.indexes.upload(gpu, context)?;
461
462 if self.vertex_attributes_changed
466 || upload::needs_upload(context, &self.vertex_attributes, &self.vertex_slots_of)
467 {
468 let updated = upload::update_attribute_bindings(
469 gpu,
470 context,
471 &self.shader,
472 program.attributes,
473 self.vertex_count,
474 upload::AttributeBindingState {
475 overrides: &mut self.vertex_attributes,
476 slots: &mut self.vertex_slots_of,
477 bindings: &mut self.attribute_bindings,
478 },
479 );
480 if !matches!(updated, Ok(false)) {
481 self.vertex_slots = None;
482 self.geometry = None;
483 }
484 updated?;
485 }
486
487 let changed = self.instance_attributes_changed;
488 if let Some(attrs) = self
489 .instance_attributes
490 .as_mut()
491 .filter(|attrs| changed || upload::needs_upload(context, attrs, &self.instance_slots_of))
492 {
493 let instance_count = attrs.min_count();
494 let updated = upload::update_attribute_bindings(
495 gpu,
496 context,
497 &self.shader,
498 program.instance_attributes,
499 instance_count,
500 upload::AttributeBindingState {
501 overrides: attrs,
502 slots: &mut self.instance_slots_of,
503 bindings: &mut self.instance_bindings,
504 },
505 );
506 if !matches!(updated, Ok(false)) {
507 self.vertex_slots = None;
508 self.geometry = None;
509 }
510 updated?;
511 }
512
513 self.vertex_attributes_changed = false;
514 self.instance_attributes_changed = false;
515
516 for (_, vertices, bound) in &mut self.storage_vertices {
517 let buffer = context.upload_vertices(gpu, vertices)?;
518 if *bound != buffer {
519 *bound = buffer;
520 self.storage_epoch += 1;
521 }
522 }
523
524 for texture in self.textures.iter().flatten() {
525 if let Err(error) = context.upload_texture(gpu, texture) {
526 context.fail(format!("Uploading a texture failed: {error}"));
527 }
528 }
529
530 Ok(())
531 }
532
533 #[must_use]
535 pub(crate) fn program(&self) -> &'static Program {
536 self.shader.program()
537 }
538
539 pub(crate) fn draw(
546 &mut self,
547 gpu: &mut dyn Gpu,
548 parameters: &mut PaintParameters<'_>,
549 frame: &mut DrawBuffers,
550 depth_mode: DepthMode,
551 stencil_mode: StencilMode,
552 global_index: u32,
553 ) -> bool {
554 let drawn = self.draw_in(gpu, parameters, frame, depth_mode, stencil_mode, global_index);
555 if let Err(error) = &drawn {
556 parameters.context.fail(format!("Drawing {} failed: {error}", self.shader.program().name));
557 }
558 drawn.is_ok()
559 }
560
561 fn draw_in(
562 &mut self,
563 gpu: &mut dyn Gpu,
564 parameters: &mut PaintParameters<'_>,
565 frame: &mut DrawBuffers,
566 depth_mode: DepthMode,
567 stencil_mode: StencilMode,
568 global_index: u32,
569 ) -> Result<(), GpuError> {
570 let Some(DrawTarget { size, targets, scissor }) = parameters.draw_target() else {
571 return Ok(());
572 };
573 let context = &mut *parameters.context;
574 let Some(index_buffer) = self.indexes.buffer(context) else {
575 debug_assert!(
578 context.device().failed(),
579 "a draw of {} draws indexes it didn't upload",
580 self.shader.program().name
581 );
582 return Err(GpuError::Invalid("its indexes aren't uploaded".to_owned()));
583 };
584
585 let shader_id = match self.shader_id {
586 Some(id) => id,
587 None => *self.shader_id.insert(context.shader(gpu, &self.shader)?),
588 };
589 let bindings = frame.bindings(gpu, context, self, shader_id)?;
590 let slots = if let Some(slots) = &self.vertex_slots {
591 slots
592 } else {
593 let slots = vertex_slots(self.shader.program(), &self.attribute_bindings, &self.instance_bindings);
594 let layouts = slots.iter().map(|slot| &slot.layout);
597 if !layouts.clone().eq(self.pipeline_layouts.iter()) {
598 self.pipeline_layouts = layouts.cloned().collect();
599 self.pipelines.clear();
600 }
601 self.vertex_slots.insert(slots)
602 };
603 let geometries = match &mut self.geometry {
604 Some((indices, geometries)) if *indices == index_buffer => geometries,
605 geometry => &mut geometry.insert((index_buffer, SmallVec::new())).1,
606 };
607 let full = Scissor { x: 0, y: 0, width: size.width, height: size.height };
608 let dynamic = DynamicState {
609 depth_range: depth_mode.range,
610 scissor: scissor.unwrap_or(full),
611 stencil_reference: stencil_mode.ref_ as u32,
612 blend_constant: self.color_mode.blend_color,
613 line_width: 1.0,
614 };
615 let depth = DepthState::from(&depth_mode);
616 let stencil = StencilState::from(&stencil_mode);
617 let mut draws = 0;
618 let mode = self.mode;
619 for range in &self.ranges {
620 if range.index_count == 0 {
621 continue;
622 }
623 let variant = PipelineVariant { primitive: mode.kind, depth, stencil, targets };
624 let pipeline = if let Some(&(_, id)) = self.pipelines.iter().find(|(cached, _)| *cached == variant) {
625 id
626 } else {
627 let key = PipelineKey {
628 shader: shader_id,
629 vertex_buffers: self.pipeline_layouts.clone(),
630 state: fixed_state(variant, &self.color_mode, self.cull_face_mode),
631 targets,
632 };
633 let id = context.pipeline(gpu, &key)?;
634 self.pipelines.push((variant, id));
635 id
636 };
637 let line_width = if mode.primitive_type() == PrimitiveType::Line { mode.size } else { 1.0 };
638 let (start, base_vertex) = if range.base_vertex <= MAX_BASE_VERTEX {
639 (0, range.base_vertex)
640 } else {
641 (range.base_vertex as usize, 0)
642 };
643 let geometry = if let Some((_, geometry)) = geometries.iter().find(|(at, _)| *at == start) {
644 geometry.id()
645 } else {
646 let geometry = segment_geometry(
647 gpu,
648 context,
649 GeometryParts {
650 shader: shader_id,
651 layouts: &self.pipeline_layouts,
652 slots,
653 index_buffer,
654 index_held: self.indexes.held(),
655 },
656 start,
657 )?;
658 let id = geometry.id();
659 geometries.push((start, geometry));
660 id
661 };
662 gpu.draw(&Draw {
663 pipeline,
664 bindings,
665 geometry,
666 first_index: range.first_index,
667 index_count: range.index_count,
668 base_vertex,
669 first_instance: range.first_instance,
670 instance_count: range.instance_count,
671 global_index,
672 dynamic: DynamicState { line_width, ..dynamic },
673 })?;
674 draws += 1;
675 }
676 let stats = context.rendering_stats();
677 stats.num_draw_calls += draws;
678 stats.total_draw_calls += draws;
679 Ok(())
680 }
681
682 pub(crate) fn vertex_attributes_mut(&mut self) -> &mut VertexAttributeArray {
686 self.vertex_attributes_changed = true;
687 if self.vertex_attributes.has_own() {
688 self.geometry = None;
689 }
690 &mut self.vertex_attributes
691 }
692
693 pub(crate) fn paint_attributes_mut(&mut self) -> &mut VertexAttributeArray {
697 let (attributes, changed) = match &mut self.instance_attributes {
698 Some(instances) => (instances, &mut self.instance_attributes_changed),
699 None => (&mut self.vertex_attributes, &mut self.vertex_attributes_changed),
700 };
701 *changed = true;
702 if attributes.has_own() {
703 self.geometry = None;
704 }
705 attributes
706 }
707
708 pub(crate) fn read_as_storage(&mut self, id: usize, vertices: Option<VertexBuffer>) {
713 debug_assert!(id >= BUFFER_IDS, "a uniform buffer's id");
714 self.storage_vertices.retain(|(at, ..)| *at != id);
715 debug_assert!(vertices.is_none() || self.storage_vertices.len() < MAX_STORAGE_VERTICES);
716 if let Some(vertices) = vertices {
717 self.storage_vertices.push((id, vertices, None));
718 }
719 self.storage_epoch += 1;
720 }
721
722 pub(crate) fn storage_buffer(&self, id: usize) -> Option<BufferId> {
725 self.storage_vertices.iter().find(|(at, ..)| *at == id).and_then(|&(_, _, buffer)| buffer)
726 }
727
728 #[must_use]
730 pub(crate) fn has_instances(&self) -> bool {
731 self.instance_attributes.is_some()
732 }
733
734 #[must_use]
736 pub(crate) fn texture(&self, slot: usize) -> Option<&Texture> {
737 self.textures[slot].as_ref()
738 }
739
740 pub(crate) fn set_texture(&mut self, slot: usize, texture: Option<&Texture>) {
743 let bound = &mut self.textures[slot];
744 if bound.as_ref() != texture {
745 *bound = texture.cloned();
746 }
747 }
748
749 pub(crate) fn set_sampler(&mut self, slot: usize, state: Option<SamplerState>) {
752 self.samplers[slot] = state;
753 }
754
755 pub(crate) fn replace_indexes(&mut self, indexes: DrawIndexes, ranges: Vec<DrawRange>) {
757 if let DrawIndexes::Own(_) = self.indexes {
758 self.geometry = None;
759 }
760 self.indexes = indexes;
761 self.ranges = ranges;
762 }
763
764 pub(crate) fn set_cull_face_mode(&mut self, cull_face_mode: CullFaceMode) {
766 if self.cull_face_mode != cull_face_mode {
767 self.cull_face_mode = cull_face_mode;
768 self.pipelines.clear();
770 }
771 }
772}
773
774pub struct MeshDesc {
783 pub shader: ShaderKey,
784 pub color_mode: ColorMode,
785 pub cull_face_mode: CullFaceMode,
786 pub mode: DrawMode,
787 pub vertices: Vec<VertexBinding>,
788 pub vertex_count: usize,
789 pub instances: Option<Vec<VertexBinding>>,
790 pub indexes: IndexBuffer,
791 pub ranges: Vec<DrawRange>,
792 pub textures: Textures,
793}
794
795#[derive(Clone)]
805pub struct Mesh {
806 key: Shared<MeshKey>,
807 id: SimpleIdentity,
808 program: &'static Program,
809}
810
811impl Mesh {
812 #[must_use]
814 pub(crate) fn of(context: &mut Context, desc: MeshDesc) -> Self {
815 let MeshDesc {
816 shader,
817 color_mode,
818 cull_face_mode,
819 mode,
820 vertices,
821 vertex_count,
822 instances,
823 indexes,
824 ranges,
825 textures,
826 } = desc;
827 let geometry = DrawGeometry {
828 vertices: attributes_of(&vertices),
829 vertex_count,
830 mode,
831 indexes: DrawIndexes::Shared(indexes),
832 ranges,
833 instances: instances.as_deref().map(attributes_of),
834 };
835 Mesh::new(context, shader, color_mode, cull_face_mode, geometry, textures)
836 }
837
838 #[must_use]
841 pub(crate) fn new(
842 context: &mut Context,
843 shader: ShaderKey,
844 color_mode: ColorMode,
845 cull_face_mode: CullFaceMode,
846 geometry: DrawGeometry,
847 textures: Textures,
848 ) -> Self {
849 let mut objects = DrawObjects::new(shader, color_mode, cull_face_mode, geometry, textures);
850 let (id, program) = (objects.id, objects.program());
851 let key = context.add_mesh_with(|key| {
852 objects.handle = key.downgrade();
853 objects
854 });
855 Mesh { key, id, program }
856 }
857
858 pub(crate) fn key(&self) -> &Shared<MeshKey> {
860 &self.key
861 }
862
863 #[must_use]
866 pub fn seq(&self) -> i64 {
867 self.id.get() as i64
868 }
869
870 #[must_use]
872 pub fn program(&self) -> &'static Program {
873 self.program
874 }
875
876 pub(crate) fn update<R>(
879 &self,
880 context: &mut Context,
881 f: impl FnOnce(&mut DrawObjects, &mut Context) -> R,
882 ) -> Option<R> {
883 let mut objects = context.take_mesh(self)?;
884 let result = f(&mut objects, context);
885 context.put_mesh(self, objects);
886 Some(result)
887 }
888
889 pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
891 self.update(context, |objects, context| objects.upload(gpu, context));
892 }
893
894 pub(crate) fn vertex_attributes_mut<'c>(&self, context: &'c mut Context) -> Option<&'c mut VertexAttributeArray> {
896 context.mesh_mut(self).map(DrawObjects::vertex_attributes_mut)
897 }
898
899 pub fn set_vertices<'b>(&self, res: &mut Resources<'_>, bindings: impl IntoIterator<Item = &'b VertexBinding>) {
902 if let Some(attrs) = self.vertex_attributes_mut(res.context) {
903 replace_attributes(attrs, bindings);
904 }
905 }
906
907 pub fn bind_vertices(&self, res: &mut Resources<'_>, binding: &VertexBinding) {
910 if let Some(attrs) = self.vertex_attributes_mut(res.context) {
911 binding.bind(attrs);
912 }
913 }
914
915 pub fn set_paint(&self, res: &mut Resources<'_>, paint: &VertexBinding) {
921 if let Some(objects) = res.context.mesh_mut(self) {
922 paint.bind(objects.paint_attributes_mut());
923 }
924 }
925
926 pub fn read_as_storage(&self, res: &mut Resources<'_>, id: usize, vertices: Option<VertexBuffer>) {
928 if let Some(objects) = res.context.mesh_mut(self) {
929 objects.read_as_storage(id, vertices);
930 }
931 }
932
933 #[must_use]
935 pub(crate) fn storage_buffer(&self, context: &Context, id: usize) -> Option<BufferId> {
936 context.mesh(self)?.storage_buffer(id)
937 }
938
939 #[must_use]
941 pub fn has_instances(&self, res: &Resources<'_>) -> bool {
942 res.context.mesh(self).is_some_and(DrawObjects::has_instances)
943 }
944
945 #[must_use]
947 pub fn texture<'r>(&self, res: &'r Resources<'_>, slot: usize) -> Option<&'r Texture> {
948 res.context.mesh(self)?.texture(slot)
949 }
950
951 pub fn set_texture(&self, res: &mut Resources<'_>, slot: usize, texture: Option<&Texture>) {
953 if let Some(objects) = res.context.mesh_mut(self) {
954 objects.set_texture(slot, texture);
955 }
956 }
957
958 pub fn set_sampler(&self, res: &mut Resources<'_>, slot: usize, state: Option<SamplerState>) {
960 if let Some(objects) = res.context.mesh_mut(self) {
961 objects.set_sampler(slot, state);
962 }
963 }
964
965 pub fn replace_indexes(&self, res: &mut Resources<'_>, indexes: IndexBuffer, ranges: Vec<DrawRange>) {
967 if let Some(objects) = res.context.mesh_mut(self) {
968 objects.replace_indexes(DrawIndexes::Shared(indexes), ranges);
969 }
970 }
971
972 pub fn set_cull_face_mode(&self, res: &mut Resources<'_>, cull_face_mode: CullFaceMode) {
974 if let Some(objects) = res.context.mesh_mut(self) {
975 objects.set_cull_face_mode(cull_face_mode);
976 }
977 }
978}
979
980fn sampled_slots(program: &Program) -> impl Iterator<Item = usize> + use<> {
982 let textures = program.textures;
983 (0..textures.len()).filter(move |&slot| !textures[slot].is_unused())
984}
985
986fn fixed_state(variant: PipelineVariant, color_mode: &ColorMode, cull: CullFaceMode) -> FixedState {
987 FixedState {
988 primitive: variant.primitive,
989 cull,
990 blend: color_mode.blend_function,
991 color_mask: color_mode.mask,
992 depth: variant.depth,
993 stencil: variant.stencil,
994 }
995}
996
997fn vertex_slots(
1005 program: &Program,
1006 attributes: &AttributeBindingArray,
1007 instances: &AttributeBindingArray,
1008) -> Vec<VertexSlot> {
1009 let mut slots: Vec<VertexSlot> = Vec::new();
1010 for (bindings, step) in [(attributes, VertexStep::Vertex), (instances, VertexStep::Instance)] {
1011 let (count, first) = match step {
1012 VertexStep::Vertex => (program.attributes.len(), 0),
1013 VertexStep::Instance => (program.instance_attributes.len(), program.attributes.len()),
1014 };
1015 for (index, binding) in bindings.iter().enumerate().take(count) {
1016 let Some(binding) = binding else { continue };
1017 let buffer = &binding.buffer;
1018 let offset = u64::from(binding.vertex_offset) * u64::from(binding.vertex_stride);
1019 let attribute = GpuVertexAttribute {
1020 location: (first + index) as u32,
1021 format: binding.attribute.data_type,
1022 offset: binding.attribute.offset,
1023 };
1024 let shared = slots.iter_mut().find(|slot| {
1025 slot.buffer == *buffer
1026 && slot.layout.stride == binding.vertex_stride
1027 && slot.layout.step == step
1028 && slot.offset == offset
1029 });
1030 match shared {
1031 Some(slot) => slot.layout.attributes.push(attribute),
1032 None => slots.push(VertexSlot {
1033 buffer: *buffer,
1034 held: binding.held.clone(),
1035 offset,
1036 layout: VertexBufferLayout { stride: binding.vertex_stride, step, attributes: vec![attribute] },
1037 }),
1038 }
1039 }
1040 }
1041 if slots.len() > MAX_VERTEX_BUFFERS {
1042 tracing::warn!(
1043 target: log_target::RENDER,
1044 program = program.name,
1045 count = slots.len(),
1046 expected = MAX_VERTEX_BUFFERS,
1047 "A program uses more vertex buffers than the limit"
1048 );
1049 slots.truncate(MAX_VERTEX_BUFFERS);
1050 }
1051 slots
1052}