use crate::RenderMode;
use crate::dispatch::Dispatcher;
#[cfg(feature = "text")]
use crate::text::{GlyphAtlasResources, GlyphRunBuilder};
#[cfg(feature = "text")]
use glifo::GlyphPrepCache;
#[cfg(feature = "multithreading")]
use crate::dispatch::multi_threaded::MultiThreadedDispatcher;
use crate::dispatch::single_threaded::SingleThreadedDispatcher;
use crate::kurbo::{PathEl, Point};
use alloc::boxed::Box;
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;
use hashbrown::HashMap;
use vello_common::blurred_rounded_rect::BlurredRoundedRectangle;
use vello_common::encode::{EncodeExt, EncodedPaint};
use vello_common::fearless_simd::Level;
use vello_common::filter_effects::Filter;
use vello_common::kurbo::{Affine, BezPath, Rect, Stroke};
use vello_common::mask::Mask;
use vello_common::paint::{ImageId, ImageResolver, Paint, PaintType, Tint};
use vello_common::peniko::color::palette::css::BLACK;
use vello_common::peniko::{BlendMode, Fill};
use vello_common::pixmap::Pixmap;
use vello_common::render_state::RenderState;
use vello_common::util::is_axis_aligned;
#[cfg(feature = "text")]
pub(crate) const DEFAULT_GLYPH_ATLAS_SIZE: u16 = 4096;
pub(crate) const ATLAS_IMAGE_ID_BASE: u32 = u32::MAX / 2;
#[derive(Debug, Default)]
pub struct Resources {
pub(crate) image_registry: ImageRegistry,
#[cfg(feature = "text")]
pub(crate) glyph_prep_cache: GlyphPrepCache,
#[cfg(feature = "text")]
pub(crate) glyph_resources: Option<GlyphAtlasResources>,
}
impl Resources {
pub fn new() -> Self {
Self::default()
}
pub(crate) fn before_render(&mut self) {
#[cfg(feature = "text")]
self.prepare_glyph_cache();
}
pub(crate) fn after_render(&mut self) {
#[cfg(feature = "text")]
self.maintain_glyph_cache();
}
}
#[derive(Debug)]
pub struct RenderContext {
pub(crate) width: u16,
pub(crate) height: u16,
pub(crate) state: RenderState,
pub(crate) mask: Option<Mask>,
pub(crate) temp_path: BezPath,
pub(crate) aliasing_threshold: Option<u8>,
pub(crate) encoded_paints: Vec<EncodedPaint>,
pub(crate) filter: Option<Filter>,
#[cfg_attr(
not(feature = "text"),
allow(dead_code, reason = "used when the `text` feature is enabled")
)]
pub(crate) render_settings: RenderSettings,
dispatcher: Box<dyn Dispatcher>,
}
#[derive(Copy, Clone, Debug)]
pub struct RenderSettings {
pub level: Level,
pub num_threads: u16,
pub render_mode: RenderMode,
}
impl Default for RenderSettings {
fn default() -> Self {
Self {
level: Level::try_detect().unwrap_or(Level::baseline()),
#[cfg(feature = "multithreading")]
num_threads: (std::thread::available_parallelism()
.unwrap()
.get()
.saturating_sub(1) as u16)
.min(8),
#[cfg(not(feature = "multithreading"))]
num_threads: 0,
render_mode: RenderMode::OptimizeSpeed,
}
}
}
impl RenderContext {
pub fn new(width: u16, height: u16) -> Self {
Self::new_with(width, height, RenderSettings::default())
}
pub fn new_with(width: u16, height: u16, settings: RenderSettings) -> Self {
#[cfg(feature = "multithreading")]
let dispatcher: Box<dyn Dispatcher> = if settings.num_threads == 0 {
Box::new(SingleThreadedDispatcher::new(width, height, settings.level))
} else {
Box::new(MultiThreadedDispatcher::new(
width,
height,
settings.num_threads,
settings.level,
))
};
#[cfg(not(feature = "multithreading"))]
let dispatcher: Box<dyn Dispatcher> =
{ Box::new(SingleThreadedDispatcher::new(width, height, settings.level)) };
let encoded_paints = vec![];
let temp_path = BezPath::new();
let aliasing_threshold = None;
Self {
width,
height,
dispatcher,
state: RenderState::default(),
aliasing_threshold,
render_settings: settings,
mask: None,
temp_path,
encoded_paints,
filter: None,
}
}
fn encode_current_paint(&mut self) -> Paint {
match self.state.paint.clone() {
PaintType::Solid(s) => s.into(),
PaintType::Gradient(g) => {
g.encode_into(
&mut self.encoded_paints,
self.state.transform * self.state.paint_transform,
None,
)
}
PaintType::Image(i) => i.encode_into(
&mut self.encoded_paints,
self.state.transform * self.state.paint_transform,
self.state.tint,
),
}
}
pub fn fill_path(&mut self, path: &BezPath) {
self.with_optional_filter(|ctx| {
let paint = ctx.encode_current_paint();
ctx.dispatcher.fill_path(
path,
ctx.state.fill_rule,
ctx.state.transform,
paint,
ctx.state.blend_mode,
ctx.aliasing_threshold,
ctx.mask.clone(),
&ctx.encoded_paints,
);
});
}
pub fn stroke_path(&mut self, path: &BezPath) {
self.with_optional_filter(|ctx| {
let paint = ctx.encode_current_paint();
ctx.dispatcher.stroke_path(
path,
&ctx.state.stroke,
ctx.state.transform,
paint,
ctx.state.blend_mode,
ctx.aliasing_threshold,
ctx.mask.clone(),
&ctx.encoded_paints,
);
});
}
pub fn fill_rect(&mut self, rect: &Rect) {
self.with_optional_filter(|ctx| {
let paint = ctx.encode_current_paint();
if is_axis_aligned(&ctx.state.transform) && ctx.aliasing_threshold.is_none() {
let transformed_rect = ctx.state.transform.transform_rect_bbox(*rect);
ctx.dispatcher.fill_rect_fast(
&transformed_rect,
paint,
ctx.state.blend_mode,
ctx.mask.clone(),
&ctx.encoded_paints,
);
} else {
ctx.rect_to_temp_path(rect);
ctx.dispatcher.fill_path(
&ctx.temp_path,
ctx.state.fill_rule,
ctx.state.transform,
paint,
ctx.state.blend_mode,
ctx.aliasing_threshold,
ctx.mask.clone(),
&ctx.encoded_paints,
);
}
});
}
pub fn stroke_rect(&mut self, rect: &Rect) {
self.with_optional_filter(|ctx| {
ctx.rect_to_temp_path(rect);
let paint = ctx.encode_current_paint();
ctx.dispatcher.stroke_path(
&ctx.temp_path,
&ctx.state.stroke,
ctx.state.transform,
paint,
ctx.state.blend_mode,
ctx.aliasing_threshold,
ctx.mask.clone(),
&ctx.encoded_paints,
);
});
}
fn rect_to_temp_path(&mut self, rect: &Rect) {
self.temp_path.truncate(0);
self.temp_path
.push(PathEl::MoveTo(Point::new(rect.x0, rect.y0)));
self.temp_path
.push(PathEl::LineTo(Point::new(rect.x1, rect.y0)));
self.temp_path
.push(PathEl::LineTo(Point::new(rect.x1, rect.y1)));
self.temp_path
.push(PathEl::LineTo(Point::new(rect.x0, rect.y1)));
self.temp_path.push(PathEl::ClosePath);
}
pub fn fill_blurred_rounded_rect(&mut self, rect: &Rect, radius: f32, std_dev: f32) {
let rect = rect.abs();
let color = match self.state.paint {
PaintType::Solid(s) => s,
_ => BLACK,
};
let blurred_rect = BlurredRoundedRectangle {
rect,
color,
radius,
std_dev,
};
let kernel_size = 2.5 * std_dev;
let inflated_rect = rect.inflate(f64::from(kernel_size), f64::from(kernel_size));
let transform = self.state.transform * self.state.paint_transform;
self.rect_to_temp_path(&inflated_rect);
let paint = blurred_rect.encode_into(&mut self.encoded_paints, transform, None);
self.dispatcher.fill_path(
&self.temp_path,
Fill::NonZero,
self.state.transform,
paint,
self.state.blend_mode,
self.aliasing_threshold,
self.mask.clone(),
&self.encoded_paints,
);
}
#[cfg(feature = "text")]
pub fn glyph_run<'a>(
&'a mut self,
resources: &'a mut Resources,
font: &crate::peniko::FontData,
) -> GlyphRunBuilder<'a> {
glifo::GlyphRunBuilder::new(
font.clone(),
self.state.transform,
self.state.paint_transform,
crate::text::CpuGlyphRunBackend {
ctx: self,
resources,
atlas_cache_enabled: false,
},
)
}
pub fn push_layer(
&mut self,
clip_path: Option<&BezPath>,
blend_mode: Option<BlendMode>,
opacity: Option<f32>,
mask: Option<Mask>,
filter: Option<Filter>,
) {
let mask = mask.and_then(|m| {
if m.width() != self.width || m.height() != self.height {
None
} else {
Some(m)
}
});
let blend_mode = blend_mode.unwrap_or_default();
let opacity = opacity.unwrap_or(1.0);
self.dispatcher.push_layer(
clip_path,
self.state.fill_rule,
self.state.transform,
blend_mode,
opacity,
self.aliasing_threshold,
mask,
filter,
);
}
pub fn push_clip_layer(&mut self, path: &BezPath) {
self.push_layer(Some(path), None, None, None, None);
}
pub fn push_blend_layer(&mut self, blend_mode: BlendMode) {
self.push_layer(None, Some(blend_mode), None, None, None);
}
pub fn push_opacity_layer(&mut self, opacity: f32) {
self.push_layer(None, None, Some(opacity), None, None);
}
pub fn push_mask_layer(&mut self, mask: Mask) {
self.push_layer(None, None, None, Some(mask), None);
}
pub fn push_filter_layer(&mut self, filter: Filter) {
self.push_layer(None, None, None, None, Some(filter));
}
pub fn set_aliasing_threshold(&mut self, aliasing_threshold: Option<u8>) {
self.aliasing_threshold = aliasing_threshold;
}
pub fn pop_layer(&mut self) {
self.dispatcher.pop_layer();
}
pub fn set_stroke(&mut self, stroke: Stroke) {
self.state.stroke = stroke;
}
pub fn stroke(&self) -> &Stroke {
&self.state.stroke
}
#[cfg(feature = "text")]
pub(crate) fn stroke_mut(&mut self) -> &mut Stroke {
&mut self.state.stroke
}
pub fn set_paint(&mut self, paint: impl Into<PaintType>) {
self.state.paint = paint.into();
}
pub fn paint(&self) -> &PaintType {
&self.state.paint
}
pub fn set_tint(&mut self, tint: Option<Tint>) {
self.state.tint = tint;
}
pub fn reset_tint(&mut self) {
self.state.tint = None;
}
pub fn set_blend_mode(&mut self, blend_mode: BlendMode) {
self.state.blend_mode = blend_mode;
}
pub fn blend_mode(&self) -> BlendMode {
self.state.blend_mode
}
pub fn set_paint_transform(&mut self, paint_transform: Affine) {
self.state.paint_transform = paint_transform;
}
pub fn paint_transform(&self) -> &Affine {
&self.state.paint_transform
}
pub fn reset_paint_transform(&mut self) {
self.state.paint_transform = Affine::IDENTITY;
}
pub fn set_fill_rule(&mut self, fill_rule: Fill) {
self.state.fill_rule = fill_rule;
}
pub fn set_mask(&mut self, mask: Mask) {
self.mask = Some(mask);
}
pub fn reset_mask(&mut self) {
self.mask = None;
}
pub fn fill_rule(&self) -> &Fill {
&self.state.fill_rule
}
pub fn set_transform(&mut self, transform: Affine) {
self.state.transform = transform;
}
pub fn transform(&self) -> &Affine {
&self.state.transform
}
pub fn reset_transform(&mut self) {
self.state.transform = Affine::IDENTITY;
}
pub fn set_filter_effect(&mut self, filter: Filter) {
self.filter = Some(filter);
}
pub fn reset_filter_effect(&mut self) {
self.filter = None;
}
pub fn reset(&mut self) {
self.dispatcher.reset();
self.encoded_paints.clear();
self.mask = None;
self.state.reset();
}
pub fn push_clip_path(&mut self, path: &BezPath) {
self.dispatcher.push_clip_path(
path,
self.state.fill_rule,
self.state.transform,
self.aliasing_threshold,
);
}
pub fn pop_clip_path(&mut self) {
self.dispatcher.pop_clip_path();
}
pub fn flush(&mut self) {
self.dispatcher.flush(&self.encoded_paints);
}
pub fn render_to_buffer(
&self,
resources: &mut Resources,
buffer: &mut [u8],
width: u16,
height: u16,
render_mode: RenderMode,
) {
let wide = self.dispatcher.wide();
assert!(!wide.has_layers(), "some layers haven't been popped yet");
assert_eq!(
buffer.len(),
(width as usize) * (height as usize) * 4,
"provided width ({}) and height ({}) do not match buffer size ({})",
width,
height,
buffer.len(),
);
resources.before_render();
self.dispatcher.rasterize(
buffer,
render_mode,
width,
height,
&self.encoded_paints,
&resources.image_registry,
);
resources.after_render();
}
pub fn render_to_pixmap(&self, resources: &mut Resources, pixmap: &mut Pixmap) {
let width = pixmap.width();
let height = pixmap.height();
self.render_to_buffer(
resources,
pixmap.data_as_u8_slice_mut(),
width,
height,
self.render_settings.render_mode,
);
}
pub fn composite_to_pixmap_at_offset(
&self,
resources: &Resources,
pixmap: &mut Pixmap,
dst_x: u16,
dst_y: u16,
) {
let dst_buffer_width = pixmap.width();
let dst_buffer_height = pixmap.height();
self.dispatcher.composite_at_offset(
pixmap.data_as_u8_slice_mut(),
self.width,
self.height,
dst_x,
dst_y,
dst_buffer_width,
dst_buffer_height,
self.render_settings.render_mode,
&self.encoded_paints,
&resources.image_registry,
);
}
pub fn width(&self) -> u16 {
self.width
}
pub fn height(&self) -> u16 {
self.height
}
pub fn render_settings(&self) -> &RenderSettings {
&self.render_settings
}
fn with_optional_filter<F>(&mut self, mut f: F)
where
F: FnMut(&mut Self),
{
if let Some(filter) = self.filter.clone() {
self.push_filter_layer(filter);
f(self);
self.pop_layer();
} else {
f(self);
}
}
pub fn take_current_state(&mut self) -> RenderState {
core::mem::take(&mut self.state)
}
pub fn save_current_state(&mut self) -> RenderState {
self.state.clone()
}
pub fn restore_state(&mut self, state: RenderState) {
self.state = state;
}
}
impl Resources {
pub fn register_image(&mut self, pixmap: Arc<Pixmap>) -> ImageId {
self.image_registry.register(pixmap)
}
pub fn destroy_image(&mut self, id: ImageId) -> bool {
self.image_registry.destroy(id)
}
pub fn resolve_image(&self, id: ImageId) -> Option<Arc<Pixmap>> {
self.image_registry.resolve(id)
}
pub fn clear_images(&mut self) {
self.image_registry.clear();
}
}
#[derive(Debug, Default)]
pub(crate) struct ImageRegistry {
images: HashMap<u32, Arc<Pixmap>>,
next_id: u32,
}
impl ImageRegistry {
fn register(&mut self, pixmap: Arc<Pixmap>) -> ImageId {
let id = self.next_id;
assert!(
id < ATLAS_IMAGE_ID_BASE,
"image registry exhausted non-atlas image IDs"
);
self.next_id += 1;
self.images.insert(id, pixmap);
ImageId::new(id)
}
#[cfg(feature = "text")]
pub(crate) fn register_atlas_page(&mut self, page_index: u32, pixmap: Arc<Pixmap>) {
self.images.insert(
ImageId::new(ATLAS_IMAGE_ID_BASE + page_index).as_u32(),
pixmap,
);
}
pub(crate) fn destroy(&mut self, id: ImageId) -> bool {
self.images.remove(&id.as_u32()).is_some()
}
#[cfg(feature = "text")]
pub(crate) fn destroy_atlas_page(&mut self, page_index: u32) -> bool {
self.destroy(ImageId::new(ATLAS_IMAGE_ID_BASE + page_index))
}
fn resolve(&self, id: ImageId) -> Option<Arc<Pixmap>> {
self.images.get(&id.as_u32()).cloned()
}
fn clear(&mut self) {
self.images.clear();
self.next_id = 0;
}
}
impl ImageResolver for ImageRegistry {
fn resolve(&self, id: ImageId) -> Option<Arc<Pixmap>> {
self.images.get(&id.as_u32()).cloned()
}
}
#[cfg(test)]
mod tests {
use crate::RenderContext;
#[cfg(feature = "text")]
use crate::peniko::{Blob, FontData};
#[cfg(feature = "text")]
use alloc::sync::Arc;
#[cfg(feature = "text")]
use glifo::Glyph;
use vello_common::kurbo::{Rect, Shape};
use vello_common::tile::Tile;
#[test]
fn clip_overflow() {
let mut ctx = RenderContext::new(100, 100);
for _ in 0..(usize::from(u16::MAX) + 1).div_ceil(usize::from(Tile::HEIGHT * Tile::WIDTH)) {
ctx.fill_rect(&Rect::new(0.0, 0.0, 1.0, 1.0));
}
ctx.push_clip_layer(&Rect::new(20.0, 20.0, 180.0, 180.0).to_path(0.1));
ctx.pop_layer();
ctx.flush();
}
#[cfg(feature = "multithreading")]
#[test]
fn multithreaded_crash_after_reset() {
use crate::{Level, RenderMode, RenderSettings};
use vello_common::pixmap::Pixmap;
let mut pixmap = Pixmap::new(200, 200);
let settings = RenderSettings {
level: Level::try_detect().unwrap_or(Level::baseline()),
num_threads: 1,
render_mode: RenderMode::OptimizeQuality,
};
let mut resources = crate::Resources::new();
let mut ctx = RenderContext::new_with(200, 200, settings);
ctx.reset();
ctx.fill_path(&Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1));
ctx.flush();
ctx.render_to_pixmap(&mut resources, &mut pixmap);
ctx.flush();
ctx.render_to_pixmap(&mut resources, &mut pixmap);
}
#[cfg(feature = "text")]
#[test]
fn glyph_atlas_resources_are_lazy() {
const ROBOTO_FONT: &[u8] =
include_bytes!("../../../examples/assets/roboto/Roboto-Regular.ttf");
let font = FontData::new(Blob::new(Arc::new(ROBOTO_FONT)), 0);
let glyphs = [Glyph {
id: 1,
x: 0.0,
y: 0.0,
}];
let mut resources = crate::Resources::new();
let mut ctx = RenderContext::new(100, 100);
ctx.fill_rect(&Rect::new(0.0, 0.0, 10.0, 10.0));
ctx.fill_path(&Rect::new(10.0, 10.0, 20.0, 20.0).to_path(0.1));
ctx.glyph_run(&mut resources, &font)
.fill_glyphs(glyphs.into_iter());
assert!(resources.glyph_resources.is_none());
ctx.glyph_run(&mut resources, &font)
.atlas_cache(true)
.fill_glyphs(glyphs.into_iter());
assert!(resources.glyph_resources.is_some());
}
}