mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-09-20 03:18:06 +08:00
Gradient Tool (#546)
* Refactor to support fill enum & svg defs * Init tool * Fix advertise * Gradient tool click and drag * Overlays * Drag overlays * Cleanup * Fix transform on elongated shapes * Snap rotate * Snapping * Add hints * Rename to solid * Code review changes Co-authored-by: Keavon Chambers <keavon@keavon.com>
This commit is contained in:
committed by
Keavon Chambers
parent
2bf1d5ebea
commit
2aba0fc06b
@@ -15,9 +15,9 @@ pub struct FolderLayer {
|
||||
}
|
||||
|
||||
impl LayerData for FolderLayer {
|
||||
fn render(&mut self, svg: &mut String, transforms: &mut Vec<glam::DAffine2>, view_mode: ViewMode) {
|
||||
fn render(&mut self, svg: &mut String, svg_defs: &mut String, transforms: &mut Vec<glam::DAffine2>, view_mode: ViewMode) {
|
||||
for layer in &mut self.layers {
|
||||
let _ = writeln!(svg, "{}", layer.render(transforms, view_mode));
|
||||
let _ = writeln!(svg, "{}", layer.render(transforms, view_mode, svg_defs));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::blend_mode::BlendMode;
|
||||
use super::folder_layer::FolderLayer;
|
||||
use super::shape_layer::ShapeLayer;
|
||||
use super::style::ViewMode;
|
||||
use super::style::{PathStyle, ViewMode};
|
||||
use super::text_layer::TextLayer;
|
||||
use crate::intersection::Quad;
|
||||
use crate::DocumentError;
|
||||
@@ -37,14 +37,14 @@ impl LayerDataType {
|
||||
}
|
||||
|
||||
pub trait LayerData {
|
||||
fn render(&mut self, svg: &mut String, transforms: &mut Vec<glam::DAffine2>, view_mode: ViewMode);
|
||||
fn render(&mut self, svg: &mut String, svg_defs: &mut String, transforms: &mut Vec<glam::DAffine2>, view_mode: ViewMode);
|
||||
fn intersects_quad(&self, quad: Quad, path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>);
|
||||
fn bounding_box(&self, transform: glam::DAffine2) -> Option<[DVec2; 2]>;
|
||||
}
|
||||
|
||||
impl LayerData for LayerDataType {
|
||||
fn render(&mut self, svg: &mut String, transforms: &mut Vec<glam::DAffine2>, view_mode: ViewMode) {
|
||||
self.inner_mut().render(svg, transforms, view_mode)
|
||||
fn render(&mut self, svg: &mut String, svg_defs: &mut String, transforms: &mut Vec<glam::DAffine2>, view_mode: ViewMode) {
|
||||
self.inner_mut().render(svg, svg_defs, transforms, view_mode)
|
||||
}
|
||||
|
||||
fn intersects_quad(&self, quad: Quad, path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>) {
|
||||
@@ -78,6 +78,8 @@ pub struct Layer {
|
||||
pub cache: String,
|
||||
#[serde(skip)]
|
||||
pub thumbnail_cache: String,
|
||||
#[serde(skip)]
|
||||
pub svg_defs_cache: String,
|
||||
#[serde(skip, default = "return_true")]
|
||||
pub cache_dirty: bool,
|
||||
pub blend_mode: BlendMode,
|
||||
@@ -93,6 +95,7 @@ impl Layer {
|
||||
transform: glam::DAffine2::from_cols_array(&transform),
|
||||
cache: String::new(),
|
||||
thumbnail_cache: String::new(),
|
||||
svg_defs_cache: String::new(),
|
||||
cache_dirty: true,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 1.,
|
||||
@@ -103,7 +106,7 @@ impl Layer {
|
||||
LayerIter { stack: vec![self] }
|
||||
}
|
||||
|
||||
pub fn render(&mut self, transforms: &mut Vec<DAffine2>, view_mode: ViewMode) -> &str {
|
||||
pub fn render(&mut self, transforms: &mut Vec<DAffine2>, view_mode: ViewMode, svg_defs: &mut String) -> &str {
|
||||
if !self.visible {
|
||||
return "";
|
||||
}
|
||||
@@ -111,7 +114,8 @@ impl Layer {
|
||||
if self.cache_dirty {
|
||||
transforms.push(self.transform);
|
||||
self.thumbnail_cache.clear();
|
||||
self.data.render(&mut self.thumbnail_cache, transforms, view_mode);
|
||||
self.svg_defs_cache.clear();
|
||||
self.data.render(&mut self.thumbnail_cache, &mut self.svg_defs_cache, transforms, view_mode);
|
||||
|
||||
self.cache.clear();
|
||||
let _ = writeln!(self.cache, r#"<g transform="matrix("#);
|
||||
@@ -128,6 +132,7 @@ impl Layer {
|
||||
transforms.pop();
|
||||
self.cache_dirty = false;
|
||||
}
|
||||
svg_defs.push_str(&self.svg_defs_cache);
|
||||
|
||||
self.cache.as_str()
|
||||
}
|
||||
@@ -176,6 +181,22 @@ impl Layer {
|
||||
_ => Err(DocumentError::NotText),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn style(&self) -> Result<&PathStyle, DocumentError> {
|
||||
match &self.data {
|
||||
LayerDataType::Shape(s) => Ok(&s.style),
|
||||
LayerDataType::Text(t) => Ok(&t.style),
|
||||
_ => return Err(DocumentError::NotAShape),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn style_mut(&mut self) -> Result<&mut PathStyle, DocumentError> {
|
||||
match &mut self.data {
|
||||
LayerDataType::Shape(s) => Ok(&mut s.style),
|
||||
LayerDataType::Text(t) => Ok(&mut t.style),
|
||||
_ => return Err(DocumentError::NotAShape),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for Layer {
|
||||
@@ -187,6 +208,7 @@ impl Clone for Layer {
|
||||
transform: self.transform,
|
||||
cache: String::new(),
|
||||
thumbnail_cache: String::new(),
|
||||
svg_defs_cache: String::new(),
|
||||
cache_dirty: true,
|
||||
blend_mode: self.blend_mode,
|
||||
opacity: self.opacity,
|
||||
|
||||
@@ -21,7 +21,7 @@ pub struct ShapeLayer {
|
||||
}
|
||||
|
||||
impl LayerData for ShapeLayer {
|
||||
fn render(&mut self, svg: &mut String, transforms: &mut Vec<DAffine2>, view_mode: ViewMode) {
|
||||
fn render(&mut self, svg: &mut String, svg_defs: &mut String, transforms: &mut Vec<DAffine2>, view_mode: ViewMode) {
|
||||
let mut path = self.path.clone();
|
||||
let transform = self.transform(transforms, view_mode);
|
||||
let inverse = transform.inverse();
|
||||
@@ -36,7 +36,7 @@ impl LayerData for ShapeLayer {
|
||||
let _ = svg.write_str(&(entry.to_string() + if i == 5 { "" } else { "," }));
|
||||
});
|
||||
let _ = svg.write_str(r#")">"#);
|
||||
let _ = write!(svg, r#"<path d="{}" {} />"#, path.to_svg(), self.style.render(view_mode));
|
||||
let _ = write!(svg, r#"<path d="{}" {} />"#, path.to_svg(), self.style.render(view_mode, svg_defs));
|
||||
let _ = svg.write_str("</g>");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
use std::fmt::Write;
|
||||
|
||||
use crate::color::Color;
|
||||
use crate::consts::{LAYER_OUTLINE_STROKE_COLOR, LAYER_OUTLINE_STROKE_WIDTH};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use glam::{DAffine2, DVec2};
|
||||
|
||||
const OPACITY_PRECISION: usize = 3;
|
||||
|
||||
fn format_opacity(name: &str, opacity: f32) -> String {
|
||||
@@ -26,27 +30,106 @@ impl Default for ViewMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient fill.
|
||||
///
|
||||
/// Contains the start and end points, along with the colors at varying points along the length.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
|
||||
pub struct Fill {
|
||||
color: Color,
|
||||
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
|
||||
pub struct Gradient {
|
||||
pub start: DVec2,
|
||||
pub end: DVec2,
|
||||
pub transform: DAffine2,
|
||||
pub positions: Vec<(f64, Color)>,
|
||||
uuid: u64,
|
||||
}
|
||||
impl Gradient {
|
||||
/// Constructs a new gradient with the colors at 0 and 1 specified.
|
||||
pub fn new(start: DVec2, start_color: Color, end: DVec2, end_color: Color, transform: DAffine2, uuid: u64) -> Self {
|
||||
Gradient {
|
||||
start,
|
||||
end,
|
||||
positions: vec![(0., start_color), (1., end_color)],
|
||||
transform,
|
||||
uuid,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the gradient def with the uuid specified
|
||||
fn render_defs(&self, svg_defs: &mut String) {
|
||||
let positions = self
|
||||
.positions
|
||||
.iter()
|
||||
.map(|(position, color)| format!(r##"<stop offset="{}" stop-color="#{}" />"##, position, color.rgba_hex()))
|
||||
.collect::<String>();
|
||||
|
||||
let start = self.transform.inverse().transform_point2(self.start);
|
||||
let end = self.transform.inverse().transform_point2(self.end);
|
||||
|
||||
let transform = self
|
||||
.transform
|
||||
.to_cols_array()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, entry)| entry.to_string() + if i == 5 { "" } else { "," })
|
||||
.collect::<String>();
|
||||
|
||||
let _ = write!(
|
||||
svg_defs,
|
||||
r#"<linearGradient id="{}" x1="{}" x2="{}" y1="{}" y2="{}" gradientTransform="matrix({})">{}</linearGradient>"#,
|
||||
self.uuid, start.x, end.x, start.y, end.y, transform, positions
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Describes the fill of a layer.
|
||||
///
|
||||
/// Can be None, solid or potentially some sort of image or pattern
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Fill {
|
||||
None,
|
||||
Solid(Color),
|
||||
LinearGradient(Gradient),
|
||||
}
|
||||
|
||||
impl Default for Fill {
|
||||
fn default() -> Self {
|
||||
Self::None
|
||||
}
|
||||
}
|
||||
|
||||
impl Fill {
|
||||
pub fn new(color: Color) -> Self {
|
||||
Self { color }
|
||||
/// Construct a new solid fill
|
||||
pub fn solid(color: Color) -> Self {
|
||||
Self::Solid(color)
|
||||
}
|
||||
|
||||
/// Evaluate the color at some point on the fill
|
||||
pub fn color(&self) -> Color {
|
||||
self.color
|
||||
match self {
|
||||
Self::None => Color::BLACK,
|
||||
Self::Solid(color) => *color,
|
||||
// ToDo: Should correctly sample the gradient
|
||||
Self::LinearGradient(Gradient { positions, .. }) => positions[0].1,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(fill: Option<Fill>) -> String {
|
||||
match fill {
|
||||
Some(c) => format!(r##" fill="#{}"{}"##, c.color.rgb_hex(), format_opacity("fill", c.color.a())),
|
||||
None => r#" fill="none""#.to_string(),
|
||||
/// Renders the fill, adding necessary defs.
|
||||
pub fn render(&self, svg_defs: &mut String) -> String {
|
||||
match self {
|
||||
Self::None => r#" fill="none""#.to_string(),
|
||||
Self::Solid(color) => format!(r##" fill="#{}"{}"##, color.rgb_hex(), format_opacity("fill", color.a())),
|
||||
Self::LinearGradient(gradient) => {
|
||||
gradient.render_defs(svg_defs);
|
||||
format!(r##" fill="url('#{}')""##, gradient.uuid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the fill is not none
|
||||
pub fn is_some(&self) -> bool {
|
||||
*self != Self::None
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
@@ -75,19 +158,19 @@ impl Stroke {
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
|
||||
pub struct PathStyle {
|
||||
stroke: Option<Stroke>,
|
||||
fill: Option<Fill>,
|
||||
fill: Fill,
|
||||
}
|
||||
|
||||
impl PathStyle {
|
||||
pub fn new(stroke: Option<Stroke>, fill: Option<Fill>) -> Self {
|
||||
pub fn new(stroke: Option<Stroke>, fill: Fill) -> Self {
|
||||
Self { stroke, fill }
|
||||
}
|
||||
|
||||
pub fn fill(&self) -> Option<Fill> {
|
||||
self.fill
|
||||
pub fn fill(&self) -> &Fill {
|
||||
&self.fill
|
||||
}
|
||||
|
||||
pub fn stroke(&self) -> Option<Stroke> {
|
||||
@@ -95,7 +178,7 @@ impl PathStyle {
|
||||
}
|
||||
|
||||
pub fn set_fill(&mut self, fill: Fill) {
|
||||
self.fill = Some(fill);
|
||||
self.fill = fill;
|
||||
}
|
||||
|
||||
pub fn set_stroke(&mut self, stroke: Stroke) {
|
||||
@@ -103,17 +186,17 @@ impl PathStyle {
|
||||
}
|
||||
|
||||
pub fn clear_fill(&mut self) {
|
||||
self.fill = None;
|
||||
self.fill = Fill::None;
|
||||
}
|
||||
|
||||
pub fn clear_stroke(&mut self) {
|
||||
self.stroke = None;
|
||||
}
|
||||
|
||||
pub fn render(&self, view_mode: ViewMode) -> String {
|
||||
let fill_attribute = match (view_mode, self.fill) {
|
||||
(ViewMode::Outline, _) => Fill::render(None),
|
||||
(_, fill) => Fill::render(fill),
|
||||
pub fn render(&self, view_mode: ViewMode, svg_defs: &mut String) -> String {
|
||||
let fill_attribute = match (view_mode, &self.fill) {
|
||||
(ViewMode::Outline, _) => Fill::None.render(svg_defs),
|
||||
(_, fill) => fill.render(svg_defs),
|
||||
};
|
||||
let stroke_attribute = match (view_mode, self.stroke) {
|
||||
(ViewMode::Outline, _) => Stroke::new(LAYER_OUTLINE_STROKE_COLOR, LAYER_OUTLINE_STROKE_WIDTH).render(),
|
||||
|
||||
@@ -27,7 +27,7 @@ pub struct TextLayer {
|
||||
}
|
||||
|
||||
impl LayerData for TextLayer {
|
||||
fn render(&mut self, svg: &mut String, transforms: &mut Vec<DAffine2>, view_mode: ViewMode) {
|
||||
fn render(&mut self, svg: &mut String, svg_defs: &mut String, transforms: &mut Vec<DAffine2>, view_mode: ViewMode) {
|
||||
let transform = self.transform(transforms, view_mode);
|
||||
let inverse = transform.inverse();
|
||||
if !inverse.is_finite() {
|
||||
@@ -43,24 +43,20 @@ impl LayerData for TextLayer {
|
||||
if self.editable {
|
||||
let _ = write!(
|
||||
svg,
|
||||
r#"<foreignObject transform="matrix({})" style="color: {}"></foreignObject>"#,
|
||||
r#"<foreignObject transform="matrix({})"></foreignObject>"#,
|
||||
transform
|
||||
.to_cols_array()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, entry)| { entry.to_string() + if i == 5 { "" } else { "," } })
|
||||
.collect::<String>(),
|
||||
match self.style.fill() {
|
||||
Some(fill) => format!("#{}", fill.color().rgba_hex()),
|
||||
None => "gray".to_string(),
|
||||
}
|
||||
);
|
||||
} else {
|
||||
let mut path = self.to_bez_path();
|
||||
|
||||
path.apply_affine(glam_to_kurbo(transform));
|
||||
|
||||
let _ = write!(svg, r#"<path d="{}" {} />"#, path.to_svg(), self.style.render(view_mode));
|
||||
let _ = write!(svg, r#"<path d="{}" {} />"#, path.to_svg(), self.style.render(view_mode, svg_defs));
|
||||
}
|
||||
let _ = svg.write_str("</g>");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user