/
polygons.jl
1601 lines (1350 loc) · 47.8 KB
/
polygons.jl
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
# polygons, part of Luxor
"""
Draw a polygon.
poly(pointlist::Array{Point, 1}, action = :none;
close=false,
reversepath=false)
A polygon is an Array of Points. By default `poly()` doesn't close or fill the polygon,
to allow for clipping.
"""
function poly(pointlist::Array{Point, 1};
action = :none,
close = false,
reversepath =false)
if action != :path
newpath()
end
if reversepath == true
reverse!(pointlist)
end
move(pointlist[1].x, pointlist[1].y)
@inbounds for p in pointlist[2:end]
line(p.x, p.y)
end
if close==true
closepath()
end
do_action(action)
return pointlist
end
poly(pts::NTuple{N, Point} where N; kwargs...) = poly(collect(pts); kwargs...)
poly(pointlist::Array{Point, 1}, a::Symbol;
action = a,
close = false,
reversepath = false) = poly(pointlist, action = action, close=close, reversepath=reversepath)
"""
Find the centroid of simple polygon.
polycentroid(pointlist)
Returns a point. This only works for simple (non-intersecting) polygons.
You could test the point using `isinside()`.
"""
function polycentroid(pointlist::Array{Point,1})
# Points are immutable, use separate variables for these calculations
centroid_x = 0.0
centroid_y = 0.0
signedarea = 0.0
vertexcount = length(pointlist)
x0 = 0.0 # Current vertex X
y0 = 0.0 # Current vertex Y
x1 = 0.0 # Next vertex X
y1 = 0.0 # Next vertex Y
a = 0.0 # Partial signed area
# For all vertices except last
i = 1
@inbounds for i in 1:vertexcount-1
x0 = pointlist[i].x
y0 = pointlist[i].y
x1 = pointlist[i+1].x
y1 = pointlist[i+1].y
a = x0 * y1 - x1 * y0
signedarea += a
centroid_x += (x0 + x1) * a
centroid_y += (y0 + y1) * a
end
# Do last vertex separately to avoid performing an expensive
# modulus operation in each iteration.
x0 = pointlist[vertexcount].x
y0 = pointlist[vertexcount].y
x1 = pointlist[1].x
y1 = pointlist[1].y
a = x0 * y1 - x1 * y0
signedarea += a
centroid_x += (x0 + x1) * a
centroid_y += (y0 + y1) * a
signedarea *= 0.5
centroid_x /= (6.0 * signedarea)
centroid_y /= (6.0 * signedarea)
return Point(centroid_x, centroid_y)
end
"""
Sort the points of a polygon into order. Points are sorted according to the angle they make
with a specified point.
polysortbyangle(pointlist::Array, refpoint=minimum(pointlist))
The `refpoint` can be chosen, but the minimum point is usually OK too:
polysortbyangle(parray, polycentroid(parray))
"""
function polysortbyangle(pointlist::Array{Point, 1}, refpoint=minimum(pointlist))
angles = Float64[] ; sizehint!(angles, length(pointlist))
@inbounds for pt in pointlist
push!(angles, slope(pt, refpoint))
end
return pointlist[sortperm(angles)]
end
"""
Sort a polygon by finding the nearest point to the starting point, then
the nearest point to that, and so on.
polysortbydistance(p, starting::Point)
You can end up with convex (self-intersecting) polygons, unfortunately.
"""
function polysortbydistance(pointlist::Array{Point, 1}, starting::Point)
route = [starting]; sizehint!(route, length(pointlist))
# start with the first point in pointlist
remaining = setdiff(pointlist, route)
while length(remaining) > 0
# find the nearest point to the current position on the route
nearest = first(sort!(remaining, lt = (x, y) -> distance(route[end], x) < distance(route[end], y)))
# add this to the route and remove from remaining points
push!(route, nearest)
popfirst!(remaining)
end
return route
end
"""
Use a non-recursive Douglas-Peucker algorithm to simplify a polygon. Used by `simplify()`.
douglas_peucker(pointlist::Array, start_index, last_index, epsilon)
"""
function douglas_peucker(pointlist::Array{Point, 1}, start_index, last_index, epsilon)
temp_stack = Tuple{Int, Int}[]
push!(temp_stack, (start_index, last_index))
global_start_index = start_index
keep_list = trues(length(pointlist))
while length(temp_stack) > 0
start_index = first(temp_stack[end])
last_index = last(temp_stack[end])
pop!(temp_stack)
dmax = 0.0
index = start_index
for i in index + 1:last_index - 1
if (keep_list[i - global_start_index])
d = pointlinedistance(pointlist[i], pointlist[start_index], pointlist[last_index])
if d > dmax
index = i
dmax = d
end
end
end
if dmax > epsilon
push!(temp_stack, (start_index, index))
push!(temp_stack, (index, last_index))
else
keep_list[global_start_index + start_index: global_start_index+last_index-2] .= false
end
end
return pointlist[keep_list]
end
"""
Simplify a polygon:
simplify(pointlist::Array, detail=0.1)
`detail` is the maximum approximation error of simplified polygon.
"""
function simplify(pointlist::Array{Point, 1}, detail=0.1)
douglas_peucker(pointlist, 1, length(pointlist), detail)
end
"""
isinside(p, pol; allowonedge=false)
Is a point `p` inside a polygon `pol`? Returns true if it does, or false.
This is an implementation of the Hormann-Agathos (2001) Point in Polygon algorithm.
The classification of points lying on the edges of the target polygon, or coincident with
its vertices is not clearly defined, due to rounding errors or arithmetical
inadequacy. By default these will generate errors, but you can suppress these by setting
`allowonedge` to `true`.
"""
function isinside(p::Point, pointlist::Array{Point, 1};
allowonedge::Bool=false)
c = false
@inbounds for counter in eachindex(pointlist)
q1 = pointlist[counter]
# if reached last point, set "next point" to first point
if counter == length(pointlist)
q2 = pointlist[1]
else
q2 = pointlist[counter + 1]
end
if q1 == p
allowonedge || error("isinside(): VertexException a")
continue
end
if q2.y == p.y
if q2.x == p.x
allowonedge || error("isinside(): VertexException b")
continue
elseif (q1.y == p.y) && ((q2.x > p.x) == (q1.x < p.x))
allowonedge || error("isinside(): EdgeException")
continue
end
end
if (q1.y < p.y) != (q2.y < p.y) # crossing
if q1.x >= p.x
if q2.x > p.x
c = !c
elseif ((determinant3(q1, q2, p) > 0) == (q2.y > q1.y))
c = !c
end
elseif q2.x > p.x
if ((determinant3(q1, q2, p) > 0) == (q2.y > q1.y))
c = !c
end
end
end
end
return c
end
"""
polysplit(p, p1, p2)
Split a polygon into two where it intersects with a line. It returns two
polygons:
```
(poly1, poly2)
```
This doesn't always work, of course. For example, a polygon the shape of the
letter "E" might end up being divided into more than two parts.
"""
function polysplit(pointlist::Array{Point, 1}, p1::Point, p2::Point)
# the two-pass version
# TODO should be one-pass
newpointlist = Point[]; sizehint!(newpointlist, length(pointlist))
vertex1 = Point(0, 0)
vertex2 = Point(0, 0)
l = length(pointlist)
@inbounds for i in 1:l
vertex1 = pointlist[mod1(i, l)]
vertex2 = pointlist[mod1(i + 1, l)]
flag, intersectpoint = intersectionlines(vertex1, vertex2, p1, p2, crossingonly=true)
push!(newpointlist, vertex1)
if flag
push!(newpointlist, intersectpoint)
end
end
# close?
# push!(newpointlist, vertex2)
# now sort points
poly1 = Point[]
poly2 = Point[]
l = length(newpointlist)
@inbounds for i in 1:l
vertex1 = newpointlist[mod1(i, l)]
d = pointlinedistance(vertex1, p1, p2)
centerpoint = (p2.x - p1.x) * (vertex1.y - p1.y) > (p2.y - p1.y) * (vertex1.x - p1.x)
if centerpoint
push!(poly1, vertex1)
abs(d) < 0.1 && push!(poly2, vertex1)
else
push!(poly2, vertex1)
abs(d) < 0.1 && push!(poly1, vertex1)
end
end
return(poly1, poly2)
end
"""
prettypoly(points::Array{Point, 1}, vertexfunction = () -> circle(O, 2, :stroke);
action=:none,
close=false,
reversepath=false,
vertexlabels = (n, l) -> ()
)
Draw the polygon defined by `points`, possibly closing and reversing it, using the current
parameters, and then evaluate the `vertexfunction` function at every vertex of the polygon.
The default vertexfunction draws a 2 pt radius circle.
To mark each vertex of a polygon with a randomly colored filled circle:
p = star(O, 70, 7, 0.6, 0, vertices=true)
prettypoly(p, action=:fill, () ->
begin
randomhue()
circle(O, 10, :fill)
end,
close=true)
The optional keyword argument `vertexlabels` lets you supply a function with
two arguments that can access the current vertex number and the total number of vertices
at each vertex. For example, you can label the vertices of a triangle "1 of 3", "2 of 3",
and "3 of 3" using:
prettypoly(triangle, action=:stroke,
vertexlabels = (n, l) -> (text(string(n, " of ", l))))
"""
function prettypoly(pointlist::Array{Point, 1}, vertexfunction = () -> circle(O, 2, :stroke);
action=:none,
close=false,
reversepath=false,
vertexlabels = (n, l) -> ())
if isempty(pointlist)
return nothing
end
if action != :path
newpath()
end
if reversepath
reverse!(pointlist)
end
move(pointlist[1])
@inbounds for p in pointlist[2:end]
line(p)
end
if close
closepath()
end
do_action(action)
pointnumber = 1
for p in pointlist
gsave()
translate(p.x, p.y)
vertexfunction()
vertexlabels(pointnumber, length(pointlist))
grestore()
pointnumber += 1
end
if action == :fillpreserve || action == :strokepreserve
move(pointlist[1])
@inbounds for p in pointlist[2:end]
line(p)
end
end
return pointlist
end
# method with action as argument
prettypoly(pointlist::Array{Point, 1}, action::Symbol, vertexfunction = () -> circle(O, 2, :stroke);
close=false,
reversepath=false,
vertexlabels = (n, l) -> ()) = prettypoly(pointlist, vertexfunction,
action=action,
close=close,
reversepath=reversepath,
vertexlabels = vertexlabels)
# method with default
prettypoly(pointlist, action::Symbol) = prettypoly(pointlist, () -> circle(O, 2, :stroke);
action=action,
close=false,
reversepath=false,
vertexlabels = (n, l) -> ())
function getproportionpoint(point::Point, segment, length, dx, dy)
scalefactor = segment / length
return Point((point.x - dx * scalefactor), (point.y - dy * scalefactor))
end
function drawroundedcorner(cornerpoint::Point, p1::Point, p2::Point, radius, path; debug=false)
dx1 = cornerpoint.x - p1.x # vector 1
dy1 = cornerpoint.y - p1.y
dx2 = cornerpoint.x - p2.x # vector 2
dy2 = cornerpoint.y - p2.y
# Angle between vector 1 and vector 2 divided by 2
angle2 = (atan(dy1, dx1) - atan(dy2, dx2)) / 2
# length of segment between corner point and the
# points of intersection with the circle of a given radius
t = abs(tan(angle2))
segment = radius / t
# Check the segment
length1 = hypot(dx1, dy1)
length2 = hypot(dx2, dy2)
seglength = min(length1, length2)
if segment > seglength
segment = seglength
radius = seglength * t
end
# points of intersection are calculated by the proportion between
# the coordinates of the vector, length of vector and the length of the segment.
p1_cross = getproportionpoint(cornerpoint, segment, length1, dx1, dy1)
p2_cross = getproportionpoint(cornerpoint, segment, length2, dx2, dy2)
# calculation of the coordinates of the circle's center by the addition of angular vectors
dx = cornerpoint.x * 2 - p1_cross.x - p2_cross.x
dy = cornerpoint.y * 2 - p1_cross.y - p2_cross.y
L = hypot(dx, dy)
d = hypot(segment, radius)
# this prevents impossible constructions; Cairo will crash if L is 0
if isapprox(L, 0.0)
L= 0.01
end
circlepoint = getproportionpoint(cornerpoint, d, L, dx, dy)
# if "debugging" or you just like the circles:
debug && circle(circlepoint, radius, :stroke)
# start angle and end engle of arc
startangle = atan(p1_cross.y - circlepoint.y, p1_cross.x - circlepoint.x)
endangle = atan(p2_cross.y - circlepoint.y, p2_cross.x - circlepoint.x)
# add first line segment, up to the start of the arc
push!(path, (:line, p1_cross)) # draw line to arc start
# adjust. Cairo also does this when you draw arc()s, btw
if endangle < 0
endangle = 2pi + endangle
end
if startangle < 0
startangle = 2pi + startangle
end
sweepangle = endangle - startangle
if abs(sweepangle) > pi
if startangle < endangle
push!(path, (:carc, [circlepoint, radius, startangle, endangle]))
else
push!(path, (:arc, [circlepoint, radius, startangle, endangle]))
end
else
if startangle < endangle
push!(path, (:arc, [circlepoint, radius, startangle, endangle]))
else
push!(path, (:carc, [circlepoint, radius, startangle, endangle]))
end
end
# line from end of arc to start of next side
push!(path, (:line, p2_cross))
end
"""
polysmooth(points, radius, action=:action; debug=false)
polysmooth(points, radius; action=:none, debug=false)
Make a closed path from the `points` and round the corners by making them arcs with the
given radius. Execute the action when finished.
The arcs are sometimes different sizes: if the given radius is bigger than the length of the
shortest side, the arc can't be drawn at its full radius and is therefore drawn as large as
possible (as large as the shortest side allows).
The `debug` option also draws the construction circles at each corner.
TODO Return something more useful than a Boolean.
"""
function polysmooth(points::Array{Point, 1}, radius, action::Symbol; debug=false)
temppath = Tuple[]
l = length(points)
if l < 3
# there are less than three points to smooth
return nothing
else
@inbounds for i in 1:l
p1 = points[mod1(i, l)]
p2 = points[mod1(i + 1, l)]
p3 = points[mod1(i + 2, l)]
drawroundedcorner(p2, p1, p3, radius, temppath, debug=debug)
end
end
# need to close by joining to first point
push!(temppath, temppath[1])
# draw the path
for (c, p) in temppath
if c == :line
line(p) # add line segment
elseif c == :arc
arc(p...) # add clockwise arc segment
elseif c == :carc
carc(p...) # add counterclockwise arc segment
end
end
do_action(action)
end
polysmooth(points::Array{Point, 1}, radius; action=:none, debug=false) =
polysmooth(points, radius, action; debug=debug)
"""
offsetpoly(plist::Array{Point, 1}, d) where T<:Number
Return a polygon that is offset from a polygon by `d` units.
The incoming set of points `plist` is treated as a polygon, and another set of
points is created, which form a polygon lying `d` units away from the source
poly.
Polygon offsetting is a topic on which people have written PhD theses and
published academic papers, so this short brain-dead routine will give good
results for simple polygons up to a point (!). There are a number of issues to
be aware of:
- very short lines tend to make the algorithm 'flip' and produce larger lines
- small polygons that are counterclockwise and larger offsets may make the new
polygon appear the wrong side of the original
- very sharp vertices will produce even sharper offsets, as the calculated intersection point veers off to infinity
- duplicated adjacent points might cause the routine to scratch its head and wonder how to draw a line parallel to them
"""
function offsetpoly(plist::Array{Point, 1}, d::T) where T<:Number
# don't try to calculate offset of two identical points
l = length(plist)
resultpoly = Array{Point}(undef, l)
previouspoint = plist[end]
for i in 1:l
plist[i] == previouspoint && continue
p1 = plist[mod1(i, l)]
p2 = plist[mod1(i + 1, l)]
p3 = plist[mod1(i + 2, l)]
p1 == p2 && continue
p2 == p3 && continue
L12 = distance(p1, p2)
L23 = distance(p2, p3)
# the offset line of p1 - p2
x1p = p1.x + (d * (p2.y - p1.y))/ L12
y1p = p1.y + (d * (p1.x - p2.x))/ L12
x2p = p2.x + (d * (p2.y - p1.y))/ L12
y2p = p2.y + (d * (p1.x - p2.x))/ L12
# the offset line of p2 - p3
x3p = p2.x + (d * (p3.y - p2.y))/ L23
y3p = p2.y + (d * (p2.x - p3.x))/ L23
x4p = p3.x + (d * (p3.y - p2.y))/ L23
y4p = p3.y + (d * (p2.x - p3.x))/ L23
intersectionpoint = intersectionlines(
Point(x1p, y1p),
Point(x2p, y2p),
Point(x3p, y3p),
Point(x4p, y4p), crossingonly=false)
if intersectionpoint[1]
resultpoly[i] = intersectionpoint[2]
end
previouspoint = plist[i]
end
return resultpoly
end
"""
offsetlinesegment(p1, p2, p3, d1, d2)
Given three points, find another 3 points that are offset by
d1 at the start and d2 at the end.
Negative d values put the offset on the left.
Used by `offsetpoly()`.
"""
function offsetlinesegment(p1, p2, p3, d1, d2)
# TODO: check this, it's not right
if p1 == p2
tp = perpendicular(p1, p3, d1)
return p1, tp, p2
elseif p1 == p3
tp = perpendicular(p1, p2, d1)
return p1, p2, tp
elseif p2 == p3
tp = perpendicular(p1, p3, d2)
return p1, tp, p3
end
pt1 = perpendicular(p1, p2, -d1)
pt2 = perpendicular(p3, p2, d2)
L12 = distance(p1, p2)
L23 = distance(p2, p3)
d = (d1 + d2) / 2
# the offset line of p1 - p2
x1p = p1.x + (d * (p2.y - p1.y))/ L12
y1p = p1.y + (d * (p1.x - p2.x))/ L12
x2p = p2.x + (d * (p2.y - p1.y))/ L12
y2p = p2.y + (d * (p1.x - p2.x))/ L12
# the offset line of p2 - p3
x3p = p2.x + (d * (p3.y - p2.y))/ L23
y3p = p2.y + (d * (p2.x - p3.x))/ L23
x4p = p3.x + (d * (p3.y - p2.y))/ L23
y4p = p3.y + (d * (p2.x - p3.x))/ L23
intersectionpoint = intersectionlines(
Point(x1p, y1p),
Point(x2p, y2p),
Point(x3p, y3p),
Point(x4p, y4p), crossingonly=false)
if first(intersectionpoint)
pt3 = intersectionpoint[2]
else
# collinear probably
pt3 = midpoint(pt1, pt2)
end
return pt1, pt3, pt2
end
"""
offsetpoly(plist;
startoffset = 10,
endoffset = 10,
easingfunction = lineartween)
Return a closed polygon that is offset from and encloses an
open polygon.
The incoming set of points `plist` is treated as an open
polygon, and another set of points is created, which form a
polygon lying `...offset` units away from the source poly.
This method for `offsetpoly()` treats the list of points as
`n` vertices connected with `n - 1` lines. It allows you to
vary the offset from the start of the line to the end.
The other method `offsetpoly(plist, d)` treats the list of
points as `n` vertices connected with `n` lines.
# Extended help
This function accepts a keyword argument that allows you to
control the offset using a function, using the easing
functionality built in to Luxor. By default the function is
`lineartween()`, so the offset changes linearly between the
`startoffset` and the `endoffset`. The function:
```
f(a, b, c, d) = 2sin((a * π))
```
runs from 0 to 2 and back as `a` runs from 0 to 1.
The offsets are scaled by this amount.
"""
function offsetpoly(plist;
startoffset = 10,
endoffset = 10,
easingfunction = lineartween)
l = length(plist)
# TODO: special case a plist with 2 points
l < 3 && throw(error("variableoffsetline: not enough points, need 3 or more"))
# can't do 3 points properly, just insert a few extras
if l == 3
plist = vcat(plist[1], midpoint(plist[1], plist[2]), plist[2], midpoint(plist[2], plist[3]), plist[3])
end
# build the poly in two halves
leftcurve = Point[]
rightcurve = Point[]
pt1 = perpendicular(plist[1], plist[2], -startoffset)
pt2 = perpendicular(plist[1], plist[2], startoffset)
# start the curves off
push!(leftcurve, pt1)
push!(rightcurve, pt2)
for i in 1:l-2
# allow for the easing function that rescales the offset
k1 = easingfunction(rescale(i, 0, l ), 0.0, 1.0, 1.0)
k2 = easingfunction(rescale(i + 1, 0, l ), 0.0, 1.0, 1.0)
# because easing functions are 0 to 1, use 0 here
d1 = rescale(k1 * l, 0, l, startoffset, endoffset)
d2 = rescale(k2 * l, 0, l, startoffset, endoffset)
p1, mpt, p3 = offsetlinesegment(plist[i], plist[i + 1], plist[i + 2], d1, d2)
push!(leftcurve, mpt)
p1, mpt, p3 = offsetlinesegment(plist[i], plist[i + 1], plist[i + 2], -d1, -d2)
push!(rightcurve, mpt)
end
# final point
k = easingfunction(1, 0.0, 1.0, 1.0)
d = rescale(k * l, 0, l, startoffset, endoffset)
pt1 = perpendicular(plist[end], plist[end - 1], -d)
pt2 = perpendicular(plist[end], plist[end - 1], d)
push!(leftcurve, pt2)
push!(rightcurve, pt1)
return vcat(leftcurve, reverse(rightcurve))
end
# third method
"""
offsetpoly(plist, shape::Function)
Return a closed polygon that is offset from and encloses an
polyline.
The incoming set of points `plist` is treated as an
polyline, and another set of points is created, which form a
closed polygon offset from the source poly.
There must be at least 4 points in the polyline.
This method for `offsetpoly()` treats the list of points as
`n` vertices connected with `n - 1` lines. (The other method
`offsetpoly(plist, d)` treats the list of points as `n`
vertices connected with `n` lines.)
The supplied function determines the width of the line.
`f(0, θ)` gives the width at the start (the slope of
the curve at that point is supplied in θ), `f(1, θ)` provides
the width at the end, and `f(n, θ)` is the width of point
`n/l`.
# Examples
This example draws a tilde, with the ends starting at 20
(10 + 10) units wide, swelling to 50 (10 + 10 + 15 + 15) in
the middle, as f(0.5) = 25.
```
f(x, θ) = 10 + 15sin(x * π)
sinecurve = [Point(50x, 50sin(x)) for x in -π:π/24:π]
pgon = offsetpoly(sinecurve, f)
poly(pgon, :fill)
```
This example enhances the vertical part of the curve, and
thins the horizontal parts.
```
g(x, θ) = rescale(abs(sin(θ)), 0, 1, 0.1, 30)
sinecurve = [Point(50x, 50sin(x)) for x in -π:π/24:π]
pgon = offsetpoly(sinecurve, g)
poly(pgon, :fill)
```
TODO - rewrite it!
"""
function offsetpoly(plist, shape::Function)
# TODO - the code of this function really sucks, I wish
# I could make it suck less. :) Probably the best thing
# to do is to abandon all these amateur attempts at
# polygon-offsetting and use the Clipper library, or
# something that works.
l = length(plist)
l < 4 && throw(error("offsetpoly(): not enough points, need at least 5; try polysample()"))
# build the poly in four parts and stitch them together
# first half, two sides
L = l÷2
leftcurve = Point[]
rightcurve = Point[]
θ = slope(plist[1], plist[2])
d = shape(0.0, θ)
pt1 = perpendicular(plist[1], plist[2], -d)
pt2 = perpendicular(plist[1], plist[2], d)
push!(leftcurve, pt1)
push!(rightcurve, pt2)
for i in 1:L-1
# allow for the easing function that rescales the offset
θ = slope(plist[i], plist[i + 1])
d = shape(rescale(i, 0, l), θ)
p1, mpt, p3 = Luxor.offsetlinesegment(plist[i], plist[i + 1], plist[i + 2], d, d)
push!(leftcurve, mpt)
p1, mpt, p3 = Luxor.offsetlinesegment(plist[i], plist[i + 1], plist[i + 2], -d, -d)
push!(rightcurve, mpt)
end
# second half, both sides, going backwards
θ = slope(plist[end], plist[end-1])
d = shape(1.0, θ)
pt1 = perpendicular(plist[end], plist[end-1], -d)
pt2 = perpendicular(plist[end], plist[end-1], d)
# start the second half curves off
leftcurve_2 = Point[]
rightcurve_2 = Point[]
push!(leftcurve_2, pt1)
push!(rightcurve_2, pt2)
# work backwards from the end
for i in l-1:-1:L+1
θ = slope(plist[i-1], plist[i])
d = shape(rescale(i, 0, l), θ)
p1, mpt, p3 = Luxor.offsetlinesegment(plist[i], plist[i - 1], plist[i - 2], d, d)
push!(leftcurve_2, p1)
p1, mpt, p3 = Luxor.offsetlinesegment(plist[i], plist[i - 1], plist[i - 2], -d, -d)
push!(rightcurve_2, p1)
end
append!(leftcurve, reverse(rightcurve_2))
append!(rightcurve, reverse(leftcurve_2))
return vcat(leftcurve, reverse(rightcurve))
end
"""
polyfit(plist::Array, npoints=30)
Build a polygon that constructs a B-spine approximation to it. The resulting list of points
makes a smooth path that runs between the first and last points.
"""
function polyfit(plist::Array{Point, 1}, npoints=30)
l = length(plist)
resultpoly = Array{Point}(undef, 0) ; sizehint!(resultpoly, npoints)
# start at first point
push!(resultpoly, plist[1])
# skip the first point
@inbounds for i in 2:l-1
p1 = plist[mod1(i - 1, l)]
p2 = plist[mod1(i, l)]
p3 = plist[mod1(i + 1, l)]
p4 = plist[mod1(i + 2, l)]
a3 = (-p1.x + 3 * (p2.x - p3.x) + p4.x) / 6.0
b3 = (-p1.y + 3 * (p2.y - p3.y) + p4.y) / 6.0
a2 = (p1.x - 2p2.x + p3.x) / 2.0
b2 = (p1.y - 2p2.y + p3.y) / 2.0
a1 = (p3.x - p1.x) / 2.0
b1 = (p3.y - p1.y) / 2.0
a0 = (p1.x + 4p2.x + p3.x) / 6.0
b0 = (p1.y + 4p2.y + p3.y) / 6.0
for i in 1:l-1
t = i/npoints
x = ((((a3 * t + a2) * t) + a1) * t) + a0
y = ((((b3 * t + b2) * t) + b1) * t) + b0
push!(resultpoly, Point(x, y))
end
end
# finish at last point
push!(resultpoly, plist[end])
return resultpoly
end
"""
pathtopoly()
Convert the current path to an array of polygons.
Returns an array of polygons, corresponding to the paths and subpaths of the original path.
"""
function pathtopoly()
originalpath = getpathflat()
polygonlist = Array{Point, 1}[] ; sizehint!(polygonlist, length(originalpath))
if length(originalpath) > 0
pointslist = Point[]
for e in originalpath
if e.element_type == Cairo.CAIRO_PATH_MOVE_TO # 0
push!(pointslist, Point(first(e.points), last(e.points)))
elseif e.element_type == Cairo.CAIRO_PATH_LINE_TO # 1
push!(pointslist, Point(first(e.points), last(e.points)))
elseif e.element_type == Cairo.CAIRO_PATH_CLOSE_PATH # 3
if last(pointslist) == first(pointslist)
# don’t repeat first point, we can close it ourselves
if length(pointslist) > 2
pop!(pointslist)
end
end
push!(polygonlist, pointslist)
pointslist = Point[]
else
error("pathtopoly(): unknown CairoPathEntry " * repr(e.element_type))
error("pathtopoly(): unknown CairoPathEntry " * repr(e.points))
end
end
# the path was never closed, so flush
if length(pointslist) > 0
push!(polygonlist, pointslist)
end
end
return polygonlist
end
"""
polydistances(p::Array{Point, 1}; closed=true)
Return an array of the cumulative lengths of a polygon.
"""
function polydistances(p::Array{Point, 1}; closed=true)
l = length(p)
r = Float64[0.0] ; sizehint!(r, l)
t = 0.0
@inbounds for i in 1:l - 1
t += distance(p[i], p[i + 1])
push!(r, t)
end
if closed
t += distance(p[end], p[1])
push!(r, t)
end
return r
end
"""
polyperimeter(p::Array{Point, 1}; closed=true)
Find the total length of the sides of polygon `p`.
"""
function polyperimeter(p::Array{Point, 1}; closed=true)
return polydistances(p, closed=closed)[end]
end
"""
nearestindex(polydistancearray, value)
Return a tuple of the index of the largest value in `polydistancearray` less
than `value`, and the difference value. Array is assumed to be sorted.
(Designed for use with `polydistances()`).
"""
function nearestindex(a::Array{T, 1} where T <: Real, val)
ind = findlast(v -> (v < val), a)
surplus = 0.0
if ind > 0.0
surplus = val - a[ind]
else
ind = 1
end
return (ind, surplus)
end
"""
polyportion(p::Array{Point, 1}, portion=0.5; closed=true, pdist=[])
Return a portion of a polygon, starting at a value between
0.0 (the beginning) and 1.0 (the end). 0.5 returns the first
half of the polygon, 0.25 the first quarter, 0.75 the first
three quarters, and so on.
Use `closed=false` to exclude the line joining the final
point to the first point from the calculations.
If you already have a list of the distances between each
point in the polygon (the "polydistances"), you can pass
them in `pdist`, otherwise they'll be calculated afresh,
using `polydistances(p, closed=closed)`.
Use the complementary `polyremainder()` function to return
the other part.
"""
function polyportion(p::Array{Point, 1}, portion=0.5; closed=true, pdist=[])
# portion is 0 to 1
if isempty(pdist)
pdist = polydistances(p, closed=closed)
end
if length(p) < 2
throw(error("polyportion(): need at least two points in a polygon"))
end
portion = clamp(portion, 0.0, 1.0)
# don't bother to do 0.0
isapprox(portion, 0.0, atol=0.00001) && return p[1:1]
# don't bother to do 1.0
if closed == false && isapprox(portion, 1.0, atol=0.00001)
return p
elseif isapprox(portion, 1.0, atol=0.00001)
return p
end
ind, surplus = nearestindex(pdist, portion * pdist[end])
if surplus > 0.0
nextind = mod1(ind + 1, length(p))
overshootpoint = between(p[ind], p[nextind], surplus/distance(p[ind], p[nextind]))
return vcat(p[1:ind], overshootpoint)
else
return p[1:end]
end
end