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;
34
35use crate::camera::{FrameProjection, View};
36use crate::draw::after_gpu::AfterGpu;
37use crate::draw::context::Context;
38use crate::draw::identity::SimpleIdentity;
39use crate::draw::objects::{DrawBuffers, Mesh};
40use crate::draw::target::Target;
41use crate::render::layer_composite::Composite;
42use crate::render::light::EvaluatedLight;
43use crate::render::paint_parameters::{Composited, PaintParameters, StencilClear, TransformParameters};
44use crate::render::pass::RenderPass;
45use crate::render::terrain::FrameGround;
46use crate::tile::{OverscaledTileID, UnwrappedTileID};
47
48/// What a layer's frame draws into.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub(crate) enum DrawsInto {
51    /// The map.
52    Map,
53    /// A drape of a terrain tile, whose shading the terrain's surface adds
54    /// where `lit` ([`SurfaceLight`](crate::render::terrain::SurfaceLight)).
55    Drape { lit: bool },
56}
57
58/// The frame a layer makes its draws for, as it reads it: the camera, the
59/// target's size and scale, the light and ground, and what it draws into.
60#[derive(Clone)]
61pub struct LayerFrame<'a> {
62    pub view: &'a View,
63    pub(crate) transform_params: &'a TransformParameters,
64    /// Whether a gesture or an animation moves the camera: draws favor speed
65    /// over crispness then.
66    pub camera_moving: bool,
67    pub light: &'a EvaluatedLight,
68    pub pixel_ratio: f32,
69    pub renderable_size: Size,
70    pub pixels_to_gl_units: [f32; 2],
71    /// Whether the frame draws terrain, under which 2D layers draw without
72    /// depth.
73    pub terrain: bool,
74    /// Whether a group drawn as a whole ([`Group::composite`]) can draw
75    /// with the frame's depth and stencil: the frame has them, and a pass can
76    /// draw into them together with the layer composite's texture.
77    pub composites_with_frame_depth: bool,
78    /// The ground that the layers that stand on terrain stand on, where the
79    /// frame has terrain and such layers.
80    pub ground: Option<Rc<FrameGround>>,
81    pub(crate) into: DrawsInto,
82}
83
84impl LayerFrame<'_> {
85    /// The frame's camera.
86    #[must_use]
87    pub fn view(&self) -> &View {
88        self.view
89    }
90
91    /// The device pixels of the frame's target per logical pixel.
92    #[must_use]
93    pub fn pixel_ratio(&self) -> f32 {
94        self.pixel_ratio
95    }
96
97    /// The size of the frame's target, in device pixels.
98    #[must_use]
99    pub fn size(&self) -> Size {
100        self.renderable_size
101    }
102
103    /// Whether the frame is a drape whose shading the terrain's surface
104    /// adds: a hillshade draws its slopes there, unlit.
105    #[must_use]
106    pub fn drape_lit(&self) -> bool {
107        matches!(self.into, DrawsInto::Drape { lit: true })
108    }
109}
110
111/// How a draw tests and writes depth.
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub enum Depth {
114    /// It draws without a depth test.
115    Off,
116    /// It tests the depth of a sub-layer of the layer's depth, and writes it
117    /// as `mask` says.
118    Layer { sub_layer: u8, mask: DepthMaskType },
119    /// It tests the depth range of 3D geometry, which the 3D draws of all
120    /// layers share, and writes it as `mask` says.
121    Volume { mask: DepthMaskType },
122}
123
124/// How a draw of a mesh draws: its place among its group's draws, its pass,
125/// its depth and whether it clips.
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127pub struct Draw {
128    /// Where the draw is among its group's draws: lower orders draw first,
129    /// and draws of one order in the order they were pushed. A layer that
130    /// draws its meshes in the order they were made gives each draw its
131    /// mesh's [`seq`](Mesh::seq).
132    pub order: i64,
133    /// Whether the draw may draw in the opaque pass, where its layer draws
134    /// there, rather than in the translucent pass. It draws in one of the
135    /// two.
136    pub opaque: bool,
137    pub depth: Depth,
138    /// Whether the draw clips: a draw at the layer's depth to the mask of
139    /// its tile ([`Group::push_at`]), a 3D one to where none of the group's
140    /// 3D draws of the pass drew before it, so no pixel blends twice. A
141    /// group with a draw that clips draws the masks of its layer's tiles.
142    pub clip: bool,
143}
144
145impl Draw {
146    /// A draw of order 0 in the translucent pass that tests, and doesn't
147    /// write, the nearest depth of its layer, and doesn't clip.
148    pub const DEFAULT: Draw = Draw {
149        order: 0,
150        opaque: false,
151        depth: Depth::Layer { sub_layer: 0, mask: DepthMaskType::ReadOnly },
152        clip: false,
153    };
154
155    /// The passes the draw draws in.
156    fn passes(self) -> RenderPass {
157        if self.opaque { RenderPass::Opaque | RenderPass::Translucent } else { RenderPass::Translucent }
158    }
159}
160
161impl Default for Draw {
162    fn default() -> Self {
163        Draw::DEFAULT
164    }
165}
166
167/// One of a group's draws as the engine draws it. Its uniform values are
168/// the entries at its index in the storage buffers of its group.
169struct GroupDraw {
170    mesh: Mesh,
171    /// The tile whose mask it clips to.
172    tile: Option<OverscaledTileID>,
173    pass: RenderPass,
174    depth: Depth,
175    clip: bool,
176}
177
178/// Where a program's blocks of each draw are in the bytes a draw was pushed
179/// with, by the ids of their buffers: each block with its offset.
180struct ProgramBlocks {
181    program: &'static Program,
182    at: [Option<(usize, &'static Block)>; BUFFER_IDS],
183    /// Whether one of the draws whose buffers a write writes draws with it.
184    drawn: bool,
185}
186
187impl ProgramBlocks {
188    fn of(program: &'static Program) -> ProgramBlocks {
189        let mut at = [None; BUFFER_IDS];
190        let mut offset = 0;
191        for buffer in program.buffers {
192            if let BufferKind::Storage { block, .. } | BufferKind::DrawUniform(block) = buffer.kind {
193                at[buffer.id] = Some((offset, block));
194                offset += block.size;
195            }
196        }
197        ProgramBlocks { program, at, drawn: false }
198    }
199}
200
201/// A draw as it was pushed: the index of its program's blocks, its
202/// projection, and where its blocks start in the pushes' bytes.
203struct Pushed {
204    program: usize,
205    projection: ProjectionUBO,
206    blocks: usize,
207}
208
209/// A frame's draws as a layer pushed them, by the index it pushed them at,
210/// with the bytes of their blocks and of the blocks they share, which the
211/// engine writes to the buffers of the group's draws.
212#[derive(Default)]
213struct Pushes {
214    pushed: Vec<Pushed>,
215    /// The bytes of the pushed draws' blocks.
216    bytes: Vec<u8>,
217    /// The blocks of each draw of the pushed draws' programs.
218    programs: Vec<ProgramBlocks>,
219    /// The blocks the draws share, each its layout and where its bytes are
220    /// in `shared_bytes`.
221    shared: Vec<(&'static Block, Range<usize>)>,
222    shared_bytes: Vec<u8>,
223    /// Where a write of one of the draws' buffers gathers its bytes.
224    scratch: Vec<u8>,
225}
226
227/// Whether `a` and `b` are the layout of one block.
228fn same_block(a: &Block, b: &Block) -> bool {
229    std::ptr::eq(a, b) || a.name == b.name
230}
231
232impl Pushes {
233    fn clear(&mut self) {
234        self.pushed.clear();
235        self.bytes.clear();
236        self.shared.clear();
237        self.shared_bytes.clear();
238    }
239
240    /// Adds a draw of `program` with `projection`, whose blocks, of the
241    /// layouts `layouts`, are the pushes' bytes from `start`.
242    fn push(
243        &mut self,
244        program: &'static Program,
245        projection: Option<&ProjectionUBO>,
246        start: usize,
247        layouts: &'static [&'static Block],
248    ) {
249        debug_assert!(
250            program
251                .buffers
252                .iter()
253                .filter_map(|buffer| match buffer.kind {
254                    BufferKind::Storage { block, .. } | BufferKind::DrawUniform(block) => Some(block),
255                    _ => None,
256                })
257                .map(|block| block.name)
258                .eq(layouts.iter().map(|block| block.name)),
259            "a draw of {} pushed with blocks other than its program's of each draw",
260            program.name
261        );
262        debug_assert!(program.projection != Projection::Own, "a draw of {} with a projection of its own", program.name);
263        let index = self.programs.iter().position(|of| std::ptr::eq(of.program, program)).unwrap_or_else(|| {
264            self.programs.push(ProgramBlocks::of(program));
265            self.programs.len() - 1
266        });
267        self.pushed.push(Pushed { program: index, projection: projection.copied().unwrap_or_default(), blocks: start });
268    }
269
270    /// Makes `bytes` the value of the shared block of the layout `layout`.
271    fn block(&mut self, layout: &'static Block, bytes: &[u8]) {
272        if let Some((_, range)) = self.shared.iter().find(|(given, _)| same_block(given, layout)) {
273            self.shared_bytes[range.clone()].copy_from_slice(bytes);
274        } else {
275            let start = self.shared_bytes.len();
276            self.shared_bytes.extend_from_slice(bytes);
277            self.shared.push((layout, start..self.shared_bytes.len()));
278        }
279    }
280
281    /// Writes to `buffers` the buffers that the pushed draws at `order`'s
282    /// indexes, in drawing order, read: at the id of each of their
283    /// programs' uniform blocks, the block of its layout that they share; at
284    /// the id of each storage buffer of an element per draw, each draw's
285    /// block, or zeros for a draw whose program reads none there; at the id
286    /// of a uniform block of a draw's own, which one draw reads, its block;
287    /// the draws' projections, or a projection of zeros where none reads
288    /// one, which every program declares; and the frame's paint parameters,
289    /// `paint_params`, where it has its own.
290    fn write(
291        &mut self,
292        gpu: &mut dyn Gpu,
293        context: &mut Context,
294        order: &[(i64, usize)],
295        paint_params: Option<&GlobalPaintParamsUBO>,
296        buffers: &mut DrawBuffers,
297    ) {
298        let Pushes { pushed, bytes, programs, shared, shared_bytes, scratch } = self;
299        for of in programs.iter_mut() {
300            of.drawn = false;
301        }
302        for &(_, index) in order {
303            programs[pushed[index].program].drawn = true;
304        }
305        let mut written = [false; BUFFER_IDS];
306        let (mut per_draw_projection, mut reads_paint_params) = (false, false);
307        for of in programs.iter().filter(|of| of.drawn) {
308            per_draw_projection |= of.program.projection == Projection::PerDraw;
309            reads_paint_params |= of.program.paint_params.is_some();
310        }
311        // The shared blocks first, then the draws': a backend joins writes
312        // to buffers next to each other into one copy, and the shared
313        // blocks' buffers, whose size doesn't change, stay where the first
314        // frame made them, before the draws' buffers.
315        let shared_first = programs.iter().filter(|of| of.drawn).flat_map(|of| {
316            let shared = of.program.buffers.iter().filter(|buffer| matches!(buffer.kind, BufferKind::Uniform(_)));
317            shared.map(move |buffer| (of, buffer))
318        });
319        let per_draw = programs.iter().filter(|of| of.drawn).flat_map(|of| {
320            let per_draw = of.program.buffers.iter().filter(|buffer| !matches!(buffer.kind, BufferKind::Uniform(_)));
321            per_draw.map(move |buffer| (of, buffer))
322        });
323        for (of, buffer) in shared_first.chain(per_draw) {
324            // A mesh binds its vertices read as storage buffers.
325            if matches!(buffer.kind, BufferKind::Vertices(_)) || std::mem::replace(&mut written[buffer.id], true) {
326                continue;
327            }
328            match buffer.kind {
329                BufferKind::Uniform(block) => {
330                    let Some((_, range)) = shared.iter().find(|(given, _)| same_block(given, block)) else {
331                        debug_assert!(false, "draws of {} without their uniform block {}", of.program.name, block.name);
332                        continue;
333                    };
334                    buffers.write_uniform(gpu, buffer.id, &shared_bytes[range.clone()], context.device());
335                }
336                BufferKind::Storage { stride, .. } => {
337                    scratch.clear();
338                    for &(_, index) in order {
339                        let Pushed { program, blocks, .. } = pushed[index];
340                        let end = scratch.len() + stride;
341                        if let Some((offset, block)) = programs[program].at[buffer.id] {
342                            let at = blocks + offset;
343                            scratch.extend_from_slice(&bytes[at..at + block.size]);
344                        }
345                        scratch.resize(end, 0);
346                    }
347                    buffers.write_storage(gpu, buffer.id, scratch, context.device());
348                }
349                BufferKind::DrawUniform(block) => {
350                    let mut own = order.iter().map(|&(_, index)| &pushed[index]).filter(|draw| {
351                        programs[draw.program].at[buffer.id].is_some_and(|(_, of)| same_block(of, block))
352                    });
353                    let Some(&Pushed { program, blocks, .. }) = own.next() else { continue };
354                    debug_assert!(own.next().is_none(), "two draws of a block of {}'s own", block.name);
355                    if let Some((offset, _)) = programs[program].at[buffer.id] {
356                        let at = blocks + offset;
357                        buffers.write_uniform(gpu, buffer.id, &bytes[at..at + block.size], context.device());
358                    }
359                }
360                BufferKind::Vertices(_) => {}
361            }
362        }
363        if per_draw_projection {
364            scratch.clear();
365            for &(_, index) in order {
366                scratch.extend_from_slice(bytemuck::bytes_of(&pushed[index].projection));
367            }
368            buffers.write_storage(gpu, PROJECTION_ID, scratch, context.device());
369        } else if buffers.get(PROJECTION_ID).is_none() {
370            // GL's programs declare the block whether they read it or not,
371            // so a draw binds it all the same.
372            let none = ProjectionUBO::default();
373            buffers.write_storage(gpu, PROJECTION_ID, bytemuck::bytes_of(&none), context.device());
374        }
375        if let Some(paint_params) = paint_params.filter(|_| reads_paint_params) {
376            buffers.write_pod(gpu, PAINT_PARAMS_ID, paint_params, context.device());
377        }
378    }
379}
380
381/// A layer's draws of a frame in one place in the layers' order and depth,
382/// which the engine writes, uploads and draws in each of the frame's
383/// passes, and what they share.
384pub struct Group {
385    /// Tells the group apart in the layer composite.
386    id: SimpleIdentity,
387    /// The draws, in their order. A draw's index is the index of its
388    /// entries in the storage buffers, which shaders read as `globalIndex`.
389    draws: Vec<GroupDraw>,
390    /// The buffers the draws bind, by id, and the bindings of the meshes
391    /// they draw.
392    buffers: DrawBuffers,
393    /// How the draws composite onto the frame in the translucent pass, as one
394    /// surface, after they draw into a texture of their own; `None` where
395    /// they draw straight onto the frame.
396    composite: Option<Composite>,
397    /// The tiles whose masks the stencil buffer holds when the draws draw:
398    /// none where no draw clips.
399    stencil_tiles: Vec<UnwrappedTileID>,
400    /// The draws pushed for the next frame, by the index they were pushed
401    /// at, until [`finish`](Self::finish) makes them the frame's.
402    pending: Vec<Option<GroupDraw>>,
403    /// The pushed draws' orders, each with the draw's index in `pending`.
404    order: Vec<(i64, usize)>,
405    pushes: Pushes,
406}
407
408impl Default for Group {
409    /// No draws, with an id of their own.
410    fn default() -> Self {
411        Group {
412            id: SimpleIdentity::new(),
413            draws: Vec::new(),
414            buffers: DrawBuffers::default(),
415            composite: None,
416            stencil_tiles: Vec::new(),
417            pending: Vec::new(),
418            order: Vec::new(),
419            pushes: Pushes::default(),
420        }
421    }
422}
423
424impl Group {
425    /// Adds a draw of `mesh`, not of a tile, to the next frame's, with
426    /// `blocks`, the values of the draw's own of the blocks of each draw
427    /// that the mesh's program reads, in its order. The draw's projection,
428    /// where its program reads one, is zeros.
429    pub fn push<B: DrawBlocks>(&mut self, mesh: &Mesh, draw: Draw, blocks: B) -> &mut Self {
430        self.add(mesh, None, None, draw, blocks)
431    }
432
433    /// Adds a draw of `mesh` of the tile `tile` with `projection`, as
434    /// [`push`](Self::push) does: the draw reads `projection` where its
435    /// program reads a projection of each draw, and clips to `tile` where it
436    /// clips.
437    pub fn push_at<B: DrawBlocks>(
438        &mut self,
439        mesh: &Mesh,
440        tile: OverscaledTileID,
441        projection: &ProjectionUBO,
442        draw: Draw,
443        blocks: B,
444    ) -> &mut Self {
445        self.add(mesh, Some(tile), Some(projection), draw, blocks)
446    }
447
448    fn add<B: DrawBlocks>(
449        &mut self,
450        mesh: &Mesh,
451        tile: Option<OverscaledTileID>,
452        projection: Option<&ProjectionUBO>,
453        draw: Draw,
454        blocks: B,
455    ) -> &mut Self {
456        debug_assert!(
457            !draw.clip || tile.is_some() || matches!(draw.depth, Depth::Volume { .. }),
458            "a draw that clips without a tile"
459        );
460        let start = self.pushes.bytes.len();
461        blocks.each_bytes(|block| self.pushes.bytes.extend_from_slice(block));
462        self.pushes.push(mesh.program(), projection, start, B::BLOCKS);
463        self.order.push((draw.order, self.pending.len()));
464        self.pending.push(Some(GroupDraw {
465            mesh: mesh.clone(),
466            tile,
467            pass: draw.passes(),
468            depth: draw.depth,
469            clip: draw.clip,
470        }));
471        self
472    }
473
474    /// Makes `block` the value that the next frame's draws read of their
475    /// programs' uniform block of its layout, the last given. A draw whose
476    /// program has none ignores it.
477    pub fn block<T: UniformBlock>(&mut self, block: &T) -> &mut Self {
478        self.pushes.block(T::BLOCK, bytemuck::bytes_of(block));
479        self
480    }
481
482    /// Makes the draws composite onto the frame as `composite` says, or
483    /// draw straight onto it for `None`.
484    pub fn composite(&mut self, composite: Option<Composite>) -> &mut Self {
485        self.composite = composite;
486        self
487    }
488
489    /// Drops the draws, those pushed too, and the bindings of the meshes
490    /// that dropped.
491    pub(crate) fn clear(&mut self) {
492        self.draws.clear();
493        self.clear_pushed();
494        self.buffers.sweep();
495    }
496
497    fn clear_pushed(&mut self) {
498        self.pending.clear();
499        self.order.clear();
500        self.pushes.clear();
501    }
502
503    /// Makes the pushed draws the frame's, in their order and in the order
504    /// they were pushed among draws of the same order. Where there are any,
505    /// it first writes the buffers they read, with `paint_params` where the
506    /// frame has paint parameters of its own (a drape's). Where a draw
507    /// clips, the group clips to the masks of `tiles`.
508    pub(crate) fn finish(
509        &mut self,
510        gpu: &mut dyn Gpu,
511        context: &mut Context,
512        paint_params: Option<&GlobalPaintParamsUBO>,
513        tiles: impl IntoIterator<Item = UnwrappedTileID>,
514    ) {
515        self.order.sort_unstable();
516        if !self.order.is_empty() {
517            self.pushes.write(gpu, context, &self.order, paint_params, &mut self.buffers);
518        }
519        let Group { draws, pending, order, stencil_tiles, .. } = self;
520        draws.clear();
521        draws.extend(order.iter().filter_map(|&(_, index)| pending[index].take()));
522        stencil_tiles.clear();
523        if draws.iter().any(|draw| draw.clip) {
524            stencil_tiles.extend(tiles);
525        }
526        self.buffers.sweep();
527        self.clear_pushed();
528    }
529
530    /// The tiles whose masks the stencil buffer holds when the group draws;
531    /// `None` for a group that needs no masks.
532    #[must_use]
533    pub(crate) fn stencil_tiles(&self) -> Option<&[UnwrappedTileID]> {
534        Some(&self.stencil_tiles[..]).filter(|tiles| !tiles.is_empty())
535    }
536
537    /// Whether the group draws anything.
538    #[must_use]
539    pub(crate) fn draws(&self) -> bool {
540        !self.draws.is_empty()
541    }
542
543    /// How the draws composite onto the frame, with the id that tells them
544    /// apart in the layer composite, if there are any and they composite.
545    #[must_use]
546    pub(crate) fn composited(&self) -> Option<(SimpleIdentity, Composite)> {
547        self.composite.filter(|_| !self.draws.is_empty()).map(|composite| (self.id, composite))
548    }
549
550    /// The meshes of the draws, in drawing order.
551    #[cfg(test)]
552    pub(crate) fn meshes(&self) -> impl Iterator<Item = &Mesh> {
553        self.draws.iter().map(|draw| &draw.mesh)
554    }
555
556    /// Uploads the meshes of the draws, in drawing order.
557    pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
558        for draw in &self.draws {
559            draw.mesh.upload(gpu, context);
560        }
561    }
562
563    /// Draws the draws of `parameters`' pass into the open pass of `gpu`,
564    /// the context's: into the layer composite's texture in the translucent
565    /// pass where they composite, and onto the frame otherwise. Where none
566    /// of the pass's draws is 3D, this first draws the masks of the tiles
567    /// that those that clip clip to; 3D draws that clip share one stencil
568    /// value of their own. Returns whether no draw failed.
569    pub(crate) fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) -> bool {
570        if self.draws.is_empty() || parameters.pass_target().is_none() {
571            return true;
572        }
573        let composited = (self.composite.is_some() && parameters.pass == RenderPass::Translucent)
574            .then(|| parameters.begin_composited(gpu, self.id))
575            .flatten();
576        let drawing = composited.as_ref().is_none_or(Composited::draws);
577        let draws = if drawing { &self.draws[..] } else { &[] };
578        // A draw for both the opaque and the translucent pass draws in one:
579        // the opaque where its layer draws there, and the translucent
580        // otherwise. Drawn in both, it would cover itself.
581        let both = RenderPass::Opaque | RenderPass::Translucent;
582        let drawn_in =
583            if parameters.opaque_pass_enabled_for_layer() { RenderPass::Opaque } else { RenderPass::Translucent };
584        let pass = parameters.pass;
585        let skip = if pass & both != RenderPass::None && pass != drawn_in { both } else { RenderPass::None };
586        let in_pass = |draw: &&GroupDraw| {
587            draw.pass & pass != RenderPass::None && (skip == RenderPass::None || draw.pass & skip != skip)
588        };
589        let (volume, volume_clips) =
590            draws.iter().filter(in_pass).fold((false, false), |(volume, clips), draw| match draw.depth {
591                Depth::Volume { .. } => (true, clips || draw.clip),
592                _ => (volume, clips),
593            });
594        let mut volume_stencil = None;
595        if volume {
596            volume_stencil = volume_clips.then(|| parameters.stencil_mode_for_3d(gpu));
597        } else if drawing && !self.stencil_tiles.is_empty() {
598            parameters.render_tile_clipping_masks(gpu, &self.stencil_tiles);
599        }
600        let mut drawn = true;
601        for (index, draw) in draws.iter().enumerate().filter(|(_, draw)| in_pass(draw)) {
602            let tile_stencil = || match draw.tile.filter(|_| draw.clip) {
603                Some(tile) => parameters.stencil_mode_for_clipping(&tile.to_unwrapped()),
604                None => StencilMode::disabled(),
605            };
606            let (depth, stencil) = match draw.depth {
607                Depth::Off => (DepthMode::disabled(), tile_stencil()),
608                Depth::Layer { sub_layer, mask } => {
609                    (parameters.depth_mode_for_sublayer(sub_layer, mask), tile_stencil())
610                }
611                Depth::Volume { mask } => (
612                    parameters.depth_mode_for_3d(mask),
613                    volume_stencil.filter(|_| draw.clip).unwrap_or_else(StencilMode::disabled),
614                ),
615            };
616            let Some(mut objects) = parameters.context.take_mesh(&draw.mesh) else {
617                debug_assert!(false, "a draw of a mesh the context doesn't have");
618                continue;
619            };
620            drawn &= objects.draw(gpu, parameters, &mut self.buffers, depth, stencil, index as u32);
621            parameters.context.put_mesh(&draw.mesh, objects);
622        }
623        if let Some(composited) = composited {
624            parameters.end_composited(gpu, composited);
625        }
626        drawn
627    }
628}
629
630/// When a frame lends a layer the backend's commands ([`Draws::lend`]).
631#[derive(Clone, Copy, Debug, PartialEq, Eq)]
632pub enum LendAt {
633    /// Before the frame's passes, after the layer drew into its targets
634    /// ([`Draws::target`]): the frame's commands outside a pass.
635    BeforePasses,
636    /// In the frame's translucent pass, at the layer's place in the layers'
637    /// order and depth, after the layer's draws there: the open pass.
638    Pass,
639}
640
641/// What a frame lends a layer
642/// ([`Layer::lend`](crate::layer::Layer::lend)).
643pub struct Lent<'a> {
644    /// The backend's commands, as its `Gpu` lends them
645    /// ([`Gpu::lend`]): before the passes `mln_vulkan::CustomLayerEncoder`,
646    /// `mln_mtl::CustomLayerEncoder`, `mln_gl::CustomLayerEncoder`,
647    /// `mln_webgpu::CustomLayerEncoder` or `mln_d3d12::CustomLayerEncoder`,
648    /// and in a pass the same crate's `CustomLayerPass`, whose docs say what
649    /// the layer may change.
650    pub raw: &'a mut dyn Any,
651    /// The frame.
652    pub frame: &'a LayerFrame<'a>,
653    /// Where the frame draws the map, and the depth it writes there.
654    pub projection: &'a FrameProjection,
655    /// The depth that the frame's 2D layers write at the layer's place in
656    /// the layers' order, in a pass; `None` before the passes.
657    pub layer_depth: Option<f64>,
658    /// Where the layer queues what waits for the GPU to finish what it
659    /// drew with the commands, such as the freeing of what it made with
660    /// them. A clone stays usable for as long as the layer.
661    pub after_gpu: &'a AfterGpu,
662}
663
664/// A layer's draws of a frame, the map's or a drape's, which the engine
665/// keeps between frames: its main group, which takes a place in the layers'
666/// order and depth from the first frame that the layer has something to
667/// draw in, even with no draws; a group of draws into each target of the
668/// layer's that the frame draws into ([`target`](Self::target)); and where
669/// the frame lends the layer the backend's commands ([`lend`](Self::lend)).
670#[derive(Default)]
671pub struct Draws {
672    main: Group,
673    /// The groups of the draws into the layer's targets, each with its
674    /// target: the frame's, in the order the layer first pushed into them,
675    /// then those of the last frame that the frame hasn't drawn into yet,
676    /// which keep their buffers for it until the draws are written.
677    targets: Vec<(Target, Group)>,
678    /// How many of `targets` are the frame's.
679    frame_targets: usize,
680    /// Whether the frame lends the layer the backend's commands, at each
681    /// [`LendAt`].
682    lends: [bool; 2],
683    /// Whether a frame started the draws, from which the main group takes
684    /// its place.
685    started: bool,
686}
687
688impl Draws {
689    /// The layer's main group, which draws in its place in the layers' order
690    /// and depth.
691    pub fn main(&mut self) -> &mut Group {
692        &mut self.main
693    }
694
695    /// The group of the frame's draws into `target`, a target of the
696    /// layer's own. Once the frame's draws are written, the engine clears
697    /// the target and draws the group into it, before the frame's passes
698    /// or, in a drape, the drape's: in the opaque pass and then the
699    /// translucent one, without depth from the frame, and without clipping
700    /// to tiles. A target the frame asks for draws, cleared, even without
701    /// draws. The frame's draws sample what it drew.
702    pub fn target(&mut self, target: &Target) -> &mut Group {
703        let frame = self.frame_targets;
704        let at = match self.targets.iter().position(|(given, _)| given == target) {
705            Some(at) if at < frame => return &mut self.targets[at].1,
706            Some(at) => at,
707            None => {
708                self.targets.push((target.clone(), Group::default()));
709                self.targets.len() - 1
710            }
711        };
712        self.targets.swap(at, frame);
713        self.frame_targets += 1;
714        &mut self.targets[frame].1
715    }
716
717    /// Makes the frame lend the layer the backend's commands `at` its time
718    /// in the frame
719    /// ([`Layer::lend`](crate::layer::Layer::lend)).
720    pub fn lend(&mut self, at: LendAt) -> &mut Self {
721        self.lends[at as usize] = true;
722        self
723    }
724
725    /// Whether the frame lends the layer the backend's commands `at` its
726    /// time in the frame.
727    #[must_use]
728    pub(crate) fn lends(&self, at: LendAt) -> bool {
729        self.lends[at as usize]
730    }
731
732    /// Starts the draws of a frame the layer has something to draw in: none
733    /// yet, and the main group from now on takes its place.
734    pub(crate) fn begin(&mut self) {
735        self.started = true;
736        self.reset();
737    }
738
739    /// Drops the frame's draws, and the groups of the draws into targets.
740    /// The main group keeps its place.
741    pub(crate) fn clear(&mut self) {
742        self.reset();
743        self.targets.clear();
744    }
745
746    /// Drops the frame's draws and lends.
747    fn reset(&mut self) {
748        for (_, group) in &mut self.targets {
749            group.clear();
750        }
751        self.frame_targets = 0;
752        self.lends = [false; 2];
753        self.main.clear();
754    }
755
756    /// See [`Group::finish`], for every group: the draws into the frame's
757    /// targets, which don't clip, first, whose targets then hold what the
758    /// draws draw ([`Context::declare_target`]). The groups of the targets
759    /// the frame doesn't draw into go.
760    pub(crate) fn finish(
761        &mut self,
762        gpu: &mut dyn Gpu,
763        context: &mut Context,
764        paint_params: Option<&GlobalPaintParamsUBO>,
765        tiles: impl IntoIterator<Item = UnwrappedTileID>,
766    ) {
767        self.finish_targets(gpu, context, paint_params);
768        self.main.finish(gpu, context, paint_params, tiles);
769    }
770
771    /// The targets' part of [`finish`](Self::finish), which doesn't depend
772    /// on the type of the tiles.
773    fn finish_targets(
774        &mut self,
775        gpu: &mut dyn Gpu,
776        context: &mut Context,
777        paint_params: Option<&GlobalPaintParamsUBO>,
778    ) {
779        self.targets.truncate(self.frame_targets);
780        for (target, group) in &mut self.targets {
781            debug_assert!(group.composite.is_none(), "draws into a target that composite");
782            group.finish(gpu, context, paint_params, []);
783            context.declare_target(target);
784        }
785    }
786
787    /// Visits the groups that take a place in the layers' order and depth,
788    /// in drawing order.
789    pub(crate) fn visit_groups<'a>(&'a self, visit: &mut dyn FnMut(&'a Group)) {
790        if self.started {
791            visit(&self.main);
792        }
793    }
794
795    /// Uploads the meshes of the groups' draws: those into the frame's
796    /// targets, then the main group's.
797    pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
798        if self.started {
799            for (_, group) in &self.targets[..self.frame_targets] {
800                group.upload(gpu, context);
801            }
802            self.main.upload(gpu, context);
803        }
804    }
805
806    /// Clears each of the frame's targets and draws the draws into it
807    /// ([`Target::render`]), outside any pass of `gpu`, the context's.
808    pub(crate) fn render_targets(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
809        for (target, group) in &mut self.targets[..self.frame_targets] {
810            target.render(gpu, parameters, |gpu, parameters| group.render(gpu, parameters));
811        }
812    }
813
814    /// Draws the pass's draws of the groups into the open pass of `gpu`,
815    /// the context's, each at its depth, in `order`; `in_pass`, if any, runs
816    /// where the main group draws, after it, before the depth steps on.
817    pub(crate) fn render(
818        &mut self,
819        gpu: &mut dyn Gpu,
820        parameters: &mut PaintParameters<'_>,
821        order: DrawOrder,
822        in_pass: Option<&mut InPass<'_>>,
823    ) {
824        if self.started {
825            self.main.render(gpu, parameters);
826            if let Some(in_pass) = in_pass {
827                in_pass(gpu, parameters);
828            }
829            order.step(parameters);
830        }
831    }
832}
833
834impl Draws {
835    /// Moves `parameters` past the depth that [`render`](Self::render)
836    /// would draw the groups at, in `order`, without drawing them.
837    pub(crate) fn skip(&self, parameters: &mut PaintParameters<'_>, order: DrawOrder) {
838        if self.started {
839            order.step(parameters);
840        }
841    }
842}
843
844/// What [`Draws::render`] runs where the main group draws, in the open pass.
845pub(crate) type InPass<'a> = dyn FnMut(&mut dyn Gpu, &mut PaintParameters<'_>) + 'a;
846
847/// One mesh and a frame's draw of it, with the buffers it binds: a draw of
848/// the engine's own.
849pub(crate) struct SingleDraw {
850    pub(crate) mesh: Mesh,
851    /// How the draw draws.
852    draw: Draw,
853    group: Group,
854}
855
856impl SingleDraw {
857    /// A draw of `mesh`, as `draw` draws, which draws once its blocks are
858    /// written ([`write`](Self::write)).
859    #[must_use]
860    pub(crate) fn new(mesh: Mesh, draw: Draw) -> SingleDraw {
861        SingleDraw { mesh, draw, group: Group::default() }
862    }
863
864    /// Makes `block` the value the draw reads of its program's uniform
865    /// block of its layout, as [`Group::block`] does, from the next
866    /// [`write`](Self::write).
867    pub(crate) fn block<T: UniformBlock>(&mut self, block: &T) -> &mut Self {
868        self.group.block(block);
869        self
870    }
871
872    /// Writes the buffers the draw reads, with `blocks`, its values of its
873    /// program's blocks of each draw, as [`Group::finish`] does.
874    pub(crate) fn write<B: DrawBlocks>(&mut self, gpu: &mut dyn Gpu, context: &mut Context, blocks: B) {
875        let SingleDraw { mesh, draw, group } = self;
876        group.push(mesh, *draw, blocks);
877        group.finish(gpu, context, None, []);
878    }
879
880    /// Uploads the mesh, if the draw's blocks were written.
881    pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
882        self.group.upload(gpu, context);
883    }
884
885    /// Draws the draw, if it draws in the pass, into the open pass of `gpu`,
886    /// the context's. Returns whether it didn't fail.
887    pub(crate) fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) -> bool {
888        self.group.render(gpu, parameters)
889    }
890}
891
892/// What a frame's groups, or a drape's, need of the passes: their number,
893/// which sets the passes' depth range; the masks of the tiles they clip to
894/// and of the tiles that clear the stencil buffer; and the groups drawn as
895/// a whole, each into the layer composite's texture and then onto the
896/// frame.
897#[derive(Default)]
898pub(crate) struct DrawGroups {
899    pub(crate) count: usize,
900    pub(crate) clip_tiles: Vec<UnwrappedTileID>,
901    /// The tiles whose masks clear the stencil buffer, also in
902    /// `clip_tiles` ([`PaintParameters::stencil_clear_tiles`]).
903    pub(crate) stencil_clear: StencilClear,
904    pub(crate) composited: Vec<(SimpleIdentity, Composite)>,
905}
906
907impl DrawGroups {
908    /// The groups that `visit_groups` visits, in drawing order, of passes
909    /// whose stencil the tiles that `stencil_clear_tiles` gives for the
910    /// tiles they clip to clear ([`PaintParameters::stencil_clear_tiles`]).
911    /// Groups of one source clip to the same tiles, which are added once.
912    pub(crate) fn of<'a>(
913        visit_groups: impl FnOnce(&mut dyn FnMut(&'a Group)),
914        stencil_clear_tiles: impl FnOnce(&[UnwrappedTileID]) -> StencilClear,
915    ) -> DrawGroups {
916        let mut groups = DrawGroups::default();
917        let mut last: Option<&[UnwrappedTileID]> = None;
918        visit_groups(&mut |group| {
919            groups.count += 1;
920            if let Some(tiles) = group.stencil_tiles()
921                && last.is_none_or(|last| last != tiles)
922            {
923                groups.clip_tiles.extend(tiles.iter().copied());
924                last = Some(tiles);
925            }
926            groups.composited.extend(group.composited());
927        });
928        groups.stencil_clear = stencil_clear_tiles(&groups.clip_tiles);
929        groups.clip_tiles.extend_from_slice(&groups.stencil_clear);
930        if !groups.clip_tiles.is_sorted() {
931            groups.clip_tiles.sort_unstable();
932        }
933        groups.clip_tiles.dedup();
934        groups
935    }
936
937    /// The depth range of the passes' 3D draws, from 0, below the depths of
938    /// the groups' 2D draws.
939    #[must_use]
940    pub(crate) fn depth_range_size(&self) -> f32 {
941        depth_range_size(self.count)
942    }
943}
944
945/// The depth range of the 3D draws of passes of `groups` draw groups, from
946/// 0, below the depths of the groups' 2D draws.
947#[must_use]
948pub(crate) fn depth_range_size(groups: usize) -> f32 {
949    1.0 - ((groups + 2) * PaintParameters::NUM_SUBLAYERS as usize) as f32 * PaintParameters::DEPTH_EPSILON
950}
951
952/// The order the frame draws the layers' groups in, each at the depth of
953/// [`PaintParameters::current_layer`], which [`DrawOrder::step`] moves to
954/// the next group's.
955#[derive(Clone, Copy, Debug, PartialEq, Eq)]
956pub enum DrawOrder {
957    /// The layers' order, bottom to top, with the depth going down by one
958    /// after each group, to 0.
959    BottomUp,
960    /// The reverse order, top to bottom, with the depth going up by one
961    /// after each group.
962    TopDown,
963}
964
965impl DrawOrder {
966    /// Moves `parameters` to the depth of the group after the one it is at.
967    pub(crate) fn step(self, parameters: &mut PaintParameters<'_>) {
968        match self {
969            DrawOrder::BottomUp => parameters.current_layer = parameters.current_layer.saturating_sub(1),
970            DrawOrder::TopDown => parameters.current_layer += 1,
971        }
972    }
973}