/
polygons.jl
753 lines (656 loc) · 23.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
# polygons, part of Luxor
"""
Draw a polygon.
poly(pointlist::AbstractArray{Point, 1}, action = :nothing;
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::AbstractArray{Point, 1}, action::Symbol = :nothing; close::Bool=false, reversepath::Bool=false)
if action != :path
newpath()
end
if reversepath == true
reverse!(pointlist)
end
move(pointlist[1].x, pointlist[1].y)
for p in pointlist[2:end]
line(p.x, p.y)
end
if close==true
closepath()
end
do_action(action)
end
"""
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::AbstractArray{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
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::AbstractArray, refpoint=minimum(pointlist))
The `refpoint` can be chosen, but the minimum point is usually OK too:
polysortbyangle(parray, polycentroid(parray))
"""
function polysortbyangle(pointlist::AbstractArray{Point, 1}, refpoint=minimum(pointlist))
angles = Float64[]
for pt in pointlist
push!(angles, atan(refpoint.y - pt.y, refpoint.x - pt.x))
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::AbstractArray{Point, 1}, starting::Point)
route = [starting]
# 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::AbstractArray, start_index, last_index, epsilon)
"""
function douglas_peucker(pointlist::AbstractArray{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
for i in start_index + 2:last_index - 1 # 2 seems to keep the starting point...
keep_list[i - global_start_index] = false
end
end
end
return pointlist[keep_list]
end
"""
Simplify a polygon:
simplify(pointlist::AbstractArray, detail=0.1)
`detail` is the smallest permitted distance between two points in pixels.
"""
function simplify(pointlist::AbstractArray{Point, 1}, detail=0.1)
douglas_peucker(pointlist, 1, length(pointlist), detail)
end
function det3p(q1::Point, q2::Point, p::Point)
(q1.x - p.x) * (q2.y - p.y) - (q2.x - p.x) * (q1.y - p.y)
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::AbstractArray{Point, 1};
allowonedge::Bool=false)
c = false
@inbounds for counter in 1:length(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("VertexException a")
continue
end
if q2.y == p.y
if q2.x == p.x
allowonedge || error("VertexException b")
continue
elseif (q1.y == p.y) && ((q2.x > p.x) == (q1.x < p.x))
allowonedge || error("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 ((det3p(q1, q2, p) > 0) == (q2.y > q1.y))
c = !c
end
elseif q2.x > p.x
if ((det3p(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::AbstractArray{Point, 1}, p1::Point, p2::Point)
# the two-pass version
# TODO should be one-pass
newpointlist = Point[]
l = length(pointlist)
vertex1 = Point(0, 0)
vertex2 = Point(0, 0)
for i in 1:l
vertex1 = pointlist[mod1(i, l)]
vertex2 = pointlist[mod1(i + 1, l)]
flag, intersectpoint = intersection(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)
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::AbstractArray{Point, 1}, action=:nothing, vertexfunction = () -> circle(O, 2, :stroke);
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, :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, :stroke,
vertexlabels = (n, l) -> (text(string(n, " of ", l))))
"""
function prettypoly(pointlist::AbstractArray{Point, 1}, action=:nothing, vertexfunction = () -> circle(O, 2, :stroke);
close=false,
reversepath=false,
vertexlabels = (n, l) -> ()
)
if action != :path
newpath()
end
if reversepath
reverse!(pointlist)
end
move(pointlist[1].x, pointlist[1].y)
for p in pointlist[2:end]
line(p.x, p.y)
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
end
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)
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.
"""
function polysmooth(points::AbstractArray{Point, 1}, radius, action=:action; debug=false)
temppath = Tuple[]
l = length(points)
# perhaps should check that l >= 3?
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
# 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
"""
offsetpoly(path::AbstractArray{Point, 1}, d)
Return a polygon that is offset from a polygon by `d` units.
The incoming set of points `path` 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(path::AbstractArray{Point, 1}, d)
# don't try to calculate offset of two identical points
if path[1] == path[end]
popfirst!(path)
end
l = length(path)
resultpoly = Array{Point}(undef, l)
for i in 1:l
p1 = path[mod1(i, l)]
p2 = path[mod1(i + 1, l)]
p3 = path[mod1(i + 2, l)]
# should check for identical points here too...
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 = intersection(
Point(x1p, y1p),
Point(x2p, y2p),
Point(x3p, y3p),
Point(x4p, y4p), crossingonly=false, collinearintersect=true)
if intersectionpoint[1]
resultpoly[i] = intersectionpoint[2]
end
end
return resultpoly
end
"""
polyfit(plist::AbstractArray, 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::AbstractArray{Point, 1}, npoints=30)
l = length(plist)
resultpoly = Array{Point}(undef, 0)
# start at first point
push!(resultpoly, plist[1])
# skip the first point
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.
"""
function pathtopoly()
originalpath = getpathflat()
polygonlist = Array{Point, 1}[]
pointslist = Point[]
if length(originalpath) > 0
for e in originalpath
if e.element_type == Cairo.CAIRO_PATH_MOVE_TO # 0
pointslist = Point[]
push!(pointslist, Point(e.points[1], e.points[2]))
elseif e.element_type == Cairo.CAIRO_PATH_LINE_TO # 1
push!(pointslist, Point(e.points[1], e.points[2]))
elseif e.element_type == Cairo.CAIRO_PATH_CLOSE_PATH # 3
closepath()
push!(polygonlist, pointslist)
else
error("unknown CairoPathEntry " * repr(e.element_type))
error("unknown CairoPathEntry " * repr(e.points))
end
end
if length(pointslist) > 1
# if length is 1, there's a stray moveto point which we don't want
push!(polygonlist, pointslist)
end
end
return polygonlist
end
"""
polydistances(p::AbstractArray{Point, 1}; closed=true)
Return an array of the cumulative lengths of a polygon.
"""
function polydistances(p::AbstractArray{Point, 1}; closed=true)
r = Float64[0.0]
t = 0.0
for i in 1:length(p) - 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::AbstractArray{Point, 1}; closed=true)
Find the total length of the sides of polygon `p`.
"""
function polyperimeter(p::AbstractArray{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::AbstractArray{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::AbstractArray{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.
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::AbstractArray{Point, 1}, portion=0.5; closed=true, pdist=[])
# portion is 0 to 1
if isempty(pdist)
pdist = polydistances(p, closed=closed)
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
"""
polyremainder(p::AbstractArray{Point, 1}, portion=0.5; closed=true, pdist=[])
Return the rest of a polygon, starting at a value between 0.0 (the beginning) and 1.0 (the end). 0.5 returns the last half of the polygon, 0.25 the last three quarters, 0.75 the last quarter, and so on.
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 `polyportion()` function to return the other part.
"""
function polyremainder(p::AbstractArray{Point, 1}, portion=0.5; closed=true, pdist=[])
# portion is 0 to 1
if isempty(pdist)
pdist = polydistances(p, closed=closed)
end
portion = clamp(portion, 0.0, 1.0)
# don't bother to do 0.0
isapprox(portion, 0.0, atol=0.00001) && return p
# don't bother to do 1.0
if isapprox(portion, 1.0, atol=0.00001)
return p[1:1]
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(overshootpoint, p[nextind:end])
else
return p[1:end]
end
end
"""
polyarea(p::AbstractArray)
Find the area of a simple polygon. It works only for polygons that don't
self-intersect.
"""
function polyarea(plist::AbstractArray{Point, 1})
n = length(plist)
area = 0.0
for i in eachindex(plist)
j = mod1(i + 1, n)
area += plist[i].x * plist[j].y
area -= plist[j].x * plist[i].y
end
area = abs(area) / 2.0
return area
end
"""
intersectlinepoly(pt1::Point, pt2::Point, C)
Return an array of the points where a line between pt1 and pt2 crosses polygon C.
"""
function intersectlinepoly(pt1::Point, pt2::Point, C::AbstractArray{Point, 1})
intersectingpoints = Point[]
for j in 1:length(C)
Cpointpair = (C[j], C[mod1(j+1, length(C))])
flag, pt = intersection(pt1, pt2, Cpointpair..., crossingonly=true)
if flag
push!(intersectingpoints, pt)
end
end
# sort by distance from pt1
sort!(intersectingpoints, lt = (p1, p2) -> distance(p1, pt1) < distance(p2, pt1))
return intersectingpoints
end
"""
polyintersections(S::AbstractArray{Point, 1}, C::AbstractArray{Point, 1})
Return an array of the points in polygon S plus the points where polygon S crosses
polygon C. Calls `intersectlinepoly()`.
"""
function polyintersections(S::AbstractArray{Point, 1}, C::AbstractArray{Point, 1})
Splusintersectionpoints = Point[]
for i in 1:length(S)
Spointpair = (S[i], S[mod1(i+1, length(S))])
push!(Splusintersectionpoints, S[i])
for pt in intersectlinepoly(Spointpair..., C)
push!(Splusintersectionpoints, pt)
end
end
return Splusintersectionpoints
end