| // Copyright 2025 the Vello Authors | |
| // SPDX-License-Identifier: Apache-2.0 OR MIT | |
| //! Basic render operations. | |
| #[cfg(feature = "text")] | |
| use crate::Resources; | |
| #[cfg(feature = "text")] | |
| use crate::text::GlyphRunBuilder; | |
| use alloc::vec; | |
| use alloc::vec::Vec; | |
| use core::cell::RefCell; | |
| use core::ops::Range; | |
| #[cfg(feature = "text")] | |
| use glifo::HintCacheConfig; | |
| use vello_common::blurred_rounded_rect::BlurredRoundedRect; | |
| use vello_common::clip::{Clip, ClipRef, ClipShape}; | |
| use vello_common::encode::{EncodeExt, EncodedPaint}; | |
| use vello_common::fearless_simd::Level; | |
| use vello_common::filter::FilterData; | |
| use vello_common::filter_effects::Filter; | |
| use vello_common::geometry::{RectU16, SizeU16}; | |
| use vello_common::kurbo::{Affine, BezPath, Rect, Shape, Stroke}; | |
| use vello_common::multi_atlas::AtlasConfig; | |
| use vello_common::paint::{Brush, Paint, PaintHandle, PremulColor}; | |
| #[cfg(feature = "text")] | |
| use vello_common::peniko::FontData; | |
| use vello_common::peniko::{BlendMode, Fill, GradientKind}; | |
| use vello_common::record::{CommandRecorder, Drawable, LayerClip, LayerProps, PoppedLayer}; | |
| use vello_common::reset::ResetOptions; | |
| use vello_common::strip::Strip; | |
| use vello_common::strip_generator::{GenerationMode, StripGenerator, StripStorage}; | |
| use vello_common::util::{RectExt, into_fast_path_rect, strip_bbox}; | |
| use vello_common::viewport::ViewportState; | |
| /// Default tolerance for curve flattening | |
| pub(crate) const DEFAULT_TOLERANCE: f64 = 0.1; | |
| /// Path or rectangle draw retained by the scene recorder. | |
| #[derive(Debug)] | |
| pub(crate) enum RecordedDraw { | |
| /// Path represented by generated strips. | |
| Path(RecordedPath), | |
| /// Rectangle retained for the direct GPU rectangle path. | |
| Rect(RecordedRect), | |
| } | |
| /// Recorded path strips and their paint. | |
| #[derive(Debug)] | |
| pub(crate) struct RecordedPath { | |
| /// Range selecting the path's strips from scene strip storage. | |
| pub(crate) strips: Range<usize>, | |
| /// Paint applied to the path. | |
| pub(crate) paint: PaintHandle, | |
| } | |
| /// Recorded rectangle and its paint. | |
| #[derive(Debug)] | |
| pub(crate) struct RecordedRect { | |
| /// Rectangle in scene coordinates. | |
| pub(crate) rect: Rect, | |
| /// Paint applied to the rectangle. | |
| pub(crate) paint: PaintHandle, | |
| } | |
| impl RecordedDraw { | |
| fn new_path(strips: Range<usize>, paint: PaintHandle) -> Self { | |
| Self::Path(RecordedPath { strips, paint }) | |
| } | |
| fn new_rect(rect: Rect, paint: PaintHandle) -> Self { | |
| Self::Rect(RecordedRect { rect, paint }) | |
| } | |
| } | |
| impl Drawable for RecordedDraw { | |
| #[expect( | |
| clippy::cast_possible_truncation, | |
| reason = "recorded fast rectangles are clipped to the u16 viewport" | |
| )] | |
| fn bbox(&self, strips: &[Strip]) -> Option<RectU16> { | |
| match self { | |
| // TODO: The bbox trait should take a reference to _all_ strips, and then we select | |
| // the correct strips here. Otherwise, callers of this method always have to make sure | |
| // to slice the strips correctly themselves. | |
| // TODO: We also should just compute the bbox during strip generation instead of | |
| // recomputing it here. | |
| Self::Path(_) => strip_bbox(strips), | |
| Self::Rect(rect) => { | |
| let rect = rect.rect; | |
| (!rect.is_zero_area()).then(|| { | |
| RectU16::new( | |
| rect.x0.floor() as u16, | |
| rect.y0.floor() as u16, | |
| rect.x1.ceil() as u16, | |
| rect.y1.ceil() as u16, | |
| ) | |
| .snap_to_tile_coordinates() | |
| }) | |
| } | |
| } | |
| } | |
| fn blend_mode(&self) -> Option<&BlendMode> { | |
| None | |
| } | |
| } | |
| /// Settings to apply to the render context. | |
| #[derive(Clone, Debug)] | |
| pub struct RenderSettings { | |
| pub(crate) level: Level, | |
| pub(crate) memory_settings: MemorySettings, | |
| #[cfg(feature = "text")] | |
| pub(crate) hint_cache_config: HintCacheConfig, | |
| #[cfg(feature = "wgpu")] | |
| pub(crate) pipeline_cache: Option<wgpu::PipelineCache>, | |
| } | |
| impl RenderSettings { | |
| /// Sets the SIMD level used for rendering operations. | |
| /// | |
| /// By default, the level is detected at runtime, falling back to [`Level::baseline`]. | |
| #[must_use] | |
| pub fn with_level(mut self, level: Level) -> Self { | |
| self.level = level; | |
| self | |
| } | |
| /// Returns the SIMD level used for rendering operations. | |
| pub fn level(&self) -> Level { | |
| self.level | |
| } | |
| /// Sets the configuration for GPU memory used while rendering. | |
| #[must_use] | |
| pub fn with_memory_settings(mut self, memory_settings: MemorySettings) -> Self { | |
| self.memory_settings = memory_settings; | |
| self | |
| } | |
| /// Sets how many glyph hinting instances the renderer's resources cache. | |
| /// | |
| /// See [`HintCacheConfig::max_instances`] for how to choose the limit. | |
| #[cfg(feature = "text")] | |
| #[must_use] | |
| pub fn with_hint_cache_config(mut self, config: HintCacheConfig) -> Self { | |
| self.hint_cache_config = config; | |
| self | |
| } | |
| /// Sets the cache used when creating the wgpu render pipelines. | |
| /// | |
| /// A cache can substantially reduce startup times, especially on low-tier devices. | |
| /// Requires [`wgpu::Features::PIPELINE_CACHE`] on the device. | |
| /// By default, no cache is used. | |
| #[cfg(feature = "wgpu")] | |
| #[must_use] | |
| pub fn with_pipeline_cache(mut self, pipeline_cache: wgpu::PipelineCache) -> Self { | |
| self.pipeline_cache = Some(pipeline_cache); | |
| self | |
| } | |
| } | |
| /// Settings controlling usage of GPU memory. | |
| #[derive(Copy, Clone, Debug, Default)] | |
| pub struct MemorySettings { | |
| /// Configuration for the atlas holding cached glyphs. | |
| pub glyph_atlas_config: AtlasConfig, | |
| /// Configuration for intermediate layer and scratch textures. | |
| pub layers_config: LayersConfig, | |
| } | |
| /// Configuration for temporary textures used to render layers and effects. | |
| /// | |
| /// Layers, blend modes, and filters need temporary GPU textures before their results can be | |
| /// composited into the main scene. This configuration allows you to specify some limits to prevent | |
| /// excessive allocations for complex or adversarial scenes. | |
| /// | |
| /// In general, Vello GPU has the following priorities in that specific order: | |
| /// - Render as many scenes as possible successfully. | |
| /// - Use as little memory as possible. | |
| /// - Be as performant as possible. | |
| /// | |
| /// Vello GPU will by default prefer minimizing memory usage, even if at the cost of worse | |
| /// performance. However, since the exact tradeoff is very application-dependent, | |
| /// this configuration still allows you to tune the exact parameters such that better performance | |
| /// is accepted at the cost of larger memory consumption. | |
| #[derive(Copy, Clone, Debug)] | |
| pub struct LayersConfig { | |
| /// Maximum number of intermediate textures that may be allocated. | |
| /// | |
| /// `None` permits growth up to device limits. A finite value allows you to impose a hard limit, | |
| /// but might result in certain scenes being rejected. The exact texture requirements for | |
| /// different types of scenes are considered an implementation detail, but in general: | |
| /// | |
| /// - `0` for scenes without layers, including layers introduced by COLR glyphs. | |
| /// - `1` for scenes with only single-child layers and no blend modes / filters. | |
| /// - `4` for scenes with only single-child layers with potentially blend modes | |
| /// or simple filters. | |
| /// | |
| /// Any other type of scene with complex layer nesting might need more intermediate textures, | |
| /// depending on the exact contents. | |
| pub max_textures: Option<usize>, | |
| /// Minimum width and height of each allocated intermediate texture. | |
| /// | |
| /// By default, textures only grow to fit the largest required layer, | |
| /// up to [`Self::max_texture_size`], and do not currently shrink between frames. By increasing | |
| /// the minimum texture size, you can force Vello GPU to more aggressively batch layer draws, | |
| /// at the cost of larger memory consumption. | |
| /// | |
| /// Desktop GPUs may benefit from a larger minimum when rendering scenes with many layers. On | |
| /// mobile GPUs, experiments have shown that keeping intermediate textures smaller is | |
| /// more important for both memory usage and performance, even if it requires more render passes. | |
| /// Therefore, you should in general avoid making this value too large. The default of | |
| /// 512 by 512 is intended as a conservative starting point. Setting this to 1024 by 1024 is a | |
| /// reasonable choice, too. Higher values are only recommended if benchmarks have proven | |
| /// that your target workload profits from this and you don't plan on targeting mobile devices. | |
| pub min_texture_size: SizeU16, | |
| /// Maximum width and height of each allocated intermediate texture. | |
| /// | |
| /// This should be at least the size of the main scene (and potentially more to account for | |
| /// padding of large filters), unless you explicitly want to reject too large layers to limit | |
| /// peak memory consumption. | |
| /// | |
| /// Regardless of what this value is set to, device limits will always be respected. | |
| pub max_texture_size: SizeU16, | |
| } | |
| impl Default for LayersConfig { | |
| fn default() -> Self { | |
| Self { | |
| max_textures: None, | |
| min_texture_size: SizeU16::new(512), | |
| max_texture_size: SizeU16::new(4096), | |
| } | |
| } | |
| } | |
| impl Default for RenderSettings { | |
| fn default() -> Self { | |
| Self { | |
| level: Level::try_detect().unwrap_or(Level::baseline()), | |
| memory_settings: MemorySettings::default(), | |
| #[cfg(feature = "text")] | |
| hint_cache_config: HintCacheConfig::default(), | |
| #[cfg(feature = "wgpu")] | |
| pipeline_cache: None, | |
| } | |
| } | |
| } | |
| /// A render context for GPU rendering. | |
| /// | |
| /// This context records drawing commands and prepares them for rendering on the GPU. | |
| #[derive(Debug)] | |
| pub struct Scene { | |
| /// Width of the rendering surface in pixels. | |
| pub(crate) width: u16, | |
| /// Height of the rendering surface in pixels. | |
| pub(crate) height: u16, | |
| /// Viewport-dependent path and clip generation state. | |
| viewport_state: ViewportState, | |
| /// Storage for encoded non-solid paint data. | |
| pub(crate) encoded_paints: Vec<EncodedPaint>, | |
| /// Storage for generated strips and alpha values. | |
| pub(crate) strip_storage: RefCell<StripStorage>, | |
| /// The command recorder. | |
| pub(crate) recorder: CommandRecorder<RecordedDraw>, | |
| settings: SceneSettings, | |
| } | |
| /// Settings to apply to a [`Scene`]. | |
| #[derive(Copy, Clone, Debug)] | |
| pub struct SceneSettings { | |
| /// SIMD level used for strip generation. | |
| pub level: Level, | |
| /// Disables anti-aliasing, painting only pixels whose coverage exceeds this threshold. | |
| pub aliasing_threshold: Option<u8>, | |
| } | |
| impl Default for SceneSettings { | |
| fn default() -> Self { | |
| Self { | |
| level: Level::try_detect().unwrap_or(Level::baseline()), | |
| aliasing_threshold: None, | |
| } | |
| } | |
| } | |
| /// A layer pushed with [`Scene::push_layer`]. | |
| #[derive(Debug, Clone)] | |
| pub struct Layer<'a> { | |
| /// Clip the layer to this path. | |
| pub clip: Option<Clip<'a>>, | |
| /// The blend mode used to composite the layer. | |
| pub blend_mode: BlendMode, | |
| /// The opacity of the layer, between 0 and 1. | |
| pub opacity: f32, | |
| /// A filter applied to the layer. | |
| pub filter: Option<Filter>, | |
| } | |
| impl Default for Layer<'_> { | |
| fn default() -> Self { | |
| Self { | |
| clip: None, | |
| blend_mode: BlendMode::default(), | |
| opacity: 1.0, | |
| filter: None, | |
| } | |
| } | |
| } | |
| impl<'a> Layer<'a> { | |
| /// Clip the layer to `clip`. | |
| #[must_use] | |
| pub fn with_clip(mut self, clip: impl Into<Clip<'a>>) -> Self { | |
| self.clip = Some(clip.into()); | |
| self | |
| } | |
| /// Set the blend mode. | |
| #[must_use] | |
| pub fn with_blend_mode(mut self, blend_mode: BlendMode) -> Self { | |
| self.blend_mode = blend_mode; | |
| self | |
| } | |
| /// Set the opacity. | |
| #[must_use] | |
| pub fn with_opacity(mut self, opacity: f32) -> Self { | |
| self.opacity = opacity; | |
| self | |
| } | |
| /// Set the filter. | |
| #[must_use] | |
| pub fn with_filter(mut self, filter: Filter) -> Self { | |
| self.filter = Some(filter); | |
| self | |
| } | |
| } | |
| impl Scene { | |
| /// Create a new render context with the given width and height in pixels. | |
| pub fn new(width: u16, height: u16) -> Self { | |
| Self::new_with(width, height, SceneSettings::default()) | |
| } | |
| /// Create a new render context with specific settings. | |
| pub fn new_with(width: u16, height: u16, settings: SceneSettings) -> Self { | |
| Self { | |
| width, | |
| height, | |
| viewport_state: ViewportState::new( | |
| width, | |
| height, | |
| settings.level, | |
| settings.aliasing_threshold, | |
| ), | |
| encoded_paints: vec![], | |
| strip_storage: RefCell::new(StripStorage::new(GenerationMode::Append)), | |
| recorder: CommandRecorder::new(width, height), | |
| settings, | |
| } | |
| } | |
| fn active_rect(&self) -> Rect { | |
| Rect::new( | |
| 0.0, | |
| 0.0, | |
| f64::from(self.viewport_state.width()), | |
| f64::from(self.viewport_state.height()), | |
| ) | |
| } | |
| fn path_transform(&self, transform: Affine) -> Affine { | |
| self.viewport_state.root_transform() * transform | |
| } | |
| fn aliasing_threshold(&self) -> Option<u8> { | |
| self.settings.aliasing_threshold | |
| } | |
| /// Encode `paint` into an `PaintHandle` that can be used for rendering. | |
| /// | |
| /// For solid colors, this is a simple conversion. For gradients and images, | |
| /// this encodes the paint data into the `encoded_paints` buffer and returns | |
| /// an `PaintHandle` that references that data. The combined transform (geometry + paint) | |
| /// is applied during encoding. | |
| fn encode_paint(&mut self, paint: &Paint, path_transform: Affine) -> Option<PaintHandle> { | |
| // Note: In vello_cpu, during fine rasterization we apply a 0.5 offset to the location | |
| // to account for the fact that we want to sample the pixel center instead of the top-left | |
| // corner. For vello_gpu, we don't need this, because the GPU itself already applies | |
| // this shift automatically. | |
| let transform = path_transform * paint.transform; | |
| match &paint.brush { | |
| Brush::Solid(s) => Some(PaintHandle::Solid(PremulColor::from_alpha_color(*s))), | |
| Brush::Gradient(g) => g.encode_into(&mut self.encoded_paints, transform, None), | |
| Brush::Image(i) => i | |
| .image | |
| .encode_into(&mut self.encoded_paints, transform, i.tint), | |
| } | |
| } | |
| /// Fill a path. | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if the paint uses a destructive blend mode or requires a disabled feature. | |
| #[track_caller] | |
| pub fn fill_path( | |
| &mut self, | |
| path: &BezPath, | |
| fill: Fill, | |
| paint: impl Into<Paint>, | |
| transform: Affine, | |
| ) { | |
| let paint = paint.into(); | |
| assert_paint_supported(&paint.brush); | |
| let transform = self.path_transform(transform); | |
| let Some(encoded) = self.encode_paint(&paint, transform) else { | |
| return; | |
| }; | |
| self.with_optional_blend_layer(paint.blend_mode, |ctx| { | |
| ctx.fill_path_with(path, transform, fill, encoded); | |
| }); | |
| } | |
| /// Build strips for a filled path with the given properties and record the draw. | |
| fn fill_path_with( | |
| &mut self, | |
| path: &BezPath, | |
| transform: Affine, | |
| fill_rule: Fill, | |
| paint: PaintHandle, | |
| ) { | |
| self.record_generated_path(paint, |strip_generator, strip_storage, clip_path| { | |
| strip_generator.generate_filled_path( | |
| path, | |
| fill_rule, | |
| transform, | |
| strip_storage, | |
| clip_path.map(|clip| clip.path), | |
| ); | |
| }); | |
| } | |
| /// Push a new clip path to the clip stack. | |
| /// | |
| /// See the explanation in the [clipping](https://github.com/linebender/vello/tree/main/vello_cpu/examples) | |
| /// example for how this method differs from clip layers. | |
| pub fn push_clip_path<'a>(&mut self, clip: impl Into<Clip<'a>>, transform: Affine) { | |
| let clip = clip.into(); | |
| self.viewport_state | |
| .push_clip_path(clip.path, clip.fill, transform); | |
| } | |
| /// Push a rectangular clip path. | |
| pub fn push_clip_rect(&mut self, rect: &Rect, transform: Affine) { | |
| if let Some(rect) = into_fast_path_rect(*rect, &transform, self.aliasing_threshold()) { | |
| self.viewport_state.push_clip_rect(&rect); | |
| } else { | |
| let path = rect.to_path(DEFAULT_TOLERANCE); | |
| self.push_clip_path(&path, transform); | |
| } | |
| } | |
| /// Pop the most recently pushed clip path or clip rectangle from the clip stack. | |
| /// | |
| /// Note that unlike layers, it is permissible to have pending pushed clips before | |
| /// finishing the rendering operation. | |
| pub fn pop_clip(&mut self) { | |
| self.viewport_state.pop_clip(); | |
| } | |
| /// Stroke a path. | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if the paint uses a destructive blend mode or requires a disabled feature. | |
| #[track_caller] | |
| pub fn stroke_path( | |
| &mut self, | |
| path: &BezPath, | |
| stroke: &Stroke, | |
| paint: impl Into<Paint>, | |
| transform: Affine, | |
| ) { | |
| let paint = paint.into(); | |
| assert_paint_supported(&paint.brush); | |
| let transform = self.path_transform(transform); | |
| let Some(encoded) = self.encode_paint(&paint, transform) else { | |
| return; | |
| }; | |
| self.with_optional_blend_layer(paint.blend_mode, |ctx| { | |
| ctx.record_generated_path(encoded, |strip_generator, strip_storage, clip_path| { | |
| strip_generator.generate_stroked_path( | |
| path, | |
| stroke, | |
| transform, | |
| strip_storage, | |
| clip_path.map(|clip| clip.path), | |
| ); | |
| }); | |
| }); | |
| } | |
| /// Fill a rectangle. | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if the paint uses a destructive blend mode or requires a disabled feature. | |
| #[track_caller] | |
| pub fn fill_rect(&mut self, rect: &Rect, paint: impl Into<Paint>, transform: Affine) { | |
| let paint = paint.into(); | |
| assert_paint_supported(&paint.brush); | |
| let transform = self.path_transform(transform); | |
| if rect.is_zero_area() { | |
| return; | |
| } | |
| let Some(encoded) = self.encode_paint(&paint, transform) else { | |
| return; | |
| }; | |
| self.with_optional_blend_layer(paint.blend_mode, |ctx| { | |
| if let Some(bounds) = ctx.fast_rect_bounds(rect, transform) { | |
| ctx.recorder | |
| .push_draw(RecordedDraw::new_rect(bounds, encoded), &[]); | |
| return; | |
| } | |
| if let Some(transformed_rect) = | |
| into_fast_path_rect(*rect, &transform, ctx.aliasing_threshold()) | |
| { | |
| ctx.record_generated_path(encoded, |strip_generator, strip_storage, clip_path| { | |
| strip_generator.generate_filled_rect_fast( | |
| &transformed_rect, | |
| strip_storage, | |
| clip_path, | |
| ); | |
| }); | |
| } else { | |
| // TODO: Use a temporary storage for rect paths, like in `vello_cpu`. | |
| ctx.fill_path_with( | |
| &rect.to_path(DEFAULT_TOLERANCE), | |
| transform, | |
| Fill::NonZero, | |
| encoded, | |
| ); | |
| } | |
| }); | |
| } | |
| fn record_generated_path<F>(&mut self, paint: PaintHandle, generate: F) | |
| where | |
| F: FnOnce(&mut StripGenerator, &mut StripStorage, Option<ClipRef<'_>>), | |
| { | |
| let strips = { | |
| let mut strip_storage = self.strip_storage.borrow_mut(); | |
| let strip_start = strip_storage.strips.len(); | |
| self.viewport_state | |
| .with_generator_and_clip(|strip_generator, clip_path| { | |
| generate(strip_generator, &mut strip_storage, clip_path); | |
| }); | |
| strip_start..strip_storage.strips.len() | |
| }; | |
| if strips.is_empty() { | |
| return; | |
| } | |
| let draw = RecordedDraw::new_path(strips.clone(), paint); | |
| let strip_storage = self.strip_storage.borrow(); | |
| self.recorder.push_draw(draw, &strip_storage.strips[strips]); | |
| } | |
| fn fast_rect_bounds(&self, rect: &Rect, transform: Affine) -> Option<Rect> { | |
| // We can't handle skewed rectangles. | |
| // TODO: Maybe support rotated rectangles (https://github.com/linebender/vello/pull/1482#discussion_r2881223621) | |
| let mut transformed_rect = | |
| into_fast_path_rect(*rect, &transform, self.aliasing_threshold())? | |
| .intersect(self.active_rect()); | |
| if let Some(clip) = self.viewport_state.clip() { | |
| let ClipShape::AxisAlignedRect(clip_rect) = clip.shape else { | |
| return None; | |
| }; | |
| transformed_rect = transformed_rect.intersect(clip_rect); | |
| } | |
| // Can't handle mirrored or zero-sized rectangles. | |
| if transformed_rect.is_zero_area() { | |
| return None; | |
| } | |
| Some(transformed_rect) | |
| } | |
| /// Stroke a rectangle. | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if the paint uses a destructive blend mode or requires a disabled feature. | |
| #[track_caller] | |
| pub fn stroke_rect( | |
| &mut self, | |
| rect: &Rect, | |
| stroke: &Stroke, | |
| paint: impl Into<Paint>, | |
| transform: Affine, | |
| ) { | |
| self.stroke_path(&rect.to_path(DEFAULT_TOLERANCE), stroke, paint, transform); | |
| } | |
| /// Fill a blurred rounded rectangle. | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if the `blurred_rounded_rect` feature is disabled or `blend_mode` is destructive. | |
| #[track_caller] | |
| pub fn fill_blurred_rounded_rect( | |
| &mut self, | |
| shape: &BlurredRoundedRect, | |
| blend_mode: BlendMode, | |
| transform: Affine, | |
| ) { | |
| if !cfg!(feature = "blurred_rounded_rect") { | |
| panic!("blurred rounded rectangles require the `blurred_rounded_rect` feature"); | |
| } | |
| let transform = self.path_transform(transform); | |
| let Some(encoded) = shape.encode_into(&mut self.encoded_paints, transform, false) else { | |
| return; | |
| }; | |
| self.with_optional_blend_layer(blend_mode, |ctx| { | |
| let rect = shape.rect.abs(); | |
| let kernel_size = 2.5 * shape.std_dev; | |
| let inflated_rect = rect.inflate(f64::from(kernel_size), f64::from(kernel_size)); | |
| if let Some(bounds) = ctx.fast_rect_bounds(&inflated_rect, transform) { | |
| ctx.recorder | |
| .push_draw(RecordedDraw::new_rect(bounds, encoded), &[]); | |
| return; | |
| } | |
| if let Some(transformed_rect) = | |
| into_fast_path_rect(inflated_rect, &transform, ctx.aliasing_threshold()) | |
| { | |
| ctx.record_generated_path(encoded, |strip_generator, strip_storage, clip_path| { | |
| strip_generator.generate_filled_rect_fast( | |
| &transformed_rect, | |
| strip_storage, | |
| clip_path, | |
| ); | |
| }); | |
| } else { | |
| ctx.fill_path_with( | |
| &inflated_rect.to_path(DEFAULT_TOLERANCE), | |
| transform, | |
| Fill::NonZero, | |
| encoded, | |
| ); | |
| } | |
| }); | |
| } | |
| /// Fill `path` with a blurred rounded rectangle. | |
| /// | |
| /// This effectively draws the blurred rounded rectangle clipped to `path`. If just the blurred | |
| /// rounded rectangle is desired without clipping, use the simpler | |
| /// [`Self::fill_blurred_rounded_rect`], which will be easier to use for many users. | |
| /// | |
| /// When `invert` is `false`, the color is applied with the coverage (`alpha`) of the blurred | |
| /// rounded rectangle. Points which are more than approximately 2.5 times `shape.std_dev` | |
| /// outside of the edges of `shape.rect` will not be perceptibly painted to, but calculations | |
| /// will still be performed for them. So for performance reasons, `path` should not extend | |
| /// further than that. | |
| /// | |
| /// When `invert` is `true`, the inverse (`1 - alpha`) of that coverage is applied instead. The | |
| /// coverage then falls off towards the inside of `shape.rect`, and is effectively full at all | |
| /// points of `path` which are more than approximately 2.5 times `shape.std_dev` outside of the | |
| /// edges of `shape.rect`. This means that the extent of the painted area is determined only by | |
| /// `path`, which can extend as far beyond `shape.rect` as is needed. This can be used to | |
| /// implement inset box shadows, by using the box as `path`, the box shrunk by the spread of the | |
| /// shadow and translated by its offset as `shape.rect`, and the corner radius of the box | |
| /// reduced by the spread as `shape.radius`. | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if the `blurred_rounded_rect` feature is disabled or `blend_mode` is destructive. | |
| #[track_caller] | |
| pub fn fill_blurred_rounded_rect_in( | |
| &mut self, | |
| path: &BezPath, | |
| fill: Fill, | |
| shape: &BlurredRoundedRect, | |
| invert: bool, | |
| blend_mode: BlendMode, | |
| transform: Affine, | |
| ) { | |
| if !cfg!(feature = "blurred_rounded_rect") { | |
| panic!("blurred rounded rectangles require the `blurred_rounded_rect` feature"); | |
| } | |
| let transform = self.path_transform(transform); | |
| let Some(encoded) = shape.encode_into(&mut self.encoded_paints, transform, invert) else { | |
| return; | |
| }; | |
| self.with_optional_blend_layer(blend_mode, |ctx| { | |
| ctx.fill_path_with(path, transform, fill, encoded); | |
| }); | |
| } | |
| /// Creates a builder for drawing a run of glyphs that have the same attributes. | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if the paint uses a destructive blend mode or requires a disabled feature. | |
| #[cfg(feature = "text")] | |
| #[track_caller] | |
| pub fn glyph_run<'a>( | |
| &'a mut self, | |
| resources: &'a mut Resources, | |
| font: &FontData, | |
| paint: impl Into<Paint>, | |
| transform: Affine, | |
| ) -> GlyphRunBuilder<'a> { | |
| let paint = paint.into(); | |
| assert_paint_supported(&paint.brush); | |
| glifo::GlyphRunBuilder::new( | |
| font.clone(), | |
| transform, | |
| paint, | |
| crate::text::GpuGlyphRunBackend { | |
| scene: self, | |
| resources, | |
| atlas_cache_enabled: false, | |
| }, | |
| ) | |
| } | |
| /// Push a new layer with the given transform. | |
| pub fn push_layer(&mut self, layer: Layer<'_>, transform: Affine) { | |
| let layer_transform = self.path_transform(transform); | |
| let filter_data = layer | |
| .filter | |
| .map(|filter| FilterData::new(filter, layer_transform)); | |
| if let Some(filter_plan) = &filter_data { | |
| self.viewport_state.push_root_viewport(filter_plan); | |
| } | |
| let clip_path = layer.clip.map(|clip| { | |
| let mut strip_storage = self.strip_storage.borrow_mut(); | |
| let strip_start = strip_storage.strips.len(); | |
| self.viewport_state | |
| .with_generator_and_clip(|strip_generator, existing_clip| { | |
| strip_generator.generate_filled_path( | |
| clip.path, | |
| clip.fill, | |
| layer_transform, | |
| &mut strip_storage, | |
| existing_clip.map(|clip| clip.path), | |
| ); | |
| let strip_range = strip_start..strip_storage.strips.len(); | |
| LayerClip { | |
| bbox: strip_bbox(&strip_storage.strips[strip_range.clone()]) | |
| .unwrap_or(RectU16::ZERO), | |
| strip_range, | |
| thread_idx: 0, | |
| } | |
| }) | |
| }); | |
| self.recorder.push_layer( | |
| LayerProps { | |
| blend_mode: layer.blend_mode, | |
| opacity: layer.opacity, | |
| mask: None, | |
| clip_path, | |
| }, | |
| filter_data, | |
| ); | |
| } | |
| /// Pop the last pushed layer. | |
| pub fn pop_layer(&mut self) { | |
| if self.recorder.pop_layer() == PoppedLayer::Filter { | |
| self.viewport_state.pop_root_viewport(); | |
| } | |
| } | |
| #[track_caller] | |
| fn with_optional_blend_layer<F, T>(&mut self, blend_mode: BlendMode, f: F) -> T | |
| where | |
| F: FnOnce(&mut Self) -> T, | |
| { | |
| if blend_mode == BlendMode::default() { | |
| return f(self); | |
| } | |
| assert!( | |
| !blend_mode.is_destructive(), | |
| "destructive blend modes are currently not supported" | |
| ); | |
| let layer = Layer::default().with_blend_mode(blend_mode); | |
| self.push_layer(layer, Affine::IDENTITY); | |
| let result = f(self); | |
| self.pop_layer(); | |
| result | |
| } | |
| /// Reset scene to default values. | |
| pub fn reset(&mut self) { | |
| self.viewport_state.reset(self.width, self.height); | |
| { | |
| let mut ss = self.strip_storage.borrow_mut(); | |
| ss.clear(); | |
| } | |
| self.encoded_paints.clear(); | |
| self.recorder.reset(self.width, self.height); | |
| } | |
| /// Reset the scene according to `options`. | |
| pub fn reset_with(&mut self, options: ResetOptions) { | |
| let (width, height) = options.size.unwrap_or((self.width, self.height)); | |
| if options.shrink { | |
| *self = Self::new_with(width, height, self.settings); | |
| } else { | |
| self.width = width; | |
| self.height = height; | |
| self.reset(); | |
| } | |
| } | |
| /// Get the width of the render context. | |
| pub fn width(&self) -> u16 { | |
| self.width | |
| } | |
| /// Get the height of the render context. | |
| pub fn height(&self) -> u16 { | |
| self.height | |
| } | |
| } | |
| #[cfg(feature = "probe")] | |
| impl vello_common::probe::ProbeRenderer for Scene { | |
| fn fill_path(&mut self, path: &BezPath, paint: &Paint, transform: Affine) { | |
| Self::fill_path(self, path, Fill::NonZero, paint, transform); | |
| } | |
| fn fill_rect(&mut self, rect: &Rect, paint: &Paint, transform: Affine) { | |
| Self::fill_rect(self, rect, paint, transform); | |
| } | |
| fn fill_blurred_rounded_rect(&mut self, shape: &BlurredRoundedRect) { | |
| Self::fill_blurred_rounded_rect(self, shape, BlendMode::default(), Affine::IDENTITY); | |
| } | |
| fn push_layer(&mut self, blend_mode: BlendMode, opacity: f32, filter: Option<Filter>) { | |
| let layer = Layer { | |
| blend_mode, | |
| opacity, | |
| filter, | |
| ..Layer::default() | |
| }; | |
| Self::push_layer(self, layer, Affine::IDENTITY); | |
| } | |
| fn pop_layer(&mut self) { | |
| Self::pop_layer(self); | |
| } | |
| } | |
| #[track_caller] | |
| fn assert_paint_supported(paint: &Brush) { | |
| match paint { | |
| Brush::Solid(_) => {} | |
| Brush::Gradient(gradient) => assert!( | |
| cfg!(feature = "gradient_sweep") || !matches!(gradient.kind, GradientKind::Sweep(_)), | |
| "sweep gradients require the `gradient_sweep` feature" | |
| ), | |
| Brush::Image(image) => assert!( | |
| cfg!(feature = "full_image_support") | |
| || crate::paint::supports_native_image( | |
| &image.image.image, | |
| image.image.sampler.quality, | |
| image.tint, | |
| ), | |
| "extended image sampling requires the `full_image_support` feature" | |
| ), | |
| } | |
| } | |
| #[cfg(test)] | |
| mod tests { | |
| use super::{RecordedDraw, ResetOptions, Scene}; | |
| #[cfg(all(feature = "text", feature = "full_image_support"))] | |
| use crate::resources::Resources; | |
| #[cfg(all(feature = "text", feature = "full_image_support"))] | |
| use alloc::sync::Arc; | |
| #[cfg(all(feature = "text", feature = "full_image_support"))] | |
| use glifo::Glyph; | |
| use vello_common::TextureId; | |
| use vello_common::geometry::RectU16; | |
| use vello_common::kurbo::{Affine, BezPath, Rect}; | |
| use vello_common::paint::{Image, ImageSource, PaintHandle, PremulColor, TextureRegion}; | |
| use vello_common::peniko::color::palette::css::{BLACK, BLUE}; | |
| #[cfg(all(feature = "text", feature = "full_image_support"))] | |
| use vello_common::peniko::{Blob, FontData}; | |
| use vello_common::peniko::{Fill, ImageSampler}; | |
| use vello_common::record::Drawable; | |
| #[test] | |
| fn recorded_rect_bbox_rounds_fractional_outward() { | |
| let draw = RecordedDraw::new_rect( | |
| Rect::new(0.0, 0.0, 4.5, 4.5), | |
| PaintHandle::Solid(PremulColor::from_alpha_color(BLUE)), | |
| ); | |
| assert_eq!(draw.bbox(&[]), Some(RectU16::new(0, 0, 8, 8))); | |
| } | |
| #[test] | |
| fn rectangular_clip_keeps_direct_rect_draw_path() { | |
| let mut scene = Scene::new(100, 100); | |
| scene.push_clip_rect(&Rect::new(10.25, 5.5, 80.75, 90.0), Affine::IDENTITY); | |
| scene.push_clip_rect(&Rect::new(20.5, 0.0, 70.25, 60.75), Affine::IDENTITY); | |
| scene.fill_rect(&Rect::new(0.0, 20.25, 50.5, 80.0), BLACK, Affine::IDENTITY); | |
| let RecordedDraw::Rect(rect) = &scene.recorder.draws[0] else { | |
| panic!("expected a directly recorded rectangle"); | |
| }; | |
| assert_eq!(rect.rect, Rect::new(20.5, 20.25, 50.5, 60.75)); | |
| assert!(scene.strip_storage.borrow().strips.is_empty()); | |
| } | |
| #[test] | |
| fn reset_with_size_updates_scene_size() { | |
| for shrink in [false, true] { | |
| let mut scene = Scene::new(8, 4); | |
| scene.reset_with(ResetOptions { | |
| size: Some((4, 8)), | |
| shrink, | |
| }); | |
| assert_eq!(scene.width(), 4); | |
| assert_eq!(scene.height(), 8); | |
| assert_eq!(scene.recorder.scene_size.width(), 4); | |
| assert_eq!(scene.recorder.scene_size.height(), 8); | |
| scene.fill_rect(&Rect::new(0.0, 0.0, 8.0, 8.0), BLUE, Affine::IDENTITY); | |
| let RecordedDraw::Rect(rect) = &scene.recorder.draws[0] else { | |
| panic!("expected a recorded rectangle"); | |
| }; | |
| assert_eq!(rect.rect, Rect::new(0.0, 0.0, 4.0, 8.0)); | |
| } | |
| } | |
| #[test] | |
| fn empty_generated_path_is_not_recorded() { | |
| let mut scene = Scene::new(100, 100); | |
| scene.fill_path(&BezPath::new(), Fill::NonZero, BLACK, Affine::IDENTITY); | |
| assert!(scene.strip_storage.borrow().strips.is_empty()); | |
| assert!(scene.recorder.draws.is_empty()); | |
| assert!(scene.recorder.nodes.is_empty()); | |
| } | |
| #[test] | |
| fn zero_area_external_texture_rect_is_a_noop() { | |
| let mut scene = Scene::new(100, 100); | |
| let image = Image { | |
| image: ImageSource::external_texture(TextureId(7), TextureRegion::Full, false), | |
| sampler: ImageSampler::default(), | |
| }; | |
| scene.fill_rect(&Rect::new(10.0, 10.0, 10.0, 20.0), image, Affine::IDENTITY); | |
| assert!(scene.encoded_paints.is_empty()); | |
| assert!(scene.strip_storage.borrow().strips.is_empty()); | |
| assert!(scene.recorder.draws.is_empty()); | |
| assert!(scene.recorder.nodes.is_empty()); | |
| } | |
| #[cfg(all(feature = "text", feature = "full_image_support"))] | |
| #[test] | |
| fn glyph_atlas_resources_are_lazy() { | |
| const ROBOTO_FONT: &[u8] = include_bytes!("../../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 scene = Scene::new(200, 200); | |
| let mut resources = Resources::new( | |
| vello_common::multi_atlas::AtlasConfig::default(), | |
| crate::HintCacheConfig::default(), | |
| ); | |
| let mut triangle = BezPath::new(); | |
| triangle.move_to((10.0, 10.0)); | |
| triangle.line_to((90.0, 50.0)); | |
| triangle.line_to((10.0, 90.0)); | |
| triangle.close_path(); | |
| scene.fill_rect(&Rect::new(10.0, 10.0, 50.0, 50.0), BLACK, Affine::IDENTITY); | |
| scene.fill_path(&triangle, Fill::NonZero, BLACK, Affine::IDENTITY); | |
| scene | |
| .glyph_run(&mut resources, &font, BLACK, Affine::IDENTITY) | |
| .fill_glyphs(glyphs.into_iter()) | |
| .unwrap(); | |
| assert!(resources.glyph_resources.is_none()); | |
| scene | |
| .glyph_run(&mut resources, &font, BLACK, Affine::IDENTITY) | |
| .atlas_cache(true) | |
| .fill_glyphs(glyphs.into_iter()) | |
| .unwrap(); | |
| assert!(resources.glyph_resources.is_some()); | |
| } | |
| } |