1use std::any::Any;
22use std::ops::Range;
23use std::rc::Rc;
24
25use mln_gfx::Size;
26use mln_gfx::cull_face_mode::CullFaceMode;
27use mln_gfx::depth_mode::DepthMode;
28use mln_gfx::gpu::Gpu;
29use mln_gfx::shaders::bindings::{BUFFER_IDS, PAINT_PARAMS_ID, PROJECTION_ID};
30use mln_gfx::shaders::block::{Block, DrawBlocks, UniformBlock};
31use mln_gfx::shaders::layer_ubo::{GlobalPaintParamsUBO, ProjectionUBO};
32use mln_gfx::shaders::program::{BufferKind, Program, Projection};
33use mln_gfx::stencil_mode::StencilMode;
34use mln_gfx::types::{CullFaceWindingType, DepthMaskType};
35
36use crate::camera::{FrameProjection, ProjectionData, View, ViewportMode};
37use crate::draw::after_gpu::AfterGpu;
38use crate::draw::context::Context;
39use crate::draw::identity::SimpleIdentity;
40use crate::draw::objects::{DrawBuffers, Mesh};
41use crate::draw::target::Target;
42use crate::render::layer_composite::Composite;
43use crate::render::light::EvaluatedLight;
44use crate::render::paint_parameters::{Composited, PaintParameters, StencilClear, TransformParameters};
45use crate::render::pass::RenderPass;
46use crate::render::terrain::FrameGround;
47use crate::tile::{OverscaledTileID, UnwrappedTileID};
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub(crate) enum DrawsInto {
52 Map,
54 Drape { lit: bool },
57}
58
59#[derive(Clone)]
62pub struct LayerFrame<'a> {
63 pub view: &'a View,
64 pub(crate) transform_params: &'a TransformParameters,
65 pub camera_moving: bool,
68 pub light: &'a EvaluatedLight,
69 pub pixel_ratio: f32,
70 pub renderable_size: Size,
71 pub pixels_to_gl_units: [f32; 2],
72 pub terrain: bool,
75 pub composites_with_frame_depth: bool,
79 pub ground: Option<Rc<FrameGround>>,
82 pub(crate) into: DrawsInto,
83}
84
85impl LayerFrame<'_> {
86 #[must_use]
88 pub fn view(&self) -> &View {
89 self.view
90 }
91
92 #[must_use]
94 pub fn pixel_ratio(&self) -> f32 {
95 self.pixel_ratio
96 }
97
98 #[must_use]
100 pub fn size(&self) -> Size {
101 self.renderable_size
102 }
103
104 #[must_use]
107 pub fn drape_lit(&self) -> bool {
108 matches!(self.into, DrawsInto::Drape { lit: true })
109 }
110
111 #[must_use]
113 pub fn projection_data_for_tile(&self, tile_id: &UnwrappedTileID, aligned: bool) -> ProjectionData {
114 self.transform_params.projection_data_for_tile(tile_id, aligned)
115 }
116
117 #[must_use]
122 pub fn cull_back_faces(&self) -> CullFaceMode {
123 let turned = self.view.viewport_mode() == ViewportMode::FlippedY && !self.view.is_globe();
124 let winding = if turned { CullFaceWindingType::Clockwise } else { CullFaceWindingType::CounterClockwise };
125 CullFaceMode { winding, ..CullFaceMode::back_ccw() }
126 }
127}
128
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub enum Depth {
132 Off,
134 Layer { sub_layer: u8, mask: DepthMaskType },
137 Volume { mask: DepthMaskType },
140}
141
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub struct Draw {
146 pub order: i64,
151 pub opaque: bool,
155 pub depth: Depth,
156 pub clip: bool,
161}
162
163impl Draw {
164 pub const DEFAULT: Draw = Draw {
167 order: 0,
168 opaque: false,
169 depth: Depth::Layer { sub_layer: 0, mask: DepthMaskType::ReadOnly },
170 clip: false,
171 };
172
173 fn passes(self) -> RenderPass {
175 if self.opaque { RenderPass::Opaque | RenderPass::Translucent } else { RenderPass::Translucent }
176 }
177}
178
179impl Default for Draw {
180 fn default() -> Self {
181 Draw::DEFAULT
182 }
183}
184
185struct GroupDraw {
188 mesh: Mesh,
189 tile: Option<OverscaledTileID>,
191 pass: RenderPass,
192 depth: Depth,
193 clip: bool,
194}
195
196struct ProgramBlocks {
199 program: &'static Program,
200 at: [Option<(usize, &'static Block)>; BUFFER_IDS],
201 drawn: bool,
203}
204
205impl ProgramBlocks {
206 fn of(program: &'static Program) -> ProgramBlocks {
207 let mut at = [None; BUFFER_IDS];
208 let mut offset = 0;
209 for buffer in program.buffers {
210 if let BufferKind::Storage { block, .. } | BufferKind::DrawUniform(block) = buffer.kind {
211 at[buffer.id] = Some((offset, block));
212 offset += block.size;
213 }
214 }
215 ProgramBlocks { program, at, drawn: false }
216 }
217}
218
219struct Pushed {
222 program: usize,
223 projection: ProjectionUBO,
224 blocks: usize,
225}
226
227#[derive(Default)]
231struct Pushes {
232 pushed: Vec<Pushed>,
233 bytes: Vec<u8>,
235 programs: Vec<ProgramBlocks>,
237 shared: Vec<(&'static Block, Range<usize>)>,
240 shared_bytes: Vec<u8>,
241 scratch: Vec<u8>,
243}
244
245fn same_block(a: &Block, b: &Block) -> bool {
247 std::ptr::eq(a, b) || a.name == b.name
248}
249
250impl Pushes {
251 fn clear(&mut self) {
252 self.pushed.clear();
253 self.bytes.clear();
254 self.shared.clear();
255 self.shared_bytes.clear();
256 }
257
258 fn push(
261 &mut self,
262 program: &'static Program,
263 projection: Option<&ProjectionUBO>,
264 start: usize,
265 layouts: &'static [&'static Block],
266 ) {
267 debug_assert!(
268 program
269 .buffers
270 .iter()
271 .filter_map(|buffer| match buffer.kind {
272 BufferKind::Storage { block, .. } | BufferKind::DrawUniform(block) => Some(block),
273 _ => None,
274 })
275 .map(|block| block.name)
276 .eq(layouts.iter().map(|block| block.name)),
277 "a draw of {} pushed with blocks other than its program's of each draw",
278 program.name
279 );
280 debug_assert!(program.projection != Projection::Own, "a draw of {} with a projection of its own", program.name);
281 let index = self.programs.iter().position(|of| std::ptr::eq(of.program, program)).unwrap_or_else(|| {
282 self.programs.push(ProgramBlocks::of(program));
283 self.programs.len() - 1
284 });
285 self.pushed.push(Pushed { program: index, projection: projection.copied().unwrap_or_default(), blocks: start });
286 }
287
288 fn block(&mut self, layout: &'static Block, bytes: &[u8]) {
290 if let Some((_, range)) = self.shared.iter().find(|(given, _)| same_block(given, layout)) {
291 self.shared_bytes[range.clone()].copy_from_slice(bytes);
292 } else {
293 let start = self.shared_bytes.len();
294 self.shared_bytes.extend_from_slice(bytes);
295 self.shared.push((layout, start..self.shared_bytes.len()));
296 }
297 }
298
299 fn write(
309 &mut self,
310 gpu: &mut dyn Gpu,
311 context: &mut Context,
312 order: &[(i64, usize)],
313 paint_params: Option<&GlobalPaintParamsUBO>,
314 buffers: &mut DrawBuffers,
315 ) {
316 let Pushes { pushed, bytes, programs, shared, shared_bytes, scratch } = self;
317 for of in programs.iter_mut() {
318 of.drawn = false;
319 }
320 for &(_, index) in order {
321 programs[pushed[index].program].drawn = true;
322 }
323 let mut written = [false; BUFFER_IDS];
324 let (mut per_draw_projection, mut reads_paint_params) = (false, false);
325 for of in programs.iter().filter(|of| of.drawn) {
326 per_draw_projection |= of.program.projection == Projection::PerDraw;
327 reads_paint_params |= of.program.paint_params.is_some();
328 }
329 let shared_first = programs.iter().filter(|of| of.drawn).flat_map(|of| {
334 let shared = of.program.buffers.iter().filter(|buffer| matches!(buffer.kind, BufferKind::Uniform(_)));
335 shared.map(move |buffer| (of, buffer))
336 });
337 let per_draw = programs.iter().filter(|of| of.drawn).flat_map(|of| {
338 let per_draw = of.program.buffers.iter().filter(|buffer| !matches!(buffer.kind, BufferKind::Uniform(_)));
339 per_draw.map(move |buffer| (of, buffer))
340 });
341 for (of, buffer) in shared_first.chain(per_draw) {
342 if matches!(buffer.kind, BufferKind::Vertices(_)) || std::mem::replace(&mut written[buffer.id], true) {
344 continue;
345 }
346 match buffer.kind {
347 BufferKind::Uniform(block) => {
348 let Some((_, range)) = shared.iter().find(|(given, _)| same_block(given, block)) else {
349 debug_assert!(false, "draws of {} without their uniform block {}", of.program.name, block.name);
350 continue;
351 };
352 buffers.write_uniform(gpu, buffer.id, &shared_bytes[range.clone()], context.device());
353 }
354 BufferKind::Storage { stride, .. } => {
355 scratch.clear();
356 for &(_, index) in order {
357 let Pushed { program, blocks, .. } = pushed[index];
358 let end = scratch.len() + stride;
359 if let Some((offset, block)) = programs[program].at[buffer.id] {
360 let at = blocks + offset;
361 scratch.extend_from_slice(&bytes[at..at + block.size]);
362 }
363 scratch.resize(end, 0);
364 }
365 buffers.write_storage(gpu, buffer.id, scratch, context.device());
366 }
367 BufferKind::DrawUniform(block) => {
368 let mut own = order.iter().map(|&(_, index)| &pushed[index]).filter(|draw| {
369 programs[draw.program].at[buffer.id].is_some_and(|(_, of)| same_block(of, block))
370 });
371 let Some(&Pushed { program, blocks, .. }) = own.next() else { continue };
372 debug_assert!(own.next().is_none(), "two draws of a block of {}'s own", block.name);
373 if let Some((offset, _)) = programs[program].at[buffer.id] {
374 let at = blocks + offset;
375 buffers.write_uniform(gpu, buffer.id, &bytes[at..at + block.size], context.device());
376 }
377 }
378 BufferKind::Vertices(_) => {}
379 }
380 }
381 if per_draw_projection {
382 scratch.clear();
383 for &(_, index) in order {
384 scratch.extend_from_slice(bytemuck::bytes_of(&pushed[index].projection));
385 }
386 buffers.write_storage(gpu, PROJECTION_ID, scratch, context.device());
387 } else if buffers.get(PROJECTION_ID).is_none() {
388 let none = ProjectionUBO::default();
391 buffers.write_storage(gpu, PROJECTION_ID, bytemuck::bytes_of(&none), context.device());
392 }
393 if let Some(paint_params) = paint_params.filter(|_| reads_paint_params) {
394 buffers.write_pod(gpu, PAINT_PARAMS_ID, paint_params, context.device());
395 }
396 }
397}
398
399pub struct Group {
403 id: SimpleIdentity,
405 draws: Vec<GroupDraw>,
408 buffers: DrawBuffers,
411 composite: Option<Composite>,
415 stencil_tiles: Vec<UnwrappedTileID>,
418 pending: Vec<Option<GroupDraw>>,
421 order: Vec<(i64, usize)>,
423 pushes: Pushes,
424}
425
426impl Default for Group {
427 fn default() -> Self {
429 Group {
430 id: SimpleIdentity::new(),
431 draws: Vec::new(),
432 buffers: DrawBuffers::default(),
433 composite: None,
434 stencil_tiles: Vec::new(),
435 pending: Vec::new(),
436 order: Vec::new(),
437 pushes: Pushes::default(),
438 }
439 }
440}
441
442impl Group {
443 pub fn push<B: DrawBlocks>(&mut self, mesh: &Mesh, draw: Draw, blocks: B) -> &mut Self {
448 self.add(mesh, None, None, draw, blocks)
449 }
450
451 pub fn push_at<B: DrawBlocks>(
456 &mut self,
457 mesh: &Mesh,
458 tile: OverscaledTileID,
459 projection: &ProjectionUBO,
460 draw: Draw,
461 blocks: B,
462 ) -> &mut Self {
463 self.add(mesh, Some(tile), Some(projection), draw, blocks)
464 }
465
466 fn add<B: DrawBlocks>(
467 &mut self,
468 mesh: &Mesh,
469 tile: Option<OverscaledTileID>,
470 projection: Option<&ProjectionUBO>,
471 draw: Draw,
472 blocks: B,
473 ) -> &mut Self {
474 debug_assert!(
475 !draw.clip || tile.is_some() || matches!(draw.depth, Depth::Volume { .. }),
476 "a draw that clips without a tile"
477 );
478 let start = self.pushes.bytes.len();
479 blocks.each_bytes(|block| self.pushes.bytes.extend_from_slice(block));
480 self.pushes.push(mesh.program(), projection, start, B::BLOCKS);
481 self.order.push((draw.order, self.pending.len()));
482 self.pending.push(Some(GroupDraw {
483 mesh: mesh.clone(),
484 tile,
485 pass: draw.passes(),
486 depth: draw.depth,
487 clip: draw.clip,
488 }));
489 self
490 }
491
492 pub fn block<T: UniformBlock>(&mut self, block: &T) -> &mut Self {
496 self.pushes.block(T::BLOCK, bytemuck::bytes_of(block));
497 self
498 }
499
500 pub fn composite(&mut self, composite: Option<Composite>) -> &mut Self {
503 self.composite = composite;
504 self
505 }
506
507 pub(crate) fn clear(&mut self) {
510 self.draws.clear();
511 self.clear_pushed();
512 self.buffers.sweep();
513 }
514
515 fn clear_pushed(&mut self) {
516 self.pending.clear();
517 self.order.clear();
518 self.pushes.clear();
519 }
520
521 pub(crate) fn finish(
527 &mut self,
528 gpu: &mut dyn Gpu,
529 context: &mut Context,
530 paint_params: Option<&GlobalPaintParamsUBO>,
531 tiles: impl IntoIterator<Item = UnwrappedTileID>,
532 ) {
533 self.order.sort_unstable();
534 if !self.order.is_empty() {
535 self.pushes.write(gpu, context, &self.order, paint_params, &mut self.buffers);
536 }
537 let Group { draws, pending, order, stencil_tiles, .. } = self;
538 draws.clear();
539 draws.extend(order.iter().filter_map(|&(_, index)| pending[index].take()));
540 stencil_tiles.clear();
541 if draws.iter().any(|draw| draw.clip) {
542 stencil_tiles.extend(tiles);
543 }
544 self.buffers.sweep();
545 self.clear_pushed();
546 }
547
548 #[must_use]
551 pub(crate) fn stencil_tiles(&self) -> Option<&[UnwrappedTileID]> {
552 Some(&self.stencil_tiles[..]).filter(|tiles| !tiles.is_empty())
553 }
554
555 #[must_use]
557 pub(crate) fn draws(&self) -> bool {
558 !self.draws.is_empty()
559 }
560
561 #[must_use]
564 pub(crate) fn composited(&self) -> Option<(SimpleIdentity, Composite)> {
565 self.composite.filter(|_| !self.draws.is_empty()).map(|composite| (self.id, composite))
566 }
567
568 #[cfg(test)]
570 pub(crate) fn meshes(&self) -> impl Iterator<Item = &Mesh> {
571 self.draws.iter().map(|draw| &draw.mesh)
572 }
573
574 pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
576 for draw in &self.draws {
577 draw.mesh.upload(gpu, context);
578 }
579 }
580
581 pub(crate) fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) -> bool {
588 if self.draws.is_empty() || parameters.pass_target().is_none() {
589 return true;
590 }
591 let composited = (self.composite.is_some() && parameters.pass == RenderPass::Translucent)
592 .then(|| parameters.begin_composited(gpu, self.id))
593 .flatten();
594 let drawing = composited.as_ref().is_none_or(Composited::draws);
595 let draws = if drawing { &self.draws[..] } else { &[] };
596 let both = RenderPass::Opaque | RenderPass::Translucent;
600 let drawn_in =
601 if parameters.opaque_pass_enabled_for_layer() { RenderPass::Opaque } else { RenderPass::Translucent };
602 let pass = parameters.pass;
603 let skip = if pass & both != RenderPass::None && pass != drawn_in { both } else { RenderPass::None };
604 let in_pass = |draw: &&GroupDraw| {
605 draw.pass & pass != RenderPass::None && (skip == RenderPass::None || draw.pass & skip != skip)
606 };
607 let (volume, volume_clips) =
608 draws.iter().filter(in_pass).fold((false, false), |(volume, clips), draw| match draw.depth {
609 Depth::Volume { .. } => (true, clips || draw.clip),
610 _ => (volume, clips),
611 });
612 let mut volume_stencil = None;
613 if volume {
614 volume_stencil = volume_clips.then(|| parameters.stencil_mode_for_3d(gpu));
615 } else if drawing && !self.stencil_tiles.is_empty() {
616 parameters.render_tile_clipping_masks(gpu, &self.stencil_tiles);
617 }
618 let mut drawn = true;
619 for (index, draw) in draws.iter().enumerate().filter(|(_, draw)| in_pass(draw)) {
620 let tile_stencil = || match draw.tile.filter(|_| draw.clip) {
621 Some(tile) => parameters.stencil_mode_for_clipping(&tile.to_unwrapped()),
622 None => StencilMode::disabled(),
623 };
624 let (depth, stencil) = match draw.depth {
625 Depth::Off => (DepthMode::disabled(), tile_stencil()),
626 Depth::Layer { sub_layer, mask } => {
627 (parameters.depth_mode_for_sublayer(sub_layer, mask), tile_stencil())
628 }
629 Depth::Volume { mask } => (
630 parameters.depth_mode_for_3d(mask),
631 volume_stencil.filter(|_| draw.clip).unwrap_or_else(StencilMode::disabled),
632 ),
633 };
634 let Some(mut objects) = parameters.context.take_mesh(&draw.mesh) else {
635 debug_assert!(false, "a draw of a mesh the context doesn't have");
636 continue;
637 };
638 drawn &= objects.draw(gpu, parameters, &mut self.buffers, depth, stencil, index as u32);
639 parameters.context.put_mesh(&draw.mesh, objects);
640 }
641 if let Some(composited) = composited {
642 parameters.end_composited(gpu, composited);
643 }
644 drawn
645 }
646}
647
648#[derive(Clone, Copy, Debug, PartialEq, Eq)]
650pub enum LendAt {
651 BeforePasses,
654 Pass,
657}
658
659pub struct Lent<'a> {
662 pub raw: &'a mut dyn Any,
669 pub frame: &'a LayerFrame<'a>,
671 pub projection: &'a FrameProjection,
673 pub layer_depth: Option<f64>,
676 pub after_gpu: &'a AfterGpu,
680}
681
682#[derive(Default)]
689pub struct Draws {
690 main: Group,
691 targets: Vec<(Target, Group)>,
696 frame_targets: usize,
698 lends: [bool; 2],
701 started: bool,
704}
705
706impl Draws {
707 pub fn main(&mut self) -> &mut Group {
710 &mut self.main
711 }
712
713 pub fn target(&mut self, target: &Target) -> &mut Group {
721 let frame = self.frame_targets;
722 let at = match self.targets.iter().position(|(given, _)| given == target) {
723 Some(at) if at < frame => return &mut self.targets[at].1,
724 Some(at) => at,
725 None => {
726 self.targets.push((target.clone(), Group::default()));
727 self.targets.len() - 1
728 }
729 };
730 self.targets.swap(at, frame);
731 self.frame_targets += 1;
732 &mut self.targets[frame].1
733 }
734
735 pub fn lend(&mut self, at: LendAt) -> &mut Self {
739 self.lends[at as usize] = true;
740 self
741 }
742
743 #[must_use]
746 pub(crate) fn lends(&self, at: LendAt) -> bool {
747 self.lends[at as usize]
748 }
749
750 pub(crate) fn begin(&mut self) {
753 self.started = true;
754 self.reset();
755 }
756
757 pub(crate) fn clear(&mut self) {
760 self.reset();
761 self.targets.clear();
762 }
763
764 fn reset(&mut self) {
766 for (_, group) in &mut self.targets {
767 group.clear();
768 }
769 self.frame_targets = 0;
770 self.lends = [false; 2];
771 self.main.clear();
772 }
773
774 pub(crate) fn finish(
779 &mut self,
780 gpu: &mut dyn Gpu,
781 context: &mut Context,
782 paint_params: Option<&GlobalPaintParamsUBO>,
783 tiles: impl IntoIterator<Item = UnwrappedTileID>,
784 ) {
785 self.finish_targets(gpu, context, paint_params);
786 self.main.finish(gpu, context, paint_params, tiles);
787 }
788
789 fn finish_targets(
792 &mut self,
793 gpu: &mut dyn Gpu,
794 context: &mut Context,
795 paint_params: Option<&GlobalPaintParamsUBO>,
796 ) {
797 self.targets.truncate(self.frame_targets);
798 for (target, group) in &mut self.targets {
799 debug_assert!(group.composite.is_none(), "draws into a target that composite");
800 group.finish(gpu, context, paint_params, []);
801 context.declare_target(target);
802 }
803 }
804
805 pub(crate) fn visit_groups<'a>(&'a self, visit: &mut dyn FnMut(&'a Group)) {
808 if self.started {
809 visit(&self.main);
810 }
811 }
812
813 pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
816 if self.started {
817 for (_, group) in &self.targets[..self.frame_targets] {
818 group.upload(gpu, context);
819 }
820 self.main.upload(gpu, context);
821 }
822 }
823
824 pub(crate) fn render_targets(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
827 for (target, group) in &mut self.targets[..self.frame_targets] {
828 target.render(gpu, parameters, |gpu, parameters| group.render(gpu, parameters));
829 }
830 }
831
832 pub(crate) fn render(
836 &mut self,
837 gpu: &mut dyn Gpu,
838 parameters: &mut PaintParameters<'_>,
839 order: DrawOrder,
840 in_pass: Option<&mut InPass<'_>>,
841 ) {
842 if self.started {
843 self.main.render(gpu, parameters);
844 if let Some(in_pass) = in_pass {
845 in_pass(gpu, parameters);
846 }
847 order.step(parameters);
848 }
849 }
850}
851
852impl Draws {
853 pub(crate) fn skip(&self, parameters: &mut PaintParameters<'_>, order: DrawOrder) {
856 if self.started {
857 order.step(parameters);
858 }
859 }
860}
861
862pub(crate) type InPass<'a> = dyn FnMut(&mut dyn Gpu, &mut PaintParameters<'_>) + 'a;
864
865pub(crate) struct SingleDraw {
868 pub(crate) mesh: Mesh,
869 draw: Draw,
871 group: Group,
872}
873
874impl SingleDraw {
875 #[must_use]
878 pub(crate) fn new(mesh: Mesh, draw: Draw) -> SingleDraw {
879 SingleDraw { mesh, draw, group: Group::default() }
880 }
881
882 pub(crate) fn block<T: UniformBlock>(&mut self, block: &T) -> &mut Self {
886 self.group.block(block);
887 self
888 }
889
890 pub(crate) fn write<B: DrawBlocks>(&mut self, gpu: &mut dyn Gpu, context: &mut Context, blocks: B) {
893 let SingleDraw { mesh, draw, group } = self;
894 group.push(mesh, *draw, blocks);
895 group.finish(gpu, context, None, []);
896 }
897
898 pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
900 self.group.upload(gpu, context);
901 }
902
903 pub(crate) fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) -> bool {
906 self.group.render(gpu, parameters)
907 }
908}
909
910#[derive(Default)]
916pub(crate) struct DrawGroups {
917 pub(crate) count: usize,
918 pub(crate) clip_tiles: Vec<UnwrappedTileID>,
919 pub(crate) stencil_clear: StencilClear,
922 pub(crate) composited: Vec<(SimpleIdentity, Composite)>,
923}
924
925impl DrawGroups {
926 pub(crate) fn of<'a>(
931 visit_groups: impl FnOnce(&mut dyn FnMut(&'a Group)),
932 stencil_clear_tiles: impl FnOnce(&[UnwrappedTileID]) -> StencilClear,
933 ) -> DrawGroups {
934 let mut groups = DrawGroups::default();
935 let mut last: Option<&[UnwrappedTileID]> = None;
936 visit_groups(&mut |group| {
937 groups.count += 1;
938 if let Some(tiles) = group.stencil_tiles()
939 && last.is_none_or(|last| last != tiles)
940 {
941 groups.clip_tiles.extend(tiles.iter().copied());
942 last = Some(tiles);
943 }
944 groups.composited.extend(group.composited());
945 });
946 groups.stencil_clear = stencil_clear_tiles(&groups.clip_tiles);
947 groups.clip_tiles.extend_from_slice(&groups.stencil_clear);
948 if !groups.clip_tiles.is_sorted() {
949 groups.clip_tiles.sort_unstable();
950 }
951 groups.clip_tiles.dedup();
952 groups
953 }
954
955 #[must_use]
958 pub(crate) fn depth_range_size(&self) -> f32 {
959 depth_range_size(self.count)
960 }
961}
962
963#[must_use]
966pub(crate) fn depth_range_size(groups: usize) -> f32 {
967 1.0 - ((groups + 2) * PaintParameters::NUM_SUBLAYERS as usize) as f32 * PaintParameters::DEPTH_EPSILON
968}
969
970#[derive(Clone, Copy, Debug, PartialEq, Eq)]
974pub enum DrawOrder {
975 BottomUp,
978 TopDown,
981}
982
983impl DrawOrder {
984 pub(crate) fn step(self, parameters: &mut PaintParameters<'_>) {
986 match self {
987 DrawOrder::BottomUp => parameters.current_layer = parameters.current_layer.saturating_sub(1),
988 DrawOrder::TopDown => parameters.current_layer += 1,
989 }
990 }
991}