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_type == AttributeDataType::Invalid || 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
126#[expect(clippy::too_many_arguments, reason = "the parts of a mesh that its geometry is made of")]
129fn segment_geometry(
130 gpu: &mut dyn Gpu,
131 context: &Context,
132 shader: ShaderId,
133 layouts: &[VertexBufferLayout],
134 slots: &[VertexSlot],
135 index_buffer: BufferId,
136 index_held: Option<Held>,
137 start: usize,
138) -> Result<Owned<GeometryId>, GpuError> {
139 let mut buffers = [(BufferId::default(), 0); MAX_VERTEX_BUFFERS];
141 for (buffer, slot) in buffers.iter_mut().zip(slots) {
142 let skipped = match slot.layout.step {
143 VertexStep::Vertex => start as u64 * u64::from(slot.layout.stride),
144 VertexStep::Instance => 0,
145 };
146 *buffer = (slot.buffer, slot.offset + skipped);
147 }
148 let geometry =
149 gpu.create_geometry(&GeometryDesc { shader, layouts, vertex_buffers: &buffers[..slots.len()], index_buffer })?;
150 let len = slots.iter().filter(|slot| slot.held.is_some()).count() + usize::from(index_held.is_some());
152 let mut held = Vec::with_capacity(len);
153 held.extend(slots.iter().filter_map(|slot| slot.held.clone()).chain(index_held));
154 Ok(context.own(geometry, held))
155}
156
157struct VertexSlot {
160 buffer: BufferId,
161 held: Option<Held>,
162 offset: u64,
163 layout: VertexBufferLayout,
164}
165
166#[derive(Clone, Copy, PartialEq)]
171struct BindingsStamp {
172 global: u64,
173 storage: u64,
174 textures: [Option<(TextureId, SamplerId)>; MAX_TEXTURES],
175}
176
177struct MeshBindings {
179 mesh: WeakShared<MeshKey>,
180 bindings: Owned<BindingsId>,
181 stamp: BindingsStamp,
182}
183
184#[derive(Default)]
191pub(crate) struct DrawBuffers {
192 buffers: UniformBufferArray,
193 bindings: HashMap<SimpleIdentity, MeshBindings>,
194}
195
196impl DrawBuffers {
197 pub(crate) fn get(&self, id: usize) -> Option<&Buffer> {
199 self.buffers.get(id)
200 }
201
202 pub(crate) fn write_pod<T: bytemuck::Pod>(&mut self, gpu: &mut dyn Gpu, id: usize, value: &T, device: &mut Device) {
205 let epoch = self.buffers.epoch();
206 let _replaced = self.buffers.write_pod(gpu, id, value, device);
207 self.made(epoch);
208 }
209
210 pub(crate) fn write_uniform(&mut self, gpu: &mut dyn Gpu, id: usize, data: &[u8], device: &mut Device) {
213 let epoch = self.buffers.epoch();
214 let _replaced = self.buffers.write_uniform(gpu, id, data, device);
215 self.made(epoch);
216 }
217
218 pub(crate) fn write_storage(&mut self, gpu: &mut dyn Gpu, id: usize, data: &[u8], device: &mut Device) {
221 let epoch = self.buffers.epoch();
222 let _replaced = self.buffers.write_storage(gpu, id, data, device);
223 self.made(epoch);
224 }
225
226 fn made(&mut self, epoch: u64) {
229 if self.buffers.epoch() != epoch {
230 self.bindings.clear();
231 }
232 }
233
234 pub(crate) fn sweep(&mut self) {
236 self.bindings.retain(|_, made| made.mesh.is_held());
237 }
238
239 fn bindings(
244 &mut self,
245 gpu: &mut dyn Gpu,
246 context: &mut Context,
247 mesh: &DrawObjects,
248 shader_id: ShaderId,
249 ) -> Result<BindingsId, GpuError> {
250 let program = mesh.shader.program();
251 let mut textures = [None; MAX_TEXTURES];
252 for slot in sampled_slots(program) {
253 if let Some(texture) = mesh.textures.get(slot).and_then(Option::as_ref) {
254 textures[slot] = Some(context.texture_binding(gpu, texture, mesh.samplers[slot])?);
255 }
256 }
257 let global = context.global_uniform_buffers();
258 let stamp = BindingsStamp { global: global.epoch(), storage: mesh.storage_epoch, textures };
259 if let Some(made) = self.bindings.get(&mesh.id)
260 && made.stamp == stamp
261 {
262 return Ok(made.bindings.id());
263 }
264 self.bindings.remove(&mesh.id);
265 let mut entries = Entries::new();
266 for id in 0..BUFFER_IDS {
267 let buffer = self.buffers.get(id).or_else(|| global.get(id));
269 if let Some(buffer) = buffer {
270 entries.push(BindGroupEntry::Buffer {
271 id: id as u32,
272 buffer: buffer.id(),
273 offset: 0,
274 size: buffer.size() as u64,
275 });
276 }
277 }
278 let mut held = Vec::new();
279 for (id, vertices, buffer) in &mesh.storage_vertices {
280 let size = context.vertices(vertices).map_or(0, |stored| stored.count() * stored.vertex_size());
281 if let Some(buffer) = buffer.filter(|_| size > 0) {
282 entries.push(BindGroupEntry::Buffer { id: *id as u32, buffer, offset: 0, size: size as u64 });
283 held.push(vertices.held());
284 }
285 }
286 for (slot, binding) in textures.iter().enumerate() {
287 if let Some((texture, sampler)) = *binding {
288 entries.push(BindGroupEntry::Texture { slot: slot as u32, texture, sampler });
289 }
290 }
291 held.extend(
292 sampled_slots(program)
293 .filter_map(|slot| context.gpu_texture(mesh.textures.get(slot)?.as_ref()?).cloned().map(Held::Texture)),
294 );
295 let bindings =
296 gpu.create_bindings(&BindingsDesc { label: program.name, shader: shader_id, entries: entries.as_slice() })?;
297 let made = MeshBindings { mesh: mesh.handle.clone(), bindings: context.own(bindings, held), stamp };
298 self.bindings.insert(mesh.id, made);
299 Ok(bindings)
300 }
301
302 #[cfg(test)]
304 pub(crate) fn bind(
305 &mut self,
306 gpu: &mut dyn Gpu,
307 context: &mut Context,
308 mesh: &Mesh,
309 ) -> Result<BindingsId, GpuError> {
310 let objects = context.take_mesh(mesh).ok_or(GpuError::UnknownId("mesh"))?;
311 let bound =
312 context.shader(gpu, &objects.shader).and_then(|shader| self.bindings(gpu, context, &objects, shader));
313 context.put_mesh(mesh, objects);
314 bound
315 }
316
317 #[cfg(test)]
319 pub(crate) fn bound_meshes(&self) -> usize {
320 self.bindings.len()
321 }
322}
323
324#[derive(Clone, Copy, PartialEq)]
326struct PipelineVariant {
327 primitive: DrawModeType,
328 depth: DepthState,
329 stencil: StencilState,
330 targets: TargetFormats,
331}
332
333pub(crate) struct DrawObjects {
340 id: SimpleIdentity,
343 handle: WeakShared<MeshKey>,
346 shader: ShaderKey,
347 vertex_attributes: VertexAttributeArray,
348 instance_attributes: Option<VertexAttributeArray>,
350 vertex_attributes_changed: bool,
353 instance_attributes_changed: bool,
356 vertex_slots_of: AttributeSlots,
359 instance_slots_of: AttributeSlots,
360 textures: Textures,
362 samplers: [Option<SamplerState>; MAX_TEXTURES],
365 storage_vertices: Vec<(usize, VertexBuffer, Option<BufferId>)>,
369 storage_epoch: u64,
371 color_mode: ColorMode,
372 cull_face_mode: CullFaceMode,
373
374 mode: DrawMode,
375 ranges: Vec<DrawRange>,
376 indexes: DrawIndexes,
377 vertex_count: usize,
378 attribute_bindings: AttributeBindingArray,
379 instance_bindings: AttributeBindingArray,
380 vertex_slots: Option<Vec<VertexSlot>>,
383 shader_id: Option<ShaderId>,
385 pipelines: Vec<(PipelineVariant, PipelineId)>,
388 pipeline_layouts: Vec<VertexBufferLayout>,
391 geometry: Option<(BufferId, SmallVec<[SegmentGeometry; 1]>)>,
396}
397
398impl DrawObjects {
399 #[must_use]
402 pub(crate) fn new(
403 shader: ShaderKey,
404 color_mode: ColorMode,
405 cull_face_mode: CullFaceMode,
406 geometry: DrawGeometry,
407 textures: Textures,
408 ) -> Self {
409 let DrawGeometry { vertices, vertex_count, mode, indexes, ranges, instances } = geometry;
410 DrawObjects {
411 id: SimpleIdentity::new(),
412 handle: WeakShared::default(),
413 shader,
414 vertex_attributes: vertices,
415 instance_attributes: instances,
416 vertex_attributes_changed: true,
417 instance_attributes_changed: true,
418 vertex_slots_of: AttributeSlots::default(),
419 instance_slots_of: AttributeSlots::default(),
420 textures,
421 samplers: [None; MAX_TEXTURES],
422 storage_vertices: Vec::new(),
423 storage_epoch: 0,
424 color_mode,
425 cull_face_mode,
426 mode,
427 ranges,
428 indexes,
429 vertex_count,
430 attribute_bindings: Vec::new(),
431 instance_bindings: Vec::new(),
432 vertex_slots: None,
433 shader_id: None,
434 pipelines: Vec::new(),
435 pipeline_layouts: Vec::new(),
436 geometry: None,
437 }
438 }
439
440 pub(crate) fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context) {
443 if let Err(error) = self.upload_in(gpu, context) {
444 context.fail(format!("Uploading {} failed: {error}", self.shader.program().name));
445 }
446 }
447
448 fn upload_in(&mut self, gpu: &mut dyn Gpu, context: &mut Context) -> Result<(), GpuError> {
449 let program = self.shader.program();
450 if self.indexes.buffer(context).is_none() && self.indexes.len(context) == 0 {
451 debug_assert!(false, "a draw of {} has no index data", program.name);
452 return Ok(());
453 }
454 self.indexes.upload(gpu, context)?;
455
456 if self.vertex_attributes_changed
460 || upload::needs_upload(context, &self.vertex_attributes, &self.vertex_slots_of)
461 {
462 let updated = upload::update_attribute_bindings(
463 gpu,
464 context,
465 program.attributes,
466 &mut self.vertex_attributes,
467 &mut self.vertex_slots_of,
468 self.vertex_count,
469 &mut self.attribute_bindings,
470 );
471 if !matches!(updated, Ok(false)) {
472 self.vertex_slots = None;
473 self.geometry = None;
474 }
475 updated?;
476 }
477
478 let changed = self.instance_attributes_changed;
479 if let Some(attrs) = self
480 .instance_attributes
481 .as_mut()
482 .filter(|attrs| changed || upload::needs_upload(context, attrs, &self.instance_slots_of))
483 {
484 let instance_count = attrs.min_count();
485 let updated = upload::update_attribute_bindings(
486 gpu,
487 context,
488 program.instance_attributes,
489 attrs,
490 &mut self.instance_slots_of,
491 instance_count,
492 &mut self.instance_bindings,
493 );
494 if !matches!(updated, Ok(false)) {
495 self.vertex_slots = None;
496 self.geometry = None;
497 }
498 updated?;
499 }
500
501 self.vertex_attributes_changed = false;
502 self.instance_attributes_changed = false;
503
504 for (_, vertices, bound) in &mut self.storage_vertices {
505 let buffer = context.upload_vertices(gpu, vertices)?;
506 if *bound != buffer {
507 *bound = buffer;
508 self.storage_epoch += 1;
509 }
510 }
511
512 for texture in self.textures.iter().flatten() {
513 if let Err(error) = context.upload_texture(gpu, texture) {
514 context.fail(format!("Uploading a texture failed: {error}"));
515 }
516 }
517
518 Ok(())
519 }
520
521 #[must_use]
523 pub(crate) fn program(&self) -> &'static Program {
524 self.shader.program()
525 }
526
527 pub(crate) fn draw(
534 &mut self,
535 gpu: &mut dyn Gpu,
536 parameters: &mut PaintParameters<'_>,
537 frame: &mut DrawBuffers,
538 depth_mode: DepthMode,
539 stencil_mode: StencilMode,
540 global_index: u32,
541 ) -> bool {
542 let drawn = self.draw_in(gpu, parameters, frame, depth_mode, stencil_mode, global_index);
543 if let Err(error) = &drawn {
544 parameters.context.fail(format!("Drawing {} failed: {error}", self.shader.program().name));
545 }
546 drawn.is_ok()
547 }
548
549 fn draw_in(
550 &mut self,
551 gpu: &mut dyn Gpu,
552 parameters: &mut PaintParameters<'_>,
553 frame: &mut DrawBuffers,
554 depth_mode: DepthMode,
555 stencil_mode: StencilMode,
556 global_index: u32,
557 ) -> Result<(), GpuError> {
558 let Some(DrawTarget { size, targets, scissor }) = parameters.draw_target() else {
559 return Ok(());
560 };
561 let context = &mut *parameters.context;
562 let Some(index_buffer) = self.indexes.buffer(context) else {
563 debug_assert!(
566 context.device().failed(),
567 "a draw of {} draws indexes it didn't upload",
568 self.shader.program().name
569 );
570 return Err(GpuError::Invalid("its indexes aren't uploaded".to_owned()));
571 };
572
573 let shader_id = match self.shader_id {
574 Some(id) => id,
575 None => *self.shader_id.insert(context.shader(gpu, &self.shader)?),
576 };
577 let bindings = frame.bindings(gpu, context, self, shader_id)?;
578 let slots = if let Some(slots) = &self.vertex_slots {
579 slots
580 } else {
581 let slots = vertex_slots(self.shader.program(), &self.attribute_bindings, &self.instance_bindings);
582 let layouts = slots.iter().map(|slot| &slot.layout);
585 if !layouts.clone().eq(self.pipeline_layouts.iter()) {
586 self.pipeline_layouts = layouts.cloned().collect();
587 self.pipelines.clear();
588 }
589 self.vertex_slots.insert(slots)
590 };
591 let geometries = match &mut self.geometry {
592 Some((indices, geometries)) if *indices == index_buffer => geometries,
593 geometry => &mut geometry.insert((index_buffer, SmallVec::new())).1,
594 };
595 let full = Scissor { x: 0, y: 0, width: size.width, height: size.height };
596 let dynamic = DynamicState {
597 depth_range: depth_mode.range,
598 scissor: scissor.unwrap_or(full),
599 stencil_reference: stencil_mode.ref_ as u32,
600 blend_constant: self.color_mode.blend_color,
601 line_width: 1.0,
602 };
603 let depth = DepthState::from(&depth_mode);
604 let stencil = StencilState::from(&stencil_mode);
605 let mut draws = 0;
606 let mode = self.mode;
607 for range in &self.ranges {
608 if range.index_count == 0 {
609 continue;
610 }
611 let variant = PipelineVariant { primitive: mode.type_, depth, stencil, targets };
612 let pipeline = if let Some(&(_, id)) = self.pipelines.iter().find(|(cached, _)| *cached == variant) {
613 id
614 } else {
615 let key = PipelineKey {
616 shader: shader_id,
617 vertex_buffers: self.pipeline_layouts.clone(),
618 state: fixed_state(variant, &self.color_mode, self.cull_face_mode),
619 targets,
620 };
621 let id = context.pipeline(gpu, &key)?;
622 self.pipelines.push((variant, id));
623 id
624 };
625 let line_width = if mode.primitive_type() == PrimitiveType::Line { mode.size } else { 1.0 };
626 let (start, base_vertex) = if range.base_vertex <= MAX_BASE_VERTEX {
627 (0, range.base_vertex)
628 } else {
629 (range.base_vertex as usize, 0)
630 };
631 let geometry = if let Some((_, geometry)) = geometries.iter().find(|(at, _)| *at == start) {
632 geometry.id()
633 } else {
634 let geometry = segment_geometry(
635 gpu,
636 context,
637 shader_id,
638 &self.pipeline_layouts,
639 slots,
640 index_buffer,
641 self.indexes.held(),
642 start,
643 )?;
644 let id = geometry.id();
645 geometries.push((start, geometry));
646 id
647 };
648 gpu.draw(&Draw {
649 pipeline,
650 bindings,
651 geometry,
652 first_index: range.first_index,
653 index_count: range.index_count,
654 base_vertex,
655 first_instance: range.first_instance,
656 instance_count: range.instance_count,
657 global_index,
658 dynamic: DynamicState { line_width, ..dynamic },
659 })?;
660 draws += 1;
661 }
662 let stats = context.rendering_stats();
663 stats.num_draw_calls += draws;
664 stats.total_draw_calls += draws;
665 Ok(())
666 }
667
668 pub(crate) fn vertex_attributes_mut(&mut self) -> &mut VertexAttributeArray {
672 self.vertex_attributes_changed = true;
673 if self.vertex_attributes.has_own() {
674 self.geometry = None;
675 }
676 &mut self.vertex_attributes
677 }
678
679 pub(crate) fn paint_attributes_mut(&mut self) -> &mut VertexAttributeArray {
683 let (attributes, changed) = match &mut self.instance_attributes {
684 Some(instances) => (instances, &mut self.instance_attributes_changed),
685 None => (&mut self.vertex_attributes, &mut self.vertex_attributes_changed),
686 };
687 *changed = true;
688 if attributes.has_own() {
689 self.geometry = None;
690 }
691 attributes
692 }
693
694 pub(crate) fn read_as_storage(&mut self, id: usize, vertices: Option<VertexBuffer>) {
699 debug_assert!(id >= BUFFER_IDS, "a uniform buffer's id");
700 self.storage_vertices.retain(|(at, ..)| *at != id);
701 debug_assert!(vertices.is_none() || self.storage_vertices.len() < MAX_STORAGE_VERTICES);
702 if let Some(vertices) = vertices {
703 self.storage_vertices.push((id, vertices, None));
704 }
705 self.storage_epoch += 1;
706 }
707
708 pub(crate) fn storage_buffer(&self, id: usize) -> Option<BufferId> {
711 self.storage_vertices.iter().find(|(at, ..)| *at == id).and_then(|&(_, _, buffer)| buffer)
712 }
713
714 #[must_use]
716 pub(crate) fn has_instances(&self) -> bool {
717 self.instance_attributes.is_some()
718 }
719
720 #[must_use]
722 pub(crate) fn texture(&self, slot: usize) -> Option<&Texture> {
723 self.textures[slot].as_ref()
724 }
725
726 pub(crate) fn set_texture(&mut self, slot: usize, texture: Option<&Texture>) {
729 let bound = &mut self.textures[slot];
730 if bound.as_ref() != texture {
731 *bound = texture.cloned();
732 }
733 }
734
735 pub(crate) fn set_sampler(&mut self, slot: usize, state: Option<SamplerState>) {
738 self.samplers[slot] = state;
739 }
740
741 pub(crate) fn replace_indexes(&mut self, indexes: DrawIndexes, ranges: Vec<DrawRange>) {
743 if let DrawIndexes::Own(_) = self.indexes {
744 self.geometry = None;
745 }
746 self.indexes = indexes;
747 self.ranges = ranges;
748 }
749
750 pub(crate) fn set_cull_face_mode(&mut self, cull_face_mode: CullFaceMode) {
752 if self.cull_face_mode != cull_face_mode {
753 self.cull_face_mode = cull_face_mode;
754 self.pipelines.clear();
756 }
757 }
758}
759
760pub struct MeshDesc {
769 pub shader: ShaderKey,
770 pub color_mode: ColorMode,
771 pub cull_face_mode: CullFaceMode,
772 pub mode: DrawMode,
773 pub vertices: Vec<VertexBinding>,
774 pub vertex_count: usize,
775 pub instances: Option<Vec<VertexBinding>>,
776 pub indexes: IndexBuffer,
777 pub ranges: Vec<DrawRange>,
778 pub textures: Textures,
779}
780
781#[derive(Clone)]
791pub struct Mesh {
792 key: Shared<MeshKey>,
793 id: SimpleIdentity,
794 program: &'static Program,
795}
796
797impl Mesh {
798 #[must_use]
800 pub(crate) fn of(context: &mut Context, desc: MeshDesc) -> Self {
801 let MeshDesc {
802 shader,
803 color_mode,
804 cull_face_mode,
805 mode,
806 vertices,
807 vertex_count,
808 instances,
809 indexes,
810 ranges,
811 textures,
812 } = desc;
813 let geometry = DrawGeometry {
814 vertices: attributes_of(&vertices),
815 vertex_count,
816 mode,
817 indexes: DrawIndexes::Shared(indexes),
818 ranges,
819 instances: instances.as_deref().map(attributes_of),
820 };
821 Mesh::new(context, shader, color_mode, cull_face_mode, geometry, textures)
822 }
823
824 #[must_use]
827 pub(crate) fn new(
828 context: &mut Context,
829 shader: ShaderKey,
830 color_mode: ColorMode,
831 cull_face_mode: CullFaceMode,
832 geometry: DrawGeometry,
833 textures: Textures,
834 ) -> Self {
835 let mut objects = DrawObjects::new(shader, color_mode, cull_face_mode, geometry, textures);
836 let (id, program) = (objects.id, objects.program());
837 let key = context.add_mesh_with(|key| {
838 objects.handle = key.downgrade();
839 objects
840 });
841 Mesh { key, id, program }
842 }
843
844 pub(crate) fn key(&self) -> &Shared<MeshKey> {
846 &self.key
847 }
848
849 #[must_use]
852 pub fn seq(&self) -> i64 {
853 self.id.get() as i64
854 }
855
856 #[must_use]
858 pub fn program(&self) -> &'static Program {
859 self.program
860 }
861
862 pub(crate) fn update<R>(
865 &self,
866 context: &mut Context,
867 f: impl FnOnce(&mut DrawObjects, &mut Context) -> R,
868 ) -> Option<R> {
869 let mut objects = context.take_mesh(self)?;
870 let result = f(&mut objects, context);
871 context.put_mesh(self, objects);
872 Some(result)
873 }
874
875 pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
877 self.update(context, |objects, context| objects.upload(gpu, context));
878 }
879
880 pub(crate) fn vertex_attributes_mut<'c>(&self, context: &'c mut Context) -> Option<&'c mut VertexAttributeArray> {
882 context.mesh_mut(self).map(DrawObjects::vertex_attributes_mut)
883 }
884
885 pub fn set_vertices<'b>(&self, res: &mut Resources<'_>, bindings: impl IntoIterator<Item = &'b VertexBinding>) {
888 if let Some(attrs) = self.vertex_attributes_mut(res.context) {
889 replace_attributes(attrs, bindings);
890 }
891 }
892
893 pub fn set_paint(&self, res: &mut Resources<'_>, paint: &VertexBinding) {
899 if let Some(objects) = res.context.mesh_mut(self) {
900 paint.bind(objects.paint_attributes_mut());
901 }
902 }
903
904 pub fn read_as_storage(&self, res: &mut Resources<'_>, id: usize, vertices: Option<VertexBuffer>) {
906 if let Some(objects) = res.context.mesh_mut(self) {
907 objects.read_as_storage(id, vertices);
908 }
909 }
910
911 #[must_use]
913 pub(crate) fn storage_buffer(&self, context: &Context, id: usize) -> Option<BufferId> {
914 context.mesh(self)?.storage_buffer(id)
915 }
916
917 #[must_use]
919 pub fn has_instances(&self, res: &Resources<'_>) -> bool {
920 res.context.mesh(self).is_some_and(DrawObjects::has_instances)
921 }
922
923 #[must_use]
925 pub fn texture<'r>(&self, res: &'r Resources<'_>, slot: usize) -> Option<&'r Texture> {
926 res.context.mesh(self)?.texture(slot)
927 }
928
929 pub fn set_texture(&self, res: &mut Resources<'_>, slot: usize, texture: Option<&Texture>) {
931 if let Some(objects) = res.context.mesh_mut(self) {
932 objects.set_texture(slot, texture);
933 }
934 }
935
936 pub fn set_sampler(&self, res: &mut Resources<'_>, slot: usize, state: Option<SamplerState>) {
938 if let Some(objects) = res.context.mesh_mut(self) {
939 objects.set_sampler(slot, state);
940 }
941 }
942
943 pub fn replace_indexes(&self, res: &mut Resources<'_>, indexes: IndexBuffer, ranges: Vec<DrawRange>) {
945 if let Some(objects) = res.context.mesh_mut(self) {
946 objects.replace_indexes(DrawIndexes::Shared(indexes), ranges);
947 }
948 }
949
950 pub fn set_cull_face_mode(&self, res: &mut Resources<'_>, cull_face_mode: CullFaceMode) {
952 if let Some(objects) = res.context.mesh_mut(self) {
953 objects.set_cull_face_mode(cull_face_mode);
954 }
955 }
956}
957
958fn sampled_slots(program: &Program) -> impl Iterator<Item = usize> + use<> {
960 let textures = program.textures;
961 (0..textures.len()).filter(move |&slot| !textures[slot].is_unused())
962}
963
964fn fixed_state(variant: PipelineVariant, color_mode: &ColorMode, cull: CullFaceMode) -> FixedState {
965 FixedState {
966 primitive: variant.primitive,
967 cull,
968 blend: color_mode.blend_function,
969 color_mask: color_mode.mask,
970 depth: variant.depth,
971 stencil: variant.stencil,
972 }
973}
974
975fn vertex_slots(
982 program: &Program,
983 attributes: &AttributeBindingArray,
984 instances: &AttributeBindingArray,
985) -> Vec<VertexSlot> {
986 let mut slots: Vec<VertexSlot> = Vec::new();
987 for (bindings, step) in [(attributes, VertexStep::Vertex), (instances, VertexStep::Instance)] {
988 let (count, first) = match step {
989 VertexStep::Vertex => (program.attributes.len(), 0),
990 VertexStep::Instance => (program.instance_attributes.len(), program.attributes.len()),
991 };
992 for (index, binding) in bindings.iter().enumerate().take(count) {
993 let buffer = &binding.buffer;
994 let offset = u64::from(binding.vertex_offset) * u64::from(binding.vertex_stride);
995 let attribute = GpuVertexAttribute {
996 location: (first + index) as u32,
997 format: binding.attribute.data_type,
998 offset: binding.attribute.offset,
999 };
1000 let shared = slots.iter_mut().find(|slot| {
1001 slot.buffer == *buffer
1002 && slot.layout.stride == binding.vertex_stride
1003 && slot.layout.step == step
1004 && slot.offset == offset
1005 });
1006 match shared {
1007 Some(slot) => slot.layout.attributes.push(attribute),
1008 None => slots.push(VertexSlot {
1009 buffer: *buffer,
1010 held: binding.held.clone(),
1011 offset,
1012 layout: VertexBufferLayout { stride: binding.vertex_stride, step, attributes: vec![attribute] },
1013 }),
1014 }
1015 }
1016 }
1017 if slots.len() > MAX_VERTEX_BUFFERS {
1018 log::warn!(
1019 target: log_target::RENDER,
1020 "{} uses {} vertex buffers, exceeding the limit of {MAX_VERTEX_BUFFERS}",
1021 program.name,
1022 slots.len()
1023 );
1024 slots.truncate(MAX_VERTEX_BUFFERS);
1025 }
1026 slots
1027}