use std::{cell::Cell, ops::Range};
use crate::layout::{
backdrop::BackdropRegion,
opacity_layer::{
Extent, LayerBlur, LayerBounds, LayerCmd, LayerPlan, LayerStep, LayerTarget, RoundedBox, clipped, glyph_extent,
glyph_reach, rect_extent,
},
quad::ClipRect,
render_list::{GlyphCmd, RectCmd, RectShadow, RenderGradient, RenderGradientStop, RenderList, StrokeStyle},
};
const MAX_INPUT_BYTES: usize = 1 << 20;
const MAX_KEPT: usize = 64;
const MIN_BUDGET: usize = 1 << 20;
#[derive(Clone, Copy, Debug)]
pub(crate) enum PaintedDraw {
Rect(usize),
Glyphs {
start: usize,
count: usize,
},
#[cfg(feature = "raster")]
Image(usize),
}
pub(crate) fn backdrop_regions(
list: &RenderList,
plan: &LayerPlan,
window: [u32; 2],
regions: &mut Vec<Option<BackdropRegion>>,
) {
regions.clear();
regions.resize(list.backdrops.len(), None);
for target in plan.targets() {
let (origin, size) = match target.layer {
Some(layer) => list.layers[layer].painted(),
None => ([0, 0], window),
};
for step in plan.steps(target) {
if let LayerStep::Backdrop(index) = step {
regions[*index] = BackdropRegion::new(&list.backdrops[*index], origin, size);
}
}
}
}
#[derive(Default)]
pub(crate) struct BackdropInputs {
inputs: Vec<Input>,
extents: Vec<Cell<Option<Extent>>>,
}
#[derive(Default)]
struct Input {
bytes: Vec<u8>,
known: bool,
}
impl BackdropInputs {
pub(crate) fn describe(
&mut self,
list: &RenderList,
plan: &LayerPlan,
draws: usize,
draw: impl Fn(usize) -> PaintedDraw,
regions: &[Option<BackdropRegion>],
window: [u32; 2],
) {
self.inputs.resize_with(regions.len(), Input::default);
for input in &mut self.inputs {
input.bytes.clear();
input.known = false;
}
if regions.iter().all(Option::is_none) {
return;
}
self.extents.clear();
self.extents.resize(draws, Cell::new(None));
let frame = Frame {
list,
plan,
draw: &draw,
extents: &self.extents,
regions,
window,
};
for target in plan.targets() {
let steps = plan.steps(target);
for (at, step) in steps.iter().enumerate() {
let LayerStep::Backdrop(index) = step else {
continue;
};
let Some(blur) = regions
.get(*index)
.copied()
.flatten()
.and_then(|region| region.layer.blur)
else {
continue;
};
let mut notes = Notes {
bytes: std::mem::take(&mut self.inputs[*index].bytes),
atlas_noted: false,
};
let known = frame.note_input(&mut notes, &self.inputs, target, &steps[..at], &blur)
&& notes.bytes.len() <= MAX_INPUT_BYTES;
if !known {
notes.bytes.clear();
}
self.inputs[*index] = Input {
bytes: notes.bytes,
known,
};
}
}
}
pub(crate) fn input(&self, index: usize) -> Option<&[u8]> {
self
.inputs
.get(index)
.filter(|input| input.known)
.map(|input| input.bytes.as_slice())
}
}
#[derive(Default)]
pub(crate) struct LayerBlurInputs {
inputs: Vec<Input>,
extents: Vec<Cell<Option<Extent>>>,
}
impl LayerBlurInputs {
pub(crate) fn describe(
&mut self,
list: &RenderList,
plan: &LayerPlan,
draws: usize,
draw: impl Fn(usize) -> PaintedDraw,
regions: &[Option<BackdropRegion>],
window: [u32; 2],
) {
let targets = plan.targets();
self.inputs.resize_with(targets.len(), Input::default);
self.inputs.truncate(targets.len());
for input in &mut self.inputs {
input.bytes.clear();
input.known = false;
}
if !targets
.iter()
.any(|target| target.layer.is_some_and(|layer| list.layers[layer].blur.is_some()))
{
return;
}
self.extents.clear();
self.extents.resize(draws, Cell::new(None));
let frame = Frame {
list,
plan,
draw: &draw,
extents: &self.extents,
regions,
window,
};
for (index, target) in targets.iter().enumerate() {
let Some(layer) = target.layer.map(|layer| &list.layers[layer]) else {
continue;
};
let Some(blur) = layer.blur else {
continue;
};
if frame.has_backdrop(target) {
continue;
}
let mut notes = Notes {
bytes: std::mem::take(&mut self.inputs[index].bytes),
atlas_noted: false,
};
let (origin, size) = layer.painted();
notes.tag(b'L');
notes.i32s(&origin);
notes.u32s(&size);
notes.f32(blur.sigma);
notes.i32s(&[blur.x, blur.y]);
notes.u32s(&[blur.width, blur.height]);
let known = frame.note_layer(&mut notes, target, layer) && notes.bytes.len() <= MAX_INPUT_BYTES;
if !known {
notes.bytes.clear();
}
self.inputs[index] = Input {
bytes: notes.bytes,
known,
};
}
}
pub(crate) fn input(&self, index: usize) -> Option<&[u8]> {
self
.inputs
.get(index)
.filter(|input| input.known)
.map(|input| input.bytes.as_slice())
}
}
struct Frame<'a, D> {
list: &'a RenderList,
plan: &'a LayerPlan,
draw: &'a D,
extents: &'a [Cell<Option<Extent>>],
regions: &'a [Option<BackdropRegion>],
window: [u32; 2],
}
impl<D: Fn(usize) -> PaintedDraw> Frame<'_, D> {
fn note_input(
&self,
notes: &mut Notes,
inputs: &[Input],
target: &LayerTarget,
before: &[LayerStep],
blur: &LayerBlur,
) -> bool {
match target.layer {
Some(layer) => {
let (origin, size) = self.list.layers[layer].painted();
notes.tag(b'L');
notes.i32s(&origin);
notes.u32s(&size);
}
None => {
let clear = self.list.clear_color;
notes.tag(b'W');
notes.u32s(&self.window);
notes
.bytes
.extend_from_slice(&[clear.r(), clear.g(), clear.b(), clear.a()]);
}
}
notes.f32(blur.sigma);
notes.i32s(&[blur.x, blur.y]);
notes.u32s(&[blur.width, blur.height]);
let copied = [
blur.x as f32,
blur.y as f32,
(blur.x + blur.width as i32) as f32,
(blur.y + blur.height as i32) as f32,
];
for step in before {
let known = match step {
LayerStep::Draws(range) => self.note_draws(notes, range.clone(), Some(copied)),
LayerStep::Composite(child) => {
let child = &self.plan.targets()[*child];
match child.layer.map(|layer| &self.list.layers[layer]) {
Some(layer) if touches(bounds_extent(layer), copied) => self.note_layer(notes, child, layer),
_ => true,
}
}
LayerStep::Backdrop(index) => match self.regions.get(*index).copied().flatten() {
Some(region) if touches(bounds_extent(®ion.layer), copied) => {
let Some(input) = inputs.get(*index).filter(|input| input.known) else {
return false;
};
notes.tag(b'B');
notes.region(®ion);
notes.u32(input.bytes.len() as u32);
notes.bytes.extend_from_slice(&input.bytes);
true
}
_ => true,
},
};
if !known || notes.bytes.len() > MAX_INPUT_BYTES {
return false;
}
}
true
}
fn has_backdrop(&self, target: &LayerTarget) -> bool {
self.plan.steps(target).iter().any(|step| match step {
LayerStep::Backdrop(index) => self.regions.get(*index).copied().flatten().is_some(),
LayerStep::Composite(child) => self.has_backdrop(&self.plan.targets()[*child]),
LayerStep::Draws(_) => false,
})
}
fn note_layer(&self, notes: &mut Notes, target: &LayerTarget, layer: &LayerCmd) -> bool {
notes.tag(b'C');
notes.layer(layer);
for step in self.plan.steps(target) {
let known = match step {
LayerStep::Draws(range) => self.note_draws(notes, range.clone(), None),
LayerStep::Composite(child) => {
let child = &self.plan.targets()[*child];
match child.layer.map(|layer| &self.list.layers[layer]) {
Some(layer) => self.note_layer(notes, child, layer),
None => true,
}
}
LayerStep::Backdrop(index) => {
if let Some(region) = self.regions.get(*index).copied().flatten() {
notes.tag(b'B');
notes.region(®ion);
}
true
}
};
if !known || notes.bytes.len() > MAX_INPUT_BYTES {
return false;
}
}
notes.tag(b'c');
true
}
fn note_draws(&self, notes: &mut Notes, range: Range<usize>, within: Option<Extent>) -> bool {
for index in range {
let draw = (self.draw)(index);
if within.is_some_and(|within| !self.reaches(index, draw, within)) {
continue;
}
match draw {
PaintedDraw::Rect(index) => notes.rect(&self.list.rects[index]),
PaintedDraw::Glyphs { start, count } => {
let reaches = |glyph: &&GlyphCmd| within.is_none_or(|within| touches(glyph_bounds(glyph), within));
for glyph in self.list.glyphs[start..start + count].iter().filter(reaches) {
if !std::mem::replace(&mut notes.atlas_noted, true) {
notes.tag(b'A');
notes.u64(self.list.atlas.version);
notes.u32s(&[self.list.atlas.width, self.list.atlas.height]);
}
notes.glyph(glyph);
}
}
#[cfg(feature = "raster")]
PaintedDraw::Image(index) => {
let image = &self.list.images[index];
if image.native.is_some() {
return false;
}
notes.image(image);
}
}
}
true
}
fn reaches(&self, index: usize, draw: PaintedDraw, within: Extent) -> bool {
let clip = match draw {
PaintedDraw::Rect(index) => self.list.rects[index].clip,
PaintedDraw::Glyphs { start, .. } => self
.list
.glyphs
.get(start)
.map_or_else(ClipRect::default, |glyph| glyph.clip),
#[cfg(feature = "raster")]
PaintedDraw::Image(index) => self.list.images[index].clip,
};
let around = [
clip.x - 1.0,
clip.y - 1.0,
clip.x + clip.width + 1.0,
clip.y + clip.height + 1.0,
];
if clip.active && !touches(around, within) {
return false;
}
touches(self.extent(index, draw), within)
}
fn extent(&self, index: usize, draw: PaintedDraw) -> Extent {
let Some(known) = self.extents.get(index) else {
return EVERYWHERE;
};
if let Some(extent) = known.get() {
return extent;
}
let extent = match draw {
PaintedDraw::Rect(index) => rect_extent(&self.list.rects[index]),
PaintedDraw::Glyphs { start, count } => {
let glyphs = &self.list.glyphs[start..start + count];
let all = glyphs.iter().map(glyph_bounds).fold(NOWHERE, union);
glyphs.first().map_or(NOWHERE, |glyph| clipped(all, glyph.clip))
}
#[cfg(feature = "raster")]
PaintedDraw::Image(index) => crate::layout::opacity_layer::image_extent(&self.list.images[index]),
};
known.set(Some(extent));
extent
}
}
const EVERYWHERE: Extent = [f32::NEG_INFINITY, f32::NEG_INFINITY, f32::INFINITY, f32::INFINITY];
const NOWHERE: Extent = [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY];
fn union(a: Extent, b: Extent) -> Extent {
[a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]
}
fn glyph_bounds(glyph: &GlyphCmd) -> Extent {
if glyph.transform != [1.0, 0.0, 0.0, 1.0] {
return glyph_extent(glyph);
}
let reach = glyph_reach(glyph);
[
glyph.x - reach,
glyph.y - reach,
glyph.x + glyph.width + reach,
glyph.y + glyph.height + reach,
]
}
fn touches(a: Extent, b: Extent) -> bool {
a[0] < b[2] && a[2] > b[0] && a[1] < b[3] && a[3] > b[1]
}
fn bounds_extent(layer: &LayerCmd) -> Extent {
let bounds = layer.bounds;
[
bounds.x as f32,
bounds.y as f32,
(bounds.x + bounds.width) as f32,
(bounds.y + bounds.height) as f32,
]
}
struct Notes {
bytes: Vec<u8>,
atlas_noted: bool,
}
impl Notes {
fn tag(&mut self, tag: u8) {
self.bytes.push(tag);
}
fn flag(&mut self, flag: bool) {
self.bytes.push(u8::from(flag));
}
fn u32(&mut self, value: u32) {
self.bytes.extend_from_slice(&value.to_ne_bytes());
}
fn u64(&mut self, value: u64) {
self.bytes.extend_from_slice(&value.to_ne_bytes());
}
fn f32(&mut self, value: f32) {
self.u32(value.to_bits());
}
fn u32s(&mut self, values: &[u32]) {
self.bytes.extend_from_slice(bytemuck::cast_slice(values));
}
fn i32s(&mut self, values: &[i32]) {
self.bytes.extend_from_slice(bytemuck::cast_slice(values));
}
fn f32s(&mut self, values: &[f32]) {
self.bytes.extend_from_slice(bytemuck::cast_slice(values));
}
fn color(&mut self, color: crate::node::color::Color) {
self
.bytes
.extend_from_slice(&[color.r(), color.g(), color.b(), color.a()]);
}
fn clip(&mut self, clip: &ClipRect) {
let &ClipRect {
x,
y,
width,
height,
active,
rounded,
} = clip;
self.flag(active);
if !active {
return;
}
self.f32s(&[x, y, width, height]);
for rounded in rounded {
self.flag(rounded.is_some());
if let Some(crate::layout::quad::RoundedClip {
x,
y,
width,
height,
radius:
crate::node::border::BorderRadius {
top_left,
top_right,
bottom_right,
bottom_left,
},
}) = rounded
{
self.f32s(&[x, y, width, height]);
self.f32s(&[top_left, top_right, bottom_right, bottom_left]);
}
}
}
fn rounded(&mut self, rounded: Option<&RoundedBox>) {
self.flag(rounded.is_some());
if let Some(&RoundedBox {
center,
half,
radii,
inverse,
scale,
}) = rounded
{
self.f32s(¢er);
self.f32s(&half);
self.f32s(&radii);
self.f32s(&inverse);
self.f32(scale);
}
}
fn rect(&mut self, rect: &RectCmd) {
let RectCmd {
order: _,
x,
y,
width,
height,
color,
radii,
stroke,
stroke_color,
stroke_style: StrokeStyle {
dash,
radii_at,
side_colors,
},
transform,
transform_origin,
clip,
gradient,
shadow,
} = rect;
self.tag(b'r');
self.f32s(&[*x, *y, *width, *height]);
self.color(*color);
self.f32s(radii);
self.f32s(stroke);
self.color(*stroke_color);
self.f32s(dash);
self.f32(*radii_at);
self.flag(side_colors.is_some());
for color in side_colors.iter().flatten() {
self.color(*color);
}
self.f32s(transform);
self.f32s(transform_origin);
self.clip(clip);
self.flag(gradient.is_some());
if let Some(RenderGradient {
kind,
flags,
dir,
center,
from_angle,
stops,
}) = gradient
{
self.u32s(&[*kind, *flags, stops.len() as u32]);
self.f32s(dir);
self.f32s(center);
self.f32(*from_angle);
for RenderGradientStop { color, position } in stops {
self.f32s(color);
self.f32(*position);
}
}
self.flag(shadow.is_some());
if let Some(RectShadow {
inset,
offset,
spread,
sigma,
shape_radii,
}) = shadow
{
self.flag(*inset);
self.f32s(offset);
self.f32s(&[*spread, *sigma]);
self.f32s(shape_radii);
}
}
fn glyph(&mut self, glyph: &GlyphCmd) {
let &GlyphCmd {
order: _,
x,
y,
width,
height,
color,
atlas_min,
atlas_max,
transform,
transform_origin,
sharpness,
color_glyph,
shadow_sigma,
ref clip,
} = glyph;
self.tag(b'g');
self.f32s(&[
x,
y,
width,
height,
color[0],
color[1],
color[2],
color[3],
atlas_min[0],
atlas_min[1],
atlas_max[0],
atlas_max[1],
transform[0],
transform[1],
transform[2],
transform[3],
transform_origin[0],
transform_origin[1],
sharpness,
shadow_sigma,
]);
self.flag(color_glyph);
self.clip(clip);
}
#[cfg(feature = "raster")]
fn image(&mut self, image: &crate::images::ImageCmd) {
let crate::images::ImageCmd {
order: _,
x,
y,
width,
height,
image_id,
frame_index,
version,
data: _,
animation_frames,
native: _,
image_width,
image_height,
image_format,
uv_min,
uv_max,
radii,
transform,
transform_origin,
clip,
opacity,
} = image;
self.tag(b'i');
self.f32s(&[*x, *y, *width, *height]);
self.u64(*image_id);
self.u64(*frame_index as u64);
self.u64(*version);
self.u32s(&[*image_width, *image_height]);
self.tag(match image_format {
crate::images::ImagePixelFormat::Rgba8 => 0,
crate::images::ImagePixelFormat::Nv12 => 1,
crate::images::ImagePixelFormat::I420 => 2,
});
self.u64(animation_frames.as_ref().map_or(u64::MAX, |frames| frames.len() as u64));
self.f32s(uv_min);
self.f32s(uv_max);
self.f32s(radii);
self.f32s(transform);
self.f32s(transform_origin);
self.clip(clip);
self.f32(*opacity);
}
fn layer(&mut self, layer: &LayerCmd) {
let &LayerCmd {
start_order: _,
end_order: _,
opacity,
bounds,
blur,
} = layer;
let LayerBounds { x, y, width, height } = bounds;
self.f32(opacity);
self.u32s(&[x, y, width, height]);
self.flag(blur.is_some());
if let Some(LayerBlur {
sigma,
x,
y,
width,
height,
clips,
}) = blur
{
self.f32(sigma);
self.i32s(&[x, y]);
self.u32s(&[width, height]);
for clip in &clips {
self.rounded(clip.as_ref());
}
}
}
fn region(&mut self, region: &BackdropRegion) {
let BackdropRegion { layer, mask, clips } = region;
self.layer(layer);
self.rounded(Some(mask));
for clip in clips {
self.rounded(clip.as_ref());
}
}
}
#[derive(Default)]
pub(crate) struct BackdropCache {
kept: Vec<Kept>,
budget: usize,
}
struct Kept {
place: Vec<u8>,
input: Vec<u8>,
texture: u64,
bytes: usize,
taken: bool,
pending: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BackdropUse {
Reuse { texture: u64 },
Refresh { texture: u64 },
Blur { keep: bool },
}
impl BackdropCache {
pub(crate) fn budget_of(window: [u32; 2]) -> usize {
(window[0] as usize * window[1] as usize * 4 * 2).max(MIN_BUDGET)
}
pub(crate) fn begin_frame(
&mut self,
regions: &[Option<BackdropRegion>],
inputs: &BackdropInputs,
budget: usize,
uses: &mut Vec<Option<BackdropUse>>,
released: &mut Vec<u64>,
) {
self.begin_frame_of(
regions.len(),
|index| regions[index].is_some(),
|index| inputs.input(index),
budget,
uses,
released,
);
}
pub(crate) fn begin_frame_of<'a>(
&mut self,
count: usize,
blurs: impl Fn(usize) -> bool,
input: impl Fn(usize) -> Option<&'a [u8]>,
budget: usize,
uses: &mut Vec<Option<BackdropUse>>,
released: &mut Vec<u64>,
) {
self.budget = budget;
uses.clear();
released.clear();
for kept in &mut self.kept {
kept.taken = false;
if std::mem::take(&mut kept.pending) {
kept.input.clear();
}
}
for index in 0..count {
uses.push(blurs(index).then(|| match input(index) {
None => BackdropUse::Blur { keep: false },
Some(input) => match self.kept.iter_mut().find(|kept| !kept.taken && kept.input == input) {
Some(kept) => {
kept.taken = true;
BackdropUse::Reuse { texture: kept.texture }
}
None => BackdropUse::Blur { keep: true },
},
}));
}
for (index, used) in uses.iter_mut().enumerate() {
let (Some(BackdropUse::Blur { keep: true }), Some(input)) = (*used, input(index)) else {
continue;
};
let at_place = self
.kept
.iter_mut()
.find(|kept| !kept.taken && input.starts_with(&kept.place));
if let Some(kept) = at_place {
kept.taken = true;
kept.input.clear();
kept.input.extend_from_slice(input);
kept.pending = true;
*used = Some(BackdropUse::Refresh { texture: kept.texture });
}
}
self.kept.retain(|kept| {
if !kept.taken {
released.push(kept.texture);
}
kept.taken
});
}
pub(crate) fn keep(&mut self, inputs: &BackdropInputs, index: usize, texture: u64, bytes: usize) -> bool {
inputs
.input(index)
.is_some_and(|input| self.keep_input(input, texture, bytes))
}
pub(crate) fn keep_input(&mut self, input: &[u8], texture: u64, bytes: usize) -> bool {
if self.kept.len() >= MAX_KEPT || self.bytes() + bytes > self.budget {
return false;
}
self.kept.push(Kept {
place: input[..place_len(input)].to_vec(),
input: input.to_vec(),
texture,
bytes,
taken: true,
pending: true,
});
true
}
pub(crate) fn commit(&mut self) {
for kept in &mut self.kept {
kept.pending = false;
}
}
pub(crate) fn clear(&mut self, released: &mut Vec<u64>) {
released.extend(self.kept.drain(..).map(|kept| kept.texture));
}
pub(crate) fn len(&self) -> usize {
self.kept.len()
}
pub(crate) fn bytes(&self) -> usize {
self.kept.iter().map(|kept| kept.bytes).sum()
}
}
fn place_len(input: &[u8]) -> usize {
let target = match input.first() {
Some(b'W') => 1 + 8 + 4,
_ => 1 + 8 + 8,
};
(target + 4 + 8 + 8).min(input.len())
}
#[cfg(test)]
mod tests;