Extract gsvg_renderer from gcore, remove gcore/vello feature (#2760)

Extract `gsvg_renderer` from `gcore`, remove `gcore/vello` feature
This commit is contained in:
Firestar99
2025-06-27 15:47:46 +02:00
committed by GitHub
parent ffc6c5532b
commit 9c4ab34a58
26 changed files with 546 additions and 368 deletions

View File

@@ -1,5 +1,5 @@
use crate::math::math_ext::QuadExt;
use crate::renderer::Quad;
use crate::math::quad::Quad;
use crate::vector::PointId;
use bezier_rs::Subpath;
use glam::{DAffine2, DMat2, DVec2};

View File

@@ -1,70 +1,9 @@
//! Contains stylistic options for SVG elements.
use crate::Color;
use crate::consts::{LAYER_OUTLINE_STROKE_COLOR, LAYER_OUTLINE_STROKE_WEIGHT};
pub use crate::gradient::*;
use crate::renderer::{RenderParams, format_transform_matrix};
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use std::fmt::Write;
impl Gradient {
/// Adds the gradient def through mutating the first argument, returning the gradient ID.
fn render_defs(&self, svg_defs: &mut String, element_transform: DAffine2, stroke_transform: DAffine2, bounds: [DVec2; 2], transformed_bounds: [DVec2; 2], _render_params: &RenderParams) -> u64 {
// TODO: Figure out how to use `self.transform` as part of the gradient transform, since that field (`Gradient::transform`) is currently never read from, it's only written to.
let bound_transform = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
let transformed_bound_transform = element_transform * DAffine2::from_scale_angle_translation(transformed_bounds[1] - transformed_bounds[0], 0., transformed_bounds[0]);
let mut stop = String::new();
for (position, color) in self.stops.0.iter() {
stop.push_str("<stop");
if *position != 0. {
let _ = write!(stop, r#" offset="{}""#, (position * 1_000_000.).round() / 1_000_000.);
}
let _ = write!(stop, r##" stop-color="#{}""##, color.to_rgb_hex_srgb_from_gamma());
if color.a() < 1. {
let _ = write!(stop, r#" stop-opacity="{}""#, (color.a() * 1000.).round() / 1000.);
}
stop.push_str(" />")
}
let mod_gradient = if transformed_bound_transform.matrix2.determinant() != 0. {
transformed_bound_transform.inverse()
} else {
DAffine2::IDENTITY // Ignore if the transform cannot be inverted (the bounds are zero). See issue #1944.
};
let mod_points = element_transform * stroke_transform * bound_transform;
let start = mod_points.transform_point2(self.start);
let end = mod_points.transform_point2(self.end);
let gradient_id = crate::uuid::generate_uuid();
let matrix = format_transform_matrix(mod_gradient);
let gradient_transform = if matrix.is_empty() { String::new() } else { format!(r#" gradientTransform="{}""#, matrix) };
match self.gradient_type {
GradientType::Linear => {
let _ = write!(
svg_defs,
r#"<linearGradient id="{}" x1="{}" x2="{}" y1="{}" y2="{}"{gradient_transform}>{}</linearGradient>"#,
gradient_id, start.x, end.x, start.y, end.y, stop
);
}
GradientType::Radial => {
let radius = (f64::powi(start.x - end.x, 2) + f64::powi(start.y - end.y, 2)).sqrt();
let _ = write!(
svg_defs,
r#"<radialGradient id="{}" cx="{}" cy="{}" r="{}"{gradient_transform}>{}</radialGradient>"#,
gradient_id, start.x, start.y, radius, stop
);
}
}
gradient_id
}
}
use glam::DAffine2;
/// Describes the fill of a layer.
///
@@ -138,24 +77,6 @@ impl Fill {
}
}
/// Renders the fill, adding necessary defs through mutating the first argument.
pub fn render(&self, svg_defs: &mut String, element_transform: DAffine2, stroke_transform: DAffine2, bounds: [DVec2; 2], transformed_bounds: [DVec2; 2], render_params: &RenderParams) -> String {
match self {
Self::None => r#" fill="none""#.to_string(),
Self::Solid(color) => {
let mut result = format!(r##" fill="#{}""##, color.to_rgb_hex_srgb_from_gamma());
if color.a() < 1. {
let _ = write!(result, r#" fill-opacity="{}""#, (color.a() * 1000.).round() / 1000.);
}
result
}
Self::Gradient(gradient) => {
let gradient_id = gradient.render_defs(svg_defs, element_transform, stroke_transform, bounds, transformed_bounds, render_params);
format!(r##" fill="url('#{gradient_id}')""##)
}
}
}
/// Extract a gradient from the fill
pub fn as_gradient(&self) -> Option<&Gradient> {
match self {
@@ -279,7 +200,7 @@ pub enum StrokeCap {
}
impl StrokeCap {
fn svg_name(&self) -> &'static str {
pub fn svg_name(&self) -> &'static str {
match self {
StrokeCap::Butt => "butt",
StrokeCap::Round => "round",
@@ -299,7 +220,7 @@ pub enum StrokeJoin {
}
impl StrokeJoin {
fn svg_name(&self) -> &'static str {
pub fn svg_name(&self) -> &'static str {
match self {
StrokeJoin::Bevel => "bevel",
StrokeJoin::Miter => "miter",
@@ -469,60 +390,6 @@ impl Stroke {
self.join_miter_limit as f32
}
/// Provide the SVG attributes for the stroke.
pub fn render(&self, aligned_strokes: bool, override_paint_order: bool, _render_params: &RenderParams) -> String {
// Don't render a stroke at all if it would be invisible
let Some(color) = self.color else { return String::new() };
if !self.has_renderable_stroke() {
return String::new();
}
// Set to None if the value is the SVG default
let weight = (self.weight != 1.).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);
let paint_order = (self.paint_order != PaintOrder::StrokeAbove || override_paint_order).then_some(PaintOrder::StrokeBelow);
// Render the needed stroke attributes
let mut attributes = format!(r##" stroke="#{}""##, color.to_rgb_hex_srgb_from_gamma());
if color.a() < 1. {
let _ = write!(&mut attributes, r#" stroke-opacity="{}""#, (color.a() * 1000.).round() / 1000.);
}
if let Some(mut weight) = weight {
if stroke_align.is_some() && 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);
}
// Add vector-effect attribute to make strokes non-scaling
if self.non_scaling {
let _ = write!(&mut attributes, r#" vector-effect="non-scaling-stroke""#);
}
if paint_order.is_some() {
let _ = write!(&mut attributes, r#" style="paint-order: stroke;" "#);
}
attributes
}
pub fn with_color(mut self, color: &Option<Color>) -> Option<Self> {
self.color = *color;
@@ -604,8 +471,8 @@ impl Default for Stroke {
#[repr(C)]
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize, DynAny, specta::Type)]
pub struct PathStyle {
stroke: Option<Stroke>,
fill: Fill,
pub stroke: Option<Stroke>,
pub fill: Fill,
}
impl std::hash::Hash for PathStyle {
@@ -766,41 +633,6 @@ impl PathStyle {
pub fn clear_stroke(&mut self) {
self.stroke = None;
}
/// Renders the shape's fill and stroke attributes as a string with them concatenated together.
#[allow(clippy::too_many_arguments)]
pub fn render(
&self,
svg_defs: &mut String,
element_transform: DAffine2,
stroke_transform: DAffine2,
bounds: [DVec2; 2],
transformed_bounds: [DVec2; 2],
aligned_strokes: bool,
override_paint_order: bool,
render_params: &RenderParams,
) -> String {
let view_mode = render_params.view_mode;
match view_mode {
ViewMode::Outline => {
let fill_attribute = Fill::None.render(svg_defs, element_transform, stroke_transform, bounds, transformed_bounds, render_params);
let mut outline_stroke = Stroke::new(Some(LAYER_OUTLINE_STROKE_COLOR), LAYER_OUTLINE_STROKE_WEIGHT);
// Outline strokes should be non-scaling by default
outline_stroke.non_scaling = true;
let stroke_attribute = outline_stroke.render(aligned_strokes, override_paint_order, render_params);
format!("{fill_attribute}{stroke_attribute}")
}
_ => {
let fill_attribute = self.fill.render(svg_defs, element_transform, stroke_transform, bounds, transformed_bounds, render_params);
let stroke_attribute = self
.stroke
.as_ref()
.map(|stroke| stroke.render(aligned_strokes, override_paint_order, render_params))
.unwrap_or_default();
format!("{fill_attribute}{stroke_attribute}")
}
}
}
}
/// Represents different ways of rendering an object

View File

@@ -4,7 +4,10 @@ mod modification;
use super::misc::{dvec2_to_point, point_to_dvec2};
use super::style::{PathStyle, Stroke};
use crate::bounds::BoundingBox;
use crate::instances::Instances;
use crate::math::quad::Quad;
use crate::transform::Transform;
use crate::vector::click_target::{ClickTargetType, FreePoint};
use crate::{AlphaBlending, Color, GraphicGroupTable};
pub use attributes::*;
@@ -487,6 +490,29 @@ impl VectorData {
}
}
impl BoundingBox for VectorDataTable {
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> Option<[DVec2; 2]> {
self.instance_ref_iter()
.flat_map(|instance| {
if !include_stroke {
return instance.instance.bounding_box_with_transform(transform * *instance.transform);
}
let stroke_width = instance.instance.style.stroke().map(|s| s.weight()).unwrap_or_default();
let miter_limit = instance.instance.style.stroke().map(|s| s.join_miter_limit).unwrap_or(1.);
let scale = transform.decompose_scale();
// We use the full line width here to account for different styles of stroke caps
let offset = DVec2::splat(stroke_width * scale.x.max(scale.y) * miter_limit);
instance.instance.bounding_box_with_transform(transform * *instance.transform).map(|[a, b]| [a - offset, b + offset])
})
.reduce(Quad::combine_bounds)
}
}
/// A selectable part of a curve, either an anchor (start or end of a bézier) or a handle (doesn't necessarily go through the bézier but influences curvature).
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, DynAny, serde::Serialize, serde::Deserialize)]
pub enum ManipulatorPointId {

View File

@@ -4,10 +4,10 @@ use super::algorithms::spline::{solve_spline_first_handle_closed, solve_spline_f
use super::misc::{CentroidType, point_to_dvec2};
use super::style::{Fill, Gradient, GradientStops, Stroke};
use super::{PointId, SegmentDomain, SegmentId, StrokeId, VectorData, VectorDataExt, VectorDataTable};
use crate::bounds::BoundingBox;
use crate::instances::{Instance, InstanceMut, Instances};
use crate::raster_types::{CPU, GPU, RasterDataTable};
use crate::registry::types::{Angle, Fraction, IntegerCount, Length, Multiplier, Percentage, PixelLength, PixelSize, SeedValue};
use crate::renderer::GraphicElementRendered;
use crate::transform::{Footprint, ReferencePoint, Transform};
use crate::vector::algorithms::merge_by_distance::MergeByDistanceExt;
use crate::vector::misc::{MergeByDistanceAlgorithm, PointSpacingType};
@@ -221,10 +221,7 @@ async fn repeat<I: 'n + Send + Clone>(
direction: PixelSize,
angle: Angle,
#[default(4)] instances: IntegerCount,
) -> Instances<I>
where
Instances<I>: GraphicElementRendered,
{
) -> Instances<I> {
let angle = angle.to_radians();
let count = instances.max(1);
let total = (count - 1) as f64;
@@ -258,10 +255,7 @@ async fn circular_repeat<I: 'n + Send + Clone>(
angle_offset: Angle,
#[default(5)] radius: f64,
#[default(5)] instances: IntegerCount,
) -> Instances<I>
where
Instances<I>: GraphicElementRendered,
{
) -> Instances<I> {
let count = instances.max(1);
let mut result_table = Instances::<I>::default();
@@ -313,10 +307,7 @@ async fn copy_to_points<I: 'n + Send + Clone>(
random_rotation: Angle,
/// Seed to determine unique variations on all the randomized instance angles.
random_rotation_seed: SeedValue,
) -> Instances<I>
where
Instances<I>: GraphicElementRendered,
{
) -> Instances<I> {
let mut result_table = Instances::<I>::default();
let random_scale_difference = random_scale_max - random_scale_min;
@@ -377,7 +368,7 @@ async fn mirror<I: 'n + Send + Clone>(
#[default(true)] keep_original: bool,
) -> Instances<I>
where
Instances<I>: GraphicElementRendered,
Instances<I>: BoundingBox,
{
let mut result_table = Instances::default();
@@ -1090,7 +1081,7 @@ async fn solidify_stroke(_: impl Ctx, vector_data: VectorDataTable) -> VectorDat
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
async fn flatten_path<I: 'n + Send>(_: impl Ctx, #[implementations(GraphicGroupTable, VectorDataTable)] graphic_group_input: Instances<I>) -> VectorDataTable
where
Instances<I>: GraphicElementRendered,
GraphicElement: From<Instances<I>>,
{
// A node based solution to support passing through vector data could be a network node with a cache node connected to
// a Flatten Path connected to an if else node, another connection from the cache directly
@@ -1135,7 +1126,7 @@ where
};
// Flatten the graphic group input into the output VectorData instance
let base_graphic_group = GraphicGroupTable::new(graphic_group_input.to_graphic_element());
let base_graphic_group = GraphicGroupTable::new(GraphicElement::from(graphic_group_input));
flatten_group(&base_graphic_group, &mut output);
// Return the single-row VectorDataTable containing the flattened VectorData subpaths