1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
use super::{AtlasTextureId, BatchIterator, FilterBoundary, Scene};
use smallvec::SmallVec;
use std::ops::Range;
/// Inline capacity of renderer isolation stacks. Deeper groups allocate additional targets.
pub const MAX_FILTER_GROUP_DEPTH: usize = 2;
/// The index of an offscreen target in the renderer's content-filter target pool.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FilterTargetIndex(usize);
impl FilterTargetIndex {
/// Returns the index as a `usize`.
pub fn as_usize(self) -> usize {
self.0
}
}
/// Where the contents of a filter group are rendered.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FilterRenderTarget {
/// Render an unmatched group directly into the current target.
Inline,
/// Render into a dedicated offscreen target and composite it into the parent.
Isolated(FilterTargetIndex),
}
impl FilterRenderTarget {
fn is_isolated(self) -> bool {
matches!(self, Self::Isolated(_))
}
}
/// Allocation and draw totals collected while compiling one [`ScenePlan`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ScenePlanRequirements {
/// The number of entries in [`ScenePlan::commands`].
pub command_count: usize,
/// The number of instanced draw calls. A path batch that rasterizes counts as two.
pub instance_batch_count: usize,
/// The number of path vertices to rasterize into the path target.
pub path_rasterization_vertex_count: usize,
/// The number of sprites that composite the rasterized paths.
pub path_sprite_count: usize,
/// The number of [`crate::PaintSurface`]s to draw.
pub surface_count: usize,
/// The number of [`crate::BackdropFilter`]s to draw.
pub backdrop_filter_count: usize,
/// The number of filter or grouped-opacity groups that draw into an isolated target.
pub isolated_filter_count: usize,
/// The number of isolated targets needed at the deepest level of nesting.
pub isolated_target_count: usize,
/// Whether any path is rasterized into an offscreen target.
pub uses_path_target: bool,
/// Whether a backdrop filter or an isolated filter or opacity group needs an offscreen target.
pub uses_offscreen_target: bool,
/// Whether a foreground or backdrop filter needs a temporary blur target.
pub uses_blur_target: bool,
}
/// A compiled scene command stream, built by [`Scene::finish`] and shared by every renderer.
#[derive(Debug, Default)]
pub struct ScenePlan {
// Retain this allocation across `Scene::clear`/`Scene::finish`; scenes are rebuilt every frame.
pub(super) commands: Vec<RenderCommand>,
requirements: ScenePlanRequirements,
scene_lengths: SceneLengths,
}
impl ScenePlan {
pub(super) fn clear(&mut self) {
self.commands.clear();
self.requirements = ScenePlanRequirements::default();
self.scene_lengths = SceneLengths::default();
}
pub(super) fn build(scene: &Scene, mut commands: Vec<RenderCommand>) -> Self {
commands.clear();
commands.reserve(scene.len());
let mut matched_starts =
SmallVec::<[bool; 8]>::from_elem(false, scene.filter_boundaries.len());
let mut pending_starts = SmallVec::<[usize; 4]>::new();
for (index, boundary) in scene.filter_boundaries.iter().enumerate() {
if boundary.is_start {
pending_starts.push(index);
} else if let Some(start_index) = pending_starts.pop() {
matched_starts[start_index] = true;
}
}
let mut filter_stack = SmallVec::<[(usize, FilterRenderTarget); 4]>::new();
let mut isolated_depth = 0;
let mut requirements = ScenePlanRequirements::default();
for batch in BatchIterator::new(scene) {
match batch {
PrimitiveBatch::FilterBoundary(boundary_index) => {
let boundary = &scene.filter_boundaries[boundary_index];
if boundary.is_start {
let target = if matched_starts[boundary_index] {
FilterRenderTarget::Isolated(FilterTargetIndex(isolated_depth))
} else {
FilterRenderTarget::Inline
};
if target.is_isolated() {
isolated_depth += 1;
requirements.uses_offscreen_target = true;
requirements.uses_blur_target |= boundary.max_blur_radius() > 0.0;
requirements.isolated_target_count =
requirements.isolated_target_count.max(isolated_depth);
}
filter_stack.push((boundary_index, target));
commands.push(RenderCommand::BeginFilter {
boundary_index,
target,
});
} else if let Some((start_index, target)) = filter_stack.pop() {
if target.is_isolated() {
isolated_depth -= 1;
requirements.isolated_filter_count += 1;
}
commands.push(RenderCommand::EndFilter {
boundary_index: start_index,
closing_boundary_index: boundary_index,
target,
});
} else {
debug_assert!(false, "content-filter end boundary has no matching start");
commands.push(RenderCommand::EndFilter {
boundary_index,
closing_boundary_index: boundary_index,
target: FilterRenderTarget::Inline,
});
}
}
batch => {
if let PrimitiveBatch::BackdropFilters(range) = &batch {
requirements.uses_blur_target |= scene.backdrop_filters[range.clone()]
.iter()
.any(|filter| filter.max_blur_radius() > 0.0);
}
requirements.include_batch(&batch);
commands.push(RenderCommand::Batch(batch));
}
}
}
requirements.command_count = commands.len();
Self {
commands,
requirements,
scene_lengths: SceneLengths::for_scene(scene),
}
}
/// Returns the commands in the order they must be drawn.
pub fn commands(&self) -> &[RenderCommand] {
&self.commands
}
/// Returns the totals collected while this plan was compiled.
pub fn requirements(&self) -> &ScenePlanRequirements {
&self.requirements
}
pub(super) fn assert_matches(&self, scene: &Scene) {
debug_assert_eq!(
self.scene_lengths,
SceneLengths::for_scene(scene),
"scene primitive storage changed after Scene::finish"
);
}
}
impl ScenePlanRequirements {
fn include_batch(&mut self, batch: &PrimitiveBatch) {
match batch {
PrimitiveBatch::Shadows { range, .. }
| PrimitiveBatch::Quads { range, .. }
| PrimitiveBatch::Underlines(range) => {
self.instance_batch_count += usize::from(!range.is_empty());
}
PrimitiveBatch::Paths {
rasterization_vertex_count,
sprite_count,
..
} => {
self.path_rasterization_vertex_count += rasterization_vertex_count;
if *rasterization_vertex_count > 0 {
self.path_sprite_count += sprite_count;
self.uses_path_target = true;
self.instance_batch_count += 2;
}
}
PrimitiveBatch::MonochromeSprites { range, .. }
| PrimitiveBatch::SubpixelSprites { range, .. }
| PrimitiveBatch::PolychromeSprites { range, .. } => {
self.instance_batch_count += usize::from(!range.is_empty());
}
PrimitiveBatch::Surfaces(range) => self.surface_count += range.len(),
PrimitiveBatch::BackdropFilters(range) => {
self.backdrop_filter_count += range.len();
self.uses_offscreen_target |= !range.is_empty();
}
PrimitiveBatch::FilterBoundary(_) => {
unreachable!("filter boundaries are compiled before requirements are collected")
}
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct SceneLengths {
shadows: usize,
quads: usize,
paths: usize,
underlines: usize,
monochrome_sprites: usize,
subpixel_sprites: usize,
polychrome_sprites: usize,
surfaces: usize,
backdrop_filters: usize,
filter_boundaries: usize,
}
impl SceneLengths {
fn for_scene(scene: &Scene) -> Self {
Self {
shadows: scene.shadows.len(),
quads: scene.quads.len(),
paths: scene.paths.len(),
underlines: scene.underlines.len(),
monochrome_sprites: scene.monochrome_sprites.len(),
subpixel_sprites: scene.subpixel_sprites.len(),
polychrome_sprites: scene.polychrome_sprites.len(),
surfaces: scene.surfaces.len(),
backdrop_filters: scene.backdrop_filters.len(),
filter_boundaries: scene.filter_boundaries.len(),
}
}
}
/// A contiguous run of one primitive type that the renderer draws in one call.
///
/// The ranges index the matching vector in [`Scene`]. A batch never mixes primitive types.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PrimitiveBatch {
/// Shadows, drawn with or without corner smoothing as a unit.
Shadows {
/// The indices into [`Scene::shadows`].
range: Range<usize>,
/// Whether the shadows use corner smoothing.
smoothed: bool,
},
/// Quads, drawn with or without corner smoothing as a unit.
Quads {
/// The indices into [`Scene::quads`].
range: Range<usize>,
/// Whether the quads use corner smoothing.
smoothed: bool,
},
/// Paths. The renderer rasterizes their vertices, then composites the results as sprites.
Paths {
/// The indices into [`Scene::paths`].
range: Range<usize>,
/// The number of path vertices to rasterize in this batch.
rasterization_vertex_count: usize,
/// The number of sprites that composite the rasterized paths.
sprite_count: usize,
},
/// Underlines, as indices into [`Scene::underlines`].
Underlines(Range<usize>),
/// Single-color sprites that all read from one atlas texture.
MonochromeSprites {
/// The atlas texture that the sprites read from.
texture_id: AtlasTextureId,
/// The indices into [`Scene::monochrome_sprites`].
range: Range<usize>,
},
/// Subpixel-antialiased sprites that all read from one atlas texture.
SubpixelSprites {
/// The atlas texture that the sprites read from.
texture_id: AtlasTextureId,
/// The indices into [`Scene::subpixel_sprites`].
range: Range<usize>,
},
/// Full-color sprites that all read from one atlas texture.
PolychromeSprites {
/// The atlas texture that the sprites read from.
texture_id: AtlasTextureId,
/// The indices into [`Scene::polychrome_sprites`].
range: Range<usize>,
/// Whether the sprites use corner smoothing.
smoothed: bool,
},
/// Surfaces, as indices into [`Scene::surfaces`].
Surfaces(Range<usize>),
/// Backdrop filters, as indices into [`Scene::backdrop_filters`].
BackdropFilters(Range<usize>),
/// A filter or grouped-opacity boundary, as an index into [`Scene::filter_boundaries`].
FilterBoundary(usize),
}
/// Backend-neutral rendering work derived from a [`Scene`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RenderCommand {
/// A normal primitive batch.
Batch(PrimitiveBatch),
/// Begin rendering a filter or grouped-opacity group.
BeginFilter {
/// Index of the opening boundary in [`Scene::filter_boundaries`].
boundary_index: usize,
/// Whether this group renders inline or into an isolated target.
target: FilterRenderTarget,
},
/// Finish and composite a filter or grouped-opacity group.
EndFilter {
/// Index of the matched opening boundary in [`Scene::filter_boundaries`].
boundary_index: usize,
/// Index of the closing marker in [`Scene::filter_boundaries`].
closing_boundary_index: usize,
/// The same target selected by the matching begin command.
target: FilterRenderTarget,
},
}
impl RenderCommand {
/// Returns the opening [`FilterBoundary`] of a filter command, or `None` for a batch.
pub fn boundary<'a>(&self, scene: &'a Scene) -> Option<&'a FilterBoundary> {
match self {
Self::BeginFilter { boundary_index, .. } | Self::EndFilter { boundary_index, .. } => {
Some(&scene.filter_boundaries[*boundary_index])
}
Self::Batch(_) => None,
}
}
/// Returns a short description of this command, for GPU debugger labels.
pub fn label(&self) -> String {
match self {
Self::Batch(batch) => batch.label(),
Self::BeginFilter { target, .. } => match target {
FilterRenderTarget::Isolated(index) => {
format!("begin filter group ({})", index.as_usize())
}
FilterRenderTarget::Inline => "begin inline filter group".into(),
},
Self::EndFilter { target, .. } => match target {
FilterRenderTarget::Isolated(index) => {
format!("end filter group ({})", index.as_usize())
}
FilterRenderTarget::Inline => "end inline filter group".into(),
},
}
}
}
impl PrimitiveBatch {
/// Returns a short description of this batch, for GPU debugger labels.
pub fn label(&self) -> String {
match self {
Self::Shadows { range, smoothed } => format!(
"{}shadows ({})",
if *smoothed { "smoothed " } else { "" },
range.len()
),
Self::Quads { range, smoothed } => format!(
"{}quads ({})",
if *smoothed { "smoothed " } else { "" },
range.len()
),
Self::Paths { range, .. } => format!("paths ({})", range.len()),
Self::Underlines(range) => format!("underlines ({})", range.len()),
Self::MonochromeSprites { texture_id, range } => format!(
"monochrome sprites ({}) on atlas {}",
range.len(),
texture_id.index
),
Self::SubpixelSprites { texture_id, range } => format!(
"subpixel sprites ({}) on atlas {}",
range.len(),
texture_id.index
),
Self::PolychromeSprites {
texture_id,
range,
smoothed,
} => format!(
"{}polychrome sprites ({}) on atlas {}",
if *smoothed { "smoothed " } else { "" },
range.len(),
texture_id.index
),
Self::Surfaces(range) => format!("surfaces ({})", range.len()),
Self::BackdropFilters(range) => format!("backdrop filters ({})", range.len()),
Self::FilterBoundary(index) => format!("filter boundary ({index})"),
}
}
}