use std::sync::Arc;
use crate::filters::FilterImage;
use crate::{
AntiAliasing, BoxShadowKind, Filter, Glyph, MaskMode, NonUniformRoundedRect, NormalizedCoord,
Paint, PaintRef, PaintScene, RenderContext,
};
use kurbo::{Affine, BezPath, Shape, Stroke, Vec2};
use peniko::{BlendMode, Color, Fill, FontData, Style, StyleRef};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
const DEFAULT_TOLERANCE: f64 = 0.1;
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum RenderCommand<Font = FontData, Brush = Paint, Image = FilterImage> {
PushLayer(LayerCommand<Image>),
PushClipLayer(ClipCommand),
PushMaskLayer(MaskLayerCommand),
PopLayer,
Stroke(StrokeCommand<Brush>),
Fill(FillCommand<Brush>),
GlyphRun(GlyphRunCommand<Font, Brush>),
BoxShadow(BoxShadowCommand),
}
impl RenderCommand {
fn apply_transform(mut self, transform: Affine) -> Self {
match &mut self {
RenderCommand::PushLayer(cmd) => cmd.transform = transform * cmd.transform,
RenderCommand::PushClipLayer(cmd) => cmd.transform = transform * cmd.transform,
RenderCommand::PushMaskLayer(cmd) => cmd.transform = transform * cmd.transform,
RenderCommand::PopLayer => {}
RenderCommand::Stroke(cmd) => cmd.transform = transform * cmd.transform,
RenderCommand::Fill(cmd) => cmd.transform = transform * cmd.transform,
RenderCommand::GlyphRun(cmd) => cmd.transform = transform * cmd.transform,
RenderCommand::BoxShadow(cmd) => cmd.transform = transform * cmd.transform,
};
self
}
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct LayerCommand<Image = FilterImage> {
#[cfg_attr(feature = "serde", serde(default))]
pub fill: Fill,
pub blend: BlendMode,
pub alpha: f32,
pub transform: Affine,
#[cfg_attr(feature = "serde", serde(with = "svg_path"))]
pub clip: BezPath, pub filter: Option<Arc<Filter<Image>>>,
pub backdrop_filter: Option<Arc<Filter<Image>>>,
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ClipCommand {
#[cfg_attr(feature = "serde", serde(default))]
pub fill: Fill,
pub transform: Affine,
#[cfg_attr(feature = "serde", serde(with = "svg_path"))]
pub clip: BezPath, }
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MaskLayerCommand {
#[cfg_attr(feature = "serde", serde(default))]
pub fill: Fill,
pub mode: MaskMode,
pub transform: Affine,
#[cfg_attr(feature = "serde", serde(with = "svg_path"))]
pub clip: BezPath, }
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct StrokeCommand<Brush = Paint> {
pub style: Stroke,
pub transform: Affine,
pub brush: Brush, pub brush_transform: Option<Affine>,
#[cfg_attr(feature = "serde", serde(with = "svg_path"))]
pub shape: BezPath, #[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "AntiAliasing::is_enabled")
)]
pub anti_aliasing: AntiAliasing,
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FillCommand<Brush = Paint> {
pub fill: Fill,
pub transform: Affine,
pub brush: Brush, pub brush_transform: Option<Affine>,
#[cfg_attr(feature = "serde", serde(with = "svg_path"))]
pub shape: BezPath, #[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "AntiAliasing::is_enabled")
)]
pub anti_aliasing: AntiAliasing,
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct GlyphRunCommand<Font = FontData, Brush = Paint> {
pub font_data: Font,
pub font_size: f32,
pub hint: bool,
pub normalized_coords: Vec<NormalizedCoord>,
#[cfg_attr(feature = "serde", serde(default = "Default::default"))]
pub embolden: kurbo::Vec2,
pub style: Style,
pub brush: Brush,
pub brush_alpha: f32,
pub transform: Affine,
pub glyph_transform: Option<Affine>,
pub glyphs: Vec<Glyph>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "AntiAliasing::is_enabled")
)]
pub anti_aliasing: AntiAliasing,
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BoxShadowCommand {
pub transform: Affine,
pub box_shape: NonUniformRoundedRect,
pub offset: Vec2,
pub spread: f64,
pub std_dev: f64,
pub color: Color,
pub kind: BoxShadowKind,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Scene {
pub tolerance: f64,
pub commands: Vec<RenderCommand>,
}
impl Default for Scene {
fn default() -> Self {
Self {
tolerance: DEFAULT_TOLERANCE,
commands: Vec::new(),
}
}
}
impl Scene {
pub fn new() -> Self {
Self::default()
}
pub fn with_tolerance(tolerance: f64) -> Self {
Self {
tolerance,
commands: Vec::new(),
}
}
fn convert_paint(&mut self, paint_ref: PaintRef<'_>) -> Paint {
match paint_ref {
Paint::Solid(color) => Paint::Solid(color),
Paint::Gradient(gradient) => Paint::Gradient(gradient.clone()),
Paint::Image(image) => Paint::Image(image.to_owned()),
Paint::Resource(id) => Paint::Resource(id),
Paint::Custom(_) => Paint::Solid(Color::TRANSPARENT),
Paint::Pattern(pattern) => Paint::Pattern(pattern.clone()),
}
}
pub fn replay<S: PaintScene + ?Sized>(&self, painter: &mut S, transform: Affine) {
for cmd in &self.commands {
match cmd {
RenderCommand::PushLayer(cmd) => painter.push_layer(
cmd.fill,
cmd.blend,
cmd.alpha,
transform * cmd.transform,
&cmd.clip,
cmd.filter.clone(),
cmd.backdrop_filter.clone(),
),
RenderCommand::PushClipLayer(cmd) => {
painter.push_clip_layer(cmd.fill, transform * cmd.transform, &cmd.clip)
}
RenderCommand::PushMaskLayer(cmd) => painter.push_mask_layer(
cmd.fill,
cmd.mode,
transform * cmd.transform,
&cmd.clip,
),
RenderCommand::PopLayer => painter.pop_layer(),
RenderCommand::Stroke(cmd) => painter.stroke(
&cmd.style,
transform * cmd.transform,
cmd.brush.as_ref(),
cmd.brush_transform,
&cmd.shape,
cmd.anti_aliasing,
),
RenderCommand::Fill(cmd) => painter.fill(
cmd.fill,
transform * cmd.transform,
cmd.brush.as_ref(),
cmd.brush_transform,
&cmd.shape,
cmd.anti_aliasing,
),
RenderCommand::GlyphRun(cmd) => painter.draw_glyphs(
&cmd.font_data,
cmd.font_size,
cmd.hint,
&cmd.normalized_coords,
cmd.embolden,
&cmd.style,
cmd.brush.as_ref(),
cmd.brush_alpha,
transform * cmd.transform,
cmd.glyph_transform,
cmd.glyphs.iter().copied(),
cmd.anti_aliasing,
),
RenderCommand::BoxShadow(cmd) => painter.draw_box_shadow(
transform * cmd.transform,
&cmd.box_shape,
cmd.offset,
cmd.spread,
cmd.std_dev,
cmd.color,
cmd.kind,
),
}
}
}
}
impl RenderContext for Scene {}
impl PaintScene for Scene {
fn reset(&mut self) {
self.commands.clear()
}
fn push_layer(
&mut self,
fill: Fill,
blend: impl Into<BlendMode>,
alpha: f32,
transform: Affine,
clip: &impl Shape,
filter: Option<Arc<Filter>>,
backdrop_filter: Option<Arc<Filter>>,
) {
let blend = blend.into();
let clip = clip.into_path(self.tolerance);
let layer = LayerCommand {
fill,
blend,
alpha,
transform,
clip,
filter,
backdrop_filter,
};
self.commands.push(RenderCommand::PushLayer(layer));
}
fn push_clip_layer(&mut self, fill: Fill, transform: Affine, clip: &impl Shape) {
let clip = clip.into_path(self.tolerance);
let layer = ClipCommand {
fill,
transform,
clip,
};
self.commands.push(RenderCommand::PushClipLayer(layer));
}
fn push_mask_layer(
&mut self,
fill: Fill,
mode: MaskMode,
transform: Affine,
clip: &impl Shape,
) {
let clip = clip.into_path(self.tolerance);
let layer = MaskLayerCommand {
fill,
mode,
transform,
clip,
};
self.commands.push(RenderCommand::PushMaskLayer(layer));
}
fn pop_layer(&mut self) {
self.commands.push(RenderCommand::PopLayer);
}
fn stroke<'a>(
&mut self,
style: &Stroke,
transform: Affine,
paint_ref: impl Into<PaintRef<'a>>,
brush_transform: Option<Affine>,
shape: &impl Shape,
anti_aliasing: AntiAliasing,
) {
let shape = shape.into_path(self.tolerance);
let brush = self.convert_paint(paint_ref.into());
let stroke = StrokeCommand {
style: style.clone(),
transform,
brush,
brush_transform,
shape,
anti_aliasing,
};
self.commands.push(RenderCommand::Stroke(stroke));
}
fn fill<'a>(
&mut self,
style: Fill,
transform: Affine,
paint: impl Into<PaintRef<'a>>,
brush_transform: Option<Affine>,
shape: &impl Shape,
anti_aliasing: AntiAliasing,
) {
let shape = shape.into_path(self.tolerance);
let brush = self.convert_paint(paint.into());
let fill = FillCommand {
fill: style,
transform,
brush,
brush_transform,
shape,
anti_aliasing,
};
self.commands.push(RenderCommand::Fill(fill));
}
fn draw_glyphs<'a, 's: 'a>(
&'a mut self,
font: &'a FontData,
font_size: f32,
hint: bool,
normalized_coords: &'a [NormalizedCoord],
embolden: kurbo::Vec2,
style: impl Into<StyleRef<'a>>,
paint_ref: impl Into<PaintRef<'a>>,
brush_alpha: f32,
transform: Affine,
glyph_transform: Option<Affine>,
glyphs: impl Iterator<Item = Glyph>,
anti_aliasing: AntiAliasing,
) {
let brush = self.convert_paint(paint_ref.into());
let glyph_run = GlyphRunCommand {
font_data: font.clone(),
font_size,
hint,
normalized_coords: normalized_coords.to_vec(),
embolden,
style: style.into().to_owned(),
brush,
brush_alpha,
transform,
glyph_transform,
glyphs: glyphs.into_iter().collect(),
anti_aliasing,
};
self.commands.push(RenderCommand::GlyphRun(glyph_run));
}
fn draw_box_shadow(
&mut self,
transform: Affine,
box_shape: &NonUniformRoundedRect,
offset: Vec2,
spread: f64,
std_dev: f64,
color: Color,
kind: BoxShadowKind,
) {
let box_shadow = BoxShadowCommand {
transform,
box_shape: *box_shape,
offset,
spread,
std_dev,
color,
kind,
};
self.commands.push(RenderCommand::BoxShadow(box_shadow));
}
fn append_scene(&mut self, scene: Scene, scene_transform: Affine) {
self.commands.extend(
scene
.commands
.into_iter()
.map(|cmd| cmd.apply_transform(scene_transform)),
);
}
}
#[cfg(feature = "serde")]
mod svg_path {
use kurbo::BezPath;
use serde::{self, Deserialize, Deserializer, Serializer};
use crate::svg_path_parser;
pub fn serialize<S>(path: &BezPath, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&path.to_svg())
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<BezPath, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
svg_path_parser::parse_svg_path(&s).map_err(serde::de::Error::custom)
}
}