Skip to main content

mln_engine/draw/
draws.rs

1//! A layer's draws of a frame, which the engine holds, writes, uploads and
2//! draws.
3//!
4//! Each frame, a layer pushes its draws into its [`Draws`]' main
5//! [`Group`]: each a [`Draw`] of one of its [`Mesh`]es, placed in the
6//! group's order, with how it tests depth and whether it clips to its tile,
7//! with the values of its program's blocks of each draw ([`DrawBlocks`]),
8//! and, for a draw of a tile, the tile's projection. The blocks the group's
9//! draws share go in once ([`Group::block`]), and the group may composite
10//! onto the frame as one surface ([`Group::composite`]). A layer can also
11//! push draws into textures of its own ([`Draws::target`]), which its draws
12//! of the frame sample, and have the frame lend it the backend's commands
13//! at its time in the frame ([`Draws::lend`]). The engine then
14//! sorts the draws, writes the buffers they read once for the group, with
15//! a drape's paint parameters where the frame is a drape's, uploads their
16//! meshes, places the group in the layers' order and depth, and draws it in
17//! the frame's passes, with the masks of the layer's tiles in the stencil
18//! where its draws clip. A layer sees its frame as a [`LayerFrame`]: the
19//! map's, or a drape's.
20
21use std::any::Any;
22use std::ops::Range;
23use std::rc::Rc;
24
25use mln_gfx::Size;
26use mln_gfx::depth_mode::DepthMode;
27use mln_gfx::gpu::Gpu;
28use mln_gfx::shaders::bindings::{BUFFER_IDS, PAINT_PARAMS_ID, PROJECTION_ID};
29use mln_gfx::shaders::block::{Block, DrawBlocks, UniformBlock};
30use mln_gfx::shaders::layer_ubo::{GlobalPaintParamsUBO, ProjectionUBO};
31use mln_gfx::shaders::program::{BufferKind, Program, Projection};
32use mln_gfx::stencil_mode::StencilMode;
33use mln_gfx::types::DepthMaskType;
34use mln_style::error::Error;
35use mln_style::time::Instant;
36
37use crate::camera::{FrameProjection, View};
38use crate::draw::after_gpu::AfterGpu;
39use crate::draw::context::Context;
40use crate::draw::identity::SimpleIdentity;
41use crate::draw::objects::{DrawBuffers, Mesh};
42use crate::draw::target::Target;
43use crate::placement::TestedShape;
44use crate::render::layer_composite::Composite;
45use crate::render::light::EvaluatedLight;
46use crate::render::paint_parameters::{Composited, PaintParameters, StencilClear, TransformParameters};
47use crate::render::pass::RenderPass;
48use crate::render::terrain::FrameGround;
49use crate::tile::{OverscaledTileID, UnwrappedTileID};
50
51/// What a layer's frame draws into.
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub(crate) enum DrawsInto {
54    /// The map.
55    Map,
56    /// A drape of a terrain tile, whose shading the terrain's surface adds
57    /// where `lit` ([`SurfaceLight`](crate::render::terrain::SurfaceLight)).
58    Drape { lit: bool },
59}
60
61/// The frame a layer makes its draws for, as it reads it: the camera, the
62/// target's size and scale, the light and ground, and what it draws into.
63#[derive(Clone)]
64pub struct LayerFrame<'a> {
65    pub view: &'a View,
66    pub(crate) transform_params: &'a TransformParameters,
67    /// Whether a gesture or an animation moves the camera: draws favor speed
68    /// over crispness then.
69    pub camera_moving: bool,
70    pub light: &'a EvaluatedLight,
71    pub pixel_ratio: f32,
72    pub renderable_size: Size,
73    pub pixels_to_gl_units: [f32; 2],
74    /// Whether the frame draws terrain, under which 2D layers draw without
75    /// depth.
76    pub terrain: bool,
77    /// Whether a group drawn as a whole ([`Group::composite`]) can draw
78    /// with the frame's depth and stencil: the frame has them, and a pass can
79    /// draw into them together with the layer composite's texture.
80    pub composites_with_frame_depth: bool,
81    /// The ground that the layers that stand on terrain stand on, where the
82    /// frame has terrain and such layers.
83    pub ground: Option<Rc<FrameGround>>,
84    /// The frame's time, from the host's clock; `None` in still modes, which
85    /// have no clock and show transitions and animations as ended.
86    pub time_point: Option<Instant>,
87    /// The shapes the frame's placement tested, while a layer the frame
88    /// draws reads them ([`Evaluation::reads_collision_shapes`]); empty
89    /// otherwise.
90    ///
91    /// [`Evaluation::reads_collision_shapes`]: crate::layer::render_layer::Evaluation::reads_collision_shapes
92    pub collision_shapes: &'a [TestedShape],
93    pub(crate) into: DrawsInto,
94}
95
96impl LayerFrame<'_> {
97    /// The frame's camera.
98    #[must_use]
99    pub fn view(&self) -> &View {
100        self.view
101    }
102
103    /// The pixel scale that the frame's draws size what they size in pixels
104    /// at ([`Projection::pixel_scale`]): the view's, or in a drape over the
105    /// globe the globe's.
106    ///
107    /// [`Projection::pixel_scale`]: crate::camera::Projection::pixel_scale
108    #[must_use]
109    pub fn pixel_scale(&self) -> f64 {
110        self.transform_params.pixel_scale
111    }
112
113    /// The device pixels of the frame's target per logical pixel.
114    #[must_use]
115    pub fn pixel_ratio(&self) -> f32 {
116        self.pixel_ratio
117    }
118
119    /// The size of the frame's target, in device pixels.
120    #[must_use]
121    pub fn size(&self) -> Size {
122        self.renderable_size
123    }
124
125    /// The frame's time, from the host's clock; `None` in still modes.
126    #[must_use]
127    pub fn time_point(&self) -> Option<Instant> {
128        self.time_point
129    }
130
131    /// The shapes the frame's placement tested
132    /// ([`collision_shapes`](Self::collision_shapes)).
133    #[must_use]
134    pub fn collision_shapes(&self) -> &[TestedShape] {
135        self.collision_shapes
136    }
137
138    /// Whether the frame is a drape whose shading the terrain's surface
139    /// adds: a hillshade draws its slopes there, unlit.
140    #[must_use]
141    pub fn drape_lit(&self) -> bool {
142        matches!(self.into, DrawsInto::Drape { lit: true })
143    }
144}
145
146/// How a draw tests and writes depth.
147#[derive(Clone, Copy, Debug, PartialEq, Eq)]
148pub enum Depth {
149    /// It draws without a depth test.
150    Off,
151    /// It tests the depth of a sub-layer of the layer's depth, and writes it
152    /// as `mask` says.
153    Layer { sub_layer: u8, mask: DepthMaskType },
154    /// It tests the depth range of 3D geometry, which the 3D draws of all
155    /// layers share, and writes it as `mask` says.
156    Volume { mask: DepthMaskType },
157}
158
159/// How a draw of a mesh draws: its place among its group's draws, its pass,
160/// its depth and whether it clips.
161#[derive(Clone, Copy, Debug, PartialEq, Eq)]
162pub struct Draw {
163    /// Where the draw is among its group's draws: lower orders draw first,
164    /// and draws of one order in the order they were pushed. A layer that
165    /// draws its meshes in the order they were made gives each draw its
166    /// mesh's [`seq`](Mesh::seq).
167    pub order: i64,
168    /// Whether the draw may draw in the opaque pass, where its layer draws
169    /// there, rather than in the translucent pass. It draws in one of the
170    /// two.
171    pub opaque: bool,
172    pub depth: Depth,
173    /// Whether the draw clips: a draw at the layer's depth to the mask of
174    /// its tile ([`Group::push_at`]), a 3D one to where none of the group's
175    /// 3D draws of the pass drew before it, so no pixel blends twice. A
176    /// group with a draw that clips draws the masks of its layer's tiles.
177    pub clip: bool,
178}
179
180impl Draw {
181    /// A draw of order 0 in the translucent pass that tests, and doesn't
182    /// write, the nearest depth of its layer, and doesn't clip.
183    pub const DEFAULT: Draw = Draw {
184        order: 0,
185        opaque: false,
186        depth: Depth::Layer { sub_layer: 0, mask: DepthMaskType::ReadOnly },
187        clip: false,
188    };
189
190    /// The passes the draw draws in.
191    fn passes(self) -> RenderPass {
192        if self.opaque { RenderPass::OPAQUE | RenderPass::TRANSLUCENT } else { RenderPass::TRANSLUCENT }
193    }
194}
195
196impl Default for Draw {
197    fn default() -> Self {
198        Draw::DEFAULT
199    }
200}
201
202/// One of a group's draws as the engine draws it. Its uniform values are
203/// the entries at its index in the storage buffers of its group.
204struct GroupDraw {
205    mesh: Mesh,
206    /// The tile whose mask it clips to.
207    tile: Option<OverscaledTileID>,
208    pass: RenderPass,
209    depth: Depth,
210    clip: bool,
211}
212
213/// Where a program's blocks of each draw are in the bytes a draw was pushed
214/// with, by the ids of their buffers: each block with its offset.
215struct ProgramBlocks {
216    program: &'static Program,
217    at: [Option<(usize, &'static Block)>; BUFFER_IDS],
218    /// Whether one of the draws whose buffers a write writes draws with it.
219    drawn: bool,
220}
221
222impl ProgramBlocks {
223    fn of(program: &'static Program) -> ProgramBlocks {
224        let mut at = [None; BUFFER_IDS];
225        let mut offset = 0;
226        for buffer in program.buffers {
227            if let BufferKind::Storage { block, .. } | BufferKind::DrawUniform(block) = buffer.kind {
228                at[buffer.id] = Some((offset, block));
229                offset += block.size;
230            }
231        }
232        ProgramBlocks { program, at, drawn: false }
233    }
234}
235
236/// A draw as it was pushed: the index of its program's blocks, its
237/// projection, and where its blocks start in the pushes' bytes.
238struct Pushed {
239    program: usize,
240    projection: ProjectionUBO,
241    blocks: usize,
242}
243
244/// A frame's draws as a layer pushed them, by the index it pushed them at,
245/// with the bytes of their blocks and of the blocks they share, which the
246/// engine writes to the buffers of the group's draws.
247#[derive(Default)]
248struct Pushes {
249    pushed: Vec<Pushed>,
250    /// The bytes of the pushed draws' blocks.
251    bytes: Vec<u8>,
252    /// The blocks of each draw of the pushed draws' programs.
253    programs: Vec<ProgramBlocks>,
254    /// The blocks the draws share, each its layout and where its bytes are
255    /// in `shared_bytes`.
256    shared: Vec<(&'static Block, Range<usize>)>,
257    shared_bytes: Vec<u8>,
258    /// Where a write of one of the draws' buffers gathers its bytes.
259    scratch: Vec<u8>,
260}
261
262/// Whether `a` and `b` are the layout of one block.
263fn same_block(a: &Block, b: &Block) -> bool {
264    std::ptr::eq(a, b) || a.name == b.name
265}
266
267impl Pushes {
268    fn clear(&mut self) {
269        self.pushed.clear();
270        self.bytes.clear();
271        self.shared.clear();
272        self.shared_bytes.clear();
273    }
274
275    /// Adds a draw of `program` with `projection`, whose blocks, of the
276    /// layouts `layouts`, are the pushes' bytes from `start`.
277    fn push(
278        &mut self,
279        program: &'static Program,
280        projection: Option<&ProjectionUBO>,
281        start: usize,
282        layouts: &'static [&'static Block],
283    ) {
284        debug_assert!(
285            program
286                .buffers
287                .iter()
288                .filter_map(|buffer| match buffer.kind {
289                    BufferKind::Storage { block, .. } | BufferKind::DrawUniform(block) => Some(block),
290                    _ => None,
291                })
292                .map(|block| block.name)
293                .eq(layouts.iter().map(|block| block.name)),
294            "a draw of {} pushed with blocks other than its program's of each draw",
295            program.name
296        );
297        debug_assert!(program.projection != Projection::Own, "a draw of {} with a projection of its own", program.name);
298        let index = self.programs.iter().position(|of| std::ptr::eq(of.program, program)).unwrap_or_else(|| {
299            self.programs.push(ProgramBlocks::of(program));
300            self.programs.len() - 1
301        });
302        self.pushed.push(Pushed { program: index, projection: projection.copied().unwrap_or_default(), blocks: start });
303    }
304
305    /// Adds a draw of `program` with `projection`, whose already-validated
306    /// per-draw blocks are the pushes' bytes from `start`.
307    fn push_unchecked(&mut self, program: &'static Program, projection: Option<&ProjectionUBO>, start: usize) {
308        let index = self.programs.iter().position(|of| std::ptr::eq(of.program, program)).unwrap_or_else(|| {
309            self.programs.push(ProgramBlocks::of(program));
310            self.programs.len() - 1
311        });
312        self.pushed.push(Pushed { program: index, projection: projection.copied().unwrap_or_default(), blocks: start });
313    }
314
315    /// Makes `bytes` the value of the shared block of the layout `layout`.
316    fn block(&mut self, layout: &'static Block, bytes: &[u8]) {
317        if let Some((_, range)) = self.shared.iter().find(|(given, _)| same_block(given, layout)) {
318            self.shared_bytes[range.clone()].copy_from_slice(bytes);
319        } else {
320            let start = self.shared_bytes.len();
321            self.shared_bytes.extend_from_slice(bytes);
322            self.shared.push((layout, start..self.shared_bytes.len()));
323        }
324    }
325
326    /// Validated version of [`block`](Self::block) for raw plugin bytes:
327    /// checks `bytes.len() == layout.size` and guards against same-name
328    /// different-size collisions before copying.
329    fn try_block(&mut self, layout: &'static Block, bytes: &[u8]) -> Result<(), Error> {
330        if bytes.len() != layout.size {
331            return Err(Error::invalid_argument(format!(
332                "uniform block '{}' expects {} bytes, got {}",
333                layout.name,
334                layout.size,
335                bytes.len()
336            )));
337        }
338        if let Some((given, range)) = self.shared.iter().find(|(given, _)| same_block(given, layout)) {
339            if range.len() != bytes.len() {
340                return Err(Error::invalid_argument(format!(
341                    "uniform block '{}' size {} conflicts with existing block '{}' of size {}",
342                    layout.name,
343                    bytes.len(),
344                    given.name,
345                    range.len()
346                )));
347            }
348            self.shared_bytes[range.clone()].copy_from_slice(bytes);
349        } else {
350            let start = self.shared_bytes.len();
351            self.shared_bytes.extend_from_slice(bytes);
352            self.shared.push((layout, start..self.shared_bytes.len()));
353        }
354        Ok(())
355    }
356
357    /// Writes to `buffers` the buffers that the pushed draws at `order`'s
358    /// indexes, in drawing order, read: at the id of each of their
359    /// programs' uniform blocks, the block of its layout that they share; at
360    /// the id of each storage buffer of an element per draw, each draw's
361    /// block, or zeros for a draw whose program reads none there; at the id
362    /// of a uniform block of a draw's own, which one draw reads, its block;
363    /// the draws' projections, or a projection of zeros for each draw where
364    /// none reads one, which every program declares; and the frame's paint
365    /// parameters, `paint_params`, where it has its own.
366    fn write(
367        &mut self,
368        gpu: &mut dyn Gpu,
369        context: &mut Context,
370        order: &[(i64, usize)],
371        paint_params: Option<&GlobalPaintParamsUBO>,
372        buffers: &mut DrawBuffers,
373    ) {
374        let Pushes { pushed, bytes, programs, shared, shared_bytes, scratch } = self;
375        for of in programs.iter_mut() {
376            of.drawn = false;
377        }
378        for &(_, index) in order {
379            programs[pushed[index].program].drawn = true;
380        }
381        let mut written = [false; BUFFER_IDS];
382        let (mut per_draw_projection, mut reads_paint_params) = (false, false);
383        for of in programs.iter().filter(|of| of.drawn) {
384            per_draw_projection |= of.program.projection == Projection::PerDraw;
385            reads_paint_params |= of.program.paint_params.is_some();
386        }
387        // The shared blocks first, then the draws': a backend joins writes
388        // to buffers next to each other into one copy, and the shared
389        // blocks' buffers, whose size doesn't change, stay where the first
390        // frame made them, before the draws' buffers.
391        let shared_first = programs.iter().filter(|of| of.drawn).flat_map(|of| {
392            let shared = of.program.buffers.iter().filter(|buffer| matches!(buffer.kind, BufferKind::Uniform(_)));
393            shared.map(move |buffer| (of, buffer))
394        });
395        let per_draw = programs.iter().filter(|of| of.drawn).flat_map(|of| {
396            let per_draw = of.program.buffers.iter().filter(|buffer| !matches!(buffer.kind, BufferKind::Uniform(_)));
397            per_draw.map(move |buffer| (of, buffer))
398        });
399        for (of, buffer) in shared_first.chain(per_draw) {
400            // A mesh binds its vertices read as storage buffers.
401            if matches!(buffer.kind, BufferKind::Vertices(_)) || std::mem::replace(&mut written[buffer.id], true) {
402                continue;
403            }
404            match buffer.kind {
405                BufferKind::Uniform(block) => {
406                    let Some((_, range)) = shared.iter().find(|(given, _)| same_block(given, block)) else {
407                        debug_assert!(false, "draws of {} without their uniform block {}", of.program.name, block.name);
408                        continue;
409                    };
410                    buffers.write_uniform(gpu, buffer.id, &shared_bytes[range.clone()], context.device());
411                }
412                BufferKind::Storage { stride, .. } => {
413                    scratch.clear();
414                    for &(_, index) in order {
415                        let Pushed { program, blocks, .. } = pushed[index];
416                        let end = scratch.len() + stride;
417                        if let Some((offset, block)) = programs[program].at[buffer.id] {
418                            let at = blocks + offset;
419                            scratch.extend_from_slice(&bytes[at..at + block.size]);
420                        }
421                        scratch.resize(end, 0);
422                    }
423                    buffers.write_storage(gpu, buffer.id, scratch, context.device());
424                }
425                BufferKind::DrawUniform(block) => {
426                    let mut own = order.iter().map(|&(_, index)| &pushed[index]).filter(|draw| {
427                        programs[draw.program].at[buffer.id].is_some_and(|(_, of)| same_block(of, block))
428                    });
429                    let Some(&Pushed { program, blocks, .. }) = own.next() else { continue };
430                    debug_assert!(own.next().is_none(), "two draws of a block of {}'s own", block.name);
431                    if let Some((offset, _)) = programs[program].at[buffer.id] {
432                        let at = blocks + offset;
433                        buffers.write_uniform(gpu, buffer.id, &bytes[at..at + block.size], context.device());
434                    }
435                }
436                BufferKind::Vertices(_) => {}
437            }
438        }
439        if per_draw_projection {
440            scratch.clear();
441            for &(_, index) in order {
442                scratch.extend_from_slice(bytemuck::bytes_of(&pushed[index].projection));
443            }
444            buffers.write_storage(gpu, PROJECTION_ID, scratch, context.device());
445        } else {
446            // GL's programs declare the block whether they read it or not,
447            // so each draw binds it all the same, with an element at its
448            // index.
449            let none = ProjectionUBO::default();
450            let none = bytemuck::bytes_of(&none);
451            let draws = order.len().max(1);
452            if buffers.get(PROJECTION_ID).is_none_or(|buffer| buffer.size() < draws * none.len()) {
453                scratch.clear();
454                for _ in 0..draws {
455                    scratch.extend_from_slice(none);
456                }
457                buffers.write_storage(gpu, PROJECTION_ID, scratch, context.device());
458            }
459        }
460        if let Some(paint_params) = paint_params.filter(|_| reads_paint_params) {
461            buffers.write_pod(gpu, PAINT_PARAMS_ID, paint_params, context.device());
462        }
463    }
464}
465
466/// A layer's draws of a frame in one place in the layers' order and depth,
467/// which the engine writes, uploads and draws in each of the frame's
468/// passes, and what they share.
469pub struct Group {
470    /// Tells the group apart in the layer composite.
471    id: SimpleIdentity,
472    /// The draws, in their order. A draw's index is the index of its
473    /// entries in the storage buffers, which shaders read as `globalIndex`.
474    draws: Vec<GroupDraw>,
475    /// The buffers the draws bind, by id, and the bindings of the meshes
476    /// they draw.
477    buffers: DrawBuffers,
478    /// How the draws composite onto the frame in the translucent pass, as one
479    /// surface, after they draw into a texture of their own; `None` where
480    /// they draw straight onto the frame.
481    composite: Option<Composite>,
482    /// The tiles whose masks the stencil buffer holds when the draws draw:
483    /// none where no draw clips.
484    stencil_tiles: Vec<UnwrappedTileID>,
485    /// The draws pushed for the next frame, by the index they were pushed
486    /// at, until [`finish`](Self::finish) makes them the frame's.
487    pending: Vec<Option<GroupDraw>>,
488    /// The pushed draws' orders, each with the draw's index in `pending`.
489    order: Vec<(i64, usize)>,
490    pushes: Pushes,
491}
492
493impl Default for Group {
494    /// No draws, with an id of their own.
495    fn default() -> Self {
496        Group {
497            id: SimpleIdentity::new(),
498            draws: Vec::new(),
499            buffers: DrawBuffers::default(),
500            composite: None,
501            stencil_tiles: Vec::new(),
502            pending: Vec::new(),
503            order: Vec::new(),
504            pushes: Pushes::default(),
505        }
506    }
507}
508
509impl Group {
510    /// Adds a draw of `mesh`, not of a tile, to the next frame's, with
511    /// `blocks`, the values of the draw's own of the blocks of each draw
512    /// that the mesh's program reads, in its order. The draw's projection,
513    /// where its program reads one, is zeros.
514    pub fn push<B: DrawBlocks>(&mut self, mesh: &Mesh, draw: Draw, blocks: B) -> &mut Self {
515        self.add(mesh, None, None, draw, blocks)
516    }
517
518    /// Adds a draw of `mesh` of the tile `tile` with `projection`, as
519    /// [`push`](Self::push) does: the draw reads `projection` where its
520    /// program reads a projection of each draw, and clips to `tile` where it
521    /// clips.
522    pub fn push_at<B: DrawBlocks>(
523        &mut self,
524        mesh: &Mesh,
525        tile: OverscaledTileID,
526        projection: &ProjectionUBO,
527        draw: Draw,
528        blocks: B,
529    ) -> &mut Self {
530        self.add(mesh, Some(tile), Some(projection), draw, blocks)
531    }
532
533    fn add<B: DrawBlocks>(
534        &mut self,
535        mesh: &Mesh,
536        tile: Option<OverscaledTileID>,
537        projection: Option<&ProjectionUBO>,
538        draw: Draw,
539        blocks: B,
540    ) -> &mut Self {
541        debug_assert!(
542            !draw.clip || tile.is_some() || matches!(draw.depth, Depth::Volume { .. }),
543            "a draw that clips without a tile"
544        );
545        let start = self.pushes.bytes.len();
546        blocks.each_bytes(|block| self.pushes.bytes.extend_from_slice(block));
547        self.pushes.push(mesh.program(), projection, start, B::BLOCKS);
548        self.order.push((draw.order, self.pending.len()));
549        self.pending.push(Some(GroupDraw {
550            mesh: mesh.clone(),
551            tile,
552            pass: draw.passes(),
553            depth: draw.depth,
554            clip: draw.clip,
555        }));
556        self
557    }
558
559    /// Makes `block` the value that the next frame's draws read of their
560    /// programs' uniform block of its layout, the last given. A draw whose
561    /// program has none ignores it.
562    pub fn block<T: UniformBlock>(&mut self, block: &T) -> &mut Self {
563        self.pushes.block(T::BLOCK, bytemuck::bytes_of(block));
564        self
565    }
566
567    /// Adds a draw of `mesh`, not of a tile, with raw per-draw block byte
568    /// slices matching `mesh.program()`'s per-draw `Storage`/`DrawUniform`
569    /// blocks in order.
570    pub fn push_raw(&mut self, mesh: &Mesh, draw: Draw, blocks: &[&[u8]]) -> Result<&mut Self, Error> {
571        self.add_raw(mesh, None, None, draw, blocks)
572    }
573
574    /// Adds a draw of `mesh` of the tile `tile` with `projection` and raw
575    /// per-draw block byte slices matching `mesh.program()`'s per-draw
576    /// `Storage`/`DrawUniform` blocks in order.
577    pub fn push_at_raw(
578        &mut self,
579        mesh: &Mesh,
580        tile: OverscaledTileID,
581        projection: &ProjectionUBO,
582        draw: Draw,
583        blocks: &[&[u8]],
584    ) -> Result<&mut Self, Error> {
585        self.add_raw(mesh, Some(tile), Some(projection), draw, blocks)
586    }
587
588    fn add_raw(
589        &mut self,
590        mesh: &Mesh,
591        tile: Option<OverscaledTileID>,
592        projection: Option<&ProjectionUBO>,
593        draw: Draw,
594        blocks: &[&[u8]],
595    ) -> Result<&mut Self, Error> {
596        if draw.clip && tile.is_none() && !matches!(draw.depth, Depth::Volume { .. }) {
597            return Err(Error::invalid_argument("a non-volume draw that clips requires a tile"));
598        }
599        let program = mesh.program();
600        if program.projection == Projection::Own {
601            return Err(Error::invalid_argument(format!(
602                "program '{}' uses Projection::Own and cannot be pushed through Group",
603                program.name
604            )));
605        }
606        let mut expected = program.buffers.iter().filter_map(|buffer| match buffer.kind {
607            BufferKind::Storage { block, .. } | BufferKind::DrawUniform(block) => Some(block),
608            _ => None,
609        });
610        let mut count = 0usize;
611        for (i, &bytes) in blocks.iter().enumerate() {
612            let Some(block) = expected.next() else {
613                return Err(Error::invalid_argument(format!(
614                    "program '{}' received too many per-draw blocks (unexpected block at index {i})",
615                    program.name
616                )));
617            };
618            if bytes.len() != block.size {
619                return Err(Error::invalid_argument(format!(
620                    "program '{}' per-draw block '{}' expects {} bytes, got {}",
621                    program.name,
622                    block.name,
623                    block.size,
624                    bytes.len()
625                )));
626            }
627            count += 1;
628        }
629        if let Some(missing) = expected.next() {
630            return Err(Error::invalid_argument(format!(
631                "program '{}' missing per-draw block '{}' (got {count} blocks)",
632                program.name, missing.name
633            )));
634        }
635        let start = self.pushes.bytes.len();
636        for &bytes in blocks {
637            self.pushes.bytes.extend_from_slice(bytes);
638        }
639        self.pushes.push_unchecked(program, projection, start);
640        self.order.push((draw.order, self.pending.len()));
641        self.pending.push(Some(GroupDraw {
642            mesh: mesh.clone(),
643            tile,
644            pass: draw.passes(),
645            depth: draw.depth,
646            clip: draw.clip,
647        }));
648        Ok(self)
649    }
650
651    /// Validated raw-bytes counterpart to [`block`](Self::block).
652    pub fn block_raw(&mut self, layout: &'static Block, bytes: &[u8]) -> Result<&mut Self, Error> {
653        self.pushes.try_block(layout, bytes)?;
654        Ok(self)
655    }
656
657    /// Makes the draws composite onto the frame as `composite` says, or
658    /// draw straight onto it for `None`.
659    pub fn composite(&mut self, composite: Option<Composite>) -> &mut Self {
660        self.composite = composite;
661        self
662    }
663
664    /// Drops the draws, those pushed too, and the bindings of the meshes
665    /// that dropped.
666    pub(crate) fn clear(&mut self) {
667        self.draws.clear();
668        self.clear_pushed();
669        self.buffers.sweep();
670    }
671
672    fn clear_pushed(&mut self) {
673        self.pending.clear();
674        self.order.clear();
675        self.pushes.clear();
676    }
677
678    /// Makes the pushed draws the frame's, in their order and in the order
679    /// they were pushed among draws of the same order. Where there are any,
680    /// it first writes the buffers they read, with `paint_params` where the
681    /// frame has paint parameters of its own (a drape's). Where a draw
682    /// clips, the group clips to the masks of `tiles`.
683    pub(crate) fn finish(
684        &mut self,
685        gpu: &mut dyn Gpu,
686        context: &mut Context,
687        paint_params: Option<&GlobalPaintParamsUBO>,
688        tiles: impl IntoIterator<Item = UnwrappedTileID>,
689    ) {
690        self.order.sort_unstable();
691        if !self.order.is_empty() {
692            self.pushes.write(gpu, context, &self.order, paint_params, &mut self.buffers);
693        }
694        let Group { draws, pending, order, stencil_tiles, .. } = self;
695        draws.clear();
696        draws.extend(order.iter().filter_map(|&(_, index)| pending[index].take()));
697        stencil_tiles.clear();
698        if draws.iter().any(|draw| draw.clip) {
699            stencil_tiles.extend(tiles);
700        }
701        self.buffers.sweep();
702        self.clear_pushed();
703    }
704
705    /// The tiles whose masks the stencil buffer holds when the group draws;
706    /// `None` for a group that needs no masks.
707    #[must_use]
708    pub(crate) fn stencil_tiles(&self) -> Option<&[UnwrappedTileID]> {
709        Some(&self.stencil_tiles[..]).filter(|tiles| !tiles.is_empty())
710    }
711
712    /// Whether the group draws anything.
713    #[must_use]
714    pub(crate) fn draws(&self) -> bool {
715        !self.draws.is_empty()
716    }
717
718    /// How the draws composite onto the frame, with the id that tells them
719    /// apart in the layer composite, if there are any and they composite.
720    #[must_use]
721    pub(crate) fn composited(&self) -> Option<(SimpleIdentity, Composite)> {
722        self.composite.filter(|_| !self.draws.is_empty()).map(|composite| (self.id, composite))
723    }
724
725    /// The meshes of the draws, in drawing order.
726    #[cfg(test)]
727    pub(crate) fn meshes(&self) -> impl Iterator<Item = &Mesh> {
728        self.draws.iter().map(|draw| &draw.mesh)
729    }
730
731    /// Uploads the meshes of the draws, in drawing order.
732    pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
733        for draw in &self.draws {
734            draw.mesh.upload(gpu, context);
735        }
736    }
737
738    /// Draws the draws of `parameters`' pass into the open pass of `gpu`,
739    /// the context's: into the layer composite's texture in the translucent
740    /// pass where they composite, and onto the frame otherwise. Where none
741    /// of the pass's draws is 3D, this first draws the masks of the tiles
742    /// that those that clip clip to; 3D draws that clip share one stencil
743    /// value of their own. Returns whether no draw failed.
744    pub(crate) fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) -> bool {
745        if self.draws.is_empty() || parameters.pass_target().is_none() {
746            return true;
747        }
748        let composited = (self.composite.is_some() && parameters.pass == RenderPass::TRANSLUCENT)
749            .then(|| parameters.begin_composited(gpu, self.id))
750            .flatten();
751        let drawing = composited.as_ref().is_none_or(Composited::draws);
752        let draws = if drawing { &self.draws[..] } else { &[] };
753        // A draw for both the opaque and the translucent pass draws in one:
754        // the opaque where its layer draws there, and the translucent
755        // otherwise. Drawn in both, it would cover itself.
756        let both = RenderPass::OPAQUE | RenderPass::TRANSLUCENT;
757        let drawn_in =
758            if parameters.opaque_pass_enabled_for_layer() { RenderPass::OPAQUE } else { RenderPass::TRANSLUCENT };
759        let pass = parameters.pass;
760        let skip = if pass & both != RenderPass::NONE && pass != drawn_in { both } else { RenderPass::NONE };
761        let in_pass = |draw: &&GroupDraw| {
762            draw.pass & pass != RenderPass::NONE && (skip == RenderPass::NONE || draw.pass & skip != skip)
763        };
764        let (volume, volume_clips) =
765            draws.iter().filter(in_pass).fold((false, false), |(volume, clips), draw| match draw.depth {
766                Depth::Volume { .. } => (true, clips || draw.clip),
767                _ => (volume, clips),
768            });
769        let mut volume_stencil = None;
770        if volume {
771            volume_stencil = volume_clips.then(|| parameters.stencil_mode_for_3d(gpu));
772        } else if drawing && !self.stencil_tiles.is_empty() {
773            parameters.render_tile_clipping_masks(gpu, &self.stencil_tiles);
774        }
775        let mut drawn = true;
776        for (index, draw) in draws.iter().enumerate().filter(|(_, draw)| in_pass(draw)) {
777            let tile_stencil = || match draw.tile.filter(|_| draw.clip) {
778                Some(tile) => parameters.stencil_mode_for_clipping(&tile.to_unwrapped()),
779                None => StencilMode::disabled(),
780            };
781            let (depth, stencil) = match draw.depth {
782                Depth::Off => (DepthMode::disabled(), tile_stencil()),
783                Depth::Layer { sub_layer, mask } => {
784                    (parameters.depth_mode_for_sublayer(sub_layer, mask), tile_stencil())
785                }
786                Depth::Volume { mask } => (
787                    parameters.depth_mode_for_3d(mask),
788                    volume_stencil.filter(|_| draw.clip).unwrap_or_else(StencilMode::disabled),
789                ),
790            };
791            let Some(mut objects) = parameters.context.take_mesh(&draw.mesh) else {
792                debug_assert!(false, "a draw of a mesh the context doesn't have");
793                continue;
794            };
795            drawn &= objects.draw(gpu, parameters, &mut self.buffers, depth, stencil, index as u32);
796            parameters.context.put_mesh(&draw.mesh, objects);
797        }
798        if let Some(composited) = composited {
799            parameters.end_composited(gpu, composited);
800        }
801        drawn
802    }
803}
804
805/// When a frame lends a layer the backend's commands ([`Draws::lend`]).
806#[derive(Clone, Copy, Debug, PartialEq, Eq)]
807pub enum LendAt {
808    /// Before the frame's passes, after the layer drew into its targets
809    /// ([`Draws::target`]): the frame's commands outside a pass.
810    BeforePasses,
811    /// In the frame's translucent pass, at the layer's place in the layers'
812    /// order and depth, after the layer's draws there: the open pass.
813    Pass,
814}
815
816/// What a frame lends a layer
817/// ([`Layer::lend`](crate::layer::Layer::lend)).
818pub struct Lent<'a> {
819    /// The backend's commands, as its `Gpu` lends them
820    /// ([`Gpu::lend`]): before the passes `mln_vulkan::CustomLayerEncoder`,
821    /// `mln_mtl::CustomLayerEncoder`, `mln_gl::CustomLayerEncoder`,
822    /// `mln_webgpu::CustomLayerEncoder` or `mln_d3d12::CustomLayerEncoder`,
823    /// and in a pass the same crate's `CustomLayerPass`, whose docs say what
824    /// the layer may change.
825    pub raw: &'a mut dyn Any,
826    /// The frame.
827    pub frame: &'a LayerFrame<'a>,
828    /// Where the frame draws the map, and the depth it writes there.
829    pub projection: &'a FrameProjection,
830    /// The depth that the frame's 2D layers write at the layer's place in
831    /// the layers' order, in a pass; `None` before the passes.
832    pub layer_depth: Option<f64>,
833    /// Where the layer queues what waits for the GPU to finish what it
834    /// drew with the commands, such as the freeing of what it made with
835    /// them. A clone stays usable for as long as the layer.
836    pub after_gpu: &'a AfterGpu,
837}
838
839/// A layer's draws of a frame, the map's or a drape's, which the engine
840/// keeps between frames: its main group, which takes a place in the layers'
841/// order and depth from the first frame that the layer has something to
842/// draw in, even with no draws; a group of draws into each target of the
843/// layer's that the frame draws into ([`target`](Self::target)); and where
844/// the frame lends the layer the backend's commands ([`lend`](Self::lend)).
845#[derive(Default)]
846pub struct Draws {
847    main: Group,
848    /// The groups of the draws into the layer's targets, each with its
849    /// target: the frame's, in the order the layer first pushed into them,
850    /// then those of the last frame that the frame hasn't drawn into yet,
851    /// which keep their buffers for it until the draws are written.
852    targets: Vec<(Target, Group)>,
853    /// How many of `targets` are the frame's.
854    frame_targets: usize,
855    /// Whether the frame lends the layer the backend's commands, at each
856    /// [`LendAt`].
857    lends: [bool; 2],
858    /// Whether a frame started the draws, from which the main group takes
859    /// its place.
860    started: bool,
861}
862
863impl Draws {
864    /// The layer's main group, which draws in its place in the layers' order
865    /// and depth.
866    pub fn main(&mut self) -> &mut Group {
867        &mut self.main
868    }
869
870    /// The group of the frame's draws into `target`, a target of the
871    /// layer's own. Once the frame's draws are written, the engine clears
872    /// the target and draws the group into it, before the frame's passes
873    /// or, in a drape, the drape's: in the opaque pass and then the
874    /// translucent one, without depth from the frame, and without clipping
875    /// to tiles. A target the frame asks for draws, cleared, even without
876    /// draws. The frame's draws sample what it drew.
877    pub fn target(&mut self, target: &Target) -> &mut Group {
878        let frame = self.frame_targets;
879        let at = match self.targets.iter().position(|(given, _)| given == target) {
880            Some(at) if at < frame => return &mut self.targets[at].1,
881            Some(at) => at,
882            None => {
883                self.targets.push((target.clone(), Group::default()));
884                self.targets.len() - 1
885            }
886        };
887        self.targets.swap(at, frame);
888        self.frame_targets += 1;
889        &mut self.targets[frame].1
890    }
891
892    /// Makes the frame lend the layer the backend's commands `at` its time
893    /// in the frame
894    /// ([`Layer::lend`](crate::layer::Layer::lend)).
895    pub fn lend(&mut self, at: LendAt) -> &mut Self {
896        self.lends[at as usize] = true;
897        self
898    }
899
900    /// Whether the frame lends the layer the backend's commands `at` its
901    /// time in the frame.
902    #[must_use]
903    pub(crate) fn lends(&self, at: LendAt) -> bool {
904        self.lends[at as usize]
905    }
906
907    /// Starts the draws of a frame the layer has something to draw in: none
908    /// yet, and the main group from now on takes its place.
909    pub(crate) fn begin(&mut self) {
910        self.started = true;
911        self.reset();
912    }
913
914    /// Drops the frame's draws, and the groups of the draws into targets.
915    /// The main group keeps its place.
916    pub(crate) fn clear(&mut self) {
917        self.reset();
918        self.targets.clear();
919    }
920
921    /// Drops the frame's draws and lends.
922    fn reset(&mut self) {
923        for (_, group) in &mut self.targets {
924            group.clear();
925        }
926        self.frame_targets = 0;
927        self.lends = [false; 2];
928        self.main.clear();
929    }
930
931    /// See [`Group::finish`], for every group: the draws into the frame's
932    /// targets, which don't clip, first, whose targets then hold what the
933    /// draws draw ([`Context::declare_target`]). The groups of the targets
934    /// the frame doesn't draw into go.
935    pub(crate) fn finish(
936        &mut self,
937        gpu: &mut dyn Gpu,
938        context: &mut Context,
939        paint_params: Option<&GlobalPaintParamsUBO>,
940        tiles: impl IntoIterator<Item = UnwrappedTileID>,
941    ) {
942        self.finish_targets(gpu, context, paint_params);
943        self.main.finish(gpu, context, paint_params, tiles);
944    }
945
946    /// The targets' part of [`finish`](Self::finish), which doesn't depend
947    /// on the type of the tiles.
948    fn finish_targets(
949        &mut self,
950        gpu: &mut dyn Gpu,
951        context: &mut Context,
952        paint_params: Option<&GlobalPaintParamsUBO>,
953    ) {
954        self.targets.truncate(self.frame_targets);
955        for (target, group) in &mut self.targets {
956            debug_assert!(group.composite.is_none(), "draws into a target that composite");
957            group.finish(gpu, context, paint_params, []);
958            context.declare_target(target);
959        }
960    }
961
962    /// Visits the groups that take a place in the layers' order and depth,
963    /// in drawing order.
964    pub(crate) fn visit_groups<'a>(&'a self, visit: &mut dyn FnMut(&'a Group)) {
965        if self.started {
966            visit(&self.main);
967        }
968    }
969
970    /// Uploads the meshes of the groups' draws: those into the frame's
971    /// targets, then the main group's.
972    pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
973        if self.started {
974            for (_, group) in &self.targets[..self.frame_targets] {
975                group.upload(gpu, context);
976            }
977            self.main.upload(gpu, context);
978        }
979    }
980
981    /// Clears each of the frame's targets and draws the draws into it
982    /// ([`Target::render`]), outside any pass of `gpu`, the context's.
983    pub(crate) fn render_targets(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
984        for (target, group) in &mut self.targets[..self.frame_targets] {
985            target.render(gpu, parameters, |gpu, parameters| group.render(gpu, parameters));
986        }
987    }
988
989    /// Draws the pass's draws of the groups into the open pass of `gpu`,
990    /// the context's, each at its depth, in `order`; `in_pass`, if any, runs
991    /// where the main group draws, after it, before the depth steps on.
992    pub(crate) fn render(
993        &mut self,
994        gpu: &mut dyn Gpu,
995        parameters: &mut PaintParameters<'_>,
996        order: DrawOrder,
997        in_pass: Option<&mut InPass<'_>>,
998    ) {
999        if self.started {
1000            self.main.render(gpu, parameters);
1001            if let Some(in_pass) = in_pass {
1002                in_pass(gpu, parameters);
1003            }
1004            order.step(parameters);
1005        }
1006    }
1007}
1008
1009impl Draws {
1010    /// Moves `parameters` past the depth that [`render`](Self::render)
1011    /// would draw the groups at, in `order`, without drawing them.
1012    pub(crate) fn skip(&self, parameters: &mut PaintParameters<'_>, order: DrawOrder) {
1013        if self.started {
1014            order.step(parameters);
1015        }
1016    }
1017}
1018
1019/// What [`Draws::render`] runs where the main group draws, in the open pass.
1020pub(crate) type InPass<'a> = dyn FnMut(&mut dyn Gpu, &mut PaintParameters<'_>) + 'a;
1021
1022/// One mesh and a frame's draw of it, with the buffers it binds: a draw of
1023/// the engine's own.
1024pub(crate) struct SingleDraw {
1025    pub(crate) mesh: Mesh,
1026    /// How the draw draws.
1027    draw: Draw,
1028    group: Group,
1029}
1030
1031impl SingleDraw {
1032    /// A draw of `mesh`, as `draw` draws, which draws once its blocks are
1033    /// written ([`write`](Self::write)).
1034    #[must_use]
1035    pub(crate) fn new(mesh: Mesh, draw: Draw) -> SingleDraw {
1036        SingleDraw { mesh, draw, group: Group::default() }
1037    }
1038
1039    /// Makes `block` the value the draw reads of its program's uniform
1040    /// block of its layout, as [`Group::block`] does, from the next
1041    /// [`write`](Self::write).
1042    pub(crate) fn block<T: UniformBlock>(&mut self, block: &T) -> &mut Self {
1043        self.group.block(block);
1044        self
1045    }
1046
1047    /// Writes the buffers the draw reads, with `blocks`, its values of its
1048    /// program's blocks of each draw, as [`Group::finish`] does.
1049    pub(crate) fn write<B: DrawBlocks>(&mut self, gpu: &mut dyn Gpu, context: &mut Context, blocks: B) {
1050        let SingleDraw { mesh, draw, group } = self;
1051        group.push(mesh, *draw, blocks);
1052        group.finish(gpu, context, None, []);
1053    }
1054
1055    /// Uploads the mesh, if the draw's blocks were written.
1056    pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
1057        self.group.upload(gpu, context);
1058    }
1059
1060    /// Draws the draw, if it draws in the pass, into the open pass of `gpu`,
1061    /// the context's. Returns whether it didn't fail.
1062    pub(crate) fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) -> bool {
1063        self.group.render(gpu, parameters)
1064    }
1065}
1066
1067/// What a frame's groups, or a drape's, need of the passes: their number,
1068/// which sets the passes' depth range; the masks of the tiles they clip to
1069/// and of the tiles that clear the stencil buffer; and the groups drawn as
1070/// a whole, each into the layer composite's texture and then onto the
1071/// frame.
1072#[derive(Default)]
1073pub(crate) struct DrawGroups {
1074    pub(crate) count: usize,
1075    pub(crate) clip_tiles: Vec<UnwrappedTileID>,
1076    /// The tiles whose masks clear the stencil buffer, also in
1077    /// `clip_tiles` ([`PaintParameters::stencil_clear_tiles`]).
1078    pub(crate) stencil_clear: StencilClear,
1079    pub(crate) composited: Vec<(SimpleIdentity, Composite)>,
1080}
1081
1082impl DrawGroups {
1083    /// The groups that `visit_groups` visits, in drawing order, of passes
1084    /// whose stencil the tiles that `stencil_clear_tiles` gives for the
1085    /// tiles they clip to clear ([`PaintParameters::stencil_clear_tiles`]).
1086    /// Groups of one source clip to the same tiles, which are added once.
1087    pub(crate) fn of<'a>(
1088        visit_groups: impl FnOnce(&mut dyn FnMut(&'a Group)),
1089        stencil_clear_tiles: impl FnOnce(&[UnwrappedTileID]) -> StencilClear,
1090    ) -> DrawGroups {
1091        let mut groups = DrawGroups::default();
1092        let mut last: Option<&[UnwrappedTileID]> = None;
1093        visit_groups(&mut |group| {
1094            groups.count += 1;
1095            if let Some(tiles) = group.stencil_tiles()
1096                && last.is_none_or(|last| last != tiles)
1097            {
1098                groups.clip_tiles.extend(tiles.iter().copied());
1099                last = Some(tiles);
1100            }
1101            groups.composited.extend(group.composited());
1102        });
1103        groups.stencil_clear = stencil_clear_tiles(&groups.clip_tiles);
1104        groups.clip_tiles.extend_from_slice(&groups.stencil_clear);
1105        if !groups.clip_tiles.is_sorted() {
1106            groups.clip_tiles.sort_unstable();
1107        }
1108        groups.clip_tiles.dedup();
1109        groups
1110    }
1111
1112    /// The depth range of the passes' 3D draws, from 0, below the depths of
1113    /// the groups' 2D draws.
1114    #[must_use]
1115    pub(crate) fn depth_range_size(&self) -> f32 {
1116        depth_range_size(self.count)
1117    }
1118}
1119
1120/// The depth range of the 3D draws of passes of `groups` draw groups, from
1121/// 0, below the depths of the groups' 2D draws.
1122#[must_use]
1123pub(crate) fn depth_range_size(groups: usize) -> f32 {
1124    1.0 - ((groups + 2) * PaintParameters::NUM_SUBLAYERS as usize) as f32 * PaintParameters::DEPTH_EPSILON
1125}
1126
1127/// The order the frame draws the layers' groups in, each at the depth of
1128/// [`PaintParameters::current_layer`], which [`DrawOrder::step`] moves to
1129/// the next group's.
1130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1131pub enum DrawOrder {
1132    /// The layers' order, bottom to top, with the depth going down by one
1133    /// after each group, to 0.
1134    BottomUp,
1135    /// The reverse order, top to bottom, with the depth going up by one
1136    /// after each group.
1137    TopDown,
1138}
1139
1140impl DrawOrder {
1141    /// Moves `parameters` to the depth of the group after the one it is at.
1142    pub(crate) fn step(self, parameters: &mut PaintParameters<'_>) {
1143        match self {
1144            DrawOrder::BottomUp => parameters.current_layer = parameters.current_layer.saturating_sub(1),
1145            DrawOrder::TopDown => parameters.current_layer += 1,
1146        }
1147    }
1148}
1149
1150#[cfg(test)]
1151mod tests {
1152    use mln_gfx::projection_variant::ProjectionVariant;
1153    use mln_gfx::shaders::program::{ProgramBuffer, Stages};
1154    use mln_gfx::shaders::source::Sources;
1155    use mln_gfx::{AttributeDataType, ColorMode, CullFaceMode, DrawMode};
1156
1157    use super::*;
1158    use crate::draw::POS;
1159    use crate::draw::indexes::DrawIndexes;
1160    use crate::draw::objects::DrawGeometry;
1161    use crate::draw::range::DrawRange;
1162    use crate::draw::vertex_attribute::{SharedAttribute, Uniforms, VertexAttributeArray};
1163    use crate::shaders::ubo::{LayerCompositeUBO, SkyPropsUBO};
1164    use crate::tests::with_context;
1165
1166    static TEST_RAW_PROGRAM: Program = Program {
1167        name: "TestRawProgram",
1168        buffers: &[
1169            ProgramBuffer::storage::<LayerCompositeUBO>("per_draw", Stages::Both),
1170            ProgramBuffer::uniform::<SkyPropsUBO>("group_block", 0, Stages::Fragment),
1171        ],
1172        paint_params: None,
1173        projection: Projection::PerDraw,
1174        attributes: &[POS],
1175        instance_attributes: &[],
1176        textures: &[],
1177        properties: &[],
1178        sources: Sources::NONE,
1179    };
1180
1181    fn test_mesh(context: &mut Context, program: &'static Program) -> Mesh {
1182        let shader = context.shader_key(program, Uniforms::default(), ProjectionVariant::Mercator);
1183        let verts = context.add_vertices(vec![[0i16, 0], [1, 0], [0, 1]]);
1184        let mut attrs = VertexAttributeArray::new();
1185        attrs.set_shared("pos", SharedAttribute::new(verts, AttributeDataType::Short2, 0, 4));
1186        let geometry = DrawGeometry {
1187            vertices: attrs,
1188            vertex_count: 3,
1189            mode: DrawMode::Triangles(),
1190            indexes: DrawIndexes::new(vec![0, 1, 2]),
1191            ranges: vec![DrawRange::indexes(0)],
1192            instances: None,
1193        };
1194        Mesh::new(context, shader, ColorMode::alpha_blended(), CullFaceMode::disabled(), geometry, Default::default())
1195    }
1196
1197    #[test]
1198    fn raw_draw_and_block_validation_checks_errors_and_accepts_valid_inputs() {
1199        with_context(|gpu, context| {
1200            let raw_mesh = test_mesh(context, &TEST_RAW_PROGRAM);
1201            let own_proj_mesh = test_mesh(context, &crate::shaders::programs::CLIPPING_MASK);
1202            let tile = OverscaledTileID::new(0, 0, mln_style::tile_id::CanonicalTileID::new(0, 0, 0));
1203            let proj = ProjectionUBO::default();
1204            let draw = Draw::DEFAULT;
1205            let clipped = Draw { clip: true, ..Draw::DEFAULT };
1206
1207            let mut group = Group::default();
1208
1209            // Projection::Own rejected.
1210            assert!(group.push_raw(&own_proj_mesh, draw, &[]).is_err());
1211
1212            // Clip without tile rejected.
1213            let per_draw = vec![0u8; size_of::<LayerCompositeUBO>()];
1214            assert!(group.push_raw(&raw_mesh, clipped, &[&per_draw]).is_err());
1215
1216            // Wrong per-draw block count rejected.
1217            assert!(group.push_raw(&raw_mesh, draw, &[]).is_err());
1218            assert!(group.push_raw(&raw_mesh, draw, &[&per_draw, &per_draw]).is_err());
1219
1220            // Wrong per-draw block byte length rejected.
1221            let wrong_len = [0u8; 4];
1222            assert!(group.push_raw(&raw_mesh, draw, &[&wrong_len]).is_err());
1223
1224            // Group block same name with different byte length rejected.
1225            let block_ok = vec![1u8; size_of::<SkyPropsUBO>()];
1226            let block_wrong = [2u8; 8];
1227            assert!(group.block_raw(SkyPropsUBO::BLOCK, &block_ok).is_ok());
1228            assert!(group.block_raw(SkyPropsUBO::BLOCK, &block_wrong).is_err());
1229            // Updating same name with same length succeeds.
1230            let block_ok_2 = vec![3u8; size_of::<SkyPropsUBO>()];
1231            assert!(group.block_raw(SkyPropsUBO::BLOCK, &block_ok_2).is_ok());
1232
1233            // Valid push_raw and push_at_raw succeed and finish cleanly.
1234            assert!(group.push_raw(&raw_mesh, draw, &[&per_draw]).is_ok());
1235            assert!(group.push_at_raw(&raw_mesh, tile, &proj, clipped, &[&per_draw]).is_ok());
1236            group.finish(gpu, context, None, [tile.to_unwrapped()]);
1237            group.upload(gpu, context);
1238            assert_eq!(group.draws.len(), 2);
1239            assert_eq!(group.stencil_tiles, vec![tile.to_unwrapped()]);
1240        });
1241    }
1242
1243    #[test]
1244    fn mesh_bind_vertices_replaces_bound_vertices_and_uploads() {
1245        with_context(|gpu, context| {
1246            let mesh = test_mesh(context, &TEST_RAW_PROGRAM);
1247            let extra = context.add_vertices(vec![[10i16, 20], [30, 40], [50, 60]]);
1248            let mut res = crate::draw::Resources::new(gpu, context);
1249            let binding = crate::draw::vertex::VertexBinding::new(
1250                &extra,
1251                4,
1252                vec![crate::draw::vertex::VertexAttribute {
1253                    name: "pos",
1254                    format: AttributeDataType::Short2,
1255                    offset: 0,
1256                }],
1257            );
1258            mesh.bind_vertices(&mut res, &binding);
1259            mesh.upload(res.gpu, res.context);
1260            assert!(res.context.vertices(&extra).is_some_and(|stored| !stored.needs_upload()));
1261        });
1262    }
1263}