use crate::renderer::{ ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, paint_draws_by_its_colors, painted_gradient, spread_adjusted_samples, svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint, }; use crate::{Render, RenderSvgSegmentList, SvgRender}; use core_types::color::SRGBA8; use core_types::list::List; use core_types::uuid::generate_uuid; use core_types::{ATTR_TRANSFORM, Color}; use glam::{DAffine2, DVec2}; use graphic_types::Graphic; use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin}; use std::fmt::Write; use vector_types::Gradient; use vector_types::gradient::GradientSpread; #[derive(Copy, Clone, PartialEq)] pub enum PaintTarget { Fill, Stroke, } impl PaintTarget { fn paint_attr(self) -> &'static str { match self { Self::Fill => "fill", Self::Stroke => "stroke", } } fn opacity_attr(self) -> &'static str { match self { Self::Fill => "fill-opacity", Self::Stroke => "stroke-opacity", } } } pub trait RenderExt { type Output; /// `user_to_document` maps the user space the painted element sits in, before its `element_transform`, into the document, and the filters reading the element read it `paint_reach` past the view, in document pixels. #[allow(clippy::too_many_arguments)] fn render( &self, svg_defs: &mut String, user_to_document: DAffine2, paint_reach: f64, item_transform: DAffine2, element_transform: DAffine2, stroke_transform: DAffine2, bounds: DAffine2, render_params: &RenderParams, target: PaintTarget, ) -> Self::Output; } /// The paint attribute for an already-faded solid color, or the SVG `none` keyword when the color is absent. fn render_color_paint(color: Option, target: PaintTarget) -> String { let Some(color) = color else { return format!(r#" {}="none""#, target.paint_attr()) }; let mut result = format!(r##" {}="#{}""##, target.paint_attr(), SRGBA8::from(color).to_rgb_hex()); if color.a() < 1. { let _ = write!(result, r#" {}="{}""#, target.opacity_attr(), (color.a() * 1000.).round() / 1000.); } result } impl RenderExt for List { type Output = String; fn render( &self, _svg_defs: &mut String, _user_to_document: DAffine2, _paint_reach: f64, _item_transform: DAffine2, _element_transform: DAffine2, _stroke_transform: DAffine2, _bounds: DAffine2, render_params: &RenderParams, target: PaintTarget, ) -> Self::Output { render_color_paint(composite_paint_colors(self, render_params.for_mask), target) } } /// Adds one gradient item's paint server into `svg_defs` and returns its ID, or `None` when the item is absent or paints nothing. /// One painted through a mask fills a pattern spanning `bounds`, which `stroke_transform` places in the painted element's space. /// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_fill_and_opacity`] explains. fn render_gradient_paint( item: Option>, svg_defs: &mut String, item_transform: DAffine2, element_transform: DAffine2, stroke_transform: DAffine2, bounds: DAffine2, for_mask: bool, ) -> Option { let mut stop = String::new(); let item = item?; let (stops, settings, paint_opacity) = painted_gradient(item, for_mask)?; let shape = gradient_shape(item); let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start()); with_two_stops_at_least(shape, &mut samples); if paint_opacity < 1. { for (_, color, _) in &mut samples { *color = color.with_alpha(color.a() * paint_opacity); } } for &(position, color, original_midpoint) in &samples { stop.push_str("") } // A gradient with no stops paints as solid black, matching `Gradient::evaluate` (a stopless def would otherwise render as no paint per the SVG spec) if stop.is_empty() { stop.push_str(r##""); } // Need to cancel out the element's transform as it is already applied to the path itself. let element_transform_inverse = if transform_is_invertible(element_transform) { element_transform.inverse() } else { DAffine2::IDENTITY }; let document_transform = item_transform * local_gradient_transform; let gradient_transform = element_transform_inverse * gradient_placement(document_transform, shape); let gradient_spread = if matches!(settings.spread, GradientSpread::Pad | GradientSpread::Clear) { String::new() } else { format!(r#" spreadMethod="{}""#, settings.spread.svg_name()) }; // A paint drawn through a mask fills a pattern of the box around the painted area, which the masks are drawn over let masked = svg_gradient_standard(shape).is_some_and(|gradient| gradient.is_masked()); let pattern_area = if masked { let inverse = |length: f64| if length > 0. { 1. / length } else { 0. }; let inflate = DVec2::new(inverse(item_transform.matrix2.x_axis.length()), inverse(item_transform.matrix2.y_axis.length())); let (local_min, local_max) = (bounds.transform_point2(DVec2::ZERO) - inflate, bounds.transform_point2(DVec2::ONE) + inflate); let corners = [local_min, DVec2::new(local_max.x, local_min.y), DVec2::new(local_min.x, local_max.y), local_max].map(|corner| stroke_transform.transform_point2(corner)); let min = corners.into_iter().reduce(DVec2::min)?; let size = corners.into_iter().reduce(DVec2::max)? - min; if !(size.x > 0. && size.y > 0. && size.is_finite() && min.is_finite()) { return None; } Some((min, size)) } else { None }; let area = pattern_area.map_or(String::new(), |(min, size)| format!(r#"rect x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, size.x, size.y)); let layers = write_svg_gradient_paint(svg_defs, shape, &samples, &stop, &gradient_spread, gradient_transform, &area); if let [SvgGradientLayer { paint, mask: None }] = layers.as_slice() { return Some(*paint); } let (min, size) = pattern_area?; let pattern_id = generate_uuid(); let _ = write!( svg_defs, r#""#, min.x, min.y, size.x, size.y, min.x, min.y, size.x, size.y ); for SvgGradientLayer { paint, mask } in layers { let mask = mask.map(|mask| format!(r#" mask="url(#{mask})""#)).unwrap_or_default(); let _ = write!(svg_defs, r#"<{area} fill="url(#{paint})"{mask} />"#); } svg_defs.push_str(""); Some(pattern_id) } impl RenderExt for List { type Output = Option; /// Adds the gradient def through mutating the first argument, returning the gradient ID, or `None` when the list is empty. fn render( &self, svg_defs: &mut String, _user_to_document: DAffine2, _paint_reach: f64, item_transform: DAffine2, element_transform: DAffine2, stroke_transform: DAffine2, bounds: DAffine2, render_params: &RenderParams, _target: PaintTarget, ) -> Self::Output { render_gradient_paint( (!self.is_empty()).then_some(ItemRef::ListItem(self, 0)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask, ) } } impl RenderExt for Stroke { type Output = String; /// Provide the shape-related SVG attributes for the stroke. The paint-related attributes for the stroke are generated from `Graphic::render` with `PaintTarget::Stroke`. fn render( &self, _svg_defs: &mut String, _user_to_document: DAffine2, _paint_reach: f64, _item_transform: DAffine2, _element_transform: DAffine2, _stroke_transform: DAffine2, _bounds: DAffine2, render_params: &RenderParams, _target: PaintTarget, ) -> Self::Output { // Don't render a stroke at all if it would be invisible if !self.has_renderable_stroke() { return String::new(); } let default_weight = if self.align != StrokeAlign::Center && render_params.aligned_strokes { 1. / 2. } else { 1. }; // Set to None if the value is the SVG default let weight = (self.weight != default_weight).then_some(self.weight); let dash_array = (!self.dash_lengths.is_empty()).then_some(self.dash_lengths()); let dash_offset = (self.dash_offset != 0.).then_some(self.dash_offset); let stroke_cap = (self.cap != StrokeCap::Butt).then_some(self.cap); let stroke_join = (self.join != StrokeJoin::Miter).then_some(self.join); let stroke_join_miter_limit = (self.join_miter_limit != 4.).then_some(self.join_miter_limit); let stroke_align = (self.align != StrokeAlign::Center).then_some(self.align); // Render the needed stroke attributes let mut attributes = String::new(); if let Some(mut weight) = weight { if stroke_align.is_some() && render_params.aligned_strokes { weight *= 2.; } let _ = write!(&mut attributes, r#" stroke-width="{weight}""#); } if let Some(dash_array) = dash_array { let _ = write!(&mut attributes, r#" stroke-dasharray="{dash_array}""#); } if let Some(dash_offset) = dash_offset { let _ = write!(&mut attributes, r#" stroke-dashoffset="{dash_offset}""#); } if let Some(stroke_cap) = stroke_cap { let _ = write!(&mut attributes, r#" stroke-linecap="{}""#, stroke_cap.svg_name()); } if let Some(stroke_join) = stroke_join { let _ = write!(&mut attributes, r#" stroke-linejoin="{}""#, stroke_join.svg_name()); } if let Some(stroke_join_miter_limit) = stroke_join_miter_limit { let _ = write!(&mut attributes, r#" stroke-miterlimit="{stroke_join_miter_limit}""#); } if render_params.stroke_below { let _ = write!(&mut attributes, r#" style="paint-order: stroke;" "#); } attributes } } impl RenderExt for Graphic { type Output = String; fn render( &self, svg_defs: &mut String, user_to_document: DAffine2, paint_reach: f64, item_transform: DAffine2, element_transform: DAffine2, stroke_transform: DAffine2, bounds: DAffine2, render_params: &RenderParams, target: PaintTarget, ) -> Self::Output { let paint_attr = target.paint_attr(); let by_colors = paint_draws_by_its_colors(self); match self { Graphic::Color(item) if by_colors => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target), Graphic::ColorList(color_list) if by_colors => color_list.render( svg_defs, user_to_document, paint_reach, item_transform, element_transform, stroke_transform, bounds, render_params, target, ), Graphic::Gradient(item) if by_colors => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask) .map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##)) .unwrap_or_else(|| format!(r#" {paint_attr}="none""#)), // One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do Graphic::GradientList(gradient_list) if by_colors => gradient_list .render( svg_defs, user_to_document, paint_reach, item_transform, element_transform, stroke_transform, bounds, render_params, target, ) .map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##)) .unwrap_or_else(|| format!(r#" {paint_attr}="none""#)), Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#), Graphic::Color(_) | Graphic::ColorList(_) | Graphic::Gradient(_) | Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Generator(_) | Graphic::Text(_) | Graphic::VectorList(_) | Graphic::RasterCPUList(_) | Graphic::RasterGPUList(_) | Graphic::GeneratorList(_) | Graphic::GraphicList(_) | Graphic::GradientList(_) | Graphic::TextList(_) | Graphic::StrokeList(_) => { let bounds = if target == PaintTarget::Stroke { // To prevent a wraparound artefact occurring when the tile boundary and the stroke region are perfectly aligned, the local coordinate is expanded slightly. let inverse = |len: f64| if len > 0. { 1. / len } else { 0. }; let inflate = DVec2::new(inverse(item_transform.matrix2.x_axis.length()), inverse(item_transform.matrix2.y_axis.length())); let min = bounds.transform_point2(DVec2::ZERO) - inflate; let max = bounds.transform_point2(DVec2::ONE) + inflate; DAffine2::from_scale_angle_translation(max - min, 0., min) } else { bounds }; let content_to_document = user_to_document * element_transform * stroke_transform; render_svg_pattern(svg_defs, self, content_to_document, paint_reach, stroke_transform, bounds, render_params) .map(|id| format!(r##" {paint_attr}="url(#{id})""##)) .unwrap_or_else(|| format!(r#" {paint_attr}="none""#)) } } } } /// Emits an SVG `` paint server into `svg_defs` that renders the given graphic as the paint content, and returns the pattern ID. /// Currently, this function is only used for clipping-based filling and stroking, not considering tiling yet. /// `content_to_document` maps the paint's own space, which `stroke_transform` places inside the painted element's `element_transform`, into the document, and the filters reading the element read it `paint_reach` past the view. fn render_svg_pattern( svg_defs: &mut String, paint: &Graphic, content_to_document: DAffine2, paint_reach: f64, stroke_transform: DAffine2, bounds: DAffine2, render_params: &RenderParams, ) -> Option { let min = bounds.transform_point2(DVec2::ZERO); let max = bounds.transform_point2(DVec2::ONE); let size = max - min; if size.x <= 0. || size.y <= 0. { return None; } // Render the pattern content recursively let mut content = SvgRender::new(); content.transform = content_to_document; content.ancestors_reach = paint_reach; paint.render_svg(&mut content, &render_params.for_pattern()); // Unwrap the inner def element write!(svg_defs, "{}", content.svg_defs).unwrap(); let pattern_transform = stroke_transform * DAffine2::from_translation(min); let transform_str = format_transform_matrix(pattern_transform); let transform_attr = if transform_str.is_empty() { String::new() } else { format!(r#" patternTransform="{transform_str}""#) }; let pattern_id = format!("pattern-{}", generate_uuid()); write!( svg_defs, r##""##, size.x, size.y, ) .unwrap(); let content_shift = format_transform_matrix(DAffine2::from_translation(-min)); write!(svg_defs, r##"{}"##, content.svg.to_svg_string()).unwrap(); Some(pattern_id) }