Skip to main content

mln_engine/draw/
objects.rs

1//! Meshes, the GPU objects of what a draw draws, which the renderer keeps
2//! between frames and makes again only when what they are made of changes,
3//! and the buffers a frame's draws bind with the bindings made of them.
4//!
5//! A mesh owns what is its own, its own indexes and attribute data, and
6//! holds what it shares with other meshes, its textures and the indexes and
7//! vertices of buckets and static geometry, through handles of the context's
8//! stores (`store`), which keep them while the mesh lasts. It binds no
9//! uniform buffers: the frame that draws it does ([`DrawBuffers`]), so that
10//! frames with buffers of their own can draw one mesh.
11//!
12//! A shader reads vertices as attributes, or, where the device binds vertex
13//! buffers (`Caps::binds_vertex_buffers`), as a storage buffer that it
14//! indexes itself (`Mesh::read_as_storage`).
15
16use 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, PipelineId, PipelineKey, SamplerId, Scissor, ShaderId, ShaderKey, StencilState,
24    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_style::hash::HashMap;
30
31use crate::draw::atlas_binding::AtlasBinding;
32use crate::draw::buffer::Buffer;
33use crate::draw::context::Context;
34use crate::draw::identity::SimpleIdentity;
35use crate::draw::indexes::DrawIndexes;
36use crate::draw::owned::{Held, Owned};
37use crate::draw::resources::Device;
38use crate::draw::segment::SegmentBase;
39use crate::draw::store::{MeshKey, Shared, SharedTexture, WeakShared};
40use crate::draw::uniform_buffer::UniformBufferArray;
41use crate::draw::upload::{self, AttributeBindingArray, AttributeSlots};
42use crate::draw::vertex_attribute::VertexAttributeArray;
43use crate::draw::vertices::SharedVertices;
44use crate::log_target;
45use crate::render::paint_parameters::{DrawTarget, PaintParameters};
46
47/// The textures a draw binds, by the slots of its program's textures.
48pub type Textures = [Option<SharedTexture>; MAX_TEXTURES];
49
50/// The most vertex buffers a draw binds, WebGPU's default limit.
51const MAX_VERTEX_BUFFERS: usize = 8;
52
53/// What a mesh draws: its vertices, and the primitives its segments draw of
54/// them.
55pub struct DrawGeometry {
56    /// The vertex attributes, by the names of the program's attributes.
57    pub vertices: VertexAttributeArray,
58    /// How many vertices the attributes hold, which an attribute the
59    /// shader reads and the draw lacks gets default values for.
60    pub vertex_count: usize,
61    /// The primitive the segments draw.
62    pub mode: DrawMode,
63    pub indexes: DrawIndexes,
64    /// The ranges of the indexes and vertices each draw call draws.
65    pub segments: Vec<SegmentBase>,
66    /// The attributes of each instance, for a draw of instances.
67    pub instances: Option<VertexAttributeArray>,
68}
69
70/// `count` vertices of `data_type` in `data` as the vertex attribute `name`,
71/// none where there are no vertices.
72#[must_use]
73pub fn raw_vertices(
74    name: &'static str,
75    data: Vec<u8>,
76    count: usize,
77    data_type: AttributeDataType,
78) -> VertexAttributeArray {
79    let mut attributes = VertexAttributeArray::new();
80    if count == 0 || data_type == AttributeDataType::Invalid || data.is_empty() {
81        return attributes;
82    }
83    attributes.set_own(name, data_type, data);
84    attributes
85}
86
87/// The most vertices a draw's shader reads as storage buffers.
88const MAX_STORAGE_VERTICES: usize = 3;
89
90/// The most entries bindings have.
91const MAX_ENTRIES: usize = BUFFER_IDS + MAX_STORAGE_VERTICES + MAX_TEXTURES;
92
93/// The entries of bindings, on the stack: at most a buffer at each uniform
94/// buffer id, one of each of the vertices read as storage buffers, and a
95/// texture at each texture slot.
96pub(crate) struct Entries {
97    entries: [BindGroupEntry; MAX_ENTRIES],
98    len: usize,
99}
100
101impl Entries {
102    pub(crate) fn new() -> Entries {
103        let none = BindGroupEntry::Texture { slot: 0, texture: TextureId::default(), sampler: SamplerId::default() };
104        Entries { entries: [none; MAX_ENTRIES], len: 0 }
105    }
106
107    pub(crate) fn push(&mut self, entry: BindGroupEntry) {
108        self.entries[self.len] = entry;
109        self.len += 1;
110    }
111
112    pub(crate) fn as_slice(&self) -> &[BindGroupEntry] {
113        &self.entries[..self.len]
114    }
115}
116
117/// A vertex buffer a draw binds, what keeps it where others share it, and
118/// how its pipeline reads it.
119struct VertexSlot {
120    buffer: BufferId,
121    held: Option<Held>,
122    offset: u64,
123    layout: VertexBufferLayout,
124}
125
126/// What a mesh's bindings were made of besides its frame's buffers: the
127/// epoch of the global uniform buffers, how often the buffers of the
128/// vertices the mesh reads as storage buffers changed, and the texture and
129/// sampler it bound at each texture slot.
130#[derive(Clone, Copy, PartialEq)]
131struct BindingsStamp {
132    global: u64,
133    storage: u64,
134    textures: [Option<(TextureId, SamplerId)>; MAX_TEXTURES],
135}
136
137/// The bindings a frame made of a mesh, while the mesh lasts.
138struct MeshBindings {
139    mesh: WeakShared<MeshKey>,
140    bindings: Owned<BindingsId>,
141    stamp: BindingsStamp,
142}
143
144/// The uniform and storage buffers that a frame's draws bind, by id, and
145/// the bindings of each mesh the draws drew, made of them, of the context's
146/// global buffers and of the mesh's textures and vertices read as storage
147/// buffers. The bindings of a mesh go when the mesh drops, by the next
148/// [`sweep`](Self::sweep), and all of them when a buffer is made or
149/// replaced, before the buffer they were made of goes.
150#[derive(Default)]
151pub(crate) struct DrawBuffers {
152    buffers: UniformBufferArray,
153    bindings: HashMap<SimpleIdentity, MeshBindings>,
154}
155
156impl DrawBuffers {
157    /// The buffer `id`, if the frame has one.
158    pub(crate) fn get(&self, id: usize) -> Option<&Buffer> {
159        self.buffers.get(id)
160    }
161
162    /// Writes `value` to the uniform buffer `id`, as
163    /// [`UniformBufferArray::write_pod`] does.
164    pub(crate) fn write_pod<T: bytemuck::Pod>(&mut self, gpu: &mut dyn Gpu, id: usize, value: &T, device: &mut Device) {
165        let epoch = self.buffers.epoch();
166        let _replaced = self.buffers.write_pod(gpu, id, value, device);
167        self.made(epoch);
168    }
169
170    /// Writes `data`, the bytes of a block, to the uniform buffer `id`, as
171    /// [`UniformBufferArray::write_uniform`] does.
172    pub(crate) fn write_uniform(&mut self, gpu: &mut dyn Gpu, id: usize, data: &[u8], device: &mut Device) {
173        let epoch = self.buffers.epoch();
174        let _replaced = self.buffers.write_uniform(gpu, id, data, device);
175        self.made(epoch);
176    }
177
178    /// Writes `data` to the storage buffer `id`, as
179    /// [`UniformBufferArray::write_storage`] does.
180    pub(crate) fn write_storage(&mut self, gpu: &mut dyn Gpu, id: usize, data: &[u8], device: &mut Device) {
181        let epoch = self.buffers.epoch();
182        let _replaced = self.buffers.write_storage(gpu, id, data, device);
183        self.made(epoch);
184    }
185
186    /// Drops the bindings where a write since the buffers were at `epoch`
187    /// made or replaced a buffer, which they don't bind.
188    fn made(&mut self, epoch: u64) {
189        if self.buffers.epoch() != epoch {
190            self.bindings.clear();
191        }
192    }
193
194    /// Drops the bindings of the meshes that dropped.
195    pub(crate) fn sweep(&mut self) {
196        self.bindings.retain(|_, made| made.mesh.is_held());
197    }
198
199    /// The bindings of what `mesh`'s shader, `shader_id` on `gpu`, reads of
200    /// the context's global buffers, the frame's buffers, and the mesh's
201    /// textures and vertices read as storage buffers, made again where one
202    /// of them changed since the frame last drew the mesh.
203    fn bindings(
204        &mut self,
205        gpu: &mut dyn Gpu,
206        context: &mut Context,
207        mesh: &DrawObjects,
208        shader_id: ShaderId,
209    ) -> Result<BindingsId, GpuError> {
210        let program = mesh.shader.program();
211        let mut textures = [None; MAX_TEXTURES];
212        for slot in sampled_slots(program) {
213            if let Some(texture) = mesh.textures.get(slot).and_then(Option::as_ref) {
214                textures[slot] = Some(context.texture_binding(gpu, texture)?);
215            }
216        }
217        let global = context.global_uniform_buffers();
218        let stamp = BindingsStamp { global: global.epoch(), storage: mesh.storage_epoch, textures };
219        if let Some(made) = self.bindings.get(&mesh.id)
220            && made.stamp == stamp
221        {
222            return Ok(made.bindings.id());
223        }
224        self.bindings.remove(&mesh.id);
225        let mut entries = Entries::new();
226        for id in 0..BUFFER_IDS {
227            // The frame's buffer wins over the global one.
228            let buffer = self.buffers.get(id).or_else(|| global.get(id));
229            if let Some(buffer) = buffer {
230                entries.push(BindGroupEntry::Buffer {
231                    id: id as u32,
232                    buffer: buffer.id(),
233                    offset: 0,
234                    size: buffer.size() as u64,
235                });
236            }
237        }
238        let mut held = Vec::new();
239        for (id, vertices, buffer) in &mesh.storage_vertices {
240            let size = context.vertices(vertices).map_or(0, |stored| stored.count() * stored.vertex_size());
241            if let Some(buffer) = buffer.filter(|_| size > 0) {
242                entries.push(BindGroupEntry::Buffer { id: *id as u32, buffer, offset: 0, size: size as u64 });
243                held.push(vertices.held());
244            }
245        }
246        for (slot, binding) in textures.iter().enumerate() {
247            if let Some((texture, sampler)) = *binding {
248                entries.push(BindGroupEntry::Texture { slot: slot as u32, texture, sampler });
249            }
250        }
251        held.extend(
252            sampled_slots(program)
253                .filter_map(|slot| context.gpu_texture(mesh.textures.get(slot)?.as_ref()?).cloned().map(Held::Texture)),
254        );
255        let bindings =
256            gpu.create_bindings(&BindingsDesc { label: program.name, shader: shader_id, entries: entries.as_slice() })?;
257        let made = MeshBindings { mesh: mesh.handle.clone(), bindings: context.own(bindings, held), stamp };
258        self.bindings.insert(mesh.id, made);
259        Ok(bindings)
260    }
261
262    /// The frame's bindings of `mesh`, as a draw of it binds them.
263    #[cfg(test)]
264    pub(crate) fn bind(
265        &mut self,
266        gpu: &mut dyn Gpu,
267        context: &mut Context,
268        mesh: &Mesh,
269    ) -> Result<BindingsId, GpuError> {
270        let objects = context.take_mesh(mesh).ok_or(GpuError::UnknownId("mesh"))?;
271        let bound =
272            context.shader(gpu, &objects.shader).and_then(|shader| self.bindings(gpu, context, &objects, shader));
273        context.put_mesh(mesh, objects);
274        bound
275    }
276
277    /// How many meshes the frame keeps bindings of.
278    #[cfg(test)]
279    pub(crate) fn bound_meshes(&self) -> usize {
280        self.bindings.len()
281    }
282}
283
284/// What, besides the draw's own state, a draw's pipeline depends on.
285#[derive(Clone, Copy, PartialEq)]
286struct PipelineVariant {
287    primitive: DrawModeType,
288    depth: DepthState,
289    stencil: StencilState,
290    targets: TargetFormats,
291}
292
293/// Geometry drawn with one program, and the GPU objects that draw it: its
294/// vertices, indexes and segments, the textures it binds, the color and cull
295/// modes it draws with, and the shader, pipelines and geometry it made of
296/// them on the context's `Gpu`, which it makes again when what they are made
297/// of changes. The frames that draw it bind it with their buffers
298/// ([`DrawBuffers`]).
299pub(crate) struct DrawObjects {
300    /// Tells the mesh apart from the others, and orders it after those made
301    /// before it.
302    id: SimpleIdentity,
303    /// The mesh's handles, which the frames' bindings of it last while one
304    /// does.
305    handle: WeakShared<MeshKey>,
306    shader: ShaderKey,
307    vertex_attributes: VertexAttributeArray,
308    /// The attributes of each instance, for a draw of instances.
309    instance_attributes: Option<VertexAttributeArray>,
310    /// Whether the vertex attributes changed since the last upload, which
311    /// then binds them all again; true until the first.
312    vertex_attributes_changed: bool,
313    /// Whether the instance attributes changed since the last upload, as
314    /// `vertex_attributes_changed` says of the vertex attributes.
315    instance_attributes_changed: bool,
316    /// Where the program's vertex and instance attributes are in the
317    /// attribute arrays.
318    vertex_slots_of: AttributeSlots,
319    instance_slots_of: AttributeSlots,
320    /// The textures it binds, by slot.
321    textures: Textures,
322    /// The vertices the shader reads as storage buffers, each with the
323    /// buffer id it binds at, past the uniform buffers' ids, and its buffer
324    /// as of the last upload.
325    storage_vertices: Vec<(usize, SharedVertices, Option<BufferId>)>,
326    /// How often a buffer of `storage_vertices` changed.
327    storage_epoch: u64,
328    color_mode: ColorMode,
329    cull_face_mode: CullFaceMode,
330
331    mode: DrawMode,
332    segments: Vec<SegmentBase>,
333    indexes: DrawIndexes,
334    vertex_count: usize,
335    attribute_bindings: AttributeBindingArray,
336    instance_bindings: AttributeBindingArray,
337    /// The vertex buffers of the bindings, `None` until a draw after either
338    /// changes computes them.
339    vertex_slots: Option<Vec<VertexSlot>>,
340    /// The context's shader of the draw's, once it drew.
341    shader_id: Option<ShaderId>,
342    /// The pipelines it drew with, for its shader, `pipeline_layouts`, color
343    /// and cull modes as they are.
344    pipelines: Vec<(PipelineVariant, PipelineId)>,
345    /// The vertex buffer layouts of the vertex slots the pipelines were made
346    /// for.
347    pipeline_layouts: Vec<VertexBufferLayout>,
348    /// The geometry of its vertex slots and the index buffer it was made
349    /// with.
350    geometry: Option<(Owned<GeometryId>, BufferId)>,
351    /// Gives it the textures of its tile's atlases before each draw.
352    atlases: Option<AtlasBinding>,
353}
354
355impl DrawObjects {
356    /// The objects of `geometry`, drawn with `shader` in `color_mode` and
357    /// `cull_face_mode`, binding `textures`.
358    #[must_use]
359    pub(crate) fn new(
360        shader: ShaderKey,
361        color_mode: ColorMode,
362        cull_face_mode: CullFaceMode,
363        geometry: DrawGeometry,
364        textures: Textures,
365    ) -> Self {
366        let DrawGeometry { vertices, vertex_count, mode, indexes, segments, instances } = geometry;
367        DrawObjects {
368            id: SimpleIdentity::new(),
369            handle: WeakShared::default(),
370            shader,
371            vertex_attributes: vertices,
372            instance_attributes: instances,
373            vertex_attributes_changed: true,
374            instance_attributes_changed: true,
375            vertex_slots_of: AttributeSlots::default(),
376            instance_slots_of: AttributeSlots::default(),
377            textures,
378            storage_vertices: Vec::new(),
379            storage_epoch: 0,
380            color_mode,
381            cull_face_mode,
382            mode,
383            segments,
384            indexes,
385            vertex_count,
386            attribute_bindings: Vec::new(),
387            instance_bindings: Vec::new(),
388            vertex_slots: None,
389            shader_id: None,
390            pipelines: Vec::new(),
391            pipeline_layouts: Vec::new(),
392            geometry: None,
393            atlases: None,
394        }
395    }
396
397    /// Uploads the indexes, vertex attributes, vertices read as storage
398    /// buffers and textures, where they changed since the last upload.
399    pub(crate) fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context) {
400        if let Err(error) = self.upload_in(gpu, context) {
401            context.fail(format!("Uploading {} failed: {error}", self.shader.program().name));
402        }
403    }
404
405    fn upload_in(&mut self, gpu: &mut dyn Gpu, context: &mut Context) -> Result<(), GpuError> {
406        let program = self.shader.program();
407        if self.indexes.buffer(context).is_none() && self.indexes.len(context) == 0 {
408            debug_assert!(false, "a draw of {} has no index data", program.name);
409            return Ok(());
410        }
411        self.indexes.upload(gpu, context)?;
412
413        // An attribute binds again where its array changed, or where the
414        // upload writes what it reads, which may be new. A failed upload
415        // leaves the attributes changed, so the next binds them again.
416        if self.vertex_attributes_changed
417            || upload::needs_upload(context, &self.vertex_attributes, &self.vertex_slots_of)
418        {
419            let updated = upload::update_attribute_bindings(
420                gpu,
421                context,
422                program.attributes,
423                &mut self.vertex_attributes,
424                &mut self.vertex_slots_of,
425                self.vertex_count,
426                &mut self.attribute_bindings,
427            );
428            if !matches!(updated, Ok(false)) {
429                self.vertex_slots = None;
430                self.geometry = None;
431            }
432            updated?;
433        }
434
435        let changed = self.instance_attributes_changed;
436        if let Some(attrs) = self
437            .instance_attributes
438            .as_mut()
439            .filter(|attrs| changed || upload::needs_upload(context, attrs, &self.instance_slots_of))
440        {
441            let instance_count = attrs.min_count();
442            let updated = upload::update_attribute_bindings(
443                gpu,
444                context,
445                program.instance_attributes,
446                attrs,
447                &mut self.instance_slots_of,
448                instance_count,
449                &mut self.instance_bindings,
450            );
451            if !matches!(updated, Ok(false)) {
452                self.vertex_slots = None;
453                self.geometry = None;
454            }
455            updated?;
456        }
457
458        self.vertex_attributes_changed = false;
459        self.instance_attributes_changed = false;
460
461        for (_, vertices, bound) in &mut self.storage_vertices {
462            let buffer = context.upload_vertices(gpu, vertices)?;
463            if *bound != buffer {
464                *bound = buffer;
465                self.storage_epoch += 1;
466            }
467        }
468
469        for texture in self.textures.iter().flatten() {
470            if let Err(error) = context.upload_texture(gpu, texture) {
471                context.fail(format!("Uploading a texture failed: {error}"));
472            }
473        }
474
475        Ok(())
476    }
477
478    /// The program the mesh draws with.
479    #[must_use]
480    pub(crate) fn program(&self) -> &'static Program {
481        self.shader.program()
482    }
483
484    /// Draws the segments into `parameters`' open pass on `gpu`, the
485    /// context's, with `depth_mode` and `stencil_mode`, binding the buffers
486    /// of the draws in `frame`. Shaders read the draw's entries in those
487    /// storage buffers at `global_index`. Returns whether it didn't fail; a
488    /// draw that fails fails the frame
489    /// ([`Context::fail`](crate::draw::context::Context::fail)).
490    pub(crate) fn draw(
491        &mut self,
492        gpu: &mut dyn Gpu,
493        parameters: &mut PaintParameters<'_>,
494        frame: &mut DrawBuffers,
495        depth_mode: DepthMode,
496        stencil_mode: StencilMode,
497        global_index: u32,
498    ) -> bool {
499        if let Some(atlases) = self.atlases.take() {
500            atlases.bind(self, parameters);
501            self.atlases = Some(atlases);
502        }
503        let drawn = self.draw_in(gpu, parameters, frame, depth_mode, stencil_mode, global_index);
504        if let Err(error) = &drawn {
505            parameters.context.fail(format!("Drawing {} failed: {error}", self.shader.program().name));
506        }
507        drawn.is_ok()
508    }
509
510    fn draw_in(
511        &mut self,
512        gpu: &mut dyn Gpu,
513        parameters: &mut PaintParameters<'_>,
514        frame: &mut DrawBuffers,
515        depth_mode: DepthMode,
516        stencil_mode: StencilMode,
517        global_index: u32,
518    ) -> Result<(), GpuError> {
519        let Some(DrawTarget { size, targets, scissor }) = parameters.draw_target() else {
520            return Ok(());
521        };
522        let context = &mut *parameters.context;
523        let Some(index_buffer) = self.indexes.buffer(context) else {
524            // Only a failed upload, which failed the frame, leaves a draw
525            // without its indexes.
526            debug_assert!(
527                context.device().failed(),
528                "a draw of {} draws indexes it didn't upload",
529                self.shader.program().name
530            );
531            return Err(GpuError::Invalid("its indexes aren't uploaded".to_owned()));
532        };
533
534        let shader_id = match self.shader_id {
535            Some(id) => id,
536            None => *self.shader_id.insert(context.shader(gpu, &self.shader)?),
537        };
538        let bindings = frame.bindings(gpu, context, self, shader_id)?;
539        let slots = if let Some(slots) = &self.vertex_slots {
540            slots
541        } else {
542            let slots = vertex_slots(self.shader.program(), &self.attribute_bindings, &self.instance_bindings);
543            // New buffers in the layouts of the old ones keep the
544            // pipelines.
545            let layouts = slots.iter().map(|slot| &slot.layout);
546            if !layouts.clone().eq(self.pipeline_layouts.iter()) {
547                self.pipeline_layouts = layouts.cloned().collect();
548                self.pipelines.clear();
549            }
550            self.vertex_slots.insert(slots)
551        };
552        let geometry = match &self.geometry {
553            Some((geometry, indices)) if *indices == index_buffer => geometry.id(),
554            _ => {
555                self.geometry = None;
556                // On the stack: the geometry's handles take the allocation.
557                let mut buffers = [(BufferId::default(), 0); MAX_VERTEX_BUFFERS];
558                for (buffer, slot) in buffers.iter_mut().zip(slots) {
559                    *buffer = (slot.buffer, slot.offset);
560                }
561                let geometry = gpu.create_geometry(&GeometryDesc {
562                    shader: shader_id,
563                    layouts: &self.pipeline_layouts,
564                    vertex_buffers: &buffers[..slots.len()],
565                    index_buffer,
566                })?;
567                let index_held = self.indexes.held();
568                // Of the exact length: geometry is made as tiles come.
569                let len = slots.iter().filter(|slot| slot.held.is_some()).count() + usize::from(index_held.is_some());
570                let mut held = Vec::with_capacity(len);
571                held.extend(slots.iter().filter_map(|slot| slot.held.clone()).chain(index_held));
572                self.geometry = Some((context.own(geometry, held), index_buffer));
573                geometry
574            }
575        };
576
577        let full = Scissor { x: 0, y: 0, width: size.width, height: size.height };
578        let dynamic = DynamicState {
579            depth_range: depth_mode.range,
580            scissor: scissor.unwrap_or(full),
581            stencil_reference: stencil_mode.ref_ as u32,
582            blend_constant: self.color_mode.blend_color,
583            line_width: 1.0,
584        };
585        let depth = DepthState::from(&depth_mode);
586        let stencil = StencilState::from(&stencil_mode);
587        let mut draws = 0;
588        let mode = self.mode;
589        for segment in &self.segments {
590            if segment.index_length == 0 {
591                continue;
592            }
593            let variant = PipelineVariant { primitive: mode.type_, depth, stencil, targets };
594            let pipeline = if let Some(&(_, id)) = self.pipelines.iter().find(|(cached, _)| *cached == variant) {
595                id
596            } else {
597                let key = PipelineKey {
598                    shader: shader_id,
599                    vertex_buffers: self.pipeline_layouts.clone(),
600                    state: fixed_state(variant, &self.color_mode, self.cull_face_mode),
601                    targets,
602                };
603                let id = context.pipeline(gpu, &key)?;
604                self.pipelines.push((variant, id));
605                id
606            };
607            let line_width = if mode.primitive_type() == PrimitiveType::Line { mode.size } else { 1.0 };
608            gpu.draw(&Draw {
609                pipeline,
610                bindings,
611                geometry,
612                first_index: segment.index_offset as u32,
613                index_count: segment.index_length as u32,
614                base_vertex: segment.vertex_offset as i32,
615                first_instance: segment.base_instance as u32,
616                instance_count: segment.instance_count as u32,
617                global_index,
618                dynamic: DynamicState { line_width, ..dynamic },
619            })?;
620            draws += 1;
621        }
622        let stats = context.rendering_stats();
623        stats.num_draw_calls += draws;
624        stats.total_draw_calls += draws;
625        Ok(())
626    }
627
628    /// The vertex attributes, to change, which the next upload binds again.
629    /// The draw drops its geometry where they have values of their own,
630    /// whose buffers a change may drop.
631    pub(crate) fn vertex_attributes_mut(&mut self) -> &mut VertexAttributeArray {
632        self.vertex_attributes_changed = true;
633        if self.vertex_attributes.has_own() {
634            self.geometry = None;
635        }
636        &mut self.vertex_attributes
637    }
638
639    /// The attributes the paint values are read into, to change, which the
640    /// next upload binds again: the instance attributes of a draw of
641    /// instances, else the vertex attributes.
642    pub(crate) fn paint_attributes_mut(&mut self) -> &mut VertexAttributeArray {
643        let (attributes, changed) = match &mut self.instance_attributes {
644            Some(instances) => (instances, &mut self.instance_attributes_changed),
645            None => (&mut self.vertex_attributes, &mut self.vertex_attributes_changed),
646        };
647        *changed = true;
648        if attributes.has_own() {
649            self.geometry = None;
650        }
651        attributes
652    }
653
654    /// Makes `vertices` what the shader reads as the storage buffer `id`,
655    /// an id past the uniform buffers', on a device that binds vertex
656    /// buffers; nothing with `None`. The next upload writes them, and the
657    /// draws after it bind their buffer.
658    pub(crate) fn read_as_storage(&mut self, id: usize, vertices: Option<SharedVertices>) {
659        debug_assert!(id >= BUFFER_IDS, "a uniform buffer's id");
660        self.storage_vertices.retain(|(at, ..)| *at != id);
661        debug_assert!(vertices.is_none() || self.storage_vertices.len() < MAX_STORAGE_VERTICES);
662        if let Some(vertices) = vertices {
663            self.storage_vertices.push((id, vertices, None));
664        }
665        self.storage_epoch += 1;
666    }
667
668    /// The buffer the draws bind as the storage buffer `id`, of the
669    /// vertices read there as of the last upload.
670    pub(crate) fn storage_buffer(&self, id: usize) -> Option<BufferId> {
671        self.storage_vertices.iter().find(|(at, ..)| *at == id).and_then(|&(_, _, buffer)| buffer)
672    }
673
674    /// Whether the draw draws instances.
675    #[must_use]
676    pub(crate) fn has_instances(&self) -> bool {
677        self.instance_attributes.is_some()
678    }
679
680    /// The texture it binds at its program's texture slot `slot`.
681    #[must_use]
682    pub(crate) fn texture(&self, slot: usize) -> Option<&SharedTexture> {
683        self.textures[slot].as_ref()
684    }
685
686    /// Makes `texture` the one it binds at its program's texture slot
687    /// `slot`.
688    pub(crate) fn set_texture(&mut self, slot: usize, texture: Option<&SharedTexture>) {
689        let bound = &mut self.textures[slot];
690        if bound.as_ref() != texture {
691            *bound = texture.cloned();
692        }
693    }
694
695    /// Replaces the indexes and the segments drawn from them.
696    pub(crate) fn replace_indexes(&mut self, indexes: DrawIndexes, segments: Vec<SegmentBase>) {
697        if let DrawIndexes::Own(_) = self.indexes {
698            self.geometry = None;
699        }
700        self.indexes = indexes;
701        self.segments = segments;
702    }
703
704    /// Culls faces as `cull_face_mode` says from the next draw on.
705    pub(crate) fn set_cull_face_mode(&mut self, cull_face_mode: CullFaceMode) {
706        if self.cull_face_mode != cull_face_mode {
707            self.cull_face_mode = cull_face_mode;
708            // The pipelines bake the culling in.
709            self.pipelines.clear();
710        }
711    }
712
713    #[must_use]
714    pub(crate) fn shader(&self) -> &ShaderKey {
715        &self.shader
716    }
717}
718
719/// A handle of a mesh, the GPU objects of what a draw draws
720/// (`DrawObjects`), which the context's store keeps while a clone of the
721/// handle lasts (`Context::mesh`). A layer keeps its meshes' handles, in
722/// its tile values or its own state, and the draws it pushes name them
723/// ([`Group::push`]), so that the engine uploads and draws them after the
724/// layer made its draws. Clones of a handle are the same mesh. A mesh
725/// changes through the context, which the methods here take.
726///
727/// [`Group::push`]: crate::draw::draws::Group::push
728#[derive(Clone)]
729pub struct Mesh {
730    key: Shared<MeshKey>,
731    id: SimpleIdentity,
732    program: &'static Program,
733}
734
735impl Mesh {
736    /// The mesh of `geometry`, drawn with `shader` in `color_mode` and
737    /// `cull_face_mode`, binding `textures`, in `context`'s store.
738    #[must_use]
739    pub fn new(
740        context: &mut Context,
741        shader: ShaderKey,
742        color_mode: ColorMode,
743        cull_face_mode: CullFaceMode,
744        geometry: DrawGeometry,
745        textures: Textures,
746    ) -> Self {
747        let mut objects = DrawObjects::new(shader, color_mode, cull_face_mode, geometry, textures);
748        let (id, program) = (objects.id, objects.program());
749        let key = context.add_mesh_with(|key| {
750            objects.handle = key.downgrade();
751            objects
752        });
753        Mesh { key, id, program }
754    }
755
756    /// The handle of the mesh's entry in the context's store.
757    pub(crate) fn key(&self) -> &Shared<MeshKey> {
758        &self.key
759    }
760
761    /// The place of the mesh among the meshes, by when they were made, as a
762    /// draw's order ([`Draw::order`](crate::draw::draws::Draw::order)).
763    #[must_use]
764    pub fn seq(&self) -> i64 {
765        self.id.get() as i64
766    }
767
768    /// The program the mesh draws with.
769    #[must_use]
770    pub(crate) fn program(&self) -> &'static Program {
771        self.program
772    }
773
774    /// Runs `f` with the mesh's objects, taken out of `context`'s store
775    /// while it runs, and the context; `None` without them.
776    pub(crate) fn update<R>(
777        &self,
778        context: &mut Context,
779        f: impl FnOnce(&mut DrawObjects, &mut Context) -> R,
780    ) -> Option<R> {
781        let mut objects = context.take_mesh(self)?;
782        let result = f(&mut objects, context);
783        context.put_mesh(self, objects);
784        Some(result)
785    }
786
787    /// See `DrawObjects::upload`.
788    pub fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
789        self.update(context, |objects, context| objects.upload(gpu, context));
790    }
791
792    /// Runs `f` with the mesh's vertex attributes, to change, and the
793    /// context; `None` for a mesh whose objects went. The next upload binds
794    /// the attributes again.
795    pub fn update_vertex_attributes<R>(
796        &self,
797        context: &mut Context,
798        f: impl FnOnce(&mut VertexAttributeArray, &mut Context) -> R,
799    ) -> Option<R> {
800        self.update(context, |objects, context| f(objects.vertex_attributes_mut(), context))
801    }
802
803    /// See [`DrawObjects::vertex_attributes_mut`].
804    pub(crate) fn vertex_attributes_mut<'c>(&self, context: &'c mut Context) -> Option<&'c mut VertexAttributeArray> {
805        context.mesh_mut(self).map(DrawObjects::vertex_attributes_mut)
806    }
807
808    /// See `DrawObjects::paint_attributes_mut`.
809    pub fn paint_attributes_mut<'c>(&self, context: &'c mut Context) -> Option<&'c mut VertexAttributeArray> {
810        context.mesh_mut(self).map(DrawObjects::paint_attributes_mut)
811    }
812
813    /// See `DrawObjects::read_as_storage`.
814    pub fn read_as_storage(&self, context: &mut Context, id: usize, vertices: Option<SharedVertices>) {
815        if let Some(objects) = context.mesh_mut(self) {
816            objects.read_as_storage(id, vertices);
817        }
818    }
819
820    /// See `DrawObjects::storage_buffer`.
821    #[must_use]
822    pub fn storage_buffer(&self, context: &Context, id: usize) -> Option<BufferId> {
823        context.mesh(self)?.storage_buffer(id)
824    }
825
826    /// See `DrawObjects::has_instances`.
827    #[must_use]
828    pub fn has_instances(&self, context: &Context) -> bool {
829        context.mesh(self).is_some_and(DrawObjects::has_instances)
830    }
831
832    /// Replaces the vertex attributes with a copy of those of `other`
833    /// ([`copy_shared_attributes`]), which the next upload binds.
834    pub fn share_vertex_attributes(&self, context: &mut Context, other: &Mesh) {
835        if self.key == other.key {
836            return;
837        }
838        let Some(copy) = context.mesh(other).map(|other| copy_shared_attributes(&other.vertex_attributes)) else {
839            return;
840        };
841        if let Some(objects) = context.mesh_mut(self) {
842            *objects.vertex_attributes_mut() = copy;
843        }
844    }
845
846    /// See `DrawObjects::texture`.
847    #[must_use]
848    pub fn texture<'c>(&self, context: &'c Context, slot: usize) -> Option<&'c SharedTexture> {
849        context.mesh(self)?.texture(slot)
850    }
851
852    /// See `DrawObjects::set_texture`.
853    pub fn set_texture(&self, context: &mut Context, slot: usize, texture: Option<&SharedTexture>) {
854        if let Some(objects) = context.mesh_mut(self) {
855            objects.set_texture(slot, texture);
856        }
857    }
858
859    /// Replaces the mesh's indexes and the segments drawn from them.
860    pub fn replace_indexes(&self, context: &mut Context, indexes: DrawIndexes, segments: Vec<SegmentBase>) {
861        if let Some(objects) = context.mesh_mut(self) {
862            objects.replace_indexes(indexes, segments);
863        }
864    }
865
866    /// See `DrawObjects::set_cull_face_mode`.
867    pub fn set_cull_face_mode(&self, context: &mut Context, cull_face_mode: CullFaceMode) {
868        if let Some(objects) = context.mesh_mut(self) {
869            objects.set_cull_face_mode(cull_face_mode);
870        }
871    }
872
873    /// Makes `atlases` what gives the mesh the textures of its tile's glyph
874    /// and icon atlases before each draw.
875    pub fn set_atlases(&self, context: &mut Context, atlases: Option<AtlasBinding>) {
876        if let Some(objects) = context.mesh_mut(self) {
877            objects.atlases = atlases;
878        }
879    }
880}
881
882/// The slots of the textures `program` samples.
883fn sampled_slots(program: &Program) -> impl Iterator<Item = usize> + use<> {
884    let textures = program.textures;
885    (0..textures.len()).filter(move |&slot| !textures[slot].is_unused())
886}
887
888/// A copy of `attrs`, all of whose attributes read vertices of the
889/// context's store: the copy reads the same vertices, so draws of either
890/// bind the same buffers.
891#[must_use]
892pub fn copy_shared_attributes(attrs: &VertexAttributeArray) -> VertexAttributeArray {
893    let mut copy = VertexAttributeArray::new();
894    for (name, attr) in attrs.iter() {
895        debug_assert!(attr.shared().is_some(), "a copied attribute has values of its own");
896        if let Some(shared) = attr.shared() {
897            copy.set_shared(name, shared.clone());
898        }
899    }
900    copy
901}
902
903fn fixed_state(variant: PipelineVariant, color_mode: &ColorMode, cull: CullFaceMode) -> FixedState {
904    FixedState {
905        primitive: variant.primitive,
906        cull,
907        blend: color_mode.blend_function,
908        color_mask: color_mode.mask,
909        depth: variant.depth,
910        stencil: variant.stencil,
911    }
912}
913
914/// The vertex buffers of a draw's attribute and instance bindings, which
915/// hold an attribute for each of the shader's in the shader's order.
916/// Attributes that read one buffer with one stride from one offset share a
917/// slot; attributes of a buffer at different vertex offsets (a fill
918/// extrusion wall's outline vertex and the next one) read it through slots
919/// of their own, since an attribute's offset must stay within the stride.
920fn vertex_slots(
921    program: &Program,
922    attributes: &AttributeBindingArray,
923    instances: &AttributeBindingArray,
924) -> Vec<VertexSlot> {
925    let mut slots: Vec<VertexSlot> = Vec::new();
926    for (bindings, step) in [(attributes, VertexStep::Vertex), (instances, VertexStep::Instance)] {
927        let (count, first) = match step {
928            VertexStep::Vertex => (program.attributes.len(), 0),
929            VertexStep::Instance => (program.instance_attributes.len(), program.attributes.len()),
930        };
931        for (index, binding) in bindings.iter().enumerate().take(count) {
932            let buffer = &binding.buffer;
933            let offset = u64::from(binding.vertex_offset) * u64::from(binding.vertex_stride);
934            let attribute = GpuVertexAttribute {
935                location: (first + index) as u32,
936                format: binding.attribute.data_type,
937                offset: binding.attribute.offset,
938            };
939            let shared = slots.iter_mut().find(|slot| {
940                slot.buffer == *buffer
941                    && slot.layout.stride == binding.vertex_stride
942                    && slot.layout.step == step
943                    && slot.offset == offset
944            });
945            match shared {
946                Some(slot) => slot.layout.attributes.push(attribute),
947                None => slots.push(VertexSlot {
948                    buffer: *buffer,
949                    held: binding.held.clone(),
950                    offset,
951                    layout: VertexBufferLayout { stride: binding.vertex_stride, step, attributes: vec![attribute] },
952                }),
953            }
954        }
955    }
956    if slots.len() > MAX_VERTEX_BUFFERS {
957        log::warn!(
958            target: log_target::RENDER,
959            "{} uses {} vertex buffers, exceeding the limit of {MAX_VERTEX_BUFFERS}",
960            program.name,
961            slots.len()
962        );
963        slots.truncate(MAX_VERTEX_BUFFERS);
964    }
965    slots
966}