use std::{
hash::{Hash, Hasher},
ops::Range,
sync::Arc,
};
use cranpose_core::{NodeId, collections::growth_slack::GrowthSlack};
pub use cranpose_render_common::graph_scene::{HitRegion, Scene};
use cranpose_render_common::{
glyph_reach::{InkSpread, glyph_part},
graph::DrawCommandId,
layer_paint::LayerPaint,
layer_shadow::ShadowRRect,
scene_store::ShapeRef,
text_paint::TextPaint,
text_raster::TextRasterRequest,
};
use cranpose_ui::{TextStyle, text::RenderString};
use cranpose_ui_graphics::{
BlendMode, Color, ColorFilter, CommandRecording, DrawPrimitive, GraphicsLayer, ImageBitmap,
ImageSampling, Point, Recorded, Rect, RenderEffect, RenderHash, ShapeRecorder,
};
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct SnapAnchor {
pub origin: Point,
pub device_pixel_step: f32,
}
impl SnapAnchor {
pub(crate) fn rigid(origin: Point) -> Self {
Self {
origin,
device_pixel_step: 1.0,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct ClipRounding {
pub rect: Rect,
pub radius: f32,
}
const CLIP_HOLD_SLACK: f32 = 1e-3;
pub(crate) fn clip_holds(outer: Rect, inner: Rect) -> bool {
inner.x >= outer.x - CLIP_HOLD_SLACK
&& inner.y >= outer.y - CLIP_HOLD_SLACK
&& inner.x + inner.width <= outer.x + outer.width + CLIP_HOLD_SLACK
&& inner.y + inner.height <= outer.y + outer.height + CLIP_HOLD_SLACK
}
pub(crate) const PLACEMENT_CANONICALIZE: u32 = 1;
pub(crate) const PLACEMENT_CLIPPED: u32 = 2;
pub(crate) const PLACEMENT_FILTERED: u32 = 4;
pub(crate) const PLACEMENT_PAINTED: u32 = 8;
pub(crate) const PLACEMENT_TURNED: u32 = 16;
const PLACEMENT_ROUNDING_CUT: u32 = 32;
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Placement {
pub offset: Point,
pub snap_anchor: Option<SnapAnchor>,
pub clip: Option<Rect>,
pub rounding: Option<ClipRounding>,
pub alpha: f32,
pub color_filter: Option<Arc<ColorFilter>>,
}
impl Placement {
pub(crate) fn paints(&self) -> bool {
self.alpha != 1.0 || self.color_filter.is_some()
}
pub(crate) fn at(offset: Point, snap_anchor: Option<SnapAnchor>, clip: Option<Rect>) -> Self {
Self {
offset,
snap_anchor,
clip,
rounding: None,
alpha: 1.0,
color_filter: None,
}
}
pub(crate) fn with_rounding(self, rounding: Option<ClipRounding>) -> Self {
Self { rounding, ..self }
}
pub(crate) fn clip_rounded(&self) -> bool {
self.clip.is_some() && self.rounding.is_some()
}
pub(crate) fn rounding_cut(&self) -> bool {
self.rounding.is_some_and(|rounding| {
self.clip
.is_none_or(|clip| !clip_holds(clip, rounding.rect))
})
}
pub(crate) fn device_clip(&self, root_scale: f32) -> Option<[f32; 4]> {
self.clip.map(|clip| self.device_rect(clip, root_scale))
}
pub(crate) fn tested_device_clip(&self, root_scale: f32) -> Option<[f32; 4]> {
let rounding = self.rounding.filter(|_| self.clip_rounded());
rounding
.map(|rounding| rounding.rect)
.or(self.clip)
.map(|clip| self.device_rect(clip, root_scale))
}
pub(crate) fn device_rect(&self, rect: Rect, root_scale: f32) -> [f32; 4] {
let device = crate::geometry::device_rect(rect, root_scale, self.snap_anchor.is_some());
[device.x, device.y, device.width, device.height]
}
pub(crate) fn data_flags(&self) -> u32 {
let mut flags = 0;
if self.snap_anchor.is_some() {
flags |= PLACEMENT_CANONICALIZE;
}
if self.paints() {
flags |= PLACEMENT_PAINTED;
}
if self.clip_rounded() && self.rounding_cut() {
flags |= PLACEMENT_ROUNDING_CUT;
}
flags
}
pub(crate) fn painted(
offset: Point,
snap_anchor: Option<SnapAnchor>,
clip: Option<Rect>,
layer: &GraphicsLayer,
) -> Self {
Self {
offset,
snap_anchor,
clip,
rounding: None,
alpha: layer.alpha.clamp(0.0, 1.0),
color_filter: layer
.color_filter
.as_ref()
.map(|filter| Arc::new(filter.clone())),
}
}
pub(crate) fn translated_bounds(&self, local: Rect) -> Rect {
local.translate(self.offset.x, self.offset.y)
}
}
#[derive(Clone)]
pub(crate) struct RunDraw {
pub recorder: Arc<ShapeRecorder>,
pub print: Option<u64>,
pub command: Option<DrawCommandId>,
pub segments: Range<u32>,
pub records: u32,
pub placement: Placement,
pub bounds: Rect,
}
impl RunDraw {
pub(crate) fn of(
recording: &CommandRecording,
command: Option<DrawCommandId>,
segments: Range<u32>,
placement: Placement,
) -> Self {
let records = recording.shape_count_in(&segments);
Self::with_bounds_and_records(
Arc::clone(recording.shape_recorder()),
command,
segments,
records,
recording.shape_bounds(),
placement,
)
}
pub(crate) fn of_shapes(shape: ShapeRef<'_>, placement: Placement) -> Self {
Self {
print: Some(shape.print()),
..Self::with_bounds_and_records(
Arc::clone(shape.recorder()),
None,
shape.segments(),
shape.shape_count(),
shape.coverage(),
placement,
)
}
}
fn with_bounds_and_records(
recorder: Arc<ShapeRecorder>,
command: Option<DrawCommandId>,
segments: Range<u32>,
records: u32,
shape_bounds: Option<Rect>,
placement: Placement,
) -> Self {
let bounds = shape_bounds.map_or(
Rect {
x: placement.offset.x,
y: placement.offset.y,
width: 0.0,
height: 0.0,
},
|bounds| placement.translated_bounds(bounds),
);
Self {
recorder,
print: None,
command,
segments,
records,
placement,
bounds,
}
}
pub(crate) fn whole(recorder: Arc<ShapeRecorder>, placement: Placement) -> Option<Self> {
(!recorder.is_empty()).then(|| {
let segments = recorder.all_segments();
let records = recorder.tables().shapes.len() as u32;
let bounds = recorder.bounds();
Self::with_bounds_and_records(recorder, None, segments, records, bounds, placement)
})
}
pub(crate) fn tables(&self) -> &cranpose_ui_graphics::RecordTables {
self.recorder.tables()
}
pub(crate) fn segment_records(
&self,
) -> impl Iterator<Item = &cranpose_ui_graphics::RecordSegment> {
self.tables().segments[self.segments.start as usize..self.segments.end as usize]
.iter()
.filter(|segment| segment.lane == cranpose_ui_graphics::RecordLane::Shapes)
}
pub(crate) fn record_count(&self) -> u32 {
self.records
}
pub(crate) fn holds_only_rects(&self) -> bool {
const RECTS: u8 = (1 << cranpose_ui_graphics::FRAGMENT_KIND_FILL)
| (1 << cranpose_ui_graphics::FRAGMENT_KIND_STROKE);
self.segment_records()
.all(|segment| segment.kinds & !RECTS == 0)
}
}
struct LooseRun {
recorder: ShapeRecorder,
placement: Placement,
}
#[derive(Clone)]
pub(crate) struct DrawnText {
string: Arc<RenderString>,
hash: u64,
empty: bool,
gradient: bool,
static_motion: bool,
spread: InkSpread,
}
impl DrawnText {
pub(crate) fn of_laid_out(
string: Arc<RenderString>,
style: &TextStyle,
layout: &cranpose_text::TextLayout,
) -> Self {
let spread = InkSpread::of_text(style, string.span_styles(), layout);
Self::of(string, style, spread)
}
pub(crate) fn of(string: Arc<RenderString>, style: &TextStyle, spread: InkSpread) -> Self {
let paints_gradient = |span: &cranpose_ui::text::SpanStyle| {
span.brush
.as_ref()
.is_some_and(|brush| !matches!(brush, cranpose_ui_graphics::Brush::Solid(_)))
};
let gradient = paints_gradient(&style.span_style)
|| string
.span_styles()
.iter()
.any(|span| paints_gradient(&span.item));
Self {
hash: string.render_hash(),
empty: string.is_empty(),
gradient,
static_motion: style
.paragraph_style
.text_motion
.unwrap_or(cranpose_ui::text::TextMotion::Static)
== cranpose_ui::text::TextMotion::Static,
spread,
string,
}
}
pub(crate) fn plain(string: Arc<RenderString>, paint: &TextPaint) -> Self {
Self {
hash: string.render_hash(),
empty: string.is_empty(),
string,
gradient: false,
static_motion: paint.static_motion,
spread: paint.spread,
}
}
pub(crate) fn string(&self) -> &Arc<RenderString> {
&self.string
}
pub(crate) fn render_hash(&self) -> u64 {
self.hash
}
pub(crate) fn is_empty(&self) -> bool {
self.empty
}
pub(crate) fn gradient(&self) -> bool {
self.gradient
}
pub(crate) fn static_motion(&self) -> bool {
self.static_motion
}
}
#[derive(Clone)]
pub(crate) struct TextDraw {
pub node_id: NodeId,
pub rect: Rect,
pub snap_anchor: Option<SnapAnchor>,
pub text: DrawnText,
pub layout: cranpose_text::TextLayout,
pub color: Color,
pub layer_paint: LayerPaint,
pub text_style: Arc<TextStyle>,
pub style_hash: u64,
pub font_size: f32,
pub scale: f32,
pub clip: Option<Rect>,
}
impl TextDraw {
pub(crate) fn raster_request(&self, rect: Rect, scale: f32) -> TextRasterRequest<'_> {
TextRasterRequest::new(
&self.layout,
self.text.string().as_ref(),
rect,
&self.text_style,
self.color,
scale,
)
.with_layer_paint(&self.layer_paint)
}
pub(crate) fn hash_glyph_paint<H: Hasher>(&self, state: &mut H) {
self.color.render_hash().hash(state);
self.layer_paint.hash(state);
}
pub(crate) fn glyph_reach(&self, rect: Rect, scale: f32) -> Rect {
glyph_part(rect, &self.layout, scale, self.text.spread)
}
}
#[derive(Clone)]
pub(crate) struct ImageDraw {
pub rect: Rect,
pub quad: [[f32; 2]; 4],
pub snap_anchor: Option<SnapAnchor>,
pub image: ImageBitmap,
pub alpha: f32,
pub color_filter: Option<ColorFilter>,
pub sampling: ImageSampling,
pub clip: Option<Rect>,
pub rounding: Option<ClipRounding>,
pub blend_mode: BlendMode,
pub src_rect: Option<Rect>,
pub motion_context_animated: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum DrawOpKind {
Run(usize),
Image(usize),
Text(usize),
Shadow(usize),
RRectShadow(usize),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct DrawOp {
pub z_index: usize,
pub kind: DrawOpKind,
}
#[derive(Clone)]
pub(crate) struct ShadowDraw {
pub shapes: Option<RunDraw>,
pub post_blur_cutouts: Option<RunDraw>,
pub texts: Vec<TextDraw>,
pub blur_radius: f32,
pub clip: Option<Rect>,
pub rounded_clip: Option<LayerRoundedClip>,
pub z_index: usize,
}
impl ShadowDraw {
pub(crate) fn requires_surface(&self) -> bool {
self.blur_radius > 0.0
|| self.post_blur_cutouts.is_some()
|| self.shapes.as_ref().is_some_and(|shapes| {
shapes
.segment_records()
.any(|segment| segment.blend == BlendMode::DstOut)
})
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct RRectShadowDraw {
pub shadow: ShadowRRect,
pub color: Color,
pub clip: Option<Rect>,
pub snap_anchor: Option<SnapAnchor>,
}
#[derive(Clone)]
pub(crate) struct EffectLayer {
pub rect: Rect,
pub clip: Option<Rect>,
pub snap_anchor: Option<SnapAnchor>,
pub effect: Option<RenderEffect>,
pub blend_mode: BlendMode,
pub composite_alpha: f32,
pub z_start: usize,
pub z_end: usize,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct LayerRoundedClip {
pub(crate) rect: Rect,
pub(crate) radii: [f32; 4],
}
#[derive(Clone)]
pub(crate) struct BackdropLayer {
pub node_id: Option<NodeId>,
pub alpha: f32,
pub rect: Rect,
pub clip: Option<Rect>,
pub reach: Option<Rect>,
pub rounded_clip: Option<LayerRoundedClip>,
pub snap_anchor: Option<SnapAnchor>,
pub effect: RenderEffect,
pub z_index: usize,
}
pub(crate) struct CompositorScene {
pub runs: Vec<RunDraw>,
loose: LooseRun,
pub images: Vec<ImageDraw>,
pub texts: Vec<TextDraw>,
pub shadow_draws: Vec<ShadowDraw>,
shadow_recorders: Vec<Arc<ShapeRecorder>>,
pub rrect_shadows: Vec<RRectShadowDraw>,
pub draw_ops: Vec<DrawOp>,
pub effect_layers: Vec<EffectLayer>,
pub backdrop_layers: Vec<BackdropLayer>,
pub next_z: usize,
roomy_frames: u8,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct SceneCapacityHint {
pub runs: usize,
pub images: usize,
pub texts: usize,
pub shadow_draws: usize,
pub rrect_shadows: usize,
pub draw_ops: usize,
pub effect_layers: usize,
pub backdrop_layers: usize,
}
const SCENE_BUFFER_POOL_LIMIT: usize = 4;
const ROOMY_FRAMES: u8 = 8;
const ROOM_KEPT: usize = 64 * 1024;
pub(crate) struct SceneBuffers {
runs: Vec<RunDraw>,
loose: ShapeRecorder,
images: Vec<ImageDraw>,
texts: Vec<TextDraw>,
shadow_draws: Vec<ShadowDraw>,
shadow_recorders: Vec<Arc<ShapeRecorder>>,
rrect_shadows: Vec<RRectShadowDraw>,
draw_ops: Vec<DrawOp>,
effect_layers: Vec<EffectLayer>,
backdrop_layers: Vec<BackdropLayer>,
}
pub(crate) fn trim_scene_buffer_pool() {
crate::thread_state::with(|state| {
for buffers in state.scene_buffer_pool.borrow_mut().iter_mut() {
buffers.trim();
}
});
}
impl SceneBuffers {
fn trim(&mut self) {
self.runs.trim_growth_slack();
self.images.trim_growth_slack();
self.texts.trim_growth_slack();
self.shadow_draws.trim_growth_slack();
self.shadow_recorders.clear();
self.shadow_recorders.trim_growth_slack();
self.rrect_shadows.trim_growth_slack();
self.draw_ops.trim_growth_slack();
self.effect_layers.trim_growth_slack();
self.backdrop_layers.trim_growth_slack();
}
}
impl Drop for CompositorScene {
fn drop(&mut self) {
crate::thread_state::try_with(|state| {
let Ok(mut pool) = state.scene_buffer_pool.try_borrow_mut() else {
return;
};
if pool.len() >= SCENE_BUFFER_POOL_LIMIT {
pool.remove(0);
}
if self.roomy() {
self.give_back_room();
}
self.clear();
pool.push(SceneBuffers {
runs: std::mem::take(&mut self.runs),
loose: std::mem::take(&mut self.loose.recorder),
images: std::mem::take(&mut self.images),
texts: std::mem::take(&mut self.texts),
shadow_draws: std::mem::take(&mut self.shadow_draws),
shadow_recorders: std::mem::take(&mut self.shadow_recorders),
rrect_shadows: std::mem::take(&mut self.rrect_shadows),
draw_ops: std::mem::take(&mut self.draw_ops),
effect_layers: std::mem::take(&mut self.effect_layers),
backdrop_layers: std::mem::take(&mut self.backdrop_layers),
});
});
}
}
impl CompositorScene {
pub(crate) fn new() -> Self {
Self::with_capacity(SceneCapacityHint::default())
}
pub(crate) fn with_capacity(hint: SceneCapacityHint) -> Self {
if let Some(buffers) =
crate::thread_state::with(|state| state.scene_buffer_pool.borrow_mut().pop())
{
return Self {
runs: buffers.runs,
loose: LooseRun {
recorder: buffers.loose,
placement: Placement::at(Point::default(), None, None),
},
images: buffers.images,
texts: buffers.texts,
shadow_draws: buffers.shadow_draws,
shadow_recorders: buffers.shadow_recorders,
rrect_shadows: buffers.rrect_shadows,
draw_ops: buffers.draw_ops,
effect_layers: buffers.effect_layers,
backdrop_layers: buffers.backdrop_layers,
next_z: 0,
roomy_frames: 0,
};
}
Self {
runs: Vec::with_capacity(hint.runs),
loose: LooseRun {
recorder: ShapeRecorder::default(),
placement: Placement::at(Point::default(), None, None),
},
images: Vec::with_capacity(hint.images),
texts: Vec::with_capacity(hint.texts),
shadow_draws: Vec::with_capacity(hint.shadow_draws),
shadow_recorders: Vec::new(),
rrect_shadows: Vec::with_capacity(hint.rrect_shadows),
draw_ops: Vec::with_capacity(hint.draw_ops),
effect_layers: Vec::with_capacity(hint.effect_layers),
backdrop_layers: Vec::with_capacity(hint.backdrop_layers),
next_z: 0,
roomy_frames: 0,
}
}
pub(crate) fn capacity_hint(&self) -> SceneCapacityHint {
SceneCapacityHint {
runs: self.runs.len(),
images: self.images.len(),
texts: self.texts.len(),
shadow_draws: self.shadow_draws.len(),
rrect_shadows: self.rrect_shadows.len(),
draw_ops: self.draw_ops.len(),
effect_layers: self.effect_layers.len(),
backdrop_layers: self.backdrop_layers.len(),
}
}
pub(crate) fn settle_room(&mut self) {
if !self.roomy() {
self.roomy_frames = 0;
return;
}
self.roomy_frames += 1;
if self.roomy_frames < ROOMY_FRAMES {
return;
}
self.roomy_frames = 0;
self.give_back_room();
}
fn give_back_room(&mut self) {
self.runs.trim_growth_slack();
self.images.trim_growth_slack();
self.texts.trim_growth_slack();
self.shadow_draws.trim_growth_slack();
self.rrect_shadows.trim_growth_slack();
self.draw_ops.trim_growth_slack();
self.effect_layers.trim_growth_slack();
self.backdrop_layers.trim_growth_slack();
}
fn roomy(&self) -> bool {
let (used, kept) = self.room();
kept > ROOM_KEPT && kept > used.saturating_mul(4)
}
fn room(&self) -> (usize, usize) {
fn bytes<T>(list: &Vec<T>) -> (usize, usize) {
let size = size_of::<T>();
(list.len() * size, list.capacity() * size)
}
[
bytes(&self.runs),
bytes(&self.images),
bytes(&self.texts),
bytes(&self.shadow_draws),
bytes(&self.rrect_shadows),
bytes(&self.draw_ops),
bytes(&self.effect_layers),
bytes(&self.backdrop_layers),
]
.into_iter()
.fold((0, 0), |(used, kept), (u, k)| (used + u, kept + k))
}
pub(crate) fn clear(&mut self) {
self.runs.clear();
self.loose.recorder.clear();
self.images.clear();
self.texts.clear();
let recorder_limit = self.shadow_draws.capacity().saturating_mul(2);
for shadow in self.shadow_draws.drain(..) {
for mut run in [shadow.shapes, shadow.post_blur_cutouts]
.into_iter()
.flatten()
{
if self.shadow_recorders.len() < recorder_limit
&& let Some(recorder) = Arc::get_mut(&mut run.recorder)
{
recorder.clear();
self.shadow_recorders.push(run.recorder);
}
}
}
self.rrect_shadows.clear();
self.draw_ops.clear();
self.effect_layers.clear();
self.backdrop_layers.clear();
self.next_z = 0;
}
pub(crate) fn next_z(&mut self) -> usize {
self.flush_loose();
self.next_z
}
pub(crate) fn push_loose(&mut self, primitive: DrawPrimitive, placement: Placement) {
if !self.loose.recorder.is_empty() && self.loose.placement != placement {
self.flush_loose();
}
self.loose.placement = placement;
if let Recorded::Other(other) = self.loose.recorder.push_primitive(primitive) {
unreachable!("only shapes join a loose run, not {other:?}");
}
}
#[inline]
pub(crate) fn flush_loose(&mut self) {
if !self.loose.recorder.is_empty() {
self.push_loose_run();
}
}
#[inline(never)]
fn push_loose_run(&mut self) {
let Some(run) = RunDraw::whole(
Arc::new(std::mem::take(&mut self.loose.recorder)),
self.loose.placement.clone(),
) else {
return;
};
self.push_run_unflushed(run);
}
pub(crate) fn push_run(&mut self, run: RunDraw) {
self.flush_loose();
self.push_run_unflushed(run);
}
fn push_run_unflushed(&mut self, run: RunDraw) {
let z_index = self.next_z;
self.next_z += 1;
let index = self.runs.len();
self.runs.push(run);
self.draw_ops.push(DrawOp {
z_index,
kind: DrawOpKind::Run(index),
});
}
pub(crate) fn push_image(&mut self, draw: ImageDraw) {
self.flush_loose();
let z_index = self.next_z;
self.next_z += 1;
let index = self.images.len();
self.images.push(ImageDraw {
alpha: draw.alpha.clamp(0.0, 1.0),
..draw
});
self.draw_ops.push(DrawOp {
z_index,
kind: DrawOpKind::Image(index),
});
}
pub(crate) fn push_text(&mut self, draw: TextDraw) {
self.flush_loose();
let z_index = self.next_z;
self.next_z += 1;
let index = self.texts.len();
self.texts.push(draw);
self.draw_ops.push(DrawOp {
z_index,
kind: DrawOpKind::Text(index),
});
}
pub(crate) fn take_shadow_recorder(&mut self) -> Arc<ShapeRecorder> {
self.shadow_recorders.pop().unwrap_or_default()
}
pub(crate) fn push_shadow_draw(&mut self, mut draw: ShadowDraw) {
self.flush_loose();
let z_index = self.next_z;
self.next_z += 1;
let index = self.shadow_draws.len();
draw.z_index = z_index;
self.shadow_draws.push(draw);
self.draw_ops.push(DrawOp {
z_index,
kind: DrawOpKind::Shadow(index),
});
}
pub(crate) fn push_rrect_shadow(&mut self, draw: RRectShadowDraw) {
self.flush_loose();
let z_index = self.next_z;
self.next_z += 1;
let index = self.rrect_shadows.len();
self.rrect_shadows.push(draw);
self.draw_ops.push(DrawOp {
z_index,
kind: DrawOpKind::RRectShadow(index),
});
}
pub(crate) fn push_effect_layer(&mut self, layer: EffectLayer) {
self.flush_loose();
self.effect_layers.push(layer);
}
pub(crate) fn push_backdrop_layer(&mut self, mut layer: BackdropLayer) {
self.flush_loose();
layer.z_index = self.next_z;
self.next_z += 1;
self.backdrop_layers.push(layer);
}
}
impl Default for CompositorScene {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
#[path = "tests/scene_tests.rs"]
mod tests;
#[derive(Clone, Copy)]
pub(crate) struct ContentContext<'a> {
pub(crate) layer_bounds: Rect,
pub(crate) local_layer: &'a GraphicsLayer,
pub(crate) visual_clip: Option<Rect>,
pub(crate) rounding: Option<ClipRounding>,
pub(crate) anchor: Option<SnapAnchor>,
pub(crate) motion_context_animated: bool,
}