1use crate::instance::push_instance;
18use crate::plan::{Batch, GlyphQuad, Plan, Resolved};
19use crate::view::pixel_zoom;
20use crate::{Camera2D, FrameStats, SpriteDraw};
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
24pub(crate) enum Pipe {
25 Sprite,
29 Text,
31}
32
33#[derive(Debug)]
44pub struct SpriteBatcher<K> {
45 plan: Plan<(K, Pipe)>,
46 packed: Vec<f32>,
47}
48
49impl<K: Copy + Eq> SpriteBatcher<K> {
50 pub fn new() -> Self {
52 Self {
53 plan: Plan::new(),
54 packed: Vec::new(),
55 }
56 }
57
58 pub fn build(
66 &mut self,
67 sprites: &[SpriteDraw],
68 camera: &Camera2D,
69 texture: impl FnMut(&SpriteDraw) -> Option<(K, bool)>,
70 ) {
71 self.build_with(sprites, &[], camera, texture);
72 }
73
74 pub(crate) fn build_with(
78 &mut self,
79 sprites: &[SpriteDraw],
80 glyphs: &[GlyphQuad<(K, Pipe)>],
81 camera: &Camera2D,
82 mut texture: impl FnMut(&SpriteDraw) -> Option<(K, bool)>,
83 ) {
84 self.plan
85 .build_with(sprites, glyphs, |sprite| match texture(sprite) {
86 None => Resolved::Skip,
87 Some((texture, false)) => Resolved::Draw((texture, Pipe::Sprite)),
88 Some((texture, true)) => Resolved::Placeholder((texture, Pipe::Sprite)),
89 });
90 let zoom = pixel_zoom(camera.zoom);
91 self.packed.clear();
92 for drawn in &self.plan.order {
93 let index = drawn.sprite as usize;
94 let sprite = match sprites.get(index) {
95 Some(sprite) => sprite,
96 None => &glyphs[index - sprites.len()].sprite,
97 };
98 push_instance(&mut self.packed, sprite, drawn.placeholder, Some(zoom));
99 }
100 }
101
102 pub fn instances(&self) -> &[f32] {
106 &self.packed
107 }
108
109 pub fn stats(&self) -> FrameStats {
114 FrameStats {
116 sprites: self.plan.order.len() as u32 - self.plan.glyphs,
117 skipped: self.plan.skipped,
118 batches: self.plan.batches.len() as u32,
119 tiles: 0,
120 chunks: 0,
121 texts: 0,
122 glyphs: self.plan.glyphs,
123 skipped_texts: 0,
124 ui_sprites: 0,
125 ui_glyphs: 0,
126 ui_texts: 0,
127 ui_batches: 0,
128 }
129 }
130
131 pub(crate) fn batches(&self) -> &[Batch<(K, Pipe)>] {
133 &self.plan.batches
134 }
135
136 pub(crate) fn position(&self, layer: u8, depth: u32) -> u32 {
139 self.plan.position(layer, depth)
140 }
141}
142
143impl<K: Copy + Eq> Default for SpriteBatcher<K> {
144 fn default() -> Self {
145 Self::new()
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use nadir_assets::Handle;
152 use nadir_core::{GenIndex, Vec2};
153
154 use super::*;
155 use crate::SPRITE_INSTANCE_FLOATS;
156
157 fn sprite(texture: u32, y: f32) -> SpriteDraw {
158 let id = GenIndex::new(texture, std::num::NonZeroU32::MIN);
159 SpriteDraw::new(Handle::new(id), Vec2::new(10.0, y), Vec2::splat(8.0))
160 }
161
162 #[test]
163 fn it_skips_what_is_not_ready_and_packs_the_rest_in_draw_order() {
164 let sprites = [
167 sprite(0, 30.0),
168 sprite(1, 10.0),
169 sprite(2, 20.0),
170 sprite(0, 5.0),
171 ];
172 let mut batcher = SpriteBatcher::new();
173 batcher.build(&sprites, &Camera2D::default(), |sprite| {
174 match sprite.texture.id().index() {
175 1 => None,
176 texture => Some((texture, texture == 2)),
177 }
178 });
179 assert_eq!(
180 batcher.stats(),
181 FrameStats {
182 sprites: 3,
183 skipped: 1,
184 batches: 3,
185 ..FrameStats::default()
186 }
187 );
188 let order: Vec<u32> = batcher
189 .batches()
190 .iter()
191 .map(|batch| batch.texture.0)
192 .collect();
193 assert_eq!(order, [0, 2, 0], "by depth: y 5, then 20, then 30");
194 assert!(
196 batcher
197 .batches()
198 .iter()
199 .all(|batch| batch.texture.1 == Pipe::Sprite)
200 );
201 assert_eq!(batcher.instances().len(), 3 * SPRITE_INSTANCE_FLOATS);
202
203 batcher.build(&sprites[..1], &Camera2D::default(), |_| Some((0, false)));
205 assert_eq!(batcher.stats().sprites, 1);
206 assert_eq!(batcher.instances().len(), SPRITE_INSTANCE_FLOATS);
207 }
208
209 #[test]
210 fn glyphs_are_packed_after_sprites_at_a_tie_and_split_batches_by_program() {
211 let mut panel = sprite(0, 5.0);
212 panel.sort = crate::SortMode::Fixed(3);
213 let mut quad = panel;
214 quad.position = Vec2::new(40.0, 7.0);
215 quad.pivot = Vec2::ZERO;
216 let glyph = |pipe| GlyphQuad {
217 sprite: quad,
218 text: 0,
219 texture: (0, pipe),
220 placeholder: false,
221 };
222 let glyphs = [glyph(Pipe::Text), glyph(Pipe::Sprite)];
223 let mut batcher = SpriteBatcher::new();
224 batcher.build_with(&[panel], &glyphs, &Camera2D::default(), |_| {
225 Some((0, false))
226 });
227 let stats = batcher.stats();
228 assert_eq!((stats.sprites, stats.glyphs, stats.batches), (1, 2, 3));
229 let batches: Vec<(u32, Pipe)> = batcher.batches().iter().map(|b| b.texture).collect();
230 assert_eq!(
231 batches,
232 [(0, Pipe::Sprite), (0, Pipe::Text), (0, Pipe::Sprite)]
233 );
234 let second = &batcher.instances()[SPRITE_INSTANCE_FLOATS..];
236 assert_eq!(second[..2], [40.0, 7.0]);
237 }
238}