Transform API (#301)

* Enforce cache dirtification

* Turn all shapes into one struct

* Remove working folder

* Remove old shapes

* Major restructuring

* Refactor Ellipse, Rectangle and ShapeTool

* Simplify bounding box calculation for folder

* Fix panic in select tool

*  Refactorselect tool

* Refactor Align

* Refactor flipping layers

* Zoom to fit all

* Refactor tools to avoid state keeping

* Refactor more tools to use state that is passed along

* Fix whitespace + change selection box style

* Set viewbox of svg export based on the contents
This commit is contained in:
TrueDoctor
2021-08-06 12:34:30 +02:00
committed by GitHub
parent 63a4ed64c8
commit f79e6e378d
55 changed files with 2059 additions and 2251 deletions

View File

@@ -11,6 +11,6 @@ license = "Apache-2.0"
[dependencies]
log = "0.4"
kurbo = {version="0.8", features = ["serde"]}
kurbo = {git="https://github.com/linebender/kurbo", features = ["serde"]}
serde = { version = "1.0", features = ["derive"] }
glam = { version = "0.16", features = ["serde"] }
glam = { version = "0.17", features = ["serde"] }

View File

@@ -1,27 +1,26 @@
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use glam::{DAffine2, DVec2};
use crate::{
layers::{self, style::PathStyle, Folder, Layer, LayerDataTypes, Line, PolyLine, Rect, Shape},
DocumentError, DocumentResponse, LayerId, Operation,
layers::{self, Folder, Layer, LayerData, LayerDataType, Shape},
DocumentError, DocumentResponse, LayerId, Operation, Quad,
};
#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone)]
pub struct Document {
pub root: Layer,
pub work: Layer,
pub work_mount_path: Vec<LayerId>,
pub work_operations: Vec<Operation>,
pub work_mounted: bool,
pub hasher: DefaultHasher,
}
impl Default for Document {
fn default() -> Self {
Self {
root: Layer::new(LayerDataTypes::Folder(Folder::default()), DAffine2::IDENTITY.to_cols_array(), PathStyle::default()),
work: Layer::new(LayerDataTypes::Folder(Folder::default()), DAffine2::IDENTITY.to_cols_array(), PathStyle::default()),
work_mount_path: Vec::new(),
work_operations: Vec::new(),
work_mounted: false,
root: Layer::new(LayerDataType::Folder(Folder::default()), DAffine2::IDENTITY.to_cols_array()),
hasher: DefaultHasher::new(),
}
}
}
@@ -32,146 +31,71 @@ fn split_path(path: &[LayerId]) -> Result<(&[LayerId], LayerId), DocumentError>
}
impl Document {
/// Renders the layer graph with the root `path` as an SVG string.
/// This operation merges currently mounted folder and document_folder
/// contents together.
pub fn render(&mut self, path: &mut Vec<LayerId>, svg: &mut String) {
if !self.work_mount_path.as_slice().starts_with(path) {
self.layer_mut(path).unwrap().render();
path.pop();
return;
}
if path.as_slice() == self.work_mount_path {
// TODO: Handle if mounted in nested folders
let transform = self.document_folder(path).unwrap().transform;
self.document_folder_mut(path).unwrap().render_as_folder(svg);
self.work.transform = transform;
self.work.render_as_folder(svg);
path.pop();
}
let ids = self.folder(path).unwrap().layer_ids.clone();
for element in ids {
path.push(element);
self.render(path, svg);
}
}
/// Wrapper around render, that returns the whole document as a Response.
pub fn render_root(&mut self) -> String {
let mut svg = String::new();
self.render(&mut vec![], &mut svg);
svg
self.root.render(&mut vec![]);
self.root.cache.clone()
}
pub fn hash(&self) -> u64 {
self.hasher.finish()
}
/// Checks whether each layer under `path` intersects with the provided `quad` and adds all intersection layers as paths to `intersections`.
pub fn intersects_quad(&self, quad: [DVec2; 4], path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>) {
self.document_folder(path).unwrap().intersects_quad(quad, path, intersections);
pub fn intersects_quad(&self, quad: Quad, path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>) {
self.layer(path).unwrap().intersects_quad(quad, path, intersections);
}
/// Checks whether each layer under the root path intersects with the provided `quad` and returns the paths to all intersecting layers.
pub fn intersects_quad_root(&self, quad: [DVec2; 4]) -> Vec<Vec<LayerId>> {
pub fn intersects_quad_root(&self, quad: Quad) -> Vec<Vec<LayerId>> {
let mut intersections = Vec::new();
self.intersects_quad(quad, &mut vec![], &mut intersections);
intersections
}
fn is_mounted(&self, mount_path: &[LayerId], path: &[LayerId]) -> bool {
path.starts_with(mount_path) && self.work_mounted
}
/// Returns a reference to the requested folder. Fails if the path does not exist,
/// or if the requested layer is not of type folder.
/// This function respects mounted folders and will thus not contain the layers already
/// present in the document if a temporary folder is mounted on top.
pub fn folder(&self, mut path: &[LayerId]) -> Result<&Folder, DocumentError> {
let mut root = self.root.as_folder()?;
if self.is_mounted(self.work_mount_path.as_slice(), path) {
path = &path[self.work_mount_path.len()..];
root = self.work.as_folder()?;
}
for id in path {
root = root.folder(*id).ok_or(DocumentError::LayerNotFound)?;
}
Ok(root)
}
/// Returns a mutable reference to the requested folder. Fails if the path does not exist,
/// or if the requested layer is not of type folder.
/// This function respects mounted folders and will thus not contain the layers already
/// present in the document if a temporary folder is mounted on top.
/// If you manually edit the folder you have to set the cache_dirty flag yourself.
pub fn folder_mut(&mut self, mut path: &[LayerId]) -> Result<&mut Folder, DocumentError> {
let mut root = if self.is_mounted(self.work_mount_path.as_slice(), path) {
path = &path[self.work_mount_path.len()..];
self.work.as_folder_mut()?
} else {
self.root.as_folder_mut()?
};
for id in path {
root = root.folder_mut(*id).ok_or(DocumentError::LayerNotFound)?;
}
Ok(root)
}
/// Returns a reference to the requested folder. Fails if the path does not exist,
/// or if the requested layer is not of type folder.
/// This function does **not** respect mounted folders and will always return the current
/// state of the document, disregarding any temporary modifications.
pub fn document_folder(&self, path: &[LayerId]) -> Result<&Layer, DocumentError> {
pub fn folder(&self, path: &[LayerId]) -> Result<&Folder, DocumentError> {
let mut root = &self.root;
for id in path {
root = root.as_folder()?.layer(*id).ok_or(DocumentError::LayerNotFound)?;
}
Ok(root)
root.as_folder()
}
/// Returns a mutable reference to the requested folder. Fails if the path does not exist,
/// or if the requested layer is not of type folder.
/// This function does **not** respect mounted folders and will always return the current
/// state of the document, disregarding any temporary modifications.
/// If you manually edit the folder you have to set the cache_dirty flag yourself.
pub fn document_folder_mut(&mut self, path: &[LayerId]) -> Result<&mut Layer, DocumentError> {
pub fn folder_mut(&mut self, path: &[LayerId]) -> Result<&mut Folder, DocumentError> {
let mut root = &mut self.root;
for id in path {
root = root.as_folder_mut()?.layer_mut(*id).ok_or(DocumentError::LayerNotFound)?;
}
Ok(root)
root.as_folder_mut()
}
/// Returns a reference to the layer or folder at the path. Does not return an error for root
pub fn document_layer(&self, path: &[LayerId]) -> Result<&Layer, DocumentError> {
/// Returns a reference to the layer or folder at the path.
pub fn layer(&self, path: &[LayerId]) -> Result<&Layer, DocumentError> {
if path.is_empty() {
return Ok(&self.root);
}
let (path, id) = split_path(path)?;
self.document_folder(path)?.as_folder()?.layer(id).ok_or(DocumentError::LayerNotFound)
self.folder(path)?.layer(id).ok_or(DocumentError::LayerNotFound)
}
/// Returns a mutable reference to the layer or folder at the path. Does not return an error for root
pub fn document_layer_mut(&mut self, path: &[LayerId]) -> Result<&mut Layer, DocumentError> {
/// Returns a mutable reference to the layer or folder at the path.
pub fn layer_mut(&mut self, path: &[LayerId]) -> Result<&mut Layer, DocumentError> {
if path.is_empty() {
return Ok(&mut self.root);
}
let (path, id) = split_path(path)?;
self.document_folder_mut(path)?.as_folder_mut()?.layer_mut(id).ok_or(DocumentError::LayerNotFound)
}
/// Returns a reference to the layer struct at the specified `path`.
pub fn layer(&self, path: &[LayerId]) -> Result<&Layer, DocumentError> {
let (path, id) = split_path(path)?;
self.folder(path)?.layer(id).ok_or(DocumentError::LayerNotFound)
self.folder_mut(path)?.layer_mut(id).ok_or(DocumentError::LayerNotFound)
}
/// Given a path to a layer, returns a vector of the indices in the layer tree
/// These indices can be used to order a list of layers
pub fn indices_for_path(&self, mut path: &[LayerId]) -> Result<Vec<usize>, DocumentError> {
let mut root = if self.is_mounted(self.work_mount_path.as_slice(), path) {
path = &path[self.work_mount_path.len()..];
&self.work
} else {
&self.root
}
.as_folder()?;
pub fn indices_for_path(&self, path: &[LayerId]) -> Result<Vec<usize>, DocumentError> {
let mut root = self.root.as_folder()?;
let mut indices = vec![];
let (path, layer_id) = split_path(path)?;
@@ -186,62 +110,72 @@ impl Document {
Ok(indices)
}
/// Returns a mutable reference to the layer struct at the specified `path`.
/// If you manually edit the layer you have to set the cache_dirty flag yourself.
pub fn layer_mut(&mut self, path: &[LayerId]) -> Result<&mut Layer, DocumentError> {
let (path, id) = split_path(path)?;
self.folder_mut(path)?.layer_mut(id).ok_or(DocumentError::LayerNotFound)
}
/// Replaces the layer at the specified `path` with `layer`.
pub fn set_layer(&mut self, path: &[LayerId], layer: Layer) -> Result<(), DocumentError> {
pub fn set_layer(&mut self, path: &[LayerId], layer: Layer, insert_index: isize) -> Result<(), DocumentError> {
let mut folder = self.root.as_folder_mut()?;
let mut layer_id = None;
if let Ok((path, id)) = split_path(path) {
self.layer_mut(path)?.cache_dirty = true;
layer_id = Some(id);
self.mark_as_dirty(path)?;
folder = self.folder_mut(path)?;
if let Some(folder_layer) = folder.layer_mut(id) {
*folder_layer = layer;
return Ok(());
}
}
folder.add_layer(layer, -1).ok_or(DocumentError::IndexOutOfBounds)?;
folder.add_layer(layer, layer_id, insert_index).ok_or(DocumentError::IndexOutOfBounds)?;
Ok(())
}
/// Adds a new layer to the folder specified by `path`.
/// Passing a negative `insert_index` indexes relative to the end.
/// -1 is equivalent to adding the layer to the top.
pub fn add_layer(&mut self, path: &[LayerId], mut layer: Layer, insert_index: isize) -> Result<LayerId, DocumentError> {
layer.render();
pub fn add_layer(&mut self, path: &[LayerId], layer: Layer, insert_index: isize) -> Result<LayerId, DocumentError> {
let folder = self.folder_mut(path)?;
folder.add_layer(layer, insert_index).ok_or(DocumentError::IndexOutOfBounds)
folder.add_layer(layer, None, insert_index).ok_or(DocumentError::IndexOutOfBounds)
}
/// Deletes the layer specified by `path`.
pub fn delete(&mut self, path: &[LayerId]) -> Result<(), DocumentError> {
let (path, id) = split_path(path)?;
let _ = self.layer_mut(path).map(|x| x.cache_dirty = true);
self.document_folder_mut(path)?.as_folder_mut()?.remove_layer(id)
self.mark_as_dirty(path)?;
self.folder_mut(path)?.remove_layer(id)
}
pub fn layer_axis_aligned_bounding_box(&self, path: &[LayerId]) -> Result<Option<[DVec2; 2]>, DocumentError> {
// TODO: Replace with functions of the transform api
if path.is_empty() {
// Special case for root. Root's local is the documents global, so we avoid transforming its transform by itself.
self.layer_local_bounding_box(path)
} else {
let layer = self.document_layer(path)?;
Ok(layer.bounding_box(self.root.transform * layer.transform, layer.style))
pub fn visible_layers(&self, path: &mut Vec<LayerId>, paths: &mut Vec<Vec<LayerId>>) -> Result<(), DocumentError> {
if !self.layer(path)?.visible {
return Ok(());
}
if let Ok(folder) = self.folder(path) {
for layer in folder.layer_ids.iter() {
path.push(*layer);
self.visible_layers(path, paths)?;
path.pop();
}
} else {
paths.push(path.clone());
}
Ok(())
}
pub fn layer_local_bounding_box(&self, path: &[LayerId]) -> Result<Option<[DVec2; 2]>, DocumentError> {
// TODO: Replace with functions of the transform api
let layer = self.document_layer(path)?;
Ok(layer.bounding_box(layer.transform, layer.style))
pub fn viewport_bounding_box(&self, path: &[LayerId]) -> Result<Option<[DVec2; 2]>, DocumentError> {
let layer = self.layer(path)?;
let transform = self.multiply_transforms(path)?;
Ok(layer.data.bounding_box(transform))
}
fn mark_as_dirty(&mut self, path: &[LayerId]) -> Result<(), DocumentError> {
pub fn visible_layers_bounding_box(&self) -> Option<[DVec2; 2]> {
let mut paths = vec![];
self.visible_layers(&mut vec![], &mut paths).ok()?;
self.combined_viewport_bounding_box(paths.iter().map(|x| x.as_slice()))
}
pub fn combined_viewport_bounding_box<'a>(&self, paths: impl Iterator<Item = &'a [LayerId]>) -> Option<[DVec2; 2]> {
let boxes = paths.filter_map(|path| self.viewport_bounding_box(path).ok()?);
boxes.reduce(|a, b| [a[0].min(b[0]), a[1].max(b[1])])
}
pub fn mark_upstream_as_dirty(&mut self, path: &[LayerId]) -> Result<(), DocumentError> {
let mut root = &mut self.root;
root.cache_dirty = true;
for id in path {
@@ -251,37 +185,114 @@ impl Document {
Ok(())
}
fn working_paths(&mut self) -> Vec<Vec<LayerId>> {
self.work
.as_folder()
.unwrap()
.layer_ids
.iter()
.map(|id| self.work_mount_path.iter().chain([*id].iter()).cloned().collect())
.collect()
pub fn mark_downstream_as_dirty(&mut self, path: &[LayerId]) -> Result<(), DocumentError> {
let mut layer = self.layer_mut(path)?;
layer.cache_dirty = true;
let mut path = path.to_vec();
let len = path.len();
path.push(0);
if let Some(ids) = layer.as_folder().ok().map(|f| f.layer_ids.clone()) {
for id in ids {
path[len] = id;
self.mark_downstream_as_dirty(&path)?
}
}
Ok(())
}
pub fn mark_as_dirty(&mut self, path: &[LayerId]) -> Result<(), DocumentError> {
self.mark_downstream_as_dirty(path)?;
self.mark_upstream_as_dirty(path)?;
Ok(())
}
pub fn transforms(&self, path: &[LayerId]) -> Result<Vec<DAffine2>, DocumentError> {
let mut root = &self.root;
let mut transforms = vec![self.root.transform];
for id in path {
if let Ok(folder) = root.as_folder() {
root = folder.layer(*id).ok_or(DocumentError::LayerNotFound)?;
}
transforms.push(root.transform);
}
Ok(transforms)
}
pub fn multiply_transforms(&self, path: &[LayerId]) -> Result<DAffine2, DocumentError> {
let mut root = &self.root;
let mut trans = self.root.transform;
for id in path {
if let Ok(folder) = root.as_folder() {
root = folder.layer(*id).ok_or(DocumentError::LayerNotFound)?;
}
trans = trans * root.transform;
}
Ok(trans)
}
pub fn generate_transform_across_scope(&self, from: &[LayerId], to: Option<DAffine2>) -> Result<DAffine2, DocumentError> {
let from_rev = self.multiply_transforms(from)?;
let scope = to.unwrap_or(DAffine2::IDENTITY);
Ok(scope * from_rev)
}
pub fn transform_relative_to_scope(&mut self, layer: &[LayerId], scope: Option<DAffine2>, transform: DAffine2) -> Result<(), DocumentError> {
let to = self.generate_transform_across_scope(&layer[..layer.len() - 1], scope)?;
let layer = self.layer_mut(layer)?;
layer.transform = to.inverse() * transform * to * layer.transform;
Ok(())
}
pub fn set_transform_relative_to_scope(&mut self, layer: &[LayerId], scope: Option<DAffine2>, transform: DAffine2) -> Result<(), DocumentError> {
let to = self.generate_transform_across_scope(&layer[..layer.len() - 1], scope)?;
let layer = self.layer_mut(layer)?;
layer.transform = to.inverse() * transform;
Ok(())
}
pub fn apply_transform_relative_to_viewport(&mut self, layer: &[LayerId], transform: DAffine2) -> Result<(), DocumentError> {
self.transform_relative_to_scope(layer, None, transform)
}
pub fn set_transform_relative_to_viewport(&mut self, layer: &[LayerId], transform: DAffine2) -> Result<(), DocumentError> {
self.set_transform_relative_to_scope(layer, None, transform)
}
/// Mutate the document by applying the `operation` to it. If the operation necessitates a
/// reaction from the frontend, responses may be returned.
pub fn handle_operation(&mut self, operation: Operation) -> Result<Option<Vec<DocumentResponse>>, DocumentError> {
pub fn handle_operation(&mut self, operation: &Operation) -> Result<Option<Vec<DocumentResponse>>, DocumentError> {
operation.pseudo_hash().hash(&mut self.hasher);
let responses = match &operation {
Operation::AddEllipse { path, insert_index, transform, style } => {
let id = self.add_layer(&path, Layer::new(LayerDataTypes::Ellipse(layers::Ellipse::new()), *transform, *style), *insert_index)?;
let path = [path.clone(), vec![id]].concat();
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::CreatedLayer { path }])
self.set_layer(path, Layer::new(LayerDataType::Shape(Shape::ellipse(*style)), *transform), *insert_index)?;
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::CreatedLayer { path: path.clone() }])
}
Operation::AddRect { path, insert_index, transform, style } => {
let id = self.add_layer(&path, Layer::new(LayerDataTypes::Rect(Rect), *transform, *style), *insert_index)?;
let path = [path.clone(), vec![id]].concat();
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::CreatedLayer { path }])
self.set_layer(path, Layer::new(LayerDataType::Shape(Shape::rectangle(*style)), *transform), *insert_index)?;
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::CreatedLayer { path: path.clone() }])
}
Operation::AddBoundingBox { path, transform, style } => {
let mut rect = Shape::rectangle(*style);
rect.render_index = -1;
self.set_layer(path, Layer::new(LayerDataType::Shape(rect), *transform), -1)?;
Some(vec![DocumentResponse::DocumentChanged])
}
Operation::AddShape {
path,
insert_index,
transform,
style,
sides,
} => {
self.set_layer(path, Layer::new(LayerDataType::Shape(Shape::shape(*sides, *style)), *transform), *insert_index)?;
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::CreatedLayer { path: path.clone() }])
}
Operation::AddLine { path, insert_index, transform, style } => {
let id = self.add_layer(&path, Layer::new(LayerDataTypes::Line(Line), *transform, *style), *insert_index)?;
let path = [path.clone(), vec![id]].concat();
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::CreatedLayer { path }])
self.set_layer(path, Layer::new(LayerDataType::Shape(Shape::line(*style)), *transform), *insert_index)?;
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::CreatedLayer { path: path.clone() }])
}
Operation::AddPen {
path,
@@ -291,27 +302,11 @@ impl Document {
style,
} => {
let points: Vec<glam::DVec2> = points.iter().map(|&it| it.into()).collect();
let polyline = PolyLine::new(points);
let id = self.add_layer(&path, Layer::new(LayerDataTypes::PolyLine(polyline), *transform, *style), *insert_index)?;
let path = [path.clone(), vec![id]].concat();
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::CreatedLayer { path }])
}
Operation::AddShape {
path,
insert_index,
transform,
equal_sides,
sides,
style,
} => {
let s = Shape::new(*equal_sides, *sides);
let id = self.add_layer(&path, Layer::new(LayerDataTypes::Shape(s), *transform, *style), *insert_index)?;
let path = [path.clone(), vec![id]].concat();
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::CreatedLayer { path }])
self.set_layer(path, Layer::new(LayerDataType::Shape(Shape::poly_line(points, *style)), *transform), *insert_index)?;
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::CreatedLayer { path: path.clone() }])
}
Operation::DeleteLayer { path } => {
self.delete(&path)?;
self.delete(path)?;
let (folder, _) = split_path(path.as_slice()).unwrap_or_else(|_| (&[], 0));
Some(vec![
@@ -322,9 +317,9 @@ impl Document {
}
Operation::PasteLayer { path, layer, insert_index } => {
let folder = self.folder_mut(path)?;
//FIXME: This clone of layer should be avoided somehow
let id = folder.add_layer(layer.clone(), *insert_index).ok_or(DocumentError::IndexOutOfBounds)?;
let id = folder.add_layer(layer.clone(), None, *insert_index).ok_or(DocumentError::IndexOutOfBounds)?;
let full_path = [path.clone(), vec![id]].concat();
self.mark_as_dirty(&full_path)?;
Some(vec![
DocumentResponse::DocumentChanged,
@@ -333,111 +328,91 @@ impl Document {
])
}
Operation::DuplicateLayer { path } => {
let layer = self.layer(&path)?.clone();
let layer = self.layer(path)?.clone();
let (folder_path, _) = split_path(path.as_slice()).unwrap_or_else(|_| (&[], 0));
let folder = self.folder_mut(folder_path)?;
folder.add_layer(layer, -1).ok_or(DocumentError::IndexOutOfBounds)?;
folder.add_layer(layer, None, -1).ok_or(DocumentError::IndexOutOfBounds)?;
self.mark_as_dirty(&path[..path.len() - 1])?;
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::FolderChanged { path: folder_path.to_vec() }])
}
Operation::RenameLayer { path, name } => {
self.layer_mut(path)?.name = Some(name.clone());
Some(vec![DocumentResponse::LayerChanged { path: path.clone() }])
}
Operation::AddFolder { path } => {
self.set_layer(&path, Layer::new(LayerDataTypes::Folder(Folder::default()), DAffine2::IDENTITY.to_cols_array(), PathStyle::default()))?;
self.set_layer(path, Layer::new(LayerDataType::Folder(Folder::default()), DAffine2::IDENTITY.to_cols_array()), -1)?;
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::FolderChanged { path: path.clone() }])
}
Operation::MountWorkingFolder { path } => {
let mut responses: Vec<_> = self.working_paths().into_iter().map(|path| DocumentResponse::DeletedLayer { path }).collect();
self.work_mount_path = path.clone();
self.work_operations.clear();
self.work = Layer::new(LayerDataTypes::Folder(Folder::default()), DAffine2::IDENTITY.to_cols_array(), PathStyle::default());
self.work_mounted = true;
responses.push(DocumentResponse::DocumentChanged);
Some(responses)
}
Operation::TransformLayer { path, transform } => {
let layer = self.document_layer_mut(path).unwrap();
let transform = DAffine2::from_cols_array(&transform) * layer.transform;
let layer = self.layer_mut(path).unwrap();
let transform = DAffine2::from_cols_array(transform) * layer.transform;
layer.transform = transform;
layer.cache_dirty = true;
self.root.cache_dirty = true;
self.mark_as_dirty(path)?;
Some(vec![DocumentResponse::DocumentChanged])
}
Operation::TransformLayerInViewport { path, transform } => {
let transform = DAffine2::from_cols_array(transform);
self.apply_transform_relative_to_viewport(path, transform)?;
self.mark_as_dirty(path)?;
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::LayerChanged { path: path.clone() }])
}
Operation::SetLayerTransformInViewport { path, transform } => {
let transform = DAffine2::from_cols_array(transform);
self.set_transform_relative_to_viewport(path, transform)?;
self.mark_as_dirty(path)?;
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::LayerChanged { path: path.clone() }])
}
Operation::TransformLayerInScope { path, transform, scope } => {
let transform = DAffine2::from_cols_array(transform);
let scope = DAffine2::from_cols_array(scope);
self.transform_relative_to_scope(path, Some(scope), transform)?;
self.mark_as_dirty(path)?;
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::LayerChanged { path: path.clone() }])
}
Operation::SetLayerTransformInScope { path, transform, scope } => {
let transform = DAffine2::from_cols_array(transform);
let scope = DAffine2::from_cols_array(scope);
self.set_transform_relative_to_scope(path, Some(scope), transform)?;
self.mark_as_dirty(path)?;
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::LayerChanged { path: path.clone() }])
}
Operation::SetLayerTransform { path, transform } => {
let transform = DAffine2::from_cols_array(&transform);
let layer = self.document_layer_mut(path).unwrap();
let transform = DAffine2::from_cols_array(transform);
let layer = self.layer_mut(path)?;
layer.transform = transform;
layer.cache_dirty = true;
Some(vec![DocumentResponse::DocumentChanged])
}
Operation::DiscardWorkingFolder => {
let mut responses: Vec<_> = self.working_paths().into_iter().map(|path| DocumentResponse::DeletedLayer { path }).collect();
self.work_operations.clear();
self.work_mount_path = vec![];
self.work = Layer::new(LayerDataTypes::Folder(Folder::default()), DAffine2::IDENTITY.to_cols_array(), PathStyle::default());
self.work_mounted = false;
responses.push(DocumentResponse::DocumentChanged);
Some(responses)
}
Operation::ClearWorkingFolder => {
let mut responses: Vec<_> = self.working_paths().into_iter().map(|path| DocumentResponse::DeletedLayer { path }).collect();
self.work_operations.clear();
self.work = Layer::new(LayerDataTypes::Folder(Folder::default()), DAffine2::IDENTITY.to_cols_array(), PathStyle::default());
responses.push(DocumentResponse::DocumentChanged);
Some(responses)
}
Operation::CommitTransaction => {
let mut responses: Vec<_> = self.working_paths().into_iter().map(|path| DocumentResponse::DeletedLayer { path }).collect();
let mut ops = Vec::new();
let mut path: Vec<LayerId> = vec![];
std::mem::swap(&mut path, &mut self.work_mount_path);
std::mem::swap(&mut ops, &mut self.work_operations);
self.work_mounted = false;
self.work_mount_path = vec![];
self.work = Layer::new(LayerDataTypes::Folder(Folder::default()), DAffine2::IDENTITY.to_cols_array(), PathStyle::default());
for operation in ops.into_iter() {
if let Some(mut op_responses) = self.handle_operation(operation)? {
responses.append(&mut op_responses);
}
}
responses.extend(vec![DocumentResponse::DocumentChanged, DocumentResponse::FolderChanged { path }]);
Some(responses)
self.mark_as_dirty(path)?;
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::LayerChanged { path: path.clone() }])
}
Operation::ToggleVisibility { path } => {
if let Ok(layer) = self.layer_mut(&path) {
self.mark_as_dirty(path)?;
if let Ok(layer) = self.layer_mut(path) {
layer.visible = !layer.visible;
layer.cache_dirty = true;
}
let path = path.as_slice()[..path.len() - 1].to_vec();
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::FolderChanged { path }])
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::LayerChanged { path: path.clone() }])
}
Operation::SetLayerBlendMode { path, blend_mode } => {
self.mark_as_dirty(path)?;
self.layer_mut(path)?.blend_mode = *blend_mode;
let path = path.as_slice()[..path.len() - 1].to_vec();
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::FolderChanged { path }])
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::LayerChanged { path: path.clone() }])
}
Operation::SetLayerOpacity { path, opacity } => {
self.mark_as_dirty(path)?;
self.layer_mut(path)?.opacity = *opacity;
let path = path.as_slice()[..path.len() - 1].to_vec();
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::FolderChanged { path }])
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::LayerChanged { path: path.clone() }])
}
Operation::FillLayer { path, color } => {
self.layer_mut(path)?.style.set_fill(layers::style::Fill::new(*color));
let layer = self.layer_mut(path)?;
match &mut layer.data {
LayerDataType::Shape(s) => s.style.set_fill(layers::style::Fill::new(*color)),
_ => return Err(DocumentError::NotAShape),
}
self.mark_as_dirty(path)?;
Some(vec![DocumentResponse::DocumentChanged])
Some(vec![DocumentResponse::DocumentChanged, DocumentResponse::LayerChanged { path: path.clone() }])
}
};
if !matches!(
operation,
Operation::CommitTransaction | Operation::MountWorkingFolder { .. } | Operation::DiscardWorkingFolder | Operation::ClearWorkingFolder
) {
self.work_operations.push(operation);
}
Ok(responses)
}
}

View File

@@ -1,34 +1,57 @@
use glam::DVec2;
use std::ops::Mul;
use glam::{DAffine2, DVec2};
use kurbo::{BezPath, Line, PathSeg, Point, Shape, Vec2};
#[derive(Debug, Clone, Default, Copy)]
pub struct Quad([DVec2; 4]);
impl Quad {
pub fn from_box(bbox: [DVec2; 2]) -> Self {
let size = bbox[1] - bbox[0];
Self([bbox[0], bbox[0] + size * DVec2::X, bbox[0] + size * DVec2::Y, bbox[1]])
}
pub fn lines(&self) -> [Line; 4] {
[
Line::new(to_point(self.0[0]), to_point(self.0[1])),
Line::new(to_point(self.0[1]), to_point(self.0[2])),
Line::new(to_point(self.0[2]), to_point(self.0[3])),
Line::new(to_point(self.0[3]), to_point(self.0[0])),
]
}
}
impl Mul<Quad> for DAffine2 {
type Output = Quad;
fn mul(self, rhs: Quad) -> Self::Output {
let mut output = Quad::default();
for (i, point) in rhs.0.iter().enumerate() {
output.0[i] = self.transform_point2(*point);
}
output
}
}
fn to_point(vec: DVec2) -> Point {
Point::new(vec.x, vec.y)
}
pub fn intersect_quad_bez_path(quad: [DVec2; 4], shape: &BezPath, closed: bool) -> bool {
let lines = vec![
Line::new(to_point(quad[0]), to_point(quad[1])),
Line::new(to_point(quad[1]), to_point(quad[2])),
Line::new(to_point(quad[2]), to_point(quad[3])),
Line::new(to_point(quad[3]), to_point(quad[0])),
];
pub fn intersect_quad_bez_path(quad: Quad, shape: &BezPath, closed: bool) -> bool {
// check if outlines intersect
for path_segment in shape.segments() {
for line in &lines {
if !path_segment.intersect_line(*line).is_empty() {
return true;
}
}
if shape.segments().any(|path_segment| quad.lines().iter().any(|line| !path_segment.intersect_line(*line).is_empty())) {
return true;
}
// check if selection is entirely within the shape
if closed && shape.contains(to_point(quad[0])) {
if closed && quad.0.iter().any(|q| shape.contains(to_point(*q))) {
return true;
}
// check if shape is entirely within the selection
if let Some(shape_point) = get_arbitrary_point_on_path(shape) {
let mut pos = 0;
let mut neg = 0;
for line in lines {
for line in quad.lines() {
if line.p0 == shape_point {
return true;
};

View File

@@ -0,0 +1,44 @@
use serde::{Deserialize, Serialize};
#[derive(PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
pub enum BlendMode {
Normal,
Multiply,
Darken,
ColorBurn,
Screen,
Lighten,
ColorDodge,
Overlay,
SoftLight,
HardLight,
Difference,
Exclusion,
Hue,
Saturation,
Color,
Luminosity,
}
impl BlendMode {
pub fn to_svg_style_name(&self) -> &str {
match self {
BlendMode::Normal => "normal",
BlendMode::Multiply => "multiply",
BlendMode::Darken => "darken",
BlendMode::ColorBurn => "color-burn",
BlendMode::Screen => "screen",
BlendMode::Lighten => "lighten",
BlendMode::ColorDodge => "color-dodge",
BlendMode::Overlay => "overlay",
BlendMode::SoftLight => "soft-light",
BlendMode::HardLight => "hard-light",
BlendMode::Difference => "difference",
BlendMode::Exclusion => "exclusion",
BlendMode::Hue => "hue",
BlendMode::Saturation => "saturation",
BlendMode::Color => "color",
BlendMode::Luminosity => "luminosity",
}
}
}

View File

@@ -1,37 +0,0 @@
use glam::DAffine2;
use glam::DVec2;
use kurbo::Shape;
use crate::intersection::intersect_quad_bez_path;
use crate::LayerId;
use super::style;
use super::LayerData;
use serde::{Deserialize, Serialize};
use std::fmt::Write;
#[derive(Debug, Clone, Copy, PartialEq, Default, Deserialize, Serialize)]
pub struct Ellipse {}
impl Ellipse {
pub fn new() -> Ellipse {
Ellipse {}
}
}
impl LayerData for Ellipse {
fn to_kurbo_path(&self, transform: glam::DAffine2, _style: style::PathStyle) -> kurbo::BezPath {
kurbo::Ellipse::from_affine(kurbo::Affine::new(transform.to_cols_array())).to_path(0.01)
}
fn render(&mut self, svg: &mut String, transform: glam::DAffine2, style: style::PathStyle) {
let _ = write!(svg, r#"<path d="{}" {} />"#, self.to_kurbo_path(transform, style).to_svg(), style.render());
}
fn intersects_quad(&self, quad: [DVec2; 4], path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>, style: style::PathStyle) {
if intersect_quad_bez_path(quad, &self.to_kurbo_path(DAffine2::IDENTITY, style), true) {
intersections.push(path.clone());
}
}
}

View File

@@ -1,13 +1,13 @@
use glam::DVec2;
use crate::{DocumentError, LayerId};
use crate::{DocumentError, LayerId, Quad};
use super::{style, Layer, LayerData, LayerDataTypes};
use super::{Layer, LayerData, LayerDataType};
use serde::{Deserialize, Serialize};
use std::fmt::Write;
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
pub struct Folder {
next_assignment_id: LayerId,
pub layer_ids: Vec<LayerId>,
@@ -15,44 +15,53 @@ pub struct Folder {
}
impl LayerData for Folder {
fn to_kurbo_path(&self, _: glam::DAffine2, _: style::PathStyle) -> kurbo::BezPath {
unimplemented!()
}
fn render(&mut self, svg: &mut String, transform: glam::DAffine2, _style: style::PathStyle) {
let _ = writeln!(svg, r#"<g transform="matrix("#);
transform.to_cols_array().iter().enumerate().for_each(|(i, f)| {
let _ = svg.write_str(&(f.to_string() + if i != 5 { "," } else { "" }));
});
let _ = svg.write_str(r#")">"#);
fn render(&mut self, svg: &mut String, transforms: &mut Vec<glam::DAffine2>) {
for layer in &mut self.layers {
let _ = writeln!(svg, "{}", layer.render());
let _ = writeln!(svg, "{}", layer.render(transforms));
}
let _ = writeln!(svg, "</g>");
}
fn intersects_quad(&self, quad: [DVec2; 4], path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>, _style: style::PathStyle) {
fn intersects_quad(&self, quad: Quad, path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>) {
for (layer, layer_id) in self.layers().iter().zip(&self.layer_ids) {
path.push(*layer_id);
layer.intersects_quad(quad, path, intersections);
path.pop();
}
}
fn bounding_box(&self, transform: glam::DAffine2) -> Option<[DVec2; 2]> {
self.layers
.iter()
.filter_map(|layer| layer.data.bounding_box(transform * layer.transform))
.reduce(|a, b| [a[0].min(b[0]), a[1].max(b[1])])
}
}
impl Folder {
pub fn add_layer(&mut self, layer: Layer, insert_index: isize) -> Option<LayerId> {
/// When a insertion id is provided, try to insert the layer with the given id.
/// If that id is already used, return None.
/// When no insertion id is provided, search for the next free id and insert it with that.
pub fn add_layer(&mut self, layer: Layer, id: Option<LayerId>, insert_index: isize) -> Option<LayerId> {
let mut insert_index = insert_index as i128;
if insert_index < 0 {
insert_index = self.layers.len() as i128 + insert_index as i128 + 1;
}
if insert_index <= self.layers.len() as i128 && insert_index >= 0 {
if let Some(id) = id {
self.next_assignment_id = id;
}
if self.layer_ids.contains(&self.next_assignment_id) {
return None;
}
let id = self.next_assignment_id;
self.layers.insert(insert_index as usize, layer);
self.layer_ids.insert(insert_index as usize, self.next_assignment_id);
self.next_assignment_id += 1;
Some(self.next_assignment_id - 1)
self.layer_ids.insert(insert_index as usize, id);
// Linear probing for collision avoidance
while self.layer_ids.contains(&self.next_assignment_id) {
self.next_assignment_id += 1;
}
Some(id)
} else {
None
}
@@ -95,8 +104,8 @@ impl Folder {
pub fn folder(&self, id: LayerId) -> Option<&Folder> {
match self.layer(id) {
Some(Layer {
data: LayerDataTypes::Folder(folder), ..
}) => Some(&folder),
data: LayerDataType::Folder(folder), ..
}) => Some(folder),
_ => None,
}
}
@@ -104,46 +113,9 @@ impl Folder {
pub fn folder_mut(&mut self, id: LayerId) -> Option<&mut Folder> {
match self.layer_mut(id) {
Some(Layer {
data: LayerDataTypes::Folder(folder), ..
data: LayerDataType::Folder(folder), ..
}) => Some(folder),
_ => None,
}
}
pub fn bounding_box(&self, transform: glam::DAffine2) -> Option<[DVec2; 2]> {
let mut layers_non_empty_bounding_boxes = self.layers.iter().filter_map(|layer| layer.bounding_box(transform * layer.transform, layer.style)).peekable();
layers_non_empty_bounding_boxes.peek()?;
let mut x_min = f64::MAX;
let mut y_min = f64::MAX;
let mut x_max = f64::MIN;
let mut y_max = f64::MIN;
for [bounding_box_min, bounding_box_max] in layers_non_empty_bounding_boxes {
if bounding_box_min.x < x_min {
x_min = bounding_box_min.x
}
if bounding_box_min.y < y_min {
y_min = bounding_box_min.y
}
if bounding_box_max.x > x_max {
x_max = bounding_box_max.x
}
if bounding_box_max.y > y_max {
y_max = bounding_box_max.y
}
}
Some([DVec2::new(x_min, y_min), DVec2::new(x_max, y_max)])
}
}
impl Default for Folder {
fn default() -> Self {
Self {
layer_ids: vec![],
layers: vec![],
next_assignment_id: 0,
}
}
}

View File

@@ -1,40 +0,0 @@
use glam::DAffine2;
use glam::DVec2;
use kurbo::Point;
use crate::intersection::intersect_quad_bez_path;
use crate::LayerId;
use super::style;
use super::LayerData;
use serde::{Deserialize, Serialize};
use std::fmt::Write;
#[derive(Debug, Default, Clone, Copy, PartialEq, Deserialize, Serialize)]
pub struct Line;
impl LayerData for Line {
fn to_kurbo_path(&self, transform: glam::DAffine2, _style: style::PathStyle) -> kurbo::BezPath {
fn new_point(a: DVec2) -> Point {
Point::new(a.x, a.y)
}
let mut path = kurbo::BezPath::new();
path.move_to(new_point(transform.translation));
path.line_to(new_point(transform.transform_point2(DVec2::ONE)));
path
}
fn render(&mut self, svg: &mut String, transform: glam::DAffine2, style: style::PathStyle) {
let [x1, y1] = transform.translation.to_array();
let [x2, y2] = transform.transform_point2(DVec2::ONE).to_array();
let _ = write!(svg, r#"<line x1="{}" y1="{}" x2="{}" y2="{}"{} />"#, x1, y1, x2, y2, style.render(),);
}
fn intersects_quad(&self, quad: [DVec2; 4], path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>, style: style::PathStyle) {
if intersect_quad_bez_path(quad, &self.to_kurbo_path(DAffine2::IDENTITY, style), false) {
intersections.push(path.clone());
}
}
}

View File

@@ -1,159 +1,60 @@
pub mod style;
pub mod ellipse;
pub use ellipse::Ellipse;
pub mod line;
use glam::DAffine2;
use glam::{DMat2, DVec2};
use kurbo::BezPath;
use kurbo::Shape as KurboShape;
pub use line::Line;
pub mod rect;
pub use rect::Rect;
pub mod blend_mode;
pub use blend_mode::BlendMode;
pub mod polyline;
pub use polyline::PolyLine;
pub mod shape;
pub use shape::Shape;
pub mod simple_shape;
pub use simple_shape::Shape;
pub mod folder;
use crate::DocumentError;
use crate::LayerId;
use crate::{DocumentError, Quad};
pub use folder::Folder;
use serde::{Deserialize, Serialize};
use std::fmt::Write;
pub trait LayerData {
fn render(&mut self, svg: &mut String, transform: glam::DAffine2, style: style::PathStyle);
fn to_kurbo_path(&self, transform: glam::DAffine2, style: style::PathStyle) -> BezPath;
fn intersects_quad(&self, quad: [DVec2; 4], path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>, style: style::PathStyle);
fn render(&mut self, svg: &mut String, transforms: &mut Vec<glam::DAffine2>);
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]>;
}
// TODO: Rename this `LayerDataType` to not be plural in a separate commit (together with `enum ToolOptions`)
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub enum LayerDataTypes {
pub enum LayerDataType {
Folder(Folder),
Ellipse(Ellipse),
Rect(Rect),
Line(Line),
PolyLine(PolyLine),
Shape(Shape),
}
macro_rules! call_render {
($self:ident.render($svg:ident, $transform:ident, $style:ident) { $($variant:ident),* }) => {
match $self {
$(Self::$variant(x) => x.render($svg, $transform, $style)),*
}
};
}
macro_rules! call_kurbo_path {
($self:ident.to_kurbo_path($transform:ident, $style:ident) { $($variant:ident),* }) => {
match $self {
$(Self::$variant(x) => x.to_kurbo_path($transform, $style)),*
}
};
}
macro_rules! call_intersects_quad {
($self:ident.intersects_quad($quad:ident, $path:ident, $intersections:ident, $style:ident) { $($variant:ident),* }) => {
match $self {
$(Self::$variant(x) => x.intersects_quad($quad, $path, $intersections, $style)),*
}
};
}
impl LayerDataTypes {
pub fn render(&mut self, svg: &mut String, transform: glam::DAffine2, style: style::PathStyle) {
call_render! {
self.render(svg, transform, style) {
Folder,
Ellipse,
Rect,
Line,
PolyLine,
Shape
}
}
}
pub fn to_kurbo_path(&self, transform: glam::DAffine2, style: style::PathStyle) -> BezPath {
call_kurbo_path! {
self.to_kurbo_path(transform, style) {
Folder,
Ellipse,
Rect,
Line,
PolyLine,
Shape
}
}
}
pub fn intersects_quad(&self, quad: [DVec2; 4], path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>, style: style::PathStyle) {
call_intersects_quad! {
self.intersects_quad(quad, path, intersections, style) {
Folder,
Ellipse,
Rect,
Line,
PolyLine,
Shape
}
}
}
pub fn bounding_box(&self, transform: glam::DAffine2, style: style::PathStyle) -> [DVec2; 2] {
let bez_path = self.to_kurbo_path(transform, style);
let bbox = bez_path.bounding_box();
[DVec2::new(bbox.x0, bbox.y0), DVec2::new(bbox.x1, bbox.y1)]
}
}
#[derive(PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
pub enum BlendMode {
Normal,
Multiply,
Darken,
ColorBurn,
Screen,
Lighten,
ColorDodge,
Overlay,
SoftLight,
HardLight,
Difference,
Exclusion,
Hue,
Saturation,
Color,
Luminosity,
}
impl BlendMode {
fn to_svg_style_name(&self) -> &str {
impl LayerDataType {
pub fn inner(&self) -> &dyn LayerData {
match self {
BlendMode::Normal => "normal",
BlendMode::Multiply => "multiply",
BlendMode::Darken => "darken",
BlendMode::ColorBurn => "color-burn",
BlendMode::Screen => "screen",
BlendMode::Lighten => "lighten",
BlendMode::ColorDodge => "color-dodge",
BlendMode::Overlay => "overlay",
BlendMode::SoftLight => "soft-light",
BlendMode::HardLight => "hard-light",
BlendMode::Difference => "difference",
BlendMode::Exclusion => "exclusion",
BlendMode::Hue => "hue",
BlendMode::Saturation => "saturation",
BlendMode::Color => "color",
BlendMode::Luminosity => "luminosity",
LayerDataType::Shape(s) => s,
LayerDataType::Folder(f) => f,
}
}
pub fn inner_mut(&mut self) -> &mut dyn LayerData {
match self {
LayerDataType::Shape(s) => s,
LayerDataType::Folder(f) => f,
}
}
}
impl LayerData for LayerDataType {
fn render(&mut self, svg: &mut String, transforms: &mut Vec<glam::DAffine2>) {
self.inner_mut().render(svg, transforms)
}
fn intersects_quad(&self, quad: Quad, path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>) {
self.inner().intersects_quad(quad, path, intersections)
}
fn bounding_box(&self, transform: glam::DAffine2) -> Option<[DVec2; 2]> {
self.inner().bounding_box(transform)
}
}
#[derive(Serialize, Deserialize)]
@@ -163,14 +64,13 @@ struct DAffine2Ref {
pub translation: DVec2,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, PartialEq, Deserialize, Serialize)]
pub struct Layer {
pub visible: bool,
pub name: Option<String>,
pub data: LayerDataTypes,
pub data: LayerDataType,
#[serde(with = "DAffine2Ref")]
pub transform: glam::DAffine2,
pub style: style::PathStyle,
pub cache: String,
pub thumbnail_cache: String,
pub cache_dirty: bool,
@@ -179,13 +79,12 @@ pub struct Layer {
}
impl Layer {
pub fn new(data: LayerDataTypes, transform: [f64; 6], style: style::PathStyle) -> Self {
pub fn new(data: LayerDataType, transform: [f64; 6]) -> Self {
Self {
visible: true,
name: None,
data,
transform: glam::DAffine2::from_cols_array(&transform),
style,
cache: String::new(),
thumbnail_cache: String::new(),
cache_dirty: true,
@@ -194,79 +93,72 @@ impl Layer {
}
}
pub fn render(&mut self) -> &str {
pub fn render(&mut self, transforms: &mut Vec<DAffine2>) -> &str {
if !self.visible {
return "";
}
if self.cache_dirty {
transforms.push(self.transform);
self.thumbnail_cache.clear();
self.data.render(&mut self.thumbnail_cache, self.transform, self.style);
self.data.render(&mut self.thumbnail_cache, transforms);
self.cache.clear();
let _ = writeln!(self.cache, r#"<g transform="matrix("#);
self.transform.to_cols_array().iter().enumerate().for_each(|(i, f)| {
let _ = self.cache.write_str(&(f.to_string() + if i != 5 { "," } else { "" }));
});
let _ = write!(
self.cache,
r#"<g style="mix-blend-mode: {}; opacity: {}">{}</g>"#,
r#")" style="mix-blend-mode: {}; opacity: {}">{}</g>"#,
self.blend_mode.to_svg_style_name(),
self.opacity,
self.thumbnail_cache.as_str()
);
transforms.pop();
self.cache_dirty = false;
}
self.cache.as_str()
}
pub fn intersects_quad(&self, quad: [DVec2; 4], path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>) {
let inv_transform = self.transform.inverse();
let transformed_quad = [
inv_transform.transform_point2(quad[0]),
inv_transform.transform_point2(quad[1]),
inv_transform.transform_point2(quad[2]),
inv_transform.transform_point2(quad[3]),
];
pub fn intersects_quad(&self, quad: Quad, path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>) {
if !self.visible {
return;
}
self.data.intersects_quad(transformed_quad, path, intersections, self.style)
}
pub fn render_on(&mut self, svg: &mut String) {
*svg += self.render();
}
pub fn to_kurbo_path(&self) -> BezPath {
self.data.to_kurbo_path(self.transform, self.style)
let transformed_quad = self.transform.inverse() * quad;
self.data.intersects_quad(transformed_quad, path, intersections)
}
pub fn current_bounding_box(&self) -> Option<[DVec2; 2]> {
self.bounding_box(self.transform, self.style)
}
pub fn bounding_box(&self, transform: glam::DAffine2, style: style::PathStyle) -> Option<[DVec2; 2]> {
if let Ok(folder) = self.as_folder() {
folder.bounding_box(transform)
} else {
Some(self.data.bounding_box(transform, style))
}
self.data.bounding_box(self.transform)
}
pub fn as_folder_mut(&mut self) -> Result<&mut Folder, DocumentError> {
match &mut self.data {
LayerDataTypes::Folder(f) => Ok(f),
LayerDataType::Folder(f) => Ok(f),
_ => Err(DocumentError::NotAFolder),
}
}
pub fn as_folder(&self) -> Result<&Folder, DocumentError> {
match &self.data {
LayerDataTypes::Folder(f) => Ok(&f),
LayerDataType::Folder(f) => Ok(f),
_ => Err(DocumentError::NotAFolder),
}
}
}
pub fn render_as_folder(&mut self, svg: &mut String) {
if let LayerDataTypes::Folder(f) = &mut self.data {
f.render(svg, self.transform, self.style)
impl Clone for Layer {
fn clone(&self) -> Self {
Self {
visible: self.visible,
name: self.name.clone(),
data: self.data.clone(),
transform: self.transform,
cache: String::new(),
thumbnail_cache: String::new(),
cache_dirty: true,
blend_mode: self.blend_mode,
opacity: self.opacity,
}
}
}

View File

@@ -1,66 +0,0 @@
use crate::{intersection::intersect_quad_bez_path, LayerId};
use glam::{DAffine2, DVec2};
use serde::{Deserialize, Serialize};
use std::fmt::Write;
use super::{style, LayerData};
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct PolyLine {
points: Vec<glam::DVec2>,
}
impl PolyLine {
pub fn new(points: Vec<impl Into<glam::DVec2>>) -> PolyLine {
PolyLine {
points: points.into_iter().map(|it| it.into()).collect(),
}
}
}
impl LayerData for PolyLine {
fn to_kurbo_path(&self, transform: glam::DAffine2, _style: style::PathStyle) -> kurbo::BezPath {
let mut path = kurbo::BezPath::new();
self.points
.iter()
.map(|v| transform.transform_point2(*v))
.map(|v| kurbo::Point { x: v.x, y: v.y })
.enumerate()
.for_each(|(i, p)| if i == 0 { path.move_to(p) } else { path.line_to(p) });
path
}
fn render(&mut self, svg: &mut String, transform: glam::DAffine2, style: style::PathStyle) {
if self.points.is_empty() {
return;
}
let _ = write!(svg, r#"<polyline points=""#);
let mut points = self.points.iter().map(|v| transform.transform_point2(*v));
let first = points.next().unwrap();
let _ = write!(svg, "{:.3} {:.3}", first.x, first.y);
for point in points {
let _ = write!(svg, " {:.3} {:.3}", point.x, point.y);
}
let _ = write!(svg, r#""{} />"#, style.render());
}
fn intersects_quad(&self, quad: [DVec2; 4], path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>, style: style::PathStyle) {
if intersect_quad_bez_path(quad, &self.to_kurbo_path(DAffine2::IDENTITY, style), false) {
intersections.push(path.clone());
}
}
}
#[cfg(test)]
#[test]
fn polyline_should_render() {
use super::style::PathStyle;
use glam::DVec2;
let mut polyline = PolyLine {
points: vec![DVec2::new(3.0, 4.12354), DVec2::new(1.0, 5.54)],
};
let mut svg = String::new();
polyline.render(&mut svg, glam::DAffine2::IDENTITY, PathStyle::default());
assert_eq!(r##"<polyline points="3.000 4.124 1.000 5.540" />"##, svg);
}

View File

@@ -1,39 +0,0 @@
use glam::DAffine2;
use glam::DVec2;
use kurbo::Point;
use crate::intersection::intersect_quad_bez_path;
use crate::LayerId;
use super::style;
use super::LayerData;
use serde::{Deserialize, Serialize};
use std::fmt::Write;
#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
pub struct Rect;
impl LayerData for Rect {
fn to_kurbo_path(&self, transform: glam::DAffine2, _style: style::PathStyle) -> kurbo::BezPath {
fn new_point(a: DVec2) -> Point {
Point::new(a.x, a.y)
}
let mut path = kurbo::BezPath::new();
path.move_to(new_point(transform.translation));
// TODO: Use into_iter when new impls get added in rust 2021
[(1., 0.), (1., 1.), (0., 1.)].iter().for_each(|v| path.line_to(new_point(transform.transform_point2((*v).into()))));
path.close_path();
path
}
fn render(&mut self, svg: &mut String, transform: glam::DAffine2, style: style::PathStyle) {
let _ = write!(svg, r#"<path d="{}" {} />"#, self.to_kurbo_path(transform, style).to_svg(), style.render());
}
fn intersects_quad(&self, quad: [DVec2; 4], path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>, style: style::PathStyle) {
if intersect_quad_bez_path(quad, &self.to_kurbo_path(DAffine2::IDENTITY, style), true) {
intersections.push(path.clone());
}
}
}

View File

@@ -1,76 +0,0 @@
use glam::DAffine2;
use glam::DVec2;
use crate::intersection::intersect_quad_bez_path;
use crate::LayerId;
use kurbo::BezPath;
use super::style;
use super::LayerData;
use serde::{Deserialize, Serialize};
use std::fmt::Write;
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Shape {
equal_sides: bool,
sides: u8,
}
impl Shape {
pub fn new(equal_sides: bool, sides: u8) -> Shape {
Shape { equal_sides, sides }
}
}
impl LayerData for Shape {
fn to_kurbo_path(&self, transform: glam::DAffine2, _style: style::PathStyle) -> BezPath {
fn unit_rotation(theta: f64) -> DVec2 {
DVec2::new(-theta.sin(), theta.cos())
}
let mut path = kurbo::BezPath::new();
let apothem_offset_angle = std::f64::consts::PI / (self.sides as f64);
let relative_points = (0..self.sides).map(|i| apothem_offset_angle * ((i * 2 + ((self.sides + 1) % 2)) as f64)).map(unit_rotation);
let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
relative_points.clone().for_each(|p| {
min_x = min_x.min(p.x);
min_y = min_y.min(p.y);
max_x = max_x.max(p.x);
max_y = max_y.max(p.y);
});
relative_points
.map(|p| {
if self.equal_sides {
p
} else {
DVec2::new((p.x - min_x) / (max_x - min_x) * 2. - 1., (p.y - min_y) / (max_y - min_y) * 2. - 1.)
}
})
.map(|p| DVec2::new(p.x / 2. + 0.5, p.y / 2. + 0.5))
.map(|unit| transform.transform_point2(unit))
.map(|pos| kurbo::Point::new(pos.x, pos.y))
.enumerate()
.for_each(|(i, p)| {
if i == 0 {
path.move_to(p);
} else {
path.line_to(p);
}
});
path.close_path();
path
}
fn render(&mut self, svg: &mut String, transform: glam::DAffine2, style: style::PathStyle) {
let _ = write!(svg, r#"<path d="{}" {} />"#, self.to_kurbo_path(transform, style).to_svg(), style.render());
}
fn intersects_quad(&self, quad: [DVec2; 4], path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>, style: style::PathStyle) {
if intersect_quad_bez_path(quad, &self.to_kurbo_path(DAffine2::IDENTITY, style), true) {
intersections.push(path.clone());
}
}
}

View File

@@ -0,0 +1,146 @@
use glam::DAffine2;
use glam::DMat2;
use glam::DVec2;
use kurbo::Affine;
use kurbo::Shape as KurboShape;
use crate::intersection::intersect_quad_bez_path;
use crate::LayerId;
use crate::Quad;
use kurbo::BezPath;
use super::style;
use super::style::PathStyle;
use super::LayerData;
use serde::{Deserialize, Serialize};
use std::fmt::Write;
fn glam_to_kurbo(transform: DAffine2) -> Affine {
Affine::new(transform.to_cols_array())
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Shape {
pub path: BezPath,
pub style: style::PathStyle,
pub render_index: i32,
pub solid: bool,
}
impl LayerData for Shape {
fn render(&mut self, svg: &mut String, transforms: &mut Vec<DAffine2>) {
let mut path = self.path.clone();
let transform = self.transform(transforms);
let inverse = transform.inverse();
if !inverse.is_finite() {
let _ = write!(svg, "<!-- SVG shape has an invalid transform -->");
return;
}
path.apply_affine(glam_to_kurbo(transform));
let _ = writeln!(svg, r#"<g transform="matrix("#);
inverse.to_cols_array().iter().enumerate().for_each(|(i, entry)| {
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());
let _ = svg.write_str("</g>");
}
fn bounding_box(&self, transform: glam::DAffine2) -> Option<[DVec2; 2]> {
let mut path = self.path.clone();
if transform.matrix2 == DMat2::ZERO {
return None;
}
path.apply_affine(glam_to_kurbo(transform));
use kurbo::Shape;
let kurbo::Rect { x0, y0, x1, y1 } = path.bounding_box();
Some([(x0, y0).into(), (x1, y1).into()])
}
fn intersects_quad(&self, quad: Quad, path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>) {
if intersect_quad_bez_path(quad, &self.path, self.solid) {
intersections.push(path.clone());
}
}
}
impl Shape {
pub fn transform(&self, transforms: &[DAffine2]) -> DAffine2 {
let start = match self.render_index {
-1 => 0,
x => (transforms.len() as i32 - x).max(0) as usize,
};
transforms.iter().skip(start).cloned().reduce(|a, b| a * b).unwrap_or(DAffine2::IDENTITY)
}
pub fn shape(sides: u8, style: PathStyle) -> Self {
use std::f64::consts::{FRAC_PI_2, TAU};
fn unit_rotation(theta: f64) -> DVec2 {
DVec2::new(theta.sin(), theta.cos())
}
let mut path = kurbo::BezPath::new();
let apothem_offset_angle = TAU / (sides as f64);
// Rotate odd sided shapes by 90 degrees
let offset = ((sides + 1) % 2) as f64 * FRAC_PI_2;
let relative_points = (0..sides).map(|i| apothem_offset_angle * i as f64 + offset).map(unit_rotation);
let min = relative_points.clone().reduce(|a, b| a.min(b)).unwrap_or_default();
let transform = DAffine2::from_scale_angle_translation(DVec2::ONE / 2., 0., -min / 2.);
let point = |vec: DVec2| kurbo::Point::new(vec.x, vec.y);
let mut relative_points = relative_points.map(|p| point(transform.transform_point2(p)));
path.move_to(relative_points.next().expect("Tried to create an ngon with 0 sides"));
relative_points.for_each(|p| path.line_to(p));
path.close_path();
Self {
path,
style,
render_index: 1,
solid: true,
}
}
pub fn rectangle(style: PathStyle) -> Self {
Self {
path: kurbo::Rect::new(0., 0., 1., 1.).to_path(0.01),
style,
render_index: 1,
solid: true,
}
}
pub fn ellipse(style: PathStyle) -> Self {
Self {
path: kurbo::Ellipse::from_rect(kurbo::Rect::new(0., 0., 1., 1.)).to_path(0.01),
style,
render_index: 1,
solid: true,
}
}
pub fn line(style: PathStyle) -> Self {
Self {
path: kurbo::Line::new((0., 0.), (1., 0.)).to_path(0.01),
style,
render_index: 1,
solid: true,
}
}
pub fn poly_line(points: Vec<impl Into<glam::DVec2>>, style: PathStyle) -> Self {
let mut path = kurbo::BezPath::new();
points
.into_iter()
.map(|v| v.into())
.map(|v: DVec2| kurbo::Point { x: v.x, y: v.y })
.enumerate()
.for_each(|(i, p)| if i == 0 { path.move_to(p) } else { path.line_to(p) });
Self {
path,
style,
render_index: 0,
solid: false,
}
}
}

View File

@@ -12,6 +12,7 @@ pub mod layers;
pub mod operation;
pub mod response;
pub use intersection::Quad;
pub use operation::Operation;
pub use response::DocumentResponse;
@@ -24,4 +25,5 @@ pub enum DocumentError {
IndexOutOfBounds,
NotAFolder,
NonReorderableSelection,
NotAShape,
}

View File

@@ -1,3 +1,8 @@
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use crate::{
color::Color,
layers::{style, BlendMode, Layer},
@@ -7,7 +12,7 @@ use crate::{
use serde::{Deserialize, Serialize};
#[repr(C)]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub enum Operation {
AddEllipse {
path: Vec<LayerId>,
@@ -21,6 +26,11 @@ pub enum Operation {
transform: [f64; 6],
style: style::PathStyle,
},
AddBoundingBox {
path: Vec<LayerId>,
transform: [f64; 6],
style: style::PathStyle,
},
AddLine {
path: Vec<LayerId>,
insert_index: isize,
@@ -38,7 +48,6 @@ pub enum Operation {
path: Vec<LayerId>,
insert_index: isize,
transform: [f64; 6],
equal_sides: bool,
sides: u8,
style: style::PathStyle,
},
@@ -48,6 +57,10 @@ pub enum Operation {
DuplicateLayer {
path: Vec<LayerId>,
},
RenameLayer {
path: Vec<LayerId>,
name: String,
},
PasteLayer {
layer: Layer,
path: Vec<LayerId>,
@@ -56,20 +69,32 @@ pub enum Operation {
AddFolder {
path: Vec<LayerId>,
},
MountWorkingFolder {
path: Vec<LayerId>,
},
TransformLayer {
path: Vec<LayerId>,
transform: [f64; 6],
},
TransformLayerInViewport {
path: Vec<LayerId>,
transform: [f64; 6],
},
SetLayerTransformInViewport {
path: Vec<LayerId>,
transform: [f64; 6],
},
TransformLayerInScope {
path: Vec<LayerId>,
transform: [f64; 6],
scope: [f64; 6],
},
SetLayerTransformInScope {
path: Vec<LayerId>,
transform: [f64; 6],
scope: [f64; 6],
},
SetLayerTransform {
path: Vec<LayerId>,
transform: [f64; 6],
},
DiscardWorkingFolder,
ClearWorkingFolder,
CommitTransaction,
ToggleVisibility {
path: Vec<LayerId>,
},
@@ -86,3 +111,24 @@ pub enum Operation {
color: Color,
},
}
impl Operation {
/// Returns the byte representation of the message.
///
/// # Safety
/// This function reads from uninitialized memory!!!
/// Only use if you know what you are doing
unsafe fn as_slice(&self) -> &[u8] {
core::slice::from_raw_parts(self as *const Operation as *const u8, std::mem::size_of::<Operation>())
}
/// Returns a pseudo hash that should uniquely identify the operation.
/// This is needed because `Hash` is not implemented for f64s
///
/// # Safety
/// This function reads from uninitialized memory but the generated value should be fine.
pub fn pseudo_hash(&self) -> u64 {
let mut s = DefaultHasher::new();
unsafe { self.as_slice() }.hash(&mut s);
s.finish()
}
}

View File

@@ -9,6 +9,7 @@ pub enum DocumentResponse {
FolderChanged { path: Vec<LayerId> },
CreatedLayer { path: Vec<LayerId> },
DeletedLayer { path: Vec<LayerId> },
LayerChanged { path: Vec<LayerId> },
}
impl fmt::Display for DocumentResponse {
@@ -17,6 +18,7 @@ impl fmt::Display for DocumentResponse {
DocumentResponse::DocumentChanged { .. } => "DocumentChanged",
DocumentResponse::FolderChanged { .. } => "FolderChanged",
DocumentResponse::CreatedLayer { .. } => "CreatedLayer",
DocumentResponse::LayerChanged { .. } => "LayerChanged",
DocumentResponse::DeletedLayer { .. } => "DeleteLayer",
};