-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathvector_nodes.rs
More file actions
2891 lines (2447 loc) · 105 KB
/
vector_nodes.rs
File metadata and controls
2891 lines (2447 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use core::cmp::Ordering;
use core::f64::consts::{PI, TAU};
use core::hash::{Hash, Hasher};
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::registry::types::{Angle, Length, Multiplier, Percentage, PixelLength, Progression, SeedValue};
use core_types::table::{Table, TableRow, TableRowMut};
use core_types::transform::{Footprint, Transform};
use core_types::{CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphic_types::Vector;
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{Graphic, IntoGraphicTable};
use kurbo::simplify::{SimplifyOptions, simplify_bezpath};
use kurbo::{Affine, BezPath, DEFAULT_ACCURACY, Line, ParamCurve, PathEl, PathSeg, Shape};
use rand::{Rng, SeedableRng};
use std::collections::hash_map::DefaultHasher;
use vector_types::subpath::{BezierHandles, ManipulatorGroup};
use vector_types::vector::PointDomain;
use vector_types::vector::algorithms::bezpath_algorithms::{self, TValue, eval_pathseg_euclidean, evaluate_bezpath, sample_polyline_on_bezpath, split_bezpath, tangent_on_bezpath};
use vector_types::vector::algorithms::merge_by_distance::MergeByDistanceExt;
use vector_types::vector::algorithms::offset_subpath::offset_bezpath;
use vector_types::vector::algorithms::spline::{solve_spline_first_handle_closed, solve_spline_first_handle_open};
use vector_types::vector::misc::{
CentroidType, ExtrudeJoiningAlgorithm, HandleId, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, bezpath_from_manipulator_groups, bezpath_to_manipulator_groups, handles_to_segment,
is_linear, point_to_dvec2, segment_to_handles,
};
use vector_types::vector::style::{Fill, Gradient, GradientStops, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use vector_types::vector::{FillId, PointId, RegionId, SegmentDomain, SegmentId, StrokeId, VectorExt};
/// Implemented for types that can be converted to an iterator of vector rows.
/// Used for the fill and stroke node so they can be used on `Table<Graphic>` or `Table<Vector>`.
trait VectorTableIterMut {
fn vector_iter_mut(&mut self) -> impl Iterator<Item = TableRowMut<'_, Vector>>;
}
impl VectorTableIterMut for Table<Graphic> {
fn vector_iter_mut(&mut self) -> impl Iterator<Item = TableRowMut<'_, Vector>> {
// Grab only the direct children
self.iter_mut().filter_map(|element| element.element.as_vector_mut()).flat_map(move |vector| vector.iter_mut())
}
}
impl VectorTableIterMut for Table<Vector> {
fn vector_iter_mut(&mut self) -> impl Iterator<Item = TableRowMut<'_, Vector>> {
self.iter_mut()
}
}
/// Uniquely sets the fill and/or stroke style of every vector element to individual colors sampled along a chosen gradient.
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector))]
async fn assign_colors<T>(
_: impl Ctx,
/// The content with vector paths to apply the fill and/or stroke style to.
#[implementations(Table<Graphic>, Table<Vector>)]
#[widget(ParsedWidgetOverride::Hidden)]
mut content: T,
/// Whether to style the fill.
#[default(true)]
fill: bool,
/// Whether to style the stroke.
stroke: bool,
/// The range of colors to select from.
#[widget(ParsedWidgetOverride::Custom = "assign_colors_gradient")]
gradient: Table<GradientStops>,
/// Whether to reverse the gradient.
reverse: bool,
/// Whether to randomize the color selection for each element from throughout the gradient.
randomize: bool,
/// The seed used for randomization.
/// Seed to determine unique variations on the randomized color selection.
#[widget(ParsedWidgetOverride::Custom = "assign_colors_seed")]
seed: SeedValue,
/// The number of elements to span across the gradient before repeating. A 0 value will span the entire gradient once.
#[widget(ParsedWidgetOverride::Custom = "assign_colors_repeat_every")]
repeat_every: u32,
) -> T
where
T: VectorTableIterMut + 'n + Send,
{
let Some(row) = gradient.into_iter().next() else { return content };
let length = content.vector_iter_mut().count();
let gradient = if reverse { row.element.reversed() } else { row.element };
let mut rng = rand::rngs::StdRng::seed_from_u64(seed.into());
for (i, vector) in content.vector_iter_mut().enumerate() {
let factor = match randomize {
true => rng.random::<f64>(),
false => match repeat_every {
0 => i as f64 / (length - 1).max(1) as f64,
1 => 0.,
_ => i as f64 % repeat_every as f64 / (repeat_every - 1) as f64,
},
};
let color = gradient.evaluate(factor);
if fill {
vector.element.style.set_fill(Fill::Solid(color));
}
if stroke && let Some(stroke) = vector.element.style.stroke().and_then(|stroke| stroke.with_color(&Some(color))) {
vector.element.style.set_stroke(stroke);
}
}
content
}
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("fill_properties"))]
async fn fill<F: Into<Fill> + 'n + Send, V: VectorTableIterMut + 'n + Send>(
_: impl Ctx,
/// The content with vector paths to apply the fill style to.
#[implementations(
Table<Vector>,
Table<Vector>,
Table<Vector>,
Table<Vector>,
Table<Graphic>,
Table<Graphic>,
Table<Graphic>,
Table<Graphic>,
)]
mut content: V,
/// The fill to paint the path with.
#[default(Color::BLACK)]
#[implementations(
Fill,
Table<Color>,
Table<GradientStops>,
Gradient,
Fill,
Table<Color>,
Table<GradientStops>,
Gradient,
)]
fill: F,
_backup_color: Table<Color>,
_backup_gradient: Gradient,
) -> V {
let fill: Fill = fill.into();
for vector in content.vector_iter_mut() {
vector.element.style.set_fill(fill.clone());
}
content
}
trait IntoF64Vec {
fn into_vec(self) -> Vec<f64>;
}
impl IntoF64Vec for f64 {
fn into_vec(self) -> Vec<f64> {
vec![self]
}
}
impl IntoF64Vec for Vec<f64> {
fn into_vec(self) -> Vec<f64> {
self
}
}
impl IntoF64Vec for String {
fn into_vec(self) -> Vec<f64> {
self.split(&[',', ' ']).filter(|s| !s.is_empty()).filter_map(|s| s.parse::<f64>().ok()).collect()
}
}
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("stroke_properties"))]
async fn stroke<V, L: IntoF64Vec>(
_: impl Ctx,
/// The content with vector paths to apply the stroke style to.
#[implementations(Table<Vector>, Table<Vector>, Table<Vector>, Table<Graphic>, Table<Graphic>, Table<Graphic>)]
mut content: Table<V>,
/// The stroke color.
#[default(Color::BLACK)]
color: Table<Color>,
/// The stroke thickness.
#[unit(" px")]
#[default(2.)]
weight: f64,
/// The alignment of stroke to the path's centerline or (for closed shapes) the inside or outside of the shape.
align: StrokeAlign,
/// The shape of the stroke at open endpoints.
cap: StrokeCap,
/// The curvature of the bent stroke at sharp corners.
join: StrokeJoin,
/// The threshold for when a miter-joined stroke is converted to a bevel-joined stroke when a sharp angle becomes pointier than this ratio.
#[default(4.)]
miter_limit: f64,
// <https://svgwg.org/svg2-draft/painting.html#PaintOrderProperty>
/// The order to paint the stroke on top of the fill, or the fill on top of the stroke.
paint_order: PaintOrder,
/// The stroke dash lengths. Each length forms a distance in a pattern where the first length is a dash, the second is a gap, and so on. If the list is an odd length, the pattern repeats with solid-gap roles reversed.
#[implementations(Vec<f64>, f64, String, Vec<f64>, f64, String)]
dash_lengths: L,
/// The phase offset distance from the starting point of the dash pattern.
#[unit(" px")]
dash_offset: f64,
) -> Table<V>
where
Table<V>: VectorTableIterMut + 'n + Send,
{
let stroke = Stroke {
color: color.into(),
weight,
dash_lengths: dash_lengths.into_vec(),
dash_offset,
cap,
join,
join_miter_limit: miter_limit,
align,
transform: DAffine2::IDENTITY,
paint_order,
};
for vector in content.vector_iter_mut() {
let mut stroke = stroke.clone();
stroke.transform *= *vector.transform;
vector.element.style.set_stroke(stroke);
}
content
}
#[node_macro::node(name("Copy to Points"), category("Repeat"), path(core_types::vector))]
async fn copy_to_points<I: 'n + Send + Clone>(
_: impl Ctx,
points: Table<Vector>,
/// Artwork to be copied and placed at each point.
#[expose]
#[implementations(Table<Graphic>, Table<Vector>, Table<Raster<CPU>>, Table<Color>, Table<GradientStops>)]
instance: Table<I>,
/// Minimum range of randomized sizes given to each instance.
#[default(1)]
#[range((0., 2.))]
#[unit("x")]
random_scale_min: Multiplier,
/// Maximum range of randomized sizes given to each instance.
#[default(1)]
#[range((0., 2.))]
#[unit("x")]
random_scale_max: Multiplier,
/// Bias for the probability distribution of randomized sizes (0 is uniform, negatives favor more of small sizes, positives favor more of large sizes).
#[range((-50., 50.))]
random_scale_bias: f64,
/// Seed to determine unique variations on all the randomized instance sizes.
random_scale_seed: SeedValue,
/// Range of randomized angles given to each instance, in degrees ranging from furthest clockwise to counterclockwise.
#[range((0., 360.))]
random_rotation: Angle,
/// Seed to determine unique variations on all the randomized instance angles.
random_rotation_seed: SeedValue,
) -> Table<I> {
let mut result_table = Table::new();
let random_scale_difference = random_scale_max - random_scale_min;
for row in points.into_iter() {
let mut scale_rng = rand::rngs::StdRng::seed_from_u64(random_scale_seed.into());
let mut rotation_rng = rand::rngs::StdRng::seed_from_u64(random_rotation_seed.into());
let do_scale = random_scale_difference.abs() > 1e-6;
let do_rotation = random_rotation.abs() > 1e-6;
let points_transform = row.transform;
for &point in row.element.point_domain.positions() {
let translation = points_transform.transform_point2(point);
let rotation = if do_rotation {
let degrees = (rotation_rng.random::<f64>() - 0.5) * random_rotation;
degrees / 360. * TAU
} else {
0.
};
let scale = if do_scale {
if random_scale_bias.abs() < 1e-6 {
// Linear
random_scale_min + scale_rng.random::<f64>() * random_scale_difference
} else {
// Weighted (see <https://www.desmos.com/calculator/gmavd3m9bd>)
let horizontal_scale_factor = 1. - 2_f64.powf(random_scale_bias);
let scale_factor = (1. - scale_rng.random::<f64>() * horizontal_scale_factor).log2() / random_scale_bias;
random_scale_min + scale_factor * random_scale_difference
}
} else {
random_scale_min
};
let transform = DAffine2::from_scale_angle_translation(DVec2::splat(scale), rotation, translation);
for mut row in instance.iter().map(|row| row.into_cloned()) {
row.transform = transform * row.transform;
result_table.push(row);
}
}
}
result_table
}
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn round_corners(
_: impl Ctx,
source: Table<Vector>,
#[hard_min(0.)]
#[default(10.)]
radius: PixelLength,
#[range((0., 1.))]
#[hard_min(0.)]
#[hard_max(1.)]
#[default(0.5)]
roundness: f64,
#[default(100.)] edge_length_limit: Percentage,
#[range((0., 180.))]
#[hard_min(0.)]
#[hard_max(180.)]
#[default(5.)]
min_angle_threshold: Angle,
) -> Table<Vector> {
source
.iter()
.map(|source| {
let source_transform = *source.transform;
let source_transform_inverse = source_transform.inverse();
let source_node_id = source.source_node_id;
let source = source.element;
let upstream_nested_layers = source.upstream_data.clone();
// Flip the roundness to help with user intuition
let roundness = 1. - roundness;
// Convert 0-100 to 0-0.5
let edge_length_limit = edge_length_limit * 0.005;
let mut result = Vector {
style: source.style.clone(),
..Default::default()
};
// Grab the initial point ID as a stable starting point
let mut initial_point_id = source.point_domain.ids().first().copied().unwrap_or(PointId::generate());
for mut bezpath in source.stroke_bezpath_iter() {
bezpath.apply_affine(Affine::new(source_transform.to_cols_array()));
let (manipulator_groups, is_closed) = bezpath_to_manipulator_groups(&bezpath);
// End if not enough points for corner rounding
if manipulator_groups.len() < 3 {
result.append_bezpath(bezpath);
continue;
}
let mut new_manipulator_groups = Vec::new();
for i in 0..manipulator_groups.len() {
// Skip first and last points for open paths
if !is_closed && (i == 0 || i == manipulator_groups.len() - 1) {
new_manipulator_groups.push(manipulator_groups[i]);
continue;
}
// Not the prettiest, but it makes the rest of the logic more readable
let prev_idx = if i == 0 { if is_closed { manipulator_groups.len() - 1 } else { 0 } } else { i - 1 };
let curr_idx = i;
let next_idx = if i == manipulator_groups.len() - 1 { if is_closed { 0 } else { i } } else { i + 1 };
let prev = manipulator_groups[prev_idx].anchor;
let curr = manipulator_groups[curr_idx].anchor;
let next = manipulator_groups[next_idx].anchor;
let dir1 = (curr - prev).normalize_or(DVec2::X);
let dir2 = (next - curr).normalize_or(DVec2::X);
let theta = PI - dir1.angle_to(dir2).abs();
// Skip near-straight corners
if theta > PI - min_angle_threshold.to_radians() {
new_manipulator_groups.push(manipulator_groups[curr_idx]);
continue;
}
// Calculate L, with limits to avoid extreme values
let distance_along_edge = radius / (theta / 2.).sin();
let distance_along_edge = distance_along_edge.min(edge_length_limit * (curr - prev).length().min((next - curr).length())).max(0.01);
// Find points on each edge at distance L from corner
let p1 = curr - dir1 * distance_along_edge;
let p2 = curr + dir2 * distance_along_edge;
// Add first point (coming into the rounded corner)
new_manipulator_groups.push(ManipulatorGroup {
anchor: p1,
in_handle: None,
out_handle: Some(curr - dir1 * distance_along_edge * roundness),
id: initial_point_id.next_id(),
});
// Add second point (coming out of the rounded corner)
new_manipulator_groups.push(ManipulatorGroup {
anchor: p2,
in_handle: Some(curr + dir2 * distance_along_edge * roundness),
out_handle: None,
id: initial_point_id.next_id(),
});
}
// One subpath for each shape
let mut rounded_subpath = bezpath_from_manipulator_groups(&new_manipulator_groups, is_closed);
rounded_subpath.apply_affine(Affine::new(source_transform_inverse.to_cols_array()));
result.append_bezpath(rounded_subpath);
}
result.upstream_data = upstream_nested_layers;
TableRow {
element: result,
transform: source_transform,
alpha_blending: Default::default(),
source_node_id: *source_node_id,
}
})
.collect()
}
#[node_macro::node(name("Merge by Distance"), category("Vector: Modifier"), path(core_types::vector))]
pub fn merge_by_distance(
_: impl Ctx,
content: Table<Vector>,
#[default(0.1)]
#[hard_min(0.0001)]
distance: PixelLength,
algorithm: MergeByDistanceAlgorithm,
) -> Table<Vector> {
match algorithm {
MergeByDistanceAlgorithm::Spatial => content
.into_iter()
.map(|mut row| {
row.element.merge_by_distance_spatial(row.transform, distance);
row
})
.collect(),
MergeByDistanceAlgorithm::Topological => content
.into_iter()
.map(|mut row| {
row.element.merge_by_distance_topological(distance);
row
})
.collect(),
}
}
pub mod extrude_algorithms {
use glam::DVec2;
use kurbo::{ParamCurve, ParamCurveDeriv};
use vector_types::subpath::BezierHandles;
use vector_types::vector::StrokeId;
use vector_types::vector::misc::ExtrudeJoiningAlgorithm;
/// Convert [`vector_types::subpath::Bezier`] to [`kurbo::PathSeg`].
fn bezier_to_path_seg(bezier: vector_types::subpath::Bezier) -> kurbo::PathSeg {
let [start, end] = [(bezier.start().x, bezier.start().y), (bezier.end().x, bezier.end().y)];
match bezier.handles {
BezierHandles::Linear => kurbo::Line::new(start, end).into(),
BezierHandles::Quadratic { handle } => kurbo::QuadBez::new(start, (handle.x, handle.y), end).into(),
BezierHandles::Cubic { handle_start, handle_end } => kurbo::CubicBez::new(start, (handle_start.x, handle_start.y), (handle_end.x, handle_end.y), end).into(),
}
}
/// Convert [`kurbo::CubicBez`] to [`vector_types::subpath::BezierHandles`].
fn cubic_to_handles(cubic_bez: kurbo::CubicBez) -> BezierHandles {
BezierHandles::Cubic {
handle_start: DVec2::new(cubic_bez.p1.x, cubic_bez.p1.y),
handle_end: DVec2::new(cubic_bez.p2.x, cubic_bez.p2.y),
}
}
/// Find the `t` values to split (where the tangent changes to be on the other side of the direction).
fn find_splits(cubic_segment: kurbo::CubicBez, direction: DVec2) -> impl Iterator<Item = f64> {
let derivative = cubic_segment.deriv();
let convert = |x: kurbo::Point| DVec2::new(x.x, x.y);
let derivative_points = [derivative.p0, derivative.p1, derivative.p2].map(convert);
let t_squared = derivative_points[0] - 2. * derivative_points[1] + derivative_points[2];
let t_scalar = -2. * derivative_points[0] + 2. * derivative_points[1];
let constant = derivative_points[0];
kurbo::common::solve_quadratic(constant.perp_dot(direction), t_scalar.perp_dot(direction), t_squared.perp_dot(direction))
.into_iter()
.filter(|&t| t > 1e-6 && t < 1. - 1e-6)
}
/// Split so segments no longer have tangents on both sides of the direction vector.
fn split(vector: &mut graphic_types::Vector, direction: DVec2) {
let segment_count = vector.segment_domain.ids().len();
let mut next_point = vector.point_domain.next_id();
let mut next_segment = vector.segment_domain.next_id();
for segment_index in 0..segment_count {
let (_, _, bezier) = vector.segment_points_from_index(segment_index);
let mut start_index = vector.segment_domain.start_point()[segment_index];
let pathseg = bezier_to_path_seg(bezier).to_cubic();
let mut start_t = 0.;
for split_t in find_splits(pathseg, direction) {
let [first, second] = [pathseg.subsegment(start_t..split_t), pathseg.subsegment(split_t..1.)];
let [first_handles, second_handles] = [first, second].map(cubic_to_handles);
let middle_point = next_point.next_id();
let start_segment = next_segment.next_id();
let middle_point_index = vector.point_domain.len();
vector.point_domain.push(middle_point, DVec2::new(first.end().x, first.end().y));
vector.segment_domain.push(start_segment, start_index, middle_point_index, first_handles, StrokeId::ZERO);
vector.segment_domain.set_start_point(segment_index, middle_point_index);
vector.segment_domain.set_handles(segment_index, second_handles);
start_t = split_t;
start_index = middle_point_index;
}
}
}
/// Copy all segments with the offset of `direction`.
fn offset_copy_all_segments(vector: &mut graphic_types::Vector, direction: DVec2) {
let points_count = vector.point_domain.ids().len();
let mut next_point = vector.point_domain.next_id();
for index in 0..points_count {
vector.point_domain.push(next_point.next_id(), vector.point_domain.positions()[index] + direction);
}
let segment_count = vector.segment_domain.ids().len();
let mut next_segment = vector.segment_domain.next_id();
for index in 0..segment_count {
vector.segment_domain.push(
next_segment.next_id(),
vector.segment_domain.start_point()[index] + points_count,
vector.segment_domain.end_point()[index] + points_count,
vector.segment_domain.handles()[index].apply_transformation(|x| x + direction),
vector.segment_domain.stroke()[index],
);
}
}
/// Join points from the original to the copied that are on opposite sides of the direction.
fn join_extrema_edges(vector: &mut graphic_types::Vector, direction: DVec2) {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum Found {
#[default]
None,
Positive,
Negative,
Both,
Invalid,
}
impl Found {
fn update(&mut self, value: f64) {
*self = match (*self, value > 0.) {
(Found::None, true) => Found::Positive,
(Found::None, false) => Found::Negative,
(Found::Positive, true) | (Found::Negative, false) => Found::Both,
_ => Found::Invalid,
};
}
}
let first_half_points = vector.point_domain.len() / 2;
let mut points = vec![Found::None; first_half_points];
let first_half_segments = vector.segment_domain.ids().len() / 2;
for segment_id in 0..first_half_segments {
let index = [vector.segment_domain.start_point()[segment_id], vector.segment_domain.end_point()[segment_id]];
let position = index.map(|index| vector.point_domain.positions()[index]);
if position[0].abs_diff_eq(position[1], 1e-6) {
continue; // Skip zero length segments
}
points[index[0]].update(direction.perp_dot(position[1] - position[0]));
points[index[1]].update(direction.perp_dot(position[0] - position[1]));
}
let mut next_segment = vector.segment_domain.next_id();
for (index, &point) in points.iter().enumerate().take(first_half_points) {
// Extrema are single connected points or points with both positive and negative values
if !matches!(point, Found::Both | Found::Positive | Found::Negative) {
continue;
}
vector
.segment_domain
.push(next_segment.next_id(), index, index + first_half_points, BezierHandles::Linear, StrokeId::ZERO);
}
}
/// Join all points from the original to the copied.
fn join_all(vector: &mut graphic_types::Vector) {
let mut next_segment = vector.segment_domain.next_id();
let first_half = vector.point_domain.len() / 2;
for index in 0..first_half {
vector.segment_domain.push(next_segment.next_id(), index, index + first_half, BezierHandles::Linear, StrokeId::ZERO);
}
}
pub fn extrude(vector: &mut graphic_types::Vector, direction: DVec2, joining_algorithm: ExtrudeJoiningAlgorithm) {
split(vector, direction);
offset_copy_all_segments(vector, direction);
match joining_algorithm {
ExtrudeJoiningAlgorithm::Extrema => join_extrema_edges(vector, direction),
ExtrudeJoiningAlgorithm::All => join_all(vector),
ExtrudeJoiningAlgorithm::None => {}
}
}
#[cfg(test)]
mod extrude_tests {
use glam::DVec2;
use kurbo::{ParamCurve, ParamCurveDeriv};
#[test]
fn split_cubic() {
let l1 = kurbo::CubicBez::new((0., 0.), (100., 0.), (100., 100.), (0., 100.));
assert_eq!(super::find_splits(l1, DVec2::Y).collect::<Vec<f64>>(), vec![0.5]);
assert!(super::find_splits(l1, DVec2::X).collect::<Vec<f64>>().is_empty());
let l2 = kurbo::CubicBez::new((0., 0.), (0., 0.), (100., 0.), (100., 0.));
assert!(super::find_splits(l2, DVec2::X).collect::<Vec<f64>>().is_empty());
let l3 = kurbo::PathSeg::Line(kurbo::Line::new((0., 0.), (100., 0.)));
assert!(super::find_splits(l3.to_cubic(), DVec2::X).collect::<Vec<f64>>().is_empty());
let l4 = kurbo::CubicBez::new((0., 0.), (100., -10.), (100., 110.), (0., 100.));
let splits = super::find_splits(l4, DVec2::X).map(|t| l4.deriv().eval(t)).collect::<Vec<_>>();
assert_eq!(splits.len(), 2);
assert!(splits.iter().all(|&deriv| deriv.y.abs() < 1e-8), "{splits:?}");
}
#[test]
fn split_vector() {
let curve = kurbo::PathSeg::Cubic(kurbo::CubicBez::new((0., 0.), (100., -10.), (100., 110.), (0., 100.)));
let mut vector = graphic_types::Vector::from_bezpath(kurbo::BezPath::from_path_segments([curve].into_iter()));
super::split(&mut vector, DVec2::X);
assert_eq!(vector.segment_ids().len(), 3);
assert_eq!(vector.point_domain.ids().len(), 4);
}
}
}
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn extrude(_: impl Ctx, mut source: Table<Vector>, direction: DVec2, joining_algorithm: ExtrudeJoiningAlgorithm) -> Table<Vector> {
for TableRowMut { element: source, .. } in source.iter_mut() {
extrude_algorithms::extrude(source, direction, joining_algorithm);
}
source
}
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn box_warp(_: impl Ctx, content: Table<Vector>, #[expose] rectangle: Table<Vector>) -> Table<Vector> {
let Some((target, target_transform)) = rectangle.get(0).map(|rect| (rect.element, rect.transform)) else {
return content;
};
content
.into_iter()
.map(|mut row| {
let transform = row.transform;
let vector = row.element;
// Get the bounding box of the source vector geometry
let source_bbox = vector.bounding_box_with_transform(transform).unwrap_or([DVec2::ZERO, DVec2::ONE]);
// Extract first 4 points from target shape to form the quadrilateral
// Apply the target's transform to get points in world space
let target_points: Vec<DVec2> = target.point_domain.positions().iter().map(|&p| target_transform.transform_point2(p)).take(4).collect();
// If we have fewer than 4 points, use the corners of the source bounding box
// This handles the degenerative case
let dst_corners = if target_points.len() >= 4 {
[target_points[0], target_points[1], target_points[2], target_points[3]]
} else {
warn!("Target shape has fewer than 4 points. Using source bounding box instead.");
[
source_bbox[0],
DVec2::new(source_bbox[1].x, source_bbox[0].y),
source_bbox[1],
DVec2::new(source_bbox[0].x, source_bbox[1].y),
]
};
// Apply the warp
let mut result = vector.clone();
// Precompute source bounding box size for normalization
let source_size = source_bbox[1] - source_bbox[0];
// Transform points
for (_, position) in result.point_domain.positions_mut() {
// Get the point in world space
let world_pos = transform.transform_point2(*position);
// Normalize coordinates within the source bounding box
let t = ((world_pos - source_bbox[0]) / source_size).clamp(DVec2::ZERO, DVec2::ONE);
// Apply bilinear interpolation
*position = bilinear_interpolate(t, &dst_corners);
}
// Transform handles in bezier curves
for (_, handles, _, _) in result.handles_mut() {
*handles = handles.apply_transformation(|pos| {
// Get the handle in world space
let world_pos = transform.transform_point2(pos);
// Normalize coordinates within the source bounding box
let t = ((world_pos - source_bbox[0]) / source_size).clamp(DVec2::ZERO, DVec2::ONE);
// Apply bilinear interpolation
bilinear_interpolate(t, &dst_corners)
});
}
result.style.set_stroke_transform(DAffine2::IDENTITY);
// Add this to the table and reset the transform since we've applied it directly to the points
row.element = result;
row.transform = DAffine2::IDENTITY;
row
})
.collect()
}
// Interpolate within a quadrilateral using normalized coordinates (0-1)
fn bilinear_interpolate(t: DVec2, quad: &[DVec2; 4]) -> DVec2 {
let tl = quad[0]; // Top-left
let tr = quad[1]; // Top-right
let br = quad[2]; // Bottom-right
let bl = quad[3]; // Bottom-left
// Bilinear interpolation
tl * (1. - t.x) * (1. - t.y) + tr * t.x * (1. - t.y) + br * t.x * t.y + bl * (1. - t.x) * t.y
}
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
async fn pack_strips<T: 'n + Send + Clone>(
_: impl Ctx,
#[implementations(
Table<Graphic>,
Table<Vector>,
Table<Raster<CPU>>,
Table<Raster<GPU>>,
)]
elements: Table<T>,
#[default(0.)]
#[unit(" px")]
separation: f64,
#[default(1000.)]
#[unit(" px")]
strip_max_length: f64,
strip_direction: RowsOrColumns,
) -> Table<T>
where
Graphic: From<Table<T>>,
Table<T>: BoundingBox,
{
// Packs shapes using bounds with Best-Fit Decreasing Height (BFDH) algorithm:
// - Sort shapes by cross-axis size (tallest first for rows, widest first for columns)
// - For each shape, find the existing strip with minimum remaining space that fits
// - Create new strip only if no existing strip can accommodate the shape
struct Strip {
along_position: f64,
cross_position: f64,
cross_extent: f64,
}
// Prepare the items to be sorted
let mut items: Vec<(f64, f64, DVec2, TableRow<T>)> = elements
.into_iter()
.map(|row| {
// Single-element table to query its bounding box
let single = Table::new_from_row(row.clone());
let (w, h, top_left) = match single.bounding_box(DAffine2::IDENTITY, false) {
RenderBoundingBox::Rectangle([min, max]) => {
let size = max - min;
(size.x.max(0.), size.y.max(0.), min)
}
_ => (0., 0., DVec2::ZERO),
};
let (along, cross) = match strip_direction {
RowsOrColumns::Rows => (w, h),
RowsOrColumns::Columns => (h, w),
};
(along, cross, top_left, row)
})
.collect();
// Sort by cross-axis size, largest first
items.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(Ordering::Equal));
let mut result = Table::new();
let mut strips: Vec<Strip> = Vec::new();
// This looks n^2 but it is just n*k where k is the number of strips, which is generally much smaller than n
for (along, cross, top_left, mut row) in items {
if along <= 0. {
result.push(row);
continue;
}
// Find a good strip, minimum remaining space that can fit this item ideally
let mut best_strip_index = None;
let mut min_remaining_space = f64::INFINITY;
for (index, strip) in strips.iter().enumerate() {
let remaining_space = strip_max_length - strip.along_position;
if remaining_space >= along && remaining_space < min_remaining_space {
min_remaining_space = remaining_space;
best_strip_index = Some(index);
}
}
if let Some(strip_index) = best_strip_index {
// Place on existing strip
let strip = &mut strips[strip_index];
// Update strip cross extent if needed
if cross > strip.cross_extent {
strip.cross_extent = cross;
}
let target_position = match strip_direction {
RowsOrColumns::Rows => DVec2::new(strip.along_position, strip.cross_position),
RowsOrColumns::Columns => DVec2::new(strip.cross_position, strip.along_position),
};
row.transform = DAffine2::from_translation(target_position - top_left) * row.transform;
strip.along_position += along + separation;
} else {
// Create new strip
let new_cross = strips.last().map_or(0., |last| last.cross_position + last.cross_extent + separation);
let target_position = match strip_direction {
RowsOrColumns::Rows => DVec2::new(0., new_cross),
RowsOrColumns::Columns => DVec2::new(new_cross, 0.),
};
row.transform = DAffine2::from_translation(target_position - top_left) * row.transform;
strips.push(Strip {
along_position: along + separation,
cross_position: new_cross,
cross_extent: cross,
});
}
result.push(row);
}
result
}
/// Automatically constructs tangents (Bézier handles) for anchor points in a vector path.
#[node_macro::node(category("Vector: Modifier"), name("Auto-Tangents"), path(core_types::vector))]
async fn auto_tangents(
_: impl Ctx,
source: Table<Vector>,
/// The amount of spread for the auto-tangents, from 0 (sharp corner) to 1 (full spread).
#[default(0.5)]
// TODO: Make this a soft range to allow any value to be typed in outside the slider range of 0 to 1
#[range((0., 1.))]
spread: f64,
/// If active, existing non-zero handles won't be affected.
#[default(true)]
preserve_existing: bool,
) -> Table<Vector> {
source
.iter()
.map(|source| {
let transform = *source.transform;
let alpha_blending = *source.alpha_blending;
let source_node_id = *source.source_node_id;
let source = source.element;
let mut result = Vector {
style: source.style.clone(),
..Default::default()
};
for mut subpath in source.stroke_bezier_paths() {
subpath.apply_transform(transform);
let manipulators_list = subpath.manipulator_groups();
if manipulators_list.len() < 2 {
// Not enough points for softening or handle removal
result.append_subpath(subpath, true);
continue;
}
let mut new_manipulators_list = Vec::with_capacity(manipulators_list.len());
// Track which manipulator indices were given auto-tangent (colinear) handles
let mut auto_tangented = vec![false; manipulators_list.len()];
let is_closed = subpath.closed();
for i in 0..manipulators_list.len() {
let current = &manipulators_list[i];
let is_endpoint = !is_closed && (i == 0 || i == manipulators_list.len() - 1);
if preserve_existing {
// Check if this point has handles that are meaningfully different from the anchor
let has_handles = (current.in_handle.is_some() && !current.in_handle.unwrap().abs_diff_eq(current.anchor, 1e-5))
|| (current.out_handle.is_some() && !current.out_handle.unwrap().abs_diff_eq(current.anchor, 1e-5));
// If the point already has handles, keep it as is
if has_handles {
new_manipulators_list.push(*current);
continue;
}
}
// If spread is 0, remove handles for this point, making it a sharp corner
if spread == 0. {
new_manipulators_list.push(ManipulatorGroup {
anchor: current.anchor,
in_handle: None,
out_handle: None,
id: current.id,
});
continue;
}
// Endpoints of open paths get zero-length cubic handles so adjacent segments remain cubic (not quadratic)
if is_endpoint {
new_manipulators_list.push(ManipulatorGroup {
anchor: current.anchor,
in_handle: Some(current.anchor),
out_handle: Some(current.anchor),
id: current.id,
});
continue;
}
// Get previous and next points for auto-tangent calculation
let prev_index = if i == 0 { manipulators_list.len() - 1 } else { i - 1 };
let next_index = if i == manipulators_list.len() - 1 { 0 } else { i + 1 };
let current_position = current.anchor;
let delta_prev = manipulators_list[prev_index].anchor - current_position;
let delta_next = manipulators_list[next_index].anchor - current_position;
// Calculate normalized directions and distances to adjacent points
let distance_prev = delta_prev.length();
let distance_next = delta_next.length();
// Check if we have valid directions (e.g., points are not coincident)
if distance_prev < 1e-5 || distance_next < 1e-5 {
// Fallback: keep the original manipulator group (which has no active handles here)
new_manipulators_list.push(*current);
continue;
}
let direction_prev = delta_prev / distance_prev;
let direction_next = delta_next / distance_next;
// Calculate handle direction as the bisector of the two normalized directions.
// This ensures the in and out handles are colinear (180° apart) through the anchor.
let mut handle_direction = (direction_prev - direction_next).try_normalize().unwrap_or_else(|| direction_prev.perp());
// Ensure consistent orientation of the handle direction.
// This makes the `+ handle_direction` for in_handle and `- handle_direction` for out_handle consistent.
if direction_prev.dot(handle_direction) < 0. {
handle_direction = -handle_direction;
}
// Calculate handle lengths: 1/3 of distance to adjacent points, scaled by spread
let in_length = distance_prev / 3. * spread;
let out_length = distance_next / 3. * spread;
// Create new manipulator group with calculated auto-tangents
new_manipulators_list.push(ManipulatorGroup {
anchor: current_position,
in_handle: Some(current_position + handle_direction * in_length),
out_handle: Some(current_position - handle_direction * out_length),
id: current.id,
});
auto_tangented[i] = true;
}
// Record segment count before appending so we can find the new segment IDs
let segment_offset = result.segment_domain.ids().len();
let mut softened_bezpath = bezpath_from_manipulator_groups(&new_manipulators_list, is_closed);
softened_bezpath.apply_affine(Affine::new(transform.inverse().to_cols_array()));
result.append_bezpath(softened_bezpath);
// Mark auto-tangented points as having colinear handles
let segment_ids = result.segment_domain.ids();
let num_manipulators = new_manipulators_list.len();