use super::*;
impl Default for DisplayListFrameArena {
fn default() -> Self {
Self {
string_pool: Vec::new(),
portals_scratch: Vec::new(),
z_sort_scratch: Vec::new(),
portal_ancestors_scratch: Vec::new(),
base_layer_version: 0,
prev_base_digest: 0,
cur_base_digest: FNV1A_OFFSET_BASIS,
running_fast_hash: FNV1A_OFFSET_BASIS,
base_layer_finalized: false,
}
}
}
impl Clone for DisplayListFrameArena {
fn clone(&self) -> Self {
let Self {
base_layer_version,
prev_base_digest,
cur_base_digest,
running_fast_hash,
base_layer_finalized,
..
} = self;
Self {
string_pool: Vec::new(),
portals_scratch: Vec::new(),
z_sort_scratch: Vec::new(),
portal_ancestors_scratch: Vec::new(),
base_layer_version: *base_layer_version,
prev_base_digest: *prev_base_digest,
cur_base_digest: *cur_base_digest,
running_fast_hash: *running_fast_hash,
base_layer_finalized: *base_layer_finalized,
}
}
}
impl PartialEq for DisplayListFrameArena {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl DisplayList {
pub(crate) fn reserve_steady_state(&mut self) {
let Self {
commands, arena, ..
} = self;
if commands.capacity() < 512 {
commands.reserve(512 - commands.len());
}
if arena.string_pool.capacity() < DISPLAY_LIST_STRING_POOL_CAP {
arena
.string_pool
.reserve(DISPLAY_LIST_STRING_POOL_CAP - arena.string_pool.len());
}
}
pub(crate) fn prewarm_scroll_string_pool(&mut self, spare_count: usize) {
let Self { arena, .. } = self;
let target: usize = arena
.string_pool
.len()
.saturating_add(spare_count)
.min(DISPLAY_LIST_STRING_POOL_CAP);
if arena.string_pool.capacity() < DISPLAY_LIST_STRING_POOL_CAP {
arena
.string_pool
.reserve(DISPLAY_LIST_STRING_POOL_CAP - arena.string_pool.len());
}
while arena.string_pool.len() < target {
arena.string_pool.push(String::with_capacity(128));
}
}
pub fn reset(&mut self, viewport: Size, scale_factor: f32) {
let safe_scale: f32 = scale_factor.max(0.5);
let Self {
commands,
viewport: vp,
scale_factor: sf,
portal_split_index,
arena,
} = self;
if arena.string_pool.capacity() < DISPLAY_LIST_STRING_POOL_CAP {
arena
.string_pool
.reserve(DISPLAY_LIST_STRING_POOL_CAP - arena.string_pool.len());
}
let pool_start: usize = arena.string_pool.len();
for cmd in commands.drain(..) {
match cmd {
DrawCommand::TextRun { mut text, .. } | DrawCommand::TextCaret { mut text, .. }
if text.capacity() > 0
&& arena.string_pool.len() < DISPLAY_LIST_STRING_POOL_CAP =>
{
text.clear();
arena.string_pool.push(text);
}
_ => {}
}
}
if arena.string_pool.len() > pool_start + 1 {
arena.string_pool[pool_start..].reverse();
}
*vp = viewport;
*sf = safe_scale;
*portal_split_index = 0;
let mut seed: u64 = FNV1A_OFFSET_BASIS;
Self::mix_hash(&mut seed, viewport.get_width().to_bits() as u64);
Self::mix_hash(&mut seed, viewport.get_height().to_bits() as u64);
Self::mix_hash(&mut seed, safe_scale.to_bits() as u64);
arena.prev_base_digest = arena.cur_base_digest;
arena.cur_base_digest = seed;
arena.running_fast_hash = seed;
arena.base_layer_finalized = false;
}
#[inline]
#[must_use]
pub(crate) fn alloc_text(&mut self, src: &str) -> String {
if src.is_empty() {
return String::new();
}
let Self { arena, .. } = self;
let pool: &mut Vec<String> = &mut arena.string_pool;
let len: usize = pool.len();
if len > 0 {
let need: usize = src.len();
if pool[len - 1].capacity() >= need
&& let Some(mut reused) = pool.pop()
{
reused.clear();
reused.push_str(src);
return reused;
}
for idx in (0..len.saturating_sub(1)).rev() {
if pool[idx].capacity() >= need {
let mut reused: String = pool.swap_remove(idx);
reused.clear();
reused.push_str(src);
return reused;
}
}
if let Some(mut reused) = pool.pop() {
reused.clear();
reused.push_str(src);
return reused;
}
}
let mut fresh: String = String::with_capacity(src.len().max(128));
fresh.push_str(src);
fresh
}
pub fn push(&mut self, command: DrawCommand) {
let Self {
commands, arena, ..
} = self;
Self::fold_command_fast(&mut arena.running_fast_hash, &command);
if !arena.base_layer_finalized {
Self::fold_command_full(&mut arena.cur_base_digest, &command);
}
commands.push(command);
}
#[inline]
#[must_use]
pub(crate) fn snapshot_digest_state(&self) -> (u64, u64) {
let Self { arena, .. } = self;
(arena.running_fast_hash, arena.cur_base_digest)
}
#[inline]
pub(crate) fn pop_empty_clip(&mut self, saved: (u64, u64)) {
let Self {
commands, arena, ..
} = self;
let _: Option<DrawCommand> = commands.pop();
arena.running_fast_hash = saved.0;
arena.cur_base_digest = saved.1;
}
pub(crate) fn attenuate_range_opacity(&mut self, start: usize, end: usize, opacity: f32) {
if opacity >= 0.999 || start >= end {
return;
}
let clamped: f32 = opacity.clamp(0.0, 1.0);
let Self {
commands, arena, ..
} = self;
let end_clamped: usize = end.min(commands.len());
for cmd in commands[start..end_clamped].iter_mut() {
match cmd {
DrawCommand::Clear(c)
| DrawCommand::Line { color: c, .. }
| DrawCommand::Circle { color: c, .. }
| DrawCommand::Triangle { color: c, .. }
| DrawCommand::TextCaret { color: c, .. } => {
*c = c.multiply_alpha(clamped);
}
DrawCommand::FillRoundedRect { color, border, .. } => {
*color = color.multiply_alpha(clamped);
border.set_color(border.get_color().multiply_alpha(clamped));
}
DrawCommand::LinearGradientRect { gradient, .. } => {
gradient.set_start_color(gradient.get_start_color().multiply_alpha(clamped));
gradient.set_end_color(gradient.get_end_color().multiply_alpha(clamped));
}
DrawCommand::BoxShadow { shadow, .. } => {
shadow.set_color(shadow.get_color().multiply_alpha(clamped));
}
DrawCommand::TextRun { style, .. } => {
style.set_color(style.get_color().multiply_alpha(clamped));
}
DrawCommand::SpriteRegion { tint, .. } => {
*tint = tint.multiply_alpha(clamped);
}
DrawCommand::BackdropBlur { .. }
| DrawCommand::Image { .. }
| DrawCommand::SharedImage { .. }
| DrawCommand::PushClip(_)
| DrawCommand::PushRoundedClip { .. }
| DrawCommand::PopClip => {}
}
}
let op_bits: u64 = clamped.to_bits() as u64;
Self::mix_hash(&mut arena.running_fast_hash, op_bits);
if !arena.base_layer_finalized {
Self::mix_hash(&mut arena.cur_base_digest, op_bits);
}
}
#[inline]
pub(crate) fn finalize_base_layer(&mut self, split_index: usize) {
let Self {
portal_split_index,
arena,
..
} = self;
*portal_split_index = split_index;
Self::mix_hash(&mut arena.cur_base_digest, split_index as u64);
if arena.base_layer_version == 0 || arena.cur_base_digest != arena.prev_base_digest {
arena.base_layer_version = arena.base_layer_version.wrapping_add(1).max(1);
}
arena.base_layer_finalized = true;
}
#[inline]
#[must_use]
pub fn base_layer_version(&self) -> u64 {
let Self { arena, .. } = self;
arena.base_layer_version
}
#[must_use]
pub fn len(&self) -> usize {
self.get_commands().len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.get_commands().is_empty()
}
#[inline(always)]
fn mix_hash(hash: &mut u64, value: u64) {
*hash ^= value;
*hash = hash.wrapping_mul(FNV1A_PRIME);
}
#[inline]
fn fold_command_fast(hash: &mut u64, cmd: &DrawCommand) {
match cmd {
DrawCommand::Clear(c) => {
Self::mix_hash(hash, 1);
Self::mix_hash(hash, u32::from_le_bytes(c.to_rgba_bytes()) as u64);
}
DrawCommand::FillRoundedRect {
rect,
color,
border,
..
} => {
Self::mix_hash(hash, 2);
Self::mix_hash(hash, rect.get_x().to_bits() as u64);
Self::mix_hash(hash, rect.get_y().to_bits() as u64);
Self::mix_hash(hash, rect.get_width().to_bits() as u64);
Self::mix_hash(hash, rect.get_height().to_bits() as u64);
Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
Self::mix_hash(hash, border.get_width().to_bits() as u64);
}
DrawCommand::LinearGradientRect { rect, gradient, .. } => {
Self::mix_hash(hash, 3);
Self::mix_hash(hash, rect.get_x().to_bits() as u64);
Self::mix_hash(hash, rect.get_y().to_bits() as u64);
Self::mix_hash(
hash,
u32::from_le_bytes(gradient.get_start_color().to_rgba_bytes()) as u64,
);
}
DrawCommand::BoxShadow { rect, shadow, .. } => {
Self::mix_hash(hash, 4);
Self::mix_hash(hash, rect.get_x().to_bits() as u64);
Self::mix_hash(hash, shadow.get_blur_radius().to_bits() as u64);
}
DrawCommand::BackdropBlur {
rect, blur_radius, ..
} => {
Self::mix_hash(hash, 15);
Self::mix_hash(hash, rect.get_x().to_bits() as u64);
Self::mix_hash(hash, rect.get_y().to_bits() as u64);
Self::mix_hash(hash, blur_radius.to_bits() as u64);
}
DrawCommand::TextRun { rect, text, style } => {
Self::mix_hash(hash, 5);
Self::mix_hash(hash, rect.get_x().to_bits() as u64);
Self::mix_hash(hash, rect.get_y().to_bits() as u64);
Self::mix_hash(hash, text.len() as u64);
let bytes: &[u8] = text.as_bytes();
let prefix_len: usize = bytes.len().min(16);
for &byte in bytes[..prefix_len].iter() {
Self::mix_hash(hash, byte as u64);
}
Self::mix_hash(
hash,
u32::from_le_bytes(style.get_color().to_rgba_bytes()) as u64,
);
}
DrawCommand::TextCaret {
text_rect,
text,
color,
..
} => {
Self::mix_hash(hash, 13);
Self::mix_hash(hash, text_rect.get_x().to_bits() as u64);
Self::mix_hash(hash, text_rect.get_y().to_bits() as u64);
Self::mix_hash(hash, text.len() as u64);
Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
}
DrawCommand::Image { rect, buffer, .. } => {
Self::mix_hash(hash, 6);
Self::mix_hash(hash, rect.get_x().to_bits() as u64);
Self::mix_hash(hash, buffer.get_width() as u64);
Self::mix_hash(hash, buffer.get_height() as u64);
}
DrawCommand::SharedImage {
rect,
width,
height,
..
} => {
Self::mix_hash(hash, 6);
Self::mix_hash(hash, rect.get_x().to_bits() as u64);
Self::mix_hash(hash, *width as u64);
Self::mix_hash(hash, *height as u64);
}
DrawCommand::Line {
from,
to,
color,
width,
} => {
Self::mix_hash(hash, 7);
Self::mix_hash(hash, from.get_x().to_bits() as u64);
Self::mix_hash(hash, to.get_y().to_bits() as u64);
Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
Self::mix_hash(hash, width.to_bits() as u64);
}
DrawCommand::Circle {
center,
radius,
color,
} => {
Self::mix_hash(hash, 8);
Self::mix_hash(hash, center.get_x().to_bits() as u64);
Self::mix_hash(hash, center.get_y().to_bits() as u64);
Self::mix_hash(hash, radius.to_bits() as u64);
Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
}
DrawCommand::Triangle { p0, p1, p2, color } => {
Self::mix_hash(hash, 9);
Self::mix_hash(hash, p0.get_x().to_bits() as u64);
Self::mix_hash(hash, p1.get_y().to_bits() as u64);
Self::mix_hash(hash, p2.get_x().to_bits() as u64);
Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
}
DrawCommand::SpriteRegion {
rect,
src_rect,
tint,
..
} => {
Self::mix_hash(hash, 10);
Self::mix_hash(hash, rect.get_x().to_bits() as u64);
Self::mix_hash(hash, src_rect.get_x().to_bits() as u64);
Self::mix_hash(hash, u32::from_le_bytes(tint.to_rgba_bytes()) as u64);
}
DrawCommand::PushClip(r) => {
Self::mix_hash(hash, 11);
Self::mix_hash(hash, r.get_x().to_bits() as u64);
Self::mix_hash(hash, r.get_y().to_bits() as u64);
}
DrawCommand::PushRoundedClip { rect, radius } => {
Self::mix_hash(hash, 14);
Self::mix_hash(hash, rect.get_x().to_bits() as u64);
Self::mix_hash(hash, rect.get_y().to_bits() as u64);
Self::mix_hash(hash, radius.max_radius().to_bits() as u64);
}
DrawCommand::PopClip => {
Self::mix_hash(hash, 12);
}
}
}
#[inline]
fn fold_bytes_wordwise(hash: &mut u64, bytes: &[u8]) {
Self::mix_hash(hash, bytes.len() as u64);
let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
for chunk in chunks.iter() {
Self::mix_hash(hash, u64::from_ne_bytes(*chunk));
}
if !rem.is_empty() {
let mut tail: u64 = 0;
for (idx, &b) in rem.iter().enumerate() {
tail |= (b as u64) << (idx * 8);
}
Self::mix_hash(hash, tail);
}
}
#[inline]
pub(crate) fn fold_command_full(hash: &mut u64, cmd: &DrawCommand) {
match cmd {
DrawCommand::Clear(c) => {
Self::mix_hash(hash, 1);
Self::mix_hash(hash, u32::from_le_bytes(c.to_rgba_bytes()) as u64);
}
DrawCommand::FillRoundedRect {
rect,
color,
radius,
border,
} => {
Self::mix_hash(hash, 2);
Self::mix_hash(
hash,
((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((rect.get_width().to_bits() as u64) << 32)
| (rect.get_height().to_bits() as u64),
);
Self::mix_hash(
hash,
((u32::from_le_bytes(color.to_rgba_bytes()) as u64) << 32)
| (u32::from_le_bytes(border.get_color().to_rgba_bytes()) as u64),
);
Self::mix_hash(
hash,
((radius.get_top_left().to_bits() as u64) << 32)
| (radius.get_top_right().to_bits() as u64),
);
Self::mix_hash(
hash,
((radius.get_bottom_right().to_bits() as u64) << 32)
| (radius.get_bottom_left().to_bits() as u64),
);
Self::mix_hash(hash, border.get_width().to_bits() as u64);
}
DrawCommand::LinearGradientRect {
rect,
gradient,
radius,
} => {
Self::mix_hash(hash, 3);
Self::mix_hash(
hash,
((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((rect.get_width().to_bits() as u64) << 32)
| (rect.get_height().to_bits() as u64),
);
Self::mix_hash(
hash,
((u32::from_le_bytes(gradient.get_start_color().to_rgba_bytes()) as u64) << 32)
| (u32::from_le_bytes(gradient.get_end_color().to_rgba_bytes()) as u64),
);
Self::mix_hash(
hash,
((gradient.get_angle_deg().to_bits() as u64) << 32)
| (radius.max_radius().to_bits() as u64),
);
}
DrawCommand::BoxShadow {
rect,
radius,
shadow,
} => {
Self::mix_hash(hash, 4);
Self::mix_hash(
hash,
((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((rect.get_width().to_bits() as u64) << 32)
| (rect.get_height().to_bits() as u64),
);
Self::mix_hash(
hash,
((shadow.get_offset_x().to_bits() as u64) << 32)
| (shadow.get_offset_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((shadow.get_blur_radius().to_bits() as u64) << 32)
| (shadow.get_spread_radius().to_bits() as u64),
);
Self::mix_hash(
hash,
((radius.max_radius().to_bits() as u64) << 32)
| (u32::from_le_bytes(shadow.get_color().to_rgba_bytes()) as u64),
);
}
DrawCommand::BackdropBlur {
rect,
radius,
blur_radius,
} => {
Self::mix_hash(hash, 15);
Self::mix_hash(
hash,
((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((rect.get_width().to_bits() as u64) << 32)
| (rect.get_height().to_bits() as u64),
);
Self::mix_hash(
hash,
((radius.max_radius().to_bits() as u64) << 32) | (blur_radius.to_bits() as u64),
);
}
DrawCommand::TextRun { rect, text, style } => {
Self::mix_hash(hash, 5);
Self::mix_hash(
hash,
((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((rect.get_width().to_bits() as u64) << 32)
| (rect.get_height().to_bits() as u64),
);
let style_flags: u64 = (style.get_family() as u64)
| ((style.get_weight() as u64) << 8)
| ((style.get_align() as u64) << 16)
| (u64::from(style.get_italic()) << 24)
| ((u32::from_le_bytes(style.get_color().to_rgba_bytes()) as u64) << 32);
Self::mix_hash(hash, style_flags);
Self::mix_hash(hash, style.get_font_size().to_bits() as u64);
Self::fold_bytes_wordwise(hash, text.as_bytes());
}
DrawCommand::TextCaret {
text_rect,
content_rect,
text,
style,
caret_height,
color,
multiline,
} => {
Self::mix_hash(hash, 13);
Self::mix_hash(
hash,
((text_rect.get_x().to_bits() as u64) << 32)
| (text_rect.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((content_rect.get_width().to_bits() as u64) << 32)
| (caret_height.to_bits() as u64),
);
Self::mix_hash(
hash,
((style.get_font_size().to_bits() as u64) << 32)
| (u32::from_le_bytes(color.to_rgba_bytes()) as u64)
^ u64::from(*multiline),
);
Self::fold_bytes_wordwise(hash, text.as_bytes());
}
DrawCommand::Image {
rect,
buffer,
radius,
} => {
Self::mix_hash(hash, 6);
Self::mix_hash(
hash,
((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((rect.get_width().to_bits() as u64) << 32)
| (rect.get_height().to_bits() as u64),
);
Self::mix_hash(
hash,
((buffer.get_width() as u64) << 32) | (buffer.get_height() as u64),
);
Self::mix_hash(hash, buffer.get_pixels().as_ptr() as usize as u64);
Self::mix_hash(hash, radius.max_radius().to_bits() as u64);
}
DrawCommand::SharedImage {
rect,
width,
height,
pixels,
radius,
} => {
Self::mix_hash(hash, 6);
Self::mix_hash(
hash,
((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((rect.get_width().to_bits() as u64) << 32)
| (rect.get_height().to_bits() as u64),
);
Self::mix_hash(hash, ((*width as u64) << 32) | (*height as u64));
Self::mix_hash(hash, pixels.as_ptr() as usize as u64);
Self::mix_hash(hash, radius.max_radius().to_bits() as u64);
}
DrawCommand::Line {
from,
to,
color,
width,
} => {
Self::mix_hash(hash, 7);
Self::mix_hash(
hash,
((from.get_x().to_bits() as u64) << 32) | (from.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((to.get_x().to_bits() as u64) << 32) | (to.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((u32::from_le_bytes(color.to_rgba_bytes()) as u64) << 32)
| (width.to_bits() as u64),
);
}
DrawCommand::Circle {
center,
radius,
color,
} => {
Self::mix_hash(hash, 8);
Self::mix_hash(
hash,
((center.get_x().to_bits() as u64) << 32) | (center.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((radius.to_bits() as u64) << 32)
| (u32::from_le_bytes(color.to_rgba_bytes()) as u64),
);
}
DrawCommand::Triangle { p0, p1, p2, color } => {
Self::mix_hash(hash, 9);
Self::mix_hash(
hash,
((p0.get_x().to_bits() as u64) << 32) | (p0.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((p1.get_x().to_bits() as u64) << 32) | (p1.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((p2.get_x().to_bits() as u64) << 32) | (p2.get_y().to_bits() as u64),
);
Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
}
DrawCommand::SpriteRegion {
rect,
buffer,
src_rect,
tint,
} => {
Self::mix_hash(hash, 10);
Self::mix_hash(
hash,
((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((rect.get_width().to_bits() as u64) << 32)
| (rect.get_height().to_bits() as u64),
);
Self::mix_hash(hash, buffer.get_pixels().as_ptr() as usize as u64);
Self::mix_hash(
hash,
((src_rect.get_x().to_bits() as u64) << 32)
| (src_rect.get_y().to_bits() as u64),
);
Self::mix_hash(hash, u32::from_le_bytes(tint.to_rgba_bytes()) as u64);
}
DrawCommand::PushClip(r) => {
Self::mix_hash(hash, 11);
Self::mix_hash(
hash,
((r.get_x().to_bits() as u64) << 32) | (r.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((r.get_width().to_bits() as u64) << 32) | (r.get_height().to_bits() as u64),
);
}
DrawCommand::PushRoundedClip { rect, radius } => {
Self::mix_hash(hash, 14);
Self::mix_hash(
hash,
((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
);
Self::mix_hash(
hash,
((rect.get_width().to_bits() as u64) << 32)
| (rect.get_height().to_bits() as u64),
);
Self::mix_hash(
hash,
((radius.get_top_left().to_bits() as u64) << 32)
| (radius.get_top_right().to_bits() as u64),
);
Self::mix_hash(
hash,
((radius.get_bottom_right().to_bits() as u64) << 32)
| (radius.get_bottom_left().to_bits() as u64),
);
}
DrawCommand::PopClip => {
Self::mix_hash(hash, 12);
}
}
}
#[inline]
#[must_use]
pub fn fast_hash(&self) -> u64 {
let Self {
commands, arena, ..
} = self;
let mut hash: u64 = arena.running_fast_hash;
Self::mix_hash(&mut hash, commands.len() as u64);
hash
}
#[inline]
#[must_use]
pub fn base_layer_hash(&self) -> u64 {
let Self {
commands, arena, ..
} = self;
if arena.base_layer_finalized {
return arena.base_layer_version.max(1);
}
let mut hash: u64 = arena.cur_base_digest;
Self::mix_hash(&mut hash, commands.len() as u64);
if hash == 0 { 1 } else { hash }
}
}
impl PaintFragmentCache {
pub fn clear(&mut self) {
let Self {
has_last_scene,
last_has_canvas,
slots,
cmd_slab,
text_slab,
canvas_stability,
..
} = self;
*has_last_scene = false;
*last_has_canvas = false;
slots.fill(RetainedPaintFragment::default());
cmd_slab.clear();
text_slab.clear();
for entry in canvas_stability.iter_mut() {
*entry = CanvasStabilityEntry::default();
}
}
#[must_use]
pub fn stats(&self) -> (u64, u64, u64, u64) {
(
self.get_whole_list_hits(),
self.get_fragment_hits(),
self.get_fragment_misses(),
self.get_fragment_evictions(),
)
}
#[inline]
fn ensure_slots(&mut self) {
let Self {
slots,
cmd_slab,
text_slab,
..
} = self;
if slots.len() != PAINT_FRAGMENT_CACHE_SLOTS {
slots.resize(PAINT_FRAGMENT_CACHE_SLOTS, RetainedPaintFragment::default());
}
if cmd_slab.capacity() < PAINT_FRAGMENT_CMD_SLAB_CAP {
cmd_slab.reserve_exact(PAINT_FRAGMENT_CMD_SLAB_CAP - cmd_slab.len());
}
if text_slab.capacity() < PAINT_FRAGMENT_TEXT_SLAB_CAP {
text_slab.reserve_exact(PAINT_FRAGMENT_TEXT_SLAB_CAP - text_slab.len());
}
}
#[inline]
fn encode_cached_command(
cmd: &DrawCommand,
text_dst: &mut [u8],
text_cursor: &mut usize,
text_base: usize,
) -> CachedDrawCommand {
match cmd {
DrawCommand::Clear(c) => CachedDrawCommand::Clear(*c),
DrawCommand::FillRoundedRect {
rect,
color,
radius,
border,
} => CachedDrawCommand::FillRoundedRect {
rect: *rect,
color: *color,
radius: *radius,
border: *border,
},
DrawCommand::LinearGradientRect {
rect,
gradient,
radius,
} => CachedDrawCommand::LinearGradientRect {
rect: *rect,
gradient: *gradient,
radius: *radius,
},
DrawCommand::BoxShadow {
rect,
radius,
shadow,
} => CachedDrawCommand::BoxShadow {
rect: *rect,
radius: *radius,
shadow: *shadow,
},
DrawCommand::BackdropBlur {
rect,
radius,
blur_radius,
} => CachedDrawCommand::BackdropBlur {
rect: *rect,
radius: *radius,
blur_radius: *blur_radius,
},
DrawCommand::TextRun { rect, text, style } => {
let bytes: &[u8] = text.as_bytes();
let start_rel: usize = *text_cursor;
let end_rel: usize = start_rel.saturating_add(bytes.len());
text_dst[start_rel..end_rel].copy_from_slice(bytes);
*text_cursor = end_rel;
CachedDrawCommand::TextRun {
rect: *rect,
text_start: (text_base.saturating_add(start_rel)) as u32,
text_len: bytes.len() as u32,
style: *style,
}
}
DrawCommand::TextCaret {
text_rect,
content_rect,
text,
style,
caret_height,
color,
multiline,
} => {
let bytes: &[u8] = text.as_bytes();
let start_rel: usize = *text_cursor;
let end_rel: usize = start_rel.saturating_add(bytes.len());
text_dst[start_rel..end_rel].copy_from_slice(bytes);
*text_cursor = end_rel;
CachedDrawCommand::TextCaret {
text_rect: *text_rect,
content_rect: *content_rect,
text_start: (text_base.saturating_add(start_rel)) as u32,
text_len: bytes.len() as u32,
style: *style,
caret_height: *caret_height,
color: *color,
multiline: *multiline,
}
}
DrawCommand::Image {
rect,
buffer,
radius,
} => CachedDrawCommand::Image {
rect: *rect,
buffer: buffer.clone(),
radius: *radius,
},
DrawCommand::SharedImage {
rect,
width,
height,
pixels,
radius,
} => CachedDrawCommand::SharedImage {
rect: *rect,
width: *width,
height: *height,
pixels: Arc::clone(pixels),
radius: *radius,
},
DrawCommand::Line {
from,
to,
color,
width,
} => CachedDrawCommand::Line {
from: *from,
to: *to,
color: *color,
width: *width,
},
DrawCommand::Circle {
center,
radius,
color,
} => CachedDrawCommand::Circle {
center: *center,
radius: *radius,
color: *color,
},
DrawCommand::Triangle { p0, p1, p2, color } => CachedDrawCommand::Triangle {
p0: *p0,
p1: *p1,
p2: *p2,
color: *color,
},
DrawCommand::SpriteRegion {
rect,
buffer,
src_rect,
tint,
} => CachedDrawCommand::SpriteRegion {
rect: *rect,
buffer: buffer.clone(),
src_rect: *src_rect,
tint: *tint,
},
DrawCommand::PushClip(rect) => CachedDrawCommand::PushClip(*rect),
DrawCommand::PushRoundedClip { rect, radius } => CachedDrawCommand::PushRoundedClip {
rect: *rect,
radius: *radius,
},
DrawCommand::PopClip => CachedDrawCommand::PopClip,
}
}
fn capture_fragment(
&mut self,
slot_idx: usize,
meta: (NodeId, u32, u32, Point, u64, u64),
cmd_slice: &[DrawCommand],
) {
let (node_id, phys_scale_milli, opacity_bits, offset_phys, geom_hash, style_text_hash): (
NodeId,
u32,
u32,
Point,
u64,
u64,
) = meta;
let Self {
slots,
cmd_slab,
text_slab,
fragment_misses,
fragment_evictions,
..
} = self;
if slot_idx >= slots.len() {
return;
}
*fragment_misses = fragment_misses.wrapping_add(1);
let need_cmds: usize = cmd_slice.len();
let mut need_text: usize = 0;
for cmd in cmd_slice.iter() {
match cmd {
DrawCommand::TextRun { text, .. } | DrawCommand::TextCaret { text, .. } => {
need_text = need_text.saturating_add(text.len());
}
_ => {}
}
}
if need_cmds > PAINT_FRAGMENT_CMD_SLAB_CAP || need_text > PAINT_FRAGMENT_TEXT_SLAB_CAP {
return;
}
let existing: RetainedPaintFragment = slots[slot_idx];
if existing.occupied && existing.node_id != node_id {
*fragment_evictions = fragment_evictions.wrapping_add(1);
}
if existing.occupied
&& need_cmds <= (existing.cmd_cap as usize)
&& need_text <= (existing.text_cap as usize)
{
let cmd_base: usize = existing.cmd_start as usize;
let text_base: usize = existing.text_start as usize;
let text_end: usize = text_base.saturating_add(need_text);
let mut text_cursor: usize = 0;
let text_dst: &mut [u8] = &mut text_slab[text_base..text_end];
for (i, cmd) in cmd_slice.iter().enumerate() {
cmd_slab[cmd_base + i] =
Self::encode_cached_command(cmd, text_dst, &mut text_cursor, text_base);
}
slots[slot_idx] = RetainedPaintFragment {
occupied: true,
node_id,
phys_scale_milli,
opacity_bits,
offset_phys,
geom_hash,
style_text_hash,
cmd_start: existing.cmd_start,
cmd_len: need_cmds as u32,
cmd_cap: existing.cmd_cap,
text_start: existing.text_start,
text_cap: existing.text_cap,
};
return;
}
if cmd_slab.len().saturating_add(need_cmds) > PAINT_FRAGMENT_CMD_SLAB_CAP
|| text_slab.len().saturating_add(need_text) > PAINT_FRAGMENT_TEXT_SLAB_CAP
{
let mut evicted: u64 = 0;
for s in slots.iter_mut() {
if s.occupied {
evicted = evicted.saturating_add(1);
*s = RetainedPaintFragment::default();
}
}
*fragment_evictions = fragment_evictions.wrapping_add(evicted);
cmd_slab.clear();
text_slab.clear();
}
let cmd_start: usize = cmd_slab.len();
let text_base: usize = text_slab.len();
let text_end: usize = text_base.saturating_add(need_text);
text_slab.resize(text_end, 0);
let mut text_cursor: usize = 0;
let text_dst: &mut [u8] = &mut text_slab[text_base..text_end];
for cmd in cmd_slice.iter() {
cmd_slab.push(Self::encode_cached_command(
cmd,
text_dst,
&mut text_cursor,
text_base,
));
}
slots[slot_idx] = RetainedPaintFragment {
occupied: true,
node_id,
phys_scale_milli,
opacity_bits,
offset_phys,
geom_hash,
style_text_hash,
cmd_start: cmd_start as u32,
cmd_len: need_cmds as u32,
cmd_cap: need_cmds as u32,
text_start: text_base as u32,
text_cap: need_text as u32,
};
}
#[inline]
fn record_canvas_output(
&mut self,
node_id: NodeId,
phys_scale_milli: u32,
bounds: Rect,
tree_revision: u64,
cmds: &[DrawCommand],
) -> bool {
let slot_idx: usize = (node_id.get_index() as usize) & (CANVAS_STABILITY_SLOTS - 1);
let Self {
canvas_stability, ..
} = self;
let slot: &mut CanvasStabilityEntry = &mut canvas_stability[slot_idx];
let mut has_raster: bool = false;
let mut cmd_hash: u64 = FNV1A_OFFSET_BASIS;
for cmd in cmds.iter() {
if matches!(
cmd,
DrawCommand::Image { .. }
| DrawCommand::SharedImage { .. }
| DrawCommand::SpriteRegion { .. }
) {
has_raster = true;
break;
}
DisplayList::fold_command_full(&mut cmd_hash, cmd);
}
if has_raster {
*slot = CanvasStabilityEntry {
node_id,
phys_scale_milli,
bounds,
tree_revision,
cmd_hash: 0,
stable_hits: 0,
proven_dynamic: true,
occupied: true,
};
return true;
}
if slot.occupied
&& slot.node_id == node_id
&& slot.phys_scale_milli == phys_scale_milli
&& slot.bounds == bounds
{
if slot.proven_dynamic {
return true;
}
if slot.cmd_hash == cmd_hash {
slot.tree_revision = tree_revision;
slot.stable_hits = slot.stable_hits.saturating_add(1);
return slot.stable_hits < 2;
}
if slot.tree_revision == tree_revision {
slot.proven_dynamic = true;
return true;
}
slot.tree_revision = tree_revision;
slot.cmd_hash = cmd_hash;
slot.stable_hits = 1;
return true;
}
*slot = CanvasStabilityEntry {
node_id,
phys_scale_milli,
bounds,
tree_revision,
cmd_hash,
stable_hits: 1,
proven_dynamic: false,
occupied: true,
};
true
}
}
impl PaintPass {
#[inline]
#[must_use]
fn text_selection_sig(tree: &SceneTree) -> u64 {
let Some(sel) = tree.text_selection() else {
return 0;
};
if sel.is_empty() {
return 0;
}
let anchor_id: NodeId = sel.get_anchor_node();
let focus_id: NodeId = sel.get_focus_node();
let mut h: u64 =
((anchor_id.get_index() as u64) << 32) | (anchor_id.get_generation() as u64);
h = (h ^ (sel.get_anchor_char() as u64)).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
let focus_bits: u64 =
((focus_id.get_index() as u64) << 32) | (focus_id.get_generation() as u64);
h = (h ^ focus_bits).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
h = (h ^ (sel.get_focus_char() as u64)).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
if h == 0 { 1 } else { h }
}
#[inline(always)]
fn fx_fold(hash: &mut u64, word: u64) {
*hash = (*hash ^ word).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
}
#[inline(always)]
fn fx_fold_rect(hash: &mut u64, rect: Rect) {
let lo: u64 = ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64);
let hi: u64 =
((rect.get_width().to_bits() as u64) << 32) | (rect.get_height().to_bits() as u64);
Self::fx_fold(hash, lo);
Self::fx_fold(hash, hi);
}
#[inline]
fn fx_fold_paint(hash: &mut u64, paint: &PaintStyle) {
let bg_bits: u64 = paint
.background_color()
.map(|c: Color| u32::from_le_bytes(c.to_rgba_bytes()) as u64 | (1_u64 << 32))
.unwrap_or(0);
Self::fx_fold(hash, bg_bits);
if let Some(grad) = paint.background_gradient() {
let g0: u64 = u32::from_le_bytes(grad.get_start_color().to_rgba_bytes()) as u64;
let g1: u64 = u32::from_le_bytes(grad.get_end_color().to_rgba_bytes()) as u64;
Self::fx_fold(hash, (g0 << 32) | g1);
Self::fx_fold(hash, grad.get_angle_deg().to_bits() as u64 | (1_u64 << 33));
}
let border: Border = paint.get_border();
let b_word: u64 = ((border.get_width().to_bits() as u64) << 32)
| (u32::from_le_bytes(border.get_color().to_rgba_bytes()) as u64);
Self::fx_fold(hash, b_word);
let r: CornerRadius = paint.get_radius();
let r0: u64 =
((r.get_top_left().to_bits() as u64) << 32) | (r.get_top_right().to_bits() as u64);
let r1: u64 = ((r.get_bottom_right().to_bits() as u64) << 32)
| (r.get_bottom_left().to_bits() as u64);
Self::fx_fold(hash, r0);
Self::fx_fold(hash, r1);
Self::fx_fold(hash, paint.get_opacity().to_bits() as u64);
if let Some(sh) = paint.box_shadow() {
let s0: u64 =
((sh.get_offset_x().to_bits() as u64) << 32) | (sh.get_offset_y().to_bits() as u64);
let s1: u64 = ((sh.get_blur_radius().to_bits() as u64) << 32)
| (sh.get_spread_radius().to_bits() as u64);
Self::fx_fold(hash, s0);
Self::fx_fold(hash, s1);
Self::fx_fold(
hash,
u32::from_le_bytes(sh.get_color().to_rgba_bytes()) as u64 | (1_u64 << 34),
);
}
}
#[inline]
fn fx_fold_text(hash: &mut u64, text_style: &TextStyle, text: &str) {
let m0: u64 = ((text_style.get_font_size().to_bits() as u64) << 32)
| (text_style.get_line_height().to_bits() as u64);
let m1: u64 = ((text_style.get_letter_spacing().to_bits() as u64) << 32)
| (u32::from_le_bytes(text_style.get_color().to_rgba_bytes()) as u64);
let flags: u64 = (text_style.get_family() as u64)
| ((text_style.get_weight() as u64) << 8)
| ((text_style.get_align() as u64) << 16)
| ((text_style.get_overflow() as u64) << 24)
| (u64::from(text_style.get_italic()) << 32);
Self::fx_fold(hash, m0);
Self::fx_fold(hash, m1);
Self::fx_fold(hash, flags);
let bytes: &[u8] = text.as_bytes();
Self::fx_fold(hash, bytes.len() as u64);
let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
for chunk in chunks.iter() {
Self::fx_fold(hash, u64::from_ne_bytes(*chunk));
}
if !rem.is_empty() {
let mut tail: u64 = 0;
for (idx, &b) in rem.iter().enumerate() {
tail |= (b as u64) << (idx * 8);
}
Self::fx_fold(hash, tail);
}
}
#[inline(always)]
#[must_use]
fn quantize_scale_milli(scale: f32) -> u32 {
(scale.max(0.5) * 1000.0).round() as u32
}
#[inline]
#[must_use]
fn fingerprint_subtree_children(
tree: &SceneTree,
parent: NodeId,
depth: usize,
unclipped_cull: Option<(Point, Rect, f32, f32)>,
focus_pair: (Option<NodeId>, bool),
acc: &mut (usize, u64, u64),
) -> bool {
let child_count: usize = tree.child_count(parent);
if depth > PAINT_FRAGMENT_MAX_DEPTH || child_count > PAINT_FRAGMENT_MAX_CHILDREN {
return false;
}
let (active_hover_target, has_text_sel): (Option<NodeId>, bool) = focus_pair;
Self::fx_fold(&mut acc.1, child_count as u64);
for cid in tree.children_iter(parent) {
if acc.0 >= PAINT_FRAGMENT_MAX_NODES
|| active_hover_target == Some(cid)
|| (has_text_sel && tree.text_selection_range_for(cid).is_some())
|| tree.backdrop_blur_radius(cid) > 0.0
{
return false;
}
let Some(child) = tree.get_node(cid) else {
return false;
};
acc.0 += 1;
let c_inter: InteractionState = child.get_interaction();
let c_active: bool = c_inter.get_hovered() || c_inter.get_pressed();
if c_active || c_inter.get_focused() {
return false;
}
let c_style: &Style = child.style_ref();
if c_style.layout.get_position() == Position::Fixed {
return false;
}
let c_tag: u64 = match child.get_kind() {
NodeKind::View | NodeKind::Fragment => 1,
NodeKind::Text(text) => {
Self::fx_fold_text(&mut acc.2, &c_style.text, text.as_str());
Self::fx_fold_rect(&mut acc.1, child.layout_box.get_content_bounds());
2
}
NodeKind::Image(buf) => {
Self::fx_fold(&mut acc.2, tree.node_paint_epoch(cid) as u64);
Self::fx_fold(
&mut acc.2,
((buf.get_width() as u64) << 32) | (buf.get_height() as u64),
);
Self::fx_fold(&mut acc.2, buf.get_pixels().as_ptr() as usize as u64);
3
}
NodeKind::Canvas(CanvasCaching::RetainedStatic) => {
Self::fx_fold(&mut acc.2, tree.node_paint_epoch(cid) as u64);
if let Some(cb) = child.canvas_callback() {
let cb_addr: u64 = (Rc::as_ptr(&cb) as *const ()) as usize as u64;
Self::fx_fold(&mut acc.2, cb_addr);
}
4
}
NodeKind::Portal
| NodeKind::Canvas(CanvasCaching::DynamicPerFrame)
| NodeKind::Input(_)
| NodeKind::ScrollView => {
return false;
}
};
let c_id_bits: u64 = ((cid.get_index() as u64) << 32) | (cid.get_generation() as u64);
Self::fx_fold(&mut acc.1, c_id_bits);
let raw_b: Rect = child.layout_box.get_bounds();
Self::fx_fold_rect(&mut acc.1, raw_b);
let ct: Transform2D = c_style.paint.get_transform();
Self::fx_fold(
&mut acc.1,
((ct.get_translate_x().to_bits() as u64) << 32)
| (ct.get_translate_y().to_bits() as u64),
);
Self::fx_fold(
&mut acc.1,
((ct.get_scale_x().to_bits() as u64) << 32) | (ct.get_scale_y().to_bits() as u64),
);
let c_lay_bits: u64 = (c_tag << 40)
| ((c_style.layout.get_display() as u64) << 32)
| ((c_style.layout.get_overflow() as u64) << 24)
| ((c_style.layout.get_z_index() as u32) as u64);
Self::fx_fold(&mut acc.2, c_lay_bits);
Self::fx_fold_paint(&mut acc.2, &c_style.paint);
let mut next_cull_check: Option<(Point, Rect, f32, f32)> = None;
if let Some((off_phys, cull_rect, scale, inv_scale)) = unclipped_cull {
let tx_phys: f32 = (ct.get_translate_x() * scale).round();
let ty_phys: f32 = (ct.get_translate_y() * scale).round();
let tot_x: f32 = off_phys.get_x() + tx_phys;
let tot_y: f32 = off_phys.get_y() + ty_phys;
let rx0: f32 = (raw_b.get_x() * scale).round();
let ry0: f32 = (raw_b.get_y() * scale).round();
let rx1: f32 = (raw_b.right() * scale).round();
let ry1: f32 = (raw_b.bottom() * scale).round();
let sw: f32 = ((rx1 - rx0).max(0.0) * ct.get_scale_x()).round().max(0.0);
let sh: f32 = ((ry1 - ry0).max(0.0) * ct.get_scale_y()).round().max(0.0);
let sdx: f32 = (((rx1 - rx0).max(0.0) - sw) * 0.5).round();
let sdy: f32 = (((ry1 - ry0).max(0.0) - sh) * 0.5).round();
let c_bounds: Rect = Rect::new(
(rx0 + tot_x + sdx) * inv_scale,
(ry0 + tot_y + sdy) * inv_scale,
sw * inv_scale,
sh * inv_scale,
);
let c_vis: Rect = Self::conservative_self_vis_rect(
child,
c_bounds,
&c_style.paint,
false,
(tot_x, tot_y),
scale,
inv_scale,
);
let c_in_x: bool =
c_vis.get_x() >= cull_rect.get_x() && c_vis.right() <= cull_rect.right();
let c_in_y: bool =
c_vis.get_y() >= cull_rect.get_y() && c_vis.bottom() <= cull_rect.bottom();
if !c_in_x || !c_in_y {
return false;
}
if c_style.layout.get_overflow() != Overflow::Hidden {
let c_scroll: Point = child.layout_box.get_scroll_offset();
let next_off: Point = Point::new(
tot_x - (c_scroll.get_x() * scale).round(),
tot_y - (c_scroll.get_y() * scale).round(),
);
next_cull_check = Some((next_off, cull_rect, scale, inv_scale));
}
}
if tree.has_children(cid)
&& !Self::fingerprint_subtree_children(
tree,
cid,
depth + 1,
next_cull_check,
focus_pair,
acc,
)
{
return false;
}
}
true
}
#[inline]
#[must_use]
fn fingerprint_subtree(
tree: &SceneTree,
node_id: NodeId,
node: &SceneNode,
unclipped_cull: Option<(Point, Rect, f32, f32)>,
focus_pair: (Option<NodeId>, bool),
) -> Option<(u64, u64)> {
let child_count: usize = tree.child_count(node_id);
if child_count == 0
|| child_count > PAINT_FRAGMENT_MAX_CHILDREN
|| tree.backdrop_blur_radius(node_id) > 0.0
{
return None;
}
let style: &Style = node.style_ref();
let transform: Transform2D = style.paint.get_transform();
let scroll: Point = node.layout_box.get_scroll_offset();
let mut geom_h: u64 = child_count as u64;
Self::fx_fold_rect(&mut geom_h, node.layout_box.get_bounds());
Self::fx_fold(
&mut geom_h,
((transform.get_translate_x().to_bits() as u64) << 32)
| (transform.get_translate_y().to_bits() as u64),
);
Self::fx_fold(
&mut geom_h,
((transform.get_scale_x().to_bits() as u64) << 32)
| (transform.get_scale_y().to_bits() as u64),
);
Self::fx_fold(
&mut geom_h,
((scroll.get_x().to_bits() as u64) << 32) | (scroll.get_y().to_bits() as u64),
);
let mut style_h: u64 =
((node_id.get_index() as u64) << 32) | (node_id.get_generation() as u64);
Self::fx_fold_paint(&mut style_h, &style.paint);
let mut acc: (usize, u64, u64) = (0, geom_h, style_h);
if !Self::fingerprint_subtree_children(
tree,
node_id,
1,
unclipped_cull,
focus_pair,
&mut acc,
) {
return None;
}
Some((acc.1, acc.2))
}
#[inline(always)]
#[must_use]
fn translate_coord(v: f32, d_phys: f32, scale: f32, inv_scale: f32, dyadic: bool) -> f32 {
if d_phys == 0.0 {
return v;
}
if dyadic {
return v + d_phys * inv_scale;
}
((v * scale).round() + d_phys) * inv_scale
}
#[inline(always)]
#[must_use]
fn translate_rect(
rect: Rect,
dx_phys: f32,
dy_phys: f32,
scale: f32,
inv_scale: f32,
dyadic: bool,
) -> Rect {
Rect::new(
Self::translate_coord(rect.get_x(), dx_phys, scale, inv_scale, dyadic),
Self::translate_coord(rect.get_y(), dy_phys, scale, inv_scale, dyadic),
rect.get_width(),
rect.get_height(),
)
}
#[inline]
fn push_translated_command(
cmd: &CachedDrawCommand,
text_slab: &[u8],
delta_phys: (f32, f32),
scale_info: (f32, f32, bool),
display_list: &mut DisplayList,
) {
let (dx_phys, dy_phys): (f32, f32) = delta_phys;
let (scale, inv_scale, dyadic): (f32, f32, bool) = scale_info;
let translated: DrawCommand = match cmd {
CachedDrawCommand::Clear(c) => DrawCommand::Clear(*c),
CachedDrawCommand::FillRoundedRect {
rect,
color,
radius,
border,
} => DrawCommand::FillRoundedRect {
rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
color: *color,
radius: *radius,
border: *border,
},
CachedDrawCommand::LinearGradientRect {
rect,
gradient,
radius,
} => DrawCommand::LinearGradientRect {
rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
gradient: *gradient,
radius: *radius,
},
CachedDrawCommand::BoxShadow {
rect,
radius,
shadow,
} => DrawCommand::BoxShadow {
rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
radius: *radius,
shadow: *shadow,
},
CachedDrawCommand::BackdropBlur {
rect,
radius,
blur_radius,
} => DrawCommand::BackdropBlur {
rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
radius: *radius,
blur_radius: *blur_radius,
},
CachedDrawCommand::TextRun {
rect,
text_start,
text_len,
style,
} => {
let s: usize = *text_start as usize;
let e: usize = s.saturating_add(*text_len as usize);
let src: &str = text_slab
.get(s..e)
.and_then(|b: &[u8]| from_utf8(b).ok())
.unwrap_or("");
DrawCommand::TextRun {
rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
text: display_list.alloc_text(src),
style: *style,
}
}
CachedDrawCommand::TextCaret {
text_rect,
content_rect,
text_start,
text_len,
style,
caret_height,
color,
multiline,
} => {
let s: usize = *text_start as usize;
let e: usize = s.saturating_add(*text_len as usize);
let src: &str = text_slab
.get(s..e)
.and_then(|b: &[u8]| from_utf8(b).ok())
.unwrap_or("");
DrawCommand::TextCaret {
text_rect: Self::translate_rect(
*text_rect, dx_phys, dy_phys, scale, inv_scale, dyadic,
),
content_rect: Self::translate_rect(
*content_rect,
dx_phys,
dy_phys,
scale,
inv_scale,
dyadic,
),
text: display_list.alloc_text(src),
style: *style,
caret_height: *caret_height,
color: *color,
multiline: *multiline,
}
}
CachedDrawCommand::Image {
rect,
buffer,
radius,
} => DrawCommand::Image {
rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
buffer: buffer.clone(),
radius: *radius,
},
CachedDrawCommand::SharedImage {
rect,
width,
height,
pixels,
radius,
} => DrawCommand::SharedImage {
rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
width: *width,
height: *height,
pixels: Arc::clone(pixels),
radius: *radius,
},
CachedDrawCommand::Line {
from,
to,
color,
width,
} => DrawCommand::Line {
from: Point::new(
Self::translate_coord(from.get_x(), dx_phys, scale, inv_scale, dyadic),
Self::translate_coord(from.get_y(), dy_phys, scale, inv_scale, dyadic),
),
to: Point::new(
Self::translate_coord(to.get_x(), dx_phys, scale, inv_scale, dyadic),
Self::translate_coord(to.get_y(), dy_phys, scale, inv_scale, dyadic),
),
color: *color,
width: *width,
},
CachedDrawCommand::Circle {
center,
radius,
color,
} => DrawCommand::Circle {
center: Point::new(
Self::translate_coord(center.get_x(), dx_phys, scale, inv_scale, dyadic),
Self::translate_coord(center.get_y(), dy_phys, scale, inv_scale, dyadic),
),
radius: *radius,
color: *color,
},
CachedDrawCommand::Triangle { p0, p1, p2, color } => DrawCommand::Triangle {
p0: Point::new(
Self::translate_coord(p0.get_x(), dx_phys, scale, inv_scale, dyadic),
Self::translate_coord(p0.get_y(), dy_phys, scale, inv_scale, dyadic),
),
p1: Point::new(
Self::translate_coord(p1.get_x(), dx_phys, scale, inv_scale, dyadic),
Self::translate_coord(p1.get_y(), dy_phys, scale, inv_scale, dyadic),
),
p2: Point::new(
Self::translate_coord(p2.get_x(), dx_phys, scale, inv_scale, dyadic),
Self::translate_coord(p2.get_y(), dy_phys, scale, inv_scale, dyadic),
),
color: *color,
},
CachedDrawCommand::SpriteRegion {
rect,
buffer,
src_rect,
tint,
} => DrawCommand::SpriteRegion {
rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
buffer: buffer.clone(),
src_rect: *src_rect,
tint: *tint,
},
CachedDrawCommand::PushClip(rect) => DrawCommand::PushClip(Self::translate_rect(
*rect, dx_phys, dy_phys, scale, inv_scale, dyadic,
)),
CachedDrawCommand::PushRoundedClip { rect, radius } => DrawCommand::PushRoundedClip {
rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
radius: *radius,
},
CachedDrawCommand::PopClip => DrawCommand::PopClip,
};
display_list.push(translated);
}
pub fn build(
tree: &SceneTree,
viewport: Size,
scale_factor: f32,
clear_color: Color,
display_list: &mut DisplayList,
) {
let mut saw_canvas: bool = false;
Self::build_inner(
tree,
viewport,
scale_factor,
clear_color,
display_list,
None,
&mut saw_canvas,
);
}
#[inline(always)]
#[must_use]
fn pack_opt_node_id(node: Option<NodeId>) -> u64 {
match node {
Some(id) => ((id.get_index() as u64) << 32) | (id.get_generation() as u64),
None => u64::MAX,
}
}
pub fn build_retained(
tree: &SceneTree,
viewport: Size,
scale_factor: f32,
clear_color: Color,
layout_changed: bool,
display_list: &mut DisplayList,
cache: &mut PaintFragmentCache,
) {
let clamped_scale: f32 = scale_factor.max(0.5);
let focus: FocusManager = tree.get_focus();
let sig: PaintSceneSignature = PaintSceneSignature {
tree_ptr: (tree as *const SceneTree) as usize,
tree_revision: tree.get_revision(),
viewport_w_bits: viewport.get_width().to_bits(),
viewport_h_bits: viewport.get_height().to_bits(),
scale_bits: clamped_scale.to_bits(),
clear_rgba: u32::from_le_bytes(clear_color.to_rgba_bytes()),
focused_packed: Self::pack_opt_node_id(focus.focused_node()),
hovered_packed: Self::pack_opt_node_id(focus.hovered_node()),
pressed_packed: Self::pack_opt_node_id(focus.pressed_node()),
caret_visible: tree.get_caret_visible(),
text_sel_sig: Self::text_selection_sig(tree),
};
if !layout_changed
&& !cache.last_has_canvas
&& !display_list.is_empty()
&& cache.has_last_scene
&& cache.last_scene_sig == sig
{
cache.whole_list_hits = cache.whole_list_hits.wrapping_add(1);
return;
}
cache.ensure_slots();
let mut saw_canvas: bool = false;
Self::build_inner(
tree,
viewport,
clamped_scale,
clear_color,
display_list,
Some(cache),
&mut saw_canvas,
);
cache.last_has_canvas = saw_canvas;
cache.has_last_scene = true;
cache.last_scene_sig = sig;
}
fn collect_portal_ancestors(tree: &SceneTree, out_ancestors: &mut Vec<NodeId>) {
out_ancestors.clear();
let portal_nodes: &[NodeId] = tree.portal_nodes();
if portal_nodes.is_empty() {
return;
}
for &pid in portal_nodes.iter() {
let mut cur: Option<NodeId> = tree.get_node(pid).and_then(SceneNode::parent_id);
while let Some(anc) = cur {
if out_ancestors.contains(&anc) {
break;
}
out_ancestors.push(anc);
cur = tree.get_node(anc).and_then(SceneNode::parent_id);
}
}
if out_ancestors.len() > 16 {
out_ancestors.sort_unstable_by_key(|id: &NodeId| {
((id.get_index() as u64) << 32) | (id.get_generation() as u64)
});
}
}
#[inline]
#[must_use]
fn is_portal_ancestor(ancestors: &[NodeId], node_id: NodeId) -> bool {
if ancestors.is_empty() {
return false;
}
if ancestors.len() <= 16 {
return ancestors.contains(&node_id);
}
let target: u64 = ((node_id.get_index() as u64) << 32) | (node_id.get_generation() as u64);
ancestors
.binary_search_by_key(&target, |id: &NodeId| {
((id.get_index() as u64) << 32) | (id.get_generation() as u64)
})
.is_ok()
}
#[inline]
#[must_use]
fn conservative_self_vis_rect(
node: &SceneNode,
bounds: Rect,
paint: &PaintStyle,
focused: bool,
total_off_phys: (f32, f32),
scale: f32,
inv_scale: f32,
) -> Rect {
let mut min_x: f32 = bounds.get_x() - 1.0;
let mut min_y: f32 = bounds.get_y() - 1.0;
let mut max_x: f32 = bounds.right() + 1.0;
let mut max_y: f32 = bounds.bottom() + 1.0;
if let Some(shadow) = paint.box_shadow()
&& shadow.get_color().get_a() > 0
{
let spread: f32 = shadow.get_spread_radius().max(0.0);
let blur_phys: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
let sigma_phys: f32 = (blur_phys * 0.5).max(0.75);
let blur_pad: f32 = (sigma_phys * 3.0).ceil() * inv_scale + 2.0 * inv_scale;
let pad: f32 = spread + blur_pad;
let sx0: f32 = bounds.get_x() + shadow.get_offset_x() - pad;
let sy0: f32 = bounds.get_y() + shadow.get_offset_y() - pad;
let sx1: f32 = bounds.right() + shadow.get_offset_x() + pad;
let sy1: f32 = bounds.bottom() + shadow.get_offset_y() + pad;
min_x = min_x.min(sx0);
min_y = min_y.min(sy0);
max_x = max_x.max(sx1);
max_y = max_y.max(sy1);
}
if focused && let Some(ring) = paint.focus_ring_border() {
let rw: f32 = ring.get_width().max(0.0) + 1.0;
min_x = min_x.min(bounds.get_x() - rw);
min_y = min_y.min(bounds.get_y() - rw);
max_x = max_x.max(bounds.right() + rw);
max_y = max_y.max(bounds.bottom() + rw);
}
if matches!(node.get_kind(), NodeKind::Text(_)) {
let content_b: Rect = node.layout_box.get_content_bounds();
let cx0: f32 = ((content_b.get_x() * scale).round() + total_off_phys.0) * inv_scale;
let cy0: f32 = ((content_b.get_y() * scale).round() + total_off_phys.1) * inv_scale;
let pad: f32 = node.style_ref().text.get_font_size() * 0.5 + 2.0;
min_x = min_x.min(cx0 - pad);
min_y = min_y.min(cy0 - pad);
max_x = max_x.max(cx0 + content_b.get_width() + pad);
max_y = max_y.max(cy0 + content_b.get_height() + pad);
}
Rect::new(
min_x,
min_y,
(max_x - min_x).max(0.0),
(max_y - min_y).max(0.0),
)
}
fn visit_culled_portal_child(
tree: &SceneTree,
child_id: NodeId,
parent_opacity: f32,
scratch: &mut PaintScratch<'_>,
) {
let Some(child) = tree.get_node(child_id) else {
return;
};
let style: &Style = child.style_ref();
let layout: &LayoutStyle = &style.layout;
if layout.get_display() == Display::None {
return;
}
let is_portal: bool = matches!(child.get_kind(), NodeKind::Portal)
|| layout.get_position() == Position::Fixed;
if is_portal {
if let Some(portal_queue) = scratch.portals.as_deref_mut() {
portal_queue.push((layout.get_z_index(), portal_queue.len(), child_id));
}
return;
}
if !Self::is_portal_ancestor(scratch.portal_ancestors, child_id) {
return;
}
let hovered: bool = child.get_interaction().get_hovered();
let paint_opacity: f32 = if hovered {
child
.hover_paint()
.map(|hp: PaintStyle| hp.get_opacity())
.unwrap_or_else(|| style.paint.get_opacity())
} else {
style.paint.get_opacity()
};
let next_opacity: f32 = (parent_opacity * paint_opacity).clamp(0.0, 1.0);
if next_opacity <= 0.0 {
return;
}
Self::collect_portals_in_culled_subtree(tree, child_id, next_opacity, scratch);
}
fn collect_portals_in_culled_subtree(
tree: &SceneTree,
node_id: NodeId,
parent_opacity: f32,
scratch: &mut PaintScratch<'_>,
) {
if tree.get_node(node_id).is_none() {
return;
}
let child_count: usize = tree.child_count(node_id);
if child_count == 0 {
return;
}
let needs_z_sort: bool = child_count > 1 && tree.has_nonzero_z_child(node_id);
if !needs_z_sort {
for child_id in tree.children_iter(node_id) {
Self::visit_culled_portal_child(tree, child_id, parent_opacity, scratch);
}
} else {
let sort_start: usize = scratch.z_sort.len();
for (idx, cid) in tree.children_iter(node_id).enumerate() {
if let Some(c) = tree.get_node(cid) {
scratch
.z_sort
.push((c.style_ref().layout.get_z_index(), idx, cid));
}
}
let sort_end: usize = scratch.z_sort.len();
scratch.z_sort[sort_start..sort_end].sort_by(
|a: &(i32, usize, NodeId), b: &(i32, usize, NodeId)| {
a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
},
);
for slot_idx in sort_start..sort_end {
let child_id: NodeId = scratch.z_sort[slot_idx].2;
Self::visit_culled_portal_child(tree, child_id, parent_opacity, scratch);
}
scratch.z_sort.truncate(sort_start);
}
}
fn build_inner(
tree: &SceneTree,
viewport: Size,
scale_factor: f32,
clear_color: Color,
display_list: &mut DisplayList,
mut fragments: Option<&mut PaintFragmentCache>,
saw_canvas: &mut bool,
) {
display_list.reset(viewport, scale_factor);
display_list.push(DrawCommand::Clear(clear_color));
let viewport_rect: Rect = Rect::new(0.0, 0.0, viewport.get_width(), viewport.get_height());
let active_hover_target: Option<NodeId> = Self::resolve_active_hover_target(tree);
let mut portals: Vec<(i32, usize, NodeId)> = take(&mut display_list.arena.portals_scratch);
let mut z_sort: Vec<(i32, usize, NodeId)> = take(&mut display_list.arena.z_sort_scratch);
let mut portal_ancestors: Vec<NodeId> =
take(&mut display_list.arena.portal_ancestors_scratch);
portals.clear();
z_sort.clear();
Self::collect_portal_ancestors(tree, &mut portal_ancestors);
{
let mut scratch: PaintScratch<'_> = PaintScratch {
portals: Some(&mut portals),
z_sort: &mut z_sort,
portal_ancestors: portal_ancestors.as_slice(),
fragments: fragments.as_deref_mut(),
saw_canvas,
};
Self::emit_node(
tree,
tree.get_root(),
(Point::new(0.0, 0.0), 1.0),
viewport_rect,
active_hover_target,
&mut scratch,
display_list,
);
}
display_list.finalize_base_layer(display_list.len());
if portals.len() > 1 {
portals.sort_by(|a: &(i32, usize, NodeId), b: &(i32, usize, NodeId)| {
a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
});
}
{
let mut portal_scratch: PaintScratch<'_> = PaintScratch {
portals: None,
z_sort: &mut z_sort,
portal_ancestors: &[],
fragments,
saw_canvas,
};
for &(_, _, portal_id) in portals.iter() {
Self::emit_node(
tree,
portal_id,
(Point::new(0.0, 0.0), 1.0),
viewport_rect,
active_hover_target,
&mut portal_scratch,
display_list,
);
}
}
portals.clear();
z_sort.clear();
portal_ancestors.clear();
display_list.arena.portals_scratch = portals;
display_list.arena.z_sort_scratch = z_sort;
display_list.arena.portal_ancestors_scratch = portal_ancestors;
}
#[must_use]
fn resolve_active_hover_target(tree: &SceneTree) -> Option<NodeId> {
let mut cursor: Option<NodeId> = tree.get_focus().hovered_node();
while let Some(id) = cursor {
let Some(node) = tree.get_node(id) else {
break;
};
let style: &Style = node.style_ref();
let paint: &PaintStyle = &style.paint;
let is_scrim: bool = matches!(node.get_kind(), NodeKind::Portal)
|| style.layout.get_position() == Position::Fixed;
let is_transparent_canvas: bool = matches!(node.get_kind(), NodeKind::Canvas(_))
&& paint.background_color().is_none();
if !is_scrim && !is_transparent_canvas {
let is_interactive: bool = paint.get_cursor() == CursorIcon::Pointer
|| node
.get_handlers()
.handler_for(&UiEventKind::Click(Point::default()))
.is_some();
if is_interactive {
return Some(id);
}
}
cursor = node.parent_id();
}
None
}
fn interactive_tint(base: Option<Color>, hovered: bool, pressed: bool) -> Option<Color> {
if !hovered && !pressed {
return base;
}
let delta: i32 = if pressed { 24 } else { 14 };
match base {
Some(c) if c.get_a() > 0 => {
let luma: u32 =
(c.get_r() as u32) * 299 + (c.get_g() as u32) * 587 + (c.get_b() as u32) * 114;
if luma < 120_000 {
let lift: i32 = if pressed { 30 } else { 20 };
Some(Color::new(
(c.get_r() as i32 + lift).clamp(0, 255) as u8,
(c.get_g() as i32 + lift).clamp(0, 255) as u8,
(c.get_b() as i32 + lift).clamp(0, 255) as u8,
c.get_a(),
))
} else {
Some(Color::new(
(c.get_r() as i32 - delta).clamp(0, 255) as u8,
(c.get_g() as i32 - delta).clamp(0, 255) as u8,
(c.get_b() as i32 - delta).clamp(0, 255) as u8,
c.get_a(),
))
}
}
_ => Some(Color::rgba(113, 113, 122, if pressed { 42 } else { 26 })),
}
}
fn emit_node(
tree: &SceneTree,
node_id: NodeId,
offset_and_opacity: (Point, f32),
cull_rect: Rect,
active_hover_target: Option<NodeId>,
scratch: &mut PaintScratch<'_>,
display_list: &mut DisplayList,
) {
let (offset_phys, parent_opacity): (Point, f32) = offset_and_opacity;
let Some(node) = tree.get_node(node_id) else {
return;
};
let style: &Style = node.style_ref();
let layout: &LayoutStyle = &style.layout;
if layout.get_display() == Display::None {
return;
}
if let Some(portal_queue) = scratch.portals.as_deref_mut()
&& (matches!(node.get_kind(), NodeKind::Portal)
|| layout.get_position() == Position::Fixed)
{
portal_queue.push((layout.get_z_index(), portal_queue.len(), node_id));
return;
}
let interaction: InteractionState = node.get_interaction();
let hovered: bool = interaction.get_hovered();
let pressed: bool = interaction.get_pressed();
if !hovered && (parent_opacity * style.paint.get_opacity()) <= 0.0 {
return;
}
let mut paint_owned: Option<PaintStyle> = if hovered { node.hover_paint() } else { None };
let prelim_paint: &PaintStyle = paint_owned.as_ref().unwrap_or(&style.paint);
let opacity: f32 = (parent_opacity * prelim_paint.get_opacity()).clamp(0.0, 1.0);
if opacity <= 0.0 {
return;
}
let scale: f32 = display_list.get_scale_factor().max(0.5);
let inv_scale: f32 = 1.0 / scale;
let raw_bounds: Rect = node.layout_box.get_bounds();
let transform: Transform2D = prelim_paint.get_transform();
let tx_phys: f32 = (transform.get_translate_x() * scale).round();
let ty_phys: f32 = (transform.get_translate_y() * scale).round();
let total_off_x: f32 = offset_phys.get_x() + tx_phys;
let total_off_y: f32 = offset_phys.get_y() + ty_phys;
let raw_x0: f32 = (raw_bounds.get_x() * scale).round();
let raw_y0: f32 = (raw_bounds.get_y() * scale).round();
let raw_x1: f32 = (raw_bounds.right() * scale).round();
let raw_y1: f32 = (raw_bounds.bottom() * scale).round();
let static_w_phys: f32 = (raw_x1 - raw_x0).max(0.0);
let static_h_phys: f32 = (raw_y1 - raw_y0).max(0.0);
let scaled_w_phys: f32 = (static_w_phys * transform.get_scale_x()).round().max(0.0);
let scaled_h_phys: f32 = (static_h_phys * transform.get_scale_y()).round().max(0.0);
let scale_dx_phys: f32 = ((static_w_phys - scaled_w_phys) * 0.5).round();
let scale_dy_phys: f32 = ((static_h_phys - scaled_h_phys) * 0.5).round();
let bounds: Rect = Rect::new(
(raw_x0 + total_off_x + scale_dx_phys) * inv_scale,
(raw_y0 + total_off_y + scale_dy_phys) * inv_scale,
scaled_w_phys * inv_scale,
scaled_h_phys * inv_scale,
);
let clipped: bool = matches!(layout.get_overflow(), Overflow::Hidden | Overflow::Scroll);
let clipped_cull: Option<Rect> = if clipped {
cull_rect.intersect(bounds)
} else {
Some(cull_rect)
};
let focused: bool = interaction.get_focused();
let self_vis_rect: Rect = Self::conservative_self_vis_rect(
node,
bounds,
prelim_paint,
focused,
(total_off_x, total_off_y),
scale,
inv_scale,
);
let self_visible: bool = bounds.get_width() > 0.0
&& bounds.get_height() > 0.0
&& self_vis_rect.intersect(cull_rect).is_some();
if clipped && clipped_cull.is_none() {
if self_visible {
if let Some(mut shadow) = prelim_paint.box_shadow() {
shadow.set_color(shadow.get_color().multiply_alpha(opacity));
display_list.push(DrawCommand::BoxShadow {
rect: bounds,
radius: prelim_paint.get_radius(),
shadow,
});
}
if focused && let Some(mut ring) = prelim_paint.focus_ring_border() {
ring.set_color(ring.get_color().multiply_alpha(opacity));
let ring_w: f32 = ring.get_width();
let ring_rect: Rect = Rect::new(
bounds.get_x() - ring_w,
bounds.get_y() - ring_w,
bounds.get_width() + ring_w * 2.0,
bounds.get_height() + ring_w * 2.0,
);
display_list.push(DrawCommand::FillRoundedRect {
rect: ring_rect,
color: COLOR_TRANSPARENT,
radius: CornerRadius::all(prelim_paint.get_radius().max_radius() + ring_w),
border: ring,
});
}
}
if scratch.portals.is_some()
&& Self::is_portal_ancestor(scratch.portal_ancestors, node_id)
{
Self::collect_portals_in_culled_subtree(tree, node_id, opacity, scratch);
}
return;
}
let child_count: usize = tree.child_count(node_id);
if !self_visible && child_count == 0 {
return;
}
let next_cull: Rect = clipped_cull.unwrap_or(cull_rect);
let hover_visual: bool = hovered && active_hover_target == Some(node_id);
if self_visible
&& (hover_visual || pressed)
&& paint_owned.is_none()
&& (hovered || node.hover_paint().is_none())
{
let base_paint: &PaintStyle = &style.paint;
let is_scrim: bool = matches!(node.get_kind(), NodeKind::Portal)
|| layout.get_position() == Position::Fixed;
let is_transparent_canvas: bool = matches!(node.get_kind(), NodeKind::Canvas(_))
&& base_paint.background_color().is_none();
if !is_scrim && !is_transparent_canvas {
let is_interactive: bool = base_paint.get_cursor() == CursorIcon::Pointer
|| node
.get_handlers()
.handler_for(&UiEventKind::Click(Point::default()))
.is_some();
if is_interactive {
let mut tinted: PaintStyle = *base_paint;
tinted.set_background(Self::interactive_tint(
tinted.background_color(),
hover_visual,
pressed,
));
paint_owned = Some(tinted);
}
}
}
let paint: &PaintStyle = paint_owned.as_ref().unwrap_or(&style.paint);
let phys_scale_milli: u32 = Self::quantize_scale_milli(scale);
let mut frag_capture: Option<(usize, usize, u64, u64)> = None;
let frag_overflow_ok: bool = layout.get_overflow() == Overflow::Hidden
|| (layout.get_overflow() == Overflow::Visible
&& node_id != tree.get_root()
&& child_count >= 2);
if self_visible
&& scratch.fragments.is_some()
&& scratch.portals.is_some()
&& matches!(node.get_kind(), NodeKind::View)
&& frag_overflow_ok
&& !hovered
&& !pressed
&& !interaction.get_focused()
&& active_hover_target != Some(node_id)
{
let vis_x_in: bool = self_vis_rect.get_x() >= cull_rect.get_x()
&& self_vis_rect.right() <= cull_rect.right();
let vis_y_in: bool = self_vis_rect.get_y() >= cull_rect.get_y()
&& self_vis_rect.bottom() <= cull_rect.bottom();
if vis_x_in && vis_y_in {
let has_text_sel: bool = !tree.text_selection_spans_ref().is_empty();
let unclipped_cull: Option<(Point, Rect, f32, f32)> =
if layout.get_overflow() == Overflow::Hidden {
None
} else {
let raw_node_scroll: Point = node.layout_box.get_scroll_offset();
let child_off: Point = Point::new(
total_off_x - (raw_node_scroll.get_x() * scale).round(),
total_off_y - (raw_node_scroll.get_y() * scale).round(),
);
Some((child_off, cull_rect, scale, inv_scale))
};
if let Some((geom_hash, style_text_hash)) = Self::fingerprint_subtree(
tree,
node_id,
node,
unclipped_cull,
(active_hover_target, has_text_sel),
) {
let slot_idx: usize =
(node_id.get_index() as usize) & (PAINT_FRAGMENT_CACHE_SLOTS - 1);
let opacity_bits: u32 = parent_opacity.to_bits();
let dyadic_12: bool = scale == 1.0 || scale == 2.0;
let dyadic_scale: bool = dyadic_12 || scale == 4.0;
if let Some(cache) = scratch.fragments.as_deref_mut()
&& let Some(&cached) = cache.slots.get(slot_idx)
&& cached.occupied
&& cached.node_id == node_id
&& cached.phys_scale_milli == phys_scale_milli
&& cached.opacity_bits == opacity_bits
&& cached.geom_hash == geom_hash
&& cached.style_text_hash == style_text_hash
{
let dx_phys: f32 = offset_phys.get_x() - cached.offset_phys.get_x();
let dy_phys: f32 = offset_phys.get_y() - cached.offset_phys.get_y();
let c_start: usize = cached.cmd_start as usize;
let c_end: usize = c_start.saturating_add(cached.cmd_len as usize);
if let Some(cmds) = cache.cmd_slab.get(c_start..c_end) {
display_list.get_mut_commands().reserve(cmds.len());
let text_slab: &[u8] = cache.text_slab.as_slice();
for cmd in cmds.iter() {
Self::push_translated_command(
cmd,
text_slab,
(dx_phys, dy_phys),
(scale, inv_scale, dyadic_scale),
display_list,
);
}
cache.fragment_hits = cache.fragment_hits.wrapping_add(1);
return;
}
}
frag_capture = Some((display_list.len(), slot_idx, geom_hash, style_text_hash));
}
}
}
if self_visible {
let blur_r: f32 = tree.backdrop_blur_radius(node_id);
if blur_r > 0.0 {
display_list.push(DrawCommand::BackdropBlur {
rect: bounds,
radius: paint.get_radius(),
blur_radius: blur_r,
});
}
if let Some(mut shadow) = paint.box_shadow() {
shadow.set_color(shadow.get_color().multiply_alpha(opacity));
display_list.push(DrawCommand::BoxShadow {
rect: bounds,
radius: paint.get_radius(),
shadow,
});
}
if let Some(mut gradient) = paint.background_gradient() {
gradient.set_start_color(gradient.get_start_color().multiply_alpha(opacity));
gradient.set_end_color(gradient.get_end_color().multiply_alpha(opacity));
display_list.push(DrawCommand::LinearGradientRect {
rect: bounds,
gradient,
radius: paint.get_radius(),
});
} else if let Some(bg) = paint.background_color() {
let mut border: Border = paint.get_border();
border.set_color(border.get_color().multiply_alpha(opacity));
display_list.push(DrawCommand::FillRoundedRect {
rect: bounds,
color: bg.multiply_alpha(opacity),
radius: paint.get_radius(),
border,
});
} else if paint.get_border().get_width() > 0.0 {
let mut border: Border = paint.get_border();
border.set_color(border.get_color().multiply_alpha(opacity));
display_list.push(DrawCommand::FillRoundedRect {
rect: bounds,
color: COLOR_TRANSPARENT,
radius: paint.get_radius(),
border,
});
}
if interaction.get_focused()
&& let Some(mut ring) = paint.focus_ring_border()
{
ring.set_color(ring.get_color().multiply_alpha(opacity));
let ring_w: f32 = ring.get_width();
let ring_rect: Rect = Rect::new(
bounds.get_x() - ring_w,
bounds.get_y() - ring_w,
bounds.get_width() + ring_w * 2.0,
bounds.get_height() + ring_w * 2.0,
);
display_list.push(DrawCommand::FillRoundedRect {
rect: ring_rect,
color: COLOR_TRANSPARENT,
radius: CornerRadius::all(paint.get_radius().max_radius() + ring_w),
border: ring,
});
}
match node.get_kind() {
NodeKind::Text(text) => {
let mut text_style: TextStyle = style.text;
text_style.set_color(text_style.get_color().multiply_alpha(opacity));
let content_b: Rect = node.layout_box.get_content_bounds();
let cx0: f32 = (content_b.get_x() * scale).round();
let cy0: f32 = (content_b.get_y() * scale).round();
let shifted_content: Rect = Rect::new(
(cx0 + total_off_x) * inv_scale,
(cy0 + total_off_y) * inv_scale,
content_b.get_width(),
content_b.get_height(),
);
let has_box_chrome: bool = style
.paint
.background_color()
.is_some_and(|c: Color| c.get_a() > 0)
|| style.paint.background_gradient().is_some()
|| style.paint.get_border().get_width() > 0.0
|| style.layout.get_height() != Length::Auto
|| style.layout.get_min_height() != Length::Auto;
let text_run_rect: Rect = if has_box_chrome
&& shifted_content.get_height() > 1.0
{
let cached_h: f32 = node.layout_box.get_content_size().get_height();
let measured_h: f32 =
if cached_h > 0.0 && cached_h + 0.5 < shifted_content.get_height() {
cached_h
} else {
DeterministicTextMeasurer
.measure_size(
text.as_str(),
text_style,
Some(shifted_content.get_width().max(1.0)),
)
.get_height()
};
if measured_h > 0.0 && shifted_content.get_height() > measured_h + 0.5 {
let v_off_phys: f32 =
(((shifted_content.get_height() - measured_h) * 0.5).max(0.0)
* scale)
.round();
Rect::new(
shifted_content.get_x(),
(cy0 + total_off_y + v_off_phys) * inv_scale,
shifted_content.get_width(),
measured_h,
)
} else {
shifted_content
}
} else {
shifted_content
};
if let Some(sel_range) = tree.text_selection_range_for(node_id) {
let sel_color: Color = tree
.effective_selection_color(node_id)
.multiply_alpha(opacity);
let sel_rects: Vec<Rect> = compute_text_selection_rects(
text.as_str(),
text_style,
text_run_rect,
sel_range,
);
let sel_single_to_end: bool = sel_rects.len() == 1
&& text_style.get_align() == TextAlign::Left
&& sel_range.1 >= text.chars().count();
let exact_span_right: f32 =
((content_b.right() * scale).round() + total_off_x) * inv_scale;
for sel_rect in sel_rects.into_iter() {
let sx0: f32 = (sel_rect.get_x() * scale).round() * inv_scale;
let sy0: f32 = (sel_rect.get_y() * scale).round() * inv_scale;
let sx1: f32 = if sel_single_to_end {
exact_span_right.max(sx0 + inv_scale)
} else {
(sel_rect.right() * scale).round() * inv_scale
};
let sy1: f32 = (sel_rect.bottom() * scale).round() * inv_scale;
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(
sx0,
sy0,
(sx1 - sx0).max(inv_scale),
(sy1 - sy0).max(inv_scale),
),
color: sel_color,
radius: CornerRadius::default(),
border: Border::default(),
});
}
}
let pooled_text: String = display_list.alloc_text(text.as_str());
display_list.push(DrawCommand::TextRun {
rect: text_run_rect,
text: pooled_text,
style: text_style,
});
}
NodeKind::Input(input_state) => {
let mut text_style: TextStyle = style.text;
let is_empty_value: bool = input_state.get_value().is_empty();
let is_focused: bool = interaction.get_focused();
let rendered_text: String = if is_empty_value {
text_style.set_color(text_style.get_color().multiply_alpha(opacity * 0.55));
display_list.alloc_text(input_state.get_placeholder().as_str())
} else if input_state.get_password() {
text_style.set_color(text_style.get_color().multiply_alpha(opacity));
let star_count: usize = input_state.get_value().chars().count();
let mut masked: String = display_list.alloc_text("");
for _ in 0..star_count {
masked.push('*');
}
masked
} else {
text_style.set_color(text_style.get_color().multiply_alpha(opacity));
display_list.alloc_text(input_state.get_value().as_str())
};
let content_b: Rect = node.layout_box.get_content_bounds();
let cx0: f32 = (content_b.get_x() * scale).round();
let cy0: f32 = (content_b.get_y() * scale).round();
let shifted_content: Rect = Rect::new(
(cx0 + total_off_x) * inv_scale,
(cy0 + total_off_y) * inv_scale,
content_b.get_width(),
content_b.get_height(),
);
let line_h: f32 =
(text_style.get_font_size() * text_style.get_line_height()).max(1.0);
let text_rect: Rect = if input_state.get_multiline() {
shifted_content
} else {
text_style.set_overflow(TextOverflow::Clip);
let v_off_phys: f32 =
(((shifted_content.get_height() - line_h) * 0.5).max(0.0) * scale)
.round();
let text_y: f32 = (cy0 + total_off_y + v_off_phys) * inv_scale;
Rect::new(
shifted_content.get_x(),
text_y,
shifted_content.get_width(),
line_h,
)
};
let run_rect: Rect =
if is_empty_value && is_focused && !rendered_text.is_empty() {
let clearance_phys: f32 =
(PLACEHOLDER_FOCUSED_CARET_CLEARANCE_PX * scale).round();
let clearance_logical: f32 = clearance_phys * inv_scale;
Rect::new(
text_rect.get_x() + clearance_logical,
text_rect.get_y(),
(text_rect.get_width() - clearance_logical).max(0.0),
text_rect.get_height(),
)
} else {
text_rect
};
let show_caret: bool = is_focused && tree.get_caret_visible();
let caret_text: String = if show_caret && !is_empty_value {
let caret_prefix: &str =
input_state.caret_prefix_for_display(rendered_text.as_str());
display_list.alloc_text(caret_prefix)
} else {
String::new()
};
display_list.push(DrawCommand::PushClip(shifted_content));
if is_focused
&& !is_empty_value
&& let Some(sel_range) = input_state.selection_char_range()
{
let sel_color: Color = tree
.effective_selection_color(node_id)
.multiply_alpha(opacity);
let sel_rects: Vec<Rect> = compute_text_selection_rects(
rendered_text.as_str(),
text_style,
text_rect,
sel_range,
);
for sel_rect in sel_rects.into_iter() {
let sx0: f32 = (sel_rect.get_x() * scale).round() * inv_scale;
let sy0: f32 = (sel_rect.get_y() * scale).round() * inv_scale;
let sx1: f32 = (sel_rect.right() * scale).round() * inv_scale;
let sy1: f32 = (sel_rect.bottom() * scale).round() * inv_scale;
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(
sx0,
sy0,
(sx1 - sx0).max(inv_scale),
(sy1 - sy0).max(inv_scale),
),
color: sel_color,
radius: CornerRadius::default(),
border: Border::default(),
});
}
}
display_list.push(DrawCommand::TextRun {
rect: run_rect,
text: rendered_text,
style: text_style,
});
if show_caret {
let caret_h: f32 = (text_style.get_font_size() * 1.15)
.min(shifted_content.get_height().max(12.0));
display_list.push(DrawCommand::TextCaret {
text_rect,
content_rect: shifted_content,
text: caret_text,
style: text_style,
caret_height: caret_h,
color: style.text.get_color().multiply_alpha(opacity),
multiline: input_state.get_multiline(),
});
}
display_list.push(DrawCommand::PopClip);
}
NodeKind::Image(buffer) => {
display_list.push(DrawCommand::Image {
rect: bounds,
buffer: buffer.clone(),
radius: paint.get_radius(),
});
}
NodeKind::Canvas(caching) => {
if let Some(callback) = node.canvas_callback()
&& let Ok(mut func) = callback.try_borrow_mut()
{
let canvas_bw: f32 = paint.get_border().get_width();
let canvas_clip_rect: Rect = if canvas_bw > 0.0 {
Rect::new(
bounds.get_x() + canvas_bw,
bounds.get_y() + canvas_bw,
(bounds.get_width() - canvas_bw * 2.0).max(0.0),
(bounds.get_height() - canvas_bw * 2.0).max(0.0),
)
} else {
bounds
};
let canvas_max_r: f32 = (bounds.get_width() * 0.5)
.min(bounds.get_height() * 0.5)
.max(0.0);
let canvas_raw_r: CornerRadius = paint.get_radius();
let canvas_inner_r: CornerRadius = CornerRadius::new(
(canvas_raw_r.get_top_left().min(canvas_max_r) - canvas_bw).max(0.0),
(canvas_raw_r.get_top_right().min(canvas_max_r) - canvas_bw).max(0.0),
(canvas_raw_r.get_bottom_right().min(canvas_max_r) - canvas_bw)
.max(0.0),
(canvas_raw_r.get_bottom_left().min(canvas_max_r) - canvas_bw).max(0.0),
);
if canvas_inner_r.max_radius() > 0.25 {
display_list.push(DrawCommand::PushRoundedClip {
rect: canvas_clip_rect,
radius: canvas_inner_r,
});
} else {
display_list.push(DrawCommand::PushClip(canvas_clip_rect));
}
let canvas_cmd_start: usize = display_list.len();
func(bounds, display_list);
let canvas_cmd_end: usize = display_list.len();
if opacity < 0.999 {
display_list.attenuate_range_opacity(
canvas_cmd_start,
canvas_cmd_end,
opacity,
);
}
if *caching != CanvasCaching::RetainedStatic {
let canvas_is_dynamic: bool =
if let Some(cache) = scratch.fragments.as_deref_mut() {
let emitted: &[DrawCommand] = &display_list.get_commands()
[canvas_cmd_start..canvas_cmd_end];
cache.record_canvas_output(
node_id,
phys_scale_milli,
bounds,
tree.get_revision(),
emitted,
)
} else {
true
};
if canvas_is_dynamic {
*scratch.saw_canvas = true;
}
}
display_list.push(DrawCommand::PopClip);
} else if *caching == CanvasCaching::DynamicPerFrame {
*scratch.saw_canvas = true;
}
}
NodeKind::View | NodeKind::ScrollView | NodeKind::Portal | NodeKind::Fragment => {}
}
}
let vp: Size = display_list.get_viewport();
let show_scrollbar: bool = vp.get_width().min(vp.get_height()) >= 540.0;
let wants_scrollbar: bool = show_scrollbar
&& layout.get_overflow() == Overflow::Scroll
&& bounds.get_height() > 24.0;
let emit_clip: bool = clipped && (child_count > 0 || wants_scrollbar);
let clip_push_idx: usize = display_list.len();
let clip_saved_digest: (u64, u64) = display_list.snapshot_digest_state();
if emit_clip {
let bw: f32 = paint.get_border().get_width();
let clip_rect: Rect = if bw > 0.0 {
Rect::new(
bounds.get_x() + bw,
bounds.get_y() + bw,
(bounds.get_width() - bw * 2.0).max(0.0),
(bounds.get_height() - bw * 2.0).max(0.0),
)
} else {
bounds
};
let max_r: f32 = (bounds.get_width() * 0.5)
.min(bounds.get_height() * 0.5)
.max(0.0);
let raw_r: CornerRadius = paint.get_radius();
let inner_r: CornerRadius = CornerRadius::new(
(raw_r.get_top_left().min(max_r) - bw).max(0.0),
(raw_r.get_top_right().min(max_r) - bw).max(0.0),
(raw_r.get_bottom_right().min(max_r) - bw).max(0.0),
(raw_r.get_bottom_left().min(max_r) - bw).max(0.0),
);
if inner_r.max_radius() > 0.25 {
display_list.push(DrawCommand::PushRoundedClip {
rect: clip_rect,
radius: inner_r,
});
} else {
display_list.push(DrawCommand::PushClip(clip_rect));
}
}
if child_count > 0 {
let raw_node_scroll: Point = node.layout_box.get_scroll_offset();
let scroll_x_phys: f32 = (raw_node_scroll.get_x() * scale).round();
let scroll_y_phys: f32 = (raw_node_scroll.get_y() * scale).round();
let child_offset_phys: Point =
Point::new(total_off_x - scroll_x_phys, total_off_y - scroll_y_phys);
let needs_z_sort: bool = child_count > 1 && tree.has_nonzero_z_child(node_id);
if !needs_z_sort {
for child_id in tree.children_iter(node_id) {
Self::emit_node(
tree,
child_id,
(child_offset_phys, opacity),
next_cull,
active_hover_target,
scratch,
display_list,
);
}
} else {
let sort_start: usize = scratch.z_sort.len();
for (idx, cid) in tree.children_iter(node_id).enumerate() {
if let Some(c) = tree.get_node(cid) {
scratch
.z_sort
.push((c.style_ref().layout.get_z_index(), idx, cid));
}
}
let sort_end: usize = scratch.z_sort.len();
scratch.z_sort[sort_start..sort_end].sort_by(
|a: &(i32, usize, NodeId), b: &(i32, usize, NodeId)| {
a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
},
);
for slot_idx in sort_start..sort_end {
let child_id: NodeId = scratch.z_sort[slot_idx].2;
Self::emit_node(
tree,
child_id,
(child_offset_phys, opacity),
next_cull,
active_hover_target,
scratch,
display_list,
);
}
scratch.z_sort.truncate(sort_start);
}
}
if wants_scrollbar {
let lbox: &LayoutBox = &node.layout_box;
let border_w: f32 = paint.get_border().get_width();
let inner_x: f32 = bounds.get_x() + border_w;
let inner_y: f32 = bounds.get_y() + border_w;
let inner_w: f32 = (bounds.get_width() - border_w * 2.0).max(1.0);
let inner_h: f32 = (bounds.get_height() - border_w * 2.0).max(1.0);
let view_w: f32 = lbox.get_content_bounds().get_width().max(1.0);
let view_h: f32 = lbox.get_content_bounds().get_height().max(1.0);
let (scroll_y, total_h): (f32, f32) = match node.virtual_scroll_metrics() {
Some((vy, vh)) => (vy, vh),
None => (
lbox.get_scroll_offset().get_y(),
lbox.get_content_size().get_height(),
),
};
let scroll_x: f32 = lbox.get_scroll_offset().get_x();
let total_w: f32 = lbox.get_content_size().get_width();
let max_scroll_y: f32 = (total_h - view_h).max(0.0);
let max_scroll_x: f32 = (total_w - view_w).max(0.0);
let has_v_bar: bool = max_scroll_y > 1.0;
let has_h_bar: bool = max_scroll_x > 1.0 && bounds.get_width() > 24.0;
let corner_inset: f32 = if has_v_bar && has_h_bar { 6.0 } else { 0.0 };
if has_v_bar {
let track_margin: f32 = 3.0;
let edge_inset: f32 = 1.0;
let thumb_w: f32 = if hovered || pressed { 4.5 } else { 3.0 };
let track_x: f32 = (inner_x + inner_w - thumb_w - edge_inset).max(inner_x);
let track_y: f32 = inner_y + track_margin;
let track_h: f32 = (inner_h - track_margin * 2.0 - corner_inset).max(16.0);
let ratio: f32 = (view_h / total_h.max(view_h)).clamp(0.0, 1.0);
let min_thumb_h: f32 = 20.0_f32.min(track_h);
let thumb_h: f32 = (track_h * ratio).clamp(min_thumb_h, track_h);
let scroll_frac: f32 = (scroll_y / max_scroll_y).clamp(0.0, 1.0);
let thumb_y: f32 = track_y + (track_h - thumb_h) * scroll_frac;
let thumb_x_snapped: f32 = (track_x * scale).round() * inv_scale;
let thumb_w_snapped: f32 = (thumb_w * scale).round().max(1.0) * inv_scale;
let thumb_y_snapped: f32 = (thumb_y * scale).round() * inv_scale;
let thumb_h_snapped: f32 = (thumb_h * scale).round().max(1.0) * inv_scale;
let thumb_alpha: u8 = if pressed {
188
} else if hovered {
148
} else {
88
};
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(
thumb_x_snapped,
thumb_y_snapped,
thumb_w_snapped,
thumb_h_snapped,
),
color: Color::rgba(113, 113, 122, thumb_alpha).multiply_alpha(opacity),
radius: CornerRadius::all(thumb_w * 0.5),
border: Border::default(),
});
}
if has_h_bar {
let track_margin: f32 = 3.0;
let edge_inset: f32 = 1.0;
let thumb_h: f32 = if hovered || pressed { 4.5 } else { 3.0 };
let track_y: f32 = (inner_y + inner_h - thumb_h - edge_inset).max(inner_y);
let track_x: f32 = inner_x + track_margin;
let track_w: f32 = (inner_w - track_margin * 2.0 - corner_inset).max(16.0);
let ratio: f32 = (view_w / total_w.max(view_w)).clamp(0.0, 1.0);
let min_thumb_w: f32 = 20.0_f32.min(track_w);
let thumb_w: f32 = (track_w * ratio).clamp(min_thumb_w, track_w);
let scroll_frac: f32 = (scroll_x / max_scroll_x).clamp(0.0, 1.0);
let thumb_x: f32 = track_x + (track_w - thumb_w) * scroll_frac;
let thumb_x_snapped: f32 = (thumb_x * scale).round() * inv_scale;
let thumb_y_snapped: f32 = (track_y * scale).round() * inv_scale;
let thumb_w_snapped: f32 = (thumb_w * scale).round().max(1.0) * inv_scale;
let thumb_h_snapped: f32 = (thumb_h * scale).round().max(1.0) * inv_scale;
let thumb_alpha: u8 = if pressed {
188
} else if hovered {
148
} else {
88
};
display_list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(
thumb_x_snapped,
thumb_y_snapped,
thumb_w_snapped,
thumb_h_snapped,
),
color: Color::rgba(113, 113, 122, thumb_alpha).multiply_alpha(opacity),
radius: CornerRadius::all(thumb_h * 0.5),
border: Border::default(),
});
}
}
if emit_clip {
if display_list.len() == clip_push_idx + 1 {
display_list.pop_empty_clip(clip_saved_digest);
} else {
display_list.push(DrawCommand::PopClip);
}
}
if let Some((cmd_start, slot_idx, geom_hash, style_text_hash)) = frag_capture
&& let Some(cache) = scratch.fragments.as_deref_mut()
{
let cmd_slice: &[DrawCommand] = &display_list.get_commands()[cmd_start..];
cache.capture_fragment(
slot_idx,
(
node_id,
phys_scale_milli,
parent_opacity.to_bits(),
offset_phys,
geom_hash,
style_text_hash,
),
cmd_slice,
);
}
}
}