use super::{BatchKind, Renderer, Result, commands::split_rounded_regions, geometry::PlanarTransform};
use crate::{Color, DrawCommand, Rect};
use glow::HasContext;
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
pub(super) const MAX_CACHED_LAYERS: usize = 12;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(super) struct LayerCacheKey {
pub(super) content_hash: u64,
pub(super) width: u32,
pub(super) height: u32,
}
pub(super) struct CachedLayer {
pub(super) key: LayerCacheKey,
pub(super) fbo: glow::Framebuffer,
pub(super) texture: glow::Texture,
pub(super) width: u32,
pub(super) height: u32,
pub(super) opaque: bool,
pub(super) filter_linear: bool,
pub(super) last_frame: u64,
}
#[inline]
fn hash_f32(h: &mut DefaultHasher, v: f32) {
let bits = if v == 0.0 { 0u32 } else { v.to_bits() };
bits.hash(h);
}
#[inline]
fn hash_rel_f32(h: &mut DefaultHasher, v: f32, base: f32) {
let q = ((v - base) * 64.0).round() as i32;
q.hash(h);
}
#[inline]
fn hash_rect(h: &mut DefaultHasher, r: Rect, rel_origin: Option<[f32; 2]>) {
if let Some([ox, oy]) = rel_origin {
hash_rel_f32(h, r.x, ox);
hash_rel_f32(h, r.y, oy);
} else {
hash_f32(h, r.x);
hash_f32(h, r.y);
}
hash_f32(h, r.width);
hash_f32(h, r.height);
}
#[inline]
fn hash_color(h: &mut DefaultHasher, c: Color) {
[c.0, c.1, c.2, c.3].hash(h);
}
pub(super) fn find_matching_pop_layer(commands: &[DrawCommand], start: usize) -> Option<usize> {
let mut depth: u32 = 0;
for (idx, cmd) in commands.iter().enumerate().skip(start) {
match cmd {
DrawCommand::PushLayer { .. } | DrawCommand::PushRoundedLayer { .. } => depth += 1,
DrawCommand::PopLayer => {
depth = depth.checked_sub(1)?;
if depth == 0 {
return Some(idx);
}
}
_ => {}
}
}
None
}
pub(super) fn find_matching_pop_clip(commands: &[DrawCommand], start: usize) -> Option<usize> {
let mut depth: u32 = 0;
for (idx, cmd) in commands.iter().enumerate().skip(start) {
match cmd {
DrawCommand::PushClip(_) => depth += 1,
DrawCommand::PopClip => {
depth = depth.checked_sub(1)?;
if depth == 0 {
return Some(idx);
}
}
_ => {}
}
}
None
}
fn covers(r: Rect, bounds: Rect) -> bool {
r.x <= bounds.x + 0.01
&& r.y <= bounds.y + 0.01
&& r.x + r.width >= bounds.x + bounds.width - 0.01
&& r.y + r.height >= bounds.y + bounds.height - 0.01
}
impl Renderer {
pub(super) fn commands_start_opaque(&self, inner: &[DrawCommand], bounds: Rect) -> bool {
let mut slice = inner;
if let Some(DrawCommand::PushClip(c)) = slice.first()
&& covers(*c, bounds)
{
slice = &slice[1..];
}
match slice.first() {
Some(DrawCommand::RoundedRect {
bounds: r,
radius,
color,
}) => *radius <= 0.0 && color.3 == 255 && covers(*r, bounds),
Some(DrawCommand::Image {
bounds: r,
radius,
color,
image,
..
}) => *radius <= 0.0 && color.3 == 255 && covers(*r, bounds) && self.is_image_opaque(image),
_ => false,
}
}
}
pub(super) fn hash_layer_commands(
inner: &[DrawCommand],
bounds: Rect,
scale: f32,
) -> Option<u64> {
let mut h = DefaultHasher::new();
inner.len().hash(&mut h);
hash_f32(&mut h, scale);
hash_f32(&mut h, bounds.width);
hash_f32(&mut h, bounds.height);
let origin = [bounds.x, bounds.y];
let mut transform_depth: u32 = 0;
for cmd in inner {
let rel = (transform_depth == 0).then_some(origin);
match cmd {
DrawCommand::Clear(c) => {
0u8.hash(&mut h);
hash_color(&mut h, *c);
}
DrawCommand::PushLayer { .. }
| DrawCommand::PushRoundedLayer { .. }
| DrawCommand::PopLayer => return None,
DrawCommand::PushScaleY { origin: o, scale: s } => {
if transform_depth == 0 {
return None;
}
1u8.hash(&mut h);
hash_f32(&mut h, *o);
hash_f32(&mut h, *s);
transform_depth += 1;
}
DrawCommand::PopScaleY => {
2u8.hash(&mut h);
transform_depth = transform_depth.checked_sub(1)?;
}
DrawCommand::PushTransform {
origin: o,
translate: t,
scale: s,
rotation_rad: rot,
} => {
3u8.hash(&mut h);
hash_f32(&mut h, o[0]);
hash_f32(&mut h, o[1]);
if transform_depth == 0 {
hash_rel_f32(&mut h, t[0], origin[0]);
hash_rel_f32(&mut h, t[1], origin[1]);
} else {
hash_f32(&mut h, t[0]);
hash_f32(&mut h, t[1]);
}
hash_f32(&mut h, s[0]);
hash_f32(&mut h, s[1]);
hash_f32(&mut h, *rot);
transform_depth += 1;
}
DrawCommand::PushProjective { matrix } => {
if transform_depth == 0 {
return None;
}
4u8.hash(&mut h);
for row in matrix {
for &v in row {
hash_f32(&mut h, v);
}
}
transform_depth += 1;
}
DrawCommand::PopTransform => {
5u8.hash(&mut h);
transform_depth = transform_depth.checked_sub(1)?;
}
DrawCommand::PushClip(r) => {
6u8.hash(&mut h);
hash_rect(&mut h, *r, rel);
}
DrawCommand::PopClip => {
7u8.hash(&mut h);
}
DrawCommand::RoundedRect {
bounds: r,
radius,
color,
} => {
8u8.hash(&mut h);
hash_rect(&mut h, *r, rel);
hash_f32(&mut h, *radius);
hash_color(&mut h, *color);
}
DrawCommand::Ellipse { bounds: r, color } => {
9u8.hash(&mut h);
hash_rect(&mut h, *r, rel);
hash_color(&mut h, *color);
}
DrawCommand::Outline {
bounds: r,
radius,
width,
color,
} => {
10u8.hash(&mut h);
hash_rect(&mut h, *r, rel);
hash_f32(&mut h, *radius);
hash_f32(&mut h, *width);
hash_color(&mut h, *color);
}
DrawCommand::Ripple {
bounds: r,
corner_radius,
center,
radius,
color,
soft,
} => {
11u8.hash(&mut h);
hash_rect(&mut h, *r, rel);
hash_f32(&mut h, *corner_radius);
if let Some([ox, oy]) = rel {
hash_rel_f32(&mut h, center[0], ox);
hash_rel_f32(&mut h, center[1], oy);
} else {
hash_f32(&mut h, center[0]);
hash_f32(&mut h, center[1]);
}
hash_f32(&mut h, *radius);
hash_color(&mut h, *color);
soft.hash(&mut h);
}
DrawCommand::Line {
from,
to,
width,
color,
} => {
12u8.hash(&mut h);
if let Some([ox, oy]) = rel {
hash_rel_f32(&mut h, from[0], ox);
hash_rel_f32(&mut h, from[1], oy);
hash_rel_f32(&mut h, to[0], ox);
hash_rel_f32(&mut h, to[1], oy);
} else {
hash_f32(&mut h, from[0]);
hash_f32(&mut h, from[1]);
hash_f32(&mut h, to[0]);
hash_f32(&mut h, to[1]);
}
hash_f32(&mut h, *width);
hash_color(&mut h, *color);
}
DrawCommand::Polyline {
points,
count,
width,
color,
} => {
13u8.hash(&mut h);
count.hash(&mut h);
let n = usize::from(*count).clamp(2, 3);
for p in &points[..n] {
if let Some([ox, oy]) = rel {
hash_rel_f32(&mut h, p[0], ox);
hash_rel_f32(&mut h, p[1], oy);
} else {
hash_f32(&mut h, p[0]);
hash_f32(&mut h, p[1]);
}
}
hash_f32(&mut h, *width);
hash_color(&mut h, *color);
}
DrawCommand::Arc {
bounds: r,
start,
sweep,
stroke,
color,
rounded,
} => {
14u8.hash(&mut h);
hash_rect(&mut h, *r, rel);
hash_f32(&mut h, *start);
hash_f32(&mut h, *sweep);
hash_f32(&mut h, *stroke);
hash_color(&mut h, *color);
rounded.hash(&mut h);
}
DrawCommand::Loading {
bounds: r,
sample,
color,
} => {
15u8.hash(&mut h);
hash_rect(&mut h, *r, rel);
hash_f32(&mut h, sample.progress);
hash_f32(&mut h, sample.rotation);
hash_color(&mut h, *color);
}
DrawCommand::Shape {
bounds: r,
index,
color,
rotation,
} => {
16u8.hash(&mut h);
hash_rect(&mut h, *r, rel);
index.hash(&mut h);
hash_color(&mut h, *color);
hash_f32(&mut h, *rotation);
}
DrawCommand::Image {
bounds: r,
uv,
radius,
color,
image,
} => {
17u8.hash(&mut h);
hash_rect(&mut h, *r, rel);
for &v in uv {
hash_f32(&mut h, v);
}
hash_f32(&mut h, *radius);
hash_color(&mut h, *color);
image.id.hash(&mut h);
image.width.hash(&mut h);
image.height.hash(&mut h);
hash_f32(&mut h, image.msdf_px_range);
}
DrawCommand::Text {
bounds: r,
text,
color,
style,
} => {
18u8.hash(&mut h);
hash_rect(&mut h, *r, rel);
text.as_bytes().hash(&mut h);
hash_color(&mut h, *color);
hash_f32(&mut h, style.size);
style.weight.hash(&mut h);
style.italic.hash(&mut h);
(style.family as u8).hash(&mut h);
style.align.hash(&mut h);
hash_f32(&mut h, style.padding);
hash_f32(&mut h, style.letter_spacing);
}
DrawCommand::Shadow {
bounds: r,
radius,
offset,
blur,
spread,
color,
} => {
19u8.hash(&mut h);
hash_rect(&mut h, *r, rel);
hash_f32(&mut h, *radius);
hash_f32(&mut h, offset[0]);
hash_f32(&mut h, offset[1]);
hash_f32(&mut h, *blur);
hash_f32(&mut h, *spread);
hash_color(&mut h, *color);
}
}
}
if transform_depth != 0 {
return None;
}
Some(h.finish())
}
impl Renderer {
fn allocate_cached_layer_slot(
&mut self,
key: LayerCacheKey,
width: u32,
height: u32,
opaque: bool,
) -> Result<usize> {
if self.cached_layers.len() >= MAX_CACHED_LAYERS
&& let Some((evict_idx, _)) = self
.cached_layers
.iter()
.enumerate()
.min_by_key(|(_, e)| e.last_frame)
{
let old = self.cached_layers.swap_remove(evict_idx);
unsafe {
self.gl.delete_framebuffer(old.fbo);
self.gl.delete_texture(old.texture);
}
}
let (int_fmt, fmt) = self.fbo_tex_format();
let (fbo, texture) = unsafe {
let texture = self.gl.create_texture()?;
self.gl.active_texture(glow::TEXTURE1);
self.gl.bind_texture(glow::TEXTURE_2D, Some(texture));
self.gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_MIN_FILTER,
glow::LINEAR as i32,
);
self.gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_MAG_FILTER,
glow::LINEAR as i32,
);
self.gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_WRAP_S,
glow::CLAMP_TO_EDGE as i32,
);
self.gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_WRAP_T,
glow::CLAMP_TO_EDGE as i32,
);
self.gl.tex_image_2d(
glow::TEXTURE_2D,
0,
int_fmt,
width as i32,
height as i32,
0,
fmt,
glow::UNSIGNED_BYTE,
glow::PixelUnpackData::Slice(None),
);
let fbo = self.gl.create_framebuffer()?;
self.gl.bind_framebuffer(glow::FRAMEBUFFER, Some(fbo));
self.gl.framebuffer_texture_2d(
glow::FRAMEBUFFER,
glow::COLOR_ATTACHMENT0,
glow::TEXTURE_2D,
Some(texture),
0,
);
let status = self.gl.check_framebuffer_status(glow::FRAMEBUFFER);
self.gl
.bind_framebuffer(glow::FRAMEBUFFER, self.active_fbo());
self.gl
.bind_texture(glow::TEXTURE_2D, Some(self.image_texture));
self.gl.active_texture(glow::TEXTURE0);
if status != glow::FRAMEBUFFER_COMPLETE {
self.gl.delete_framebuffer(fbo);
self.gl.delete_texture(texture);
return Err(format!("Bhoo cached layer FBO incomplete: {status:#x}").into());
}
(fbo, texture)
};
let idx = self.cached_layers.len();
self.cached_layers.push(CachedLayer {
key,
fbo,
texture,
width,
height,
opaque,
filter_linear: true,
last_frame: self.frame_counter,
});
Ok(idx)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn try_render_cached_block(
&mut self,
inner: &[DrawCommand],
bounds: Rect,
radius: f32,
size: [u32; 2],
scale: f32,
logical_w: f32,
logical_h: f32,
require_identity: bool,
) -> Result<bool> {
if self.rendering_to_cache || !self.inherited_clip_planes.is_empty() {
return Ok(false);
}
if !self.transform.is_positive_axis_aligned() {
return Ok(false);
}
if require_identity && !self.transform.is_identity() {
return Ok(false);
}
let phys_w = (bounds.width * scale).round();
let phys_h = (bounds.height * scale).round();
if phys_w < 32.0
|| phys_h < 32.0
|| phys_w > size[0] as f32
|| phys_h > size[1] as f32
{
return Ok(false);
}
let (pw, ph) = (phys_w as u32, phys_h as u32);
let Some(content_hash) = hash_layer_commands(inner, bounds, scale) else {
return Ok(false);
};
let key = LayerCacheKey {
content_hash,
width: pw,
height: ph,
};
let existing = self.cached_layers.iter().position(|e| e.key == key);
let idx = if let Some(idx) = existing {
self.cached_layers[idx].last_frame = self.frame_counter;
idx
} else {
let promoted = self.seen_layers_prev.contains(&key)
|| !self.seen_layers_curr.insert(key);
if !promoted {
return Ok(false);
}
let opaque = self.commands_start_opaque(inner, bounds);
if require_identity && !opaque {
return Ok(false);
}
let idx = self.allocate_cached_layer_slot(key, pw, ph, opaque)?;
self.populate_cached_layer(idx, inner, bounds, size, scale, logical_w, logical_h)?;
idx
};
self.composite_cached_layer(idx, bounds, radius, size, scale)
}
#[allow(clippy::too_many_arguments)]
fn populate_cached_layer(
&mut self,
idx: usize,
inner: &[DrawCommand],
bounds: Rect,
parent_size: [u32; 2],
scale: f32,
parent_logical_w: f32,
parent_logical_h: f32,
) -> Result<()> {
let prev_scissor = self.current_gpu_scissor();
self.flush_vertices(prev_scissor, parent_size, scale)?;
let fbo = self.cached_layers[idx].fbo;
let pw = self.cached_layers[idx].width;
let ph = self.cached_layers[idx].height;
self.stats.layers += 1;
let saved_transform = self.transform;
let saved_transforms = std::mem::take(&mut self.transforms);
let saved_screen_clip = self.screen_clip;
let saved_local_clip = self.local_clip;
let saved_clips = std::mem::take(&mut self.clips);
let saved_active_layers = std::mem::take(&mut self.active_layers);
let saved_cache_fbo = self.cache_render_fbo;
let saved_rendering = self.rendering_to_cache;
self.rendering_to_cache = true;
self.cache_render_fbo = Some(fbo);
self.transform = if bounds.x == 0.0 && bounds.y == 0.0 {
PlanarTransform::IDENTITY
} else {
PlanarTransform::from_parts([0.0, 0.0], [-bounds.x, -bounds.y], [1.0, 1.0], 0.0)
};
self.screen_clip = Rect {
x: 0.0,
y: 0.0,
width: bounds.width,
height: bounds.height,
};
self.local_clip = if self.transform.is_identity() {
None
} else {
Some(bounds)
};
unsafe {
self.gl.bind_framebuffer(glow::FRAMEBUFFER, Some(fbo));
self.gl
.invalidate_framebuffer(glow::FRAMEBUFFER, &[glow::COLOR_ATTACHMENT0]);
self.gl.disable(glow::SCISSOR_TEST);
self.gl.viewport(0, 0, pw as i32, ph as i32);
self.gl.clear_color(0.0, 0.0, 0.0, 0.0);
self.gl.clear(glow::COLOR_BUFFER_BIT);
}
self.sync_viewport(bounds.width, bounds.height);
let res = self.execute_commands_inner(inner, [pw, ph], scale, bounds.width, bounds.height);
let flush_res = if res.is_ok() {
let final_scissor = self.current_gpu_scissor();
self.flush_vertices(final_scissor, [pw, ph], scale)
} else {
self.vertices.clear();
Ok(())
};
self.rendering_to_cache = saved_rendering;
self.cache_render_fbo = saved_cache_fbo;
self.transform = saved_transform;
self.transforms = saved_transforms;
self.screen_clip = saved_screen_clip;
self.local_clip = saved_local_clip;
self.clips = saved_clips;
self.active_layers = saved_active_layers;
let parent_fbo = self.active_fbo();
unsafe {
self.gl.bind_framebuffer(glow::FRAMEBUFFER, parent_fbo);
self.gl
.viewport(0, 0, parent_size[0] as i32, parent_size[1] as i32);
}
self.sync_viewport(parent_logical_w, parent_logical_h);
res?;
flush_res?;
Ok(())
}
fn composite_cached_layer(
&mut self,
idx: usize,
bounds: Rect,
radius: f32,
size: [u32; 2],
scale: f32,
) -> Result<bool> {
let texture = self.cached_layers[idx].texture;
let pw = self.cached_layers[idx].width as i32;
let ph = self.cached_layers[idx].height as i32;
let opaque = self.cached_layers[idx].opaque;
let screen_bounds = self.transform.transform_rect_aabb(bounds, self.screen_clip);
let composite_rect = screen_bounds.intersect(self.screen_clip);
if composite_rect.width <= 0.0 || composite_rect.height <= 0.0 {
return Ok(true);
}
let eff_radius = radius
.min(bounds.width * 0.5)
.min(bounds.height * 0.5)
.max(0.0);
let mut r_screen = eff_radius;
if eff_radius > 0.0 {
let s = (screen_bounds.width / bounds.width.max(1.0))
.min(screen_bounds.height / bounds.height.max(1.0));
r_screen = (eff_radius * s)
.min(screen_bounds.width.min(screen_bounds.height) * 0.5);
let pad = r_screen + (2.0 / scale.max(0.5)).max(1.0);
let touches_x = composite_rect.x < screen_bounds.x + pad
|| composite_rect.x + composite_rect.width > screen_bounds.x + screen_bounds.width - pad;
let touches_y = composite_rect.y < screen_bounds.y + pad
|| composite_rect.y + composite_rect.height > screen_bounds.y + screen_bounds.height - pad;
if !(touches_x && touches_y) {
r_screen = 0.0;
}
}
let dx0_f = screen_bounds.x * scale;
let dy0_f = screen_bounds.y * scale;
let dw_f = screen_bounds.width * scale;
let dh_f = screen_bounds.height * scale;
let is_1to1 = (dw_f - pw as f32).abs() < 0.05
&& (dh_f - ph as f32).abs() < 0.05
&& (dx0_f - dx0_f.round()).abs() < 0.05
&& (dy0_f - dy0_f.round()).abs() < 0.05;
let scissor = self.current_gpu_scissor();
self.flush_vertices(scissor, size, scale)?;
let want_linear = !is_1to1;
let filter_changed = self.cached_layers[idx].filter_linear != want_linear;
if filter_changed {
self.cached_layers[idx].filter_linear = want_linear;
}
let filter_gl = if want_linear {
glow::LINEAR as i32
} else {
glow::NEAREST as i32
};
unsafe {
self.gl.active_texture(glow::TEXTURE1);
self.gl.bind_texture(glow::TEXTURE_2D, Some(texture));
if filter_changed {
self.gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_MIN_FILTER,
filter_gl,
);
self.gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_MAG_FILTER,
filter_gl,
);
}
self.gl.active_texture(glow::TEXTURE0);
}
let uv = [0.0f32, 1.0, 1.0, 0.0];
let white = Color(255, 255, 255, 255);
let flat_kind = if opaque {
BatchKind::BlitOpaque
} else {
BatchKind::Blit
};
let saved_transform = self.transform;
let saved_local_clip = self.local_clip;
self.transform = PlanarTransform::IDENTITY;
self.local_clip = None;
let flush_result = if r_screen > 0.0
&& let Some((flats, corners)) = split_rounded_regions(screen_bounds, r_screen, scale)
{
let mut res = Ok(());
if flats.iter().any(|&f_rect| self.is_rect_visible(f_rect)) {
self.batch_kind = flat_kind;
for f_rect in flats {
if self.is_rect_visible(f_rect) {
self.quad_sub(screen_bounds, f_rect, uv, white, 0.0, -0.25);
}
}
res = self.flush_vertices(None, size, scale);
}
if res.is_ok() && corners.iter().any(|&c_rect| self.is_rect_visible(c_rect)) {
self.batch_kind = BatchKind::RoundedImage;
for c_rect in corners {
if self.is_rect_visible(c_rect) {
self.quad_sub(screen_bounds, c_rect, uv, white, r_screen, -0.25);
}
}
res = self.flush_vertices(None, size, scale);
}
res
} else {
self.batch_kind = if r_screen > 0.0 {
BatchKind::RoundedImage
} else {
flat_kind
};
self.quad(screen_bounds, uv, white, r_screen, -0.25);
self.flush_vertices(None, size, scale)
};
self.transform = saved_transform;
self.local_clip = saved_local_clip;
unsafe {
self.gl.active_texture(glow::TEXTURE1);
self.gl
.bind_texture(glow::TEXTURE_2D, Some(self.image_texture));
self.gl.active_texture(glow::TEXTURE0);
}
flush_result?;
Ok(true)
}
}