-
Notifications
You must be signed in to change notification settings - Fork 42
/
Polygon.m
1380 lines (1143 loc) · 43.4 KB
/
Polygon.m
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
%POLYGON Polygon class
%
% A general class for manipulating polygons and vectors of polygons.
%
% Methods::
% plot Plot polygon
% area Area of polygon
% moments Moments of polygon
% centroid Centroid of polygon
% perimeter Perimter of polygon
% transform Transform polygon
% inside Test if points are inside polygon
% intersection Intersection of two polygons
% difference Difference of two polygons
% union Union of two polygons
% xor Exclusive or of two polygons
% display print the polygon in human readable form
% char convert the polgyon to human readable string
%
% Properties::
% vertices List of polygon vertices, one per column
% extent Bounding box [minx maxx; miny maxy]
% n Number of vertices
%
% Notes::
% - This is reference class object
% - Polygon objects can be used in vectors and arrays
%
% Acknowledgement::
%
% The methods: inside, intersection, difference, union, and xor are based on code
% written by:
% Kirill K. Pankratov, [email protected],
% http://puddle.mit.edu/~glenn/kirill/saga.html
% and require a licence. However the author does not respond to email regarding
% the licence, so use with care, and modify with acknowledgement.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
% TODO
% split the code in two. Simple polygon functions in Polgon class, subclass with
% Pankratov code to Polygon2.
% add method to detect empty polygon, overload isempty
classdef Polygon < handle
properties
vertices
extent
end
properties (Dependent=true)
n
x
y
end
methods
function p = Polygon(v, wh)
%Polygon.Polygon Polygon class constructor
%
% P = Polygon(V) is a polygon with vertices given by V, one column per
% vertex.
%
% P = Polygon(C, WH) is a rectangle centred at C with dimensions
% WH=[WIDTH, HEIGHT].
if nargin == 0
p.n = 0;
p.vertices = [];
return;
end
if nargin < 2
if numrows(v) ~= 2
error('vertices must have two rows');
end
p.vertices = v;
end
if nargin == 2
if length(v) ~= 2
error('first argument must be polygon centre');
end
if length(wh) ~= 2
error('second arugment must be width height');
end
p.vertices = [
v(1)-wh(1)/2 v(1)+wh(1)/2 v(1)+wh(1)/2 v(1)-wh(1)/2
v(2)-wh(2)/2 v(2)-wh(2)/2 v(2)+wh(2)/2 v(2)+wh(2)/2 ];
end
% compute the extent
p.extent(1,1) = min(p.x);
p.extent(1,2) = max(p.x);
p.extent(2,1) = min(p.y);
p.extent(2,2) = max(p.y);
end
function r = get.n(p)
r = numcols(p.vertices);
end
function r = get.x(p)
r = p.vertices(1,:)';
end
function r = get.y(p)
r = p.vertices(2,:)';
end
function r = set.n(p)
error('cant set property');
end
function r = set.x(p)
error('cant set property');
end
function r = set.y(p)
error('cant set property');
end
function ss = char(p)
%Polygon.char String representation
%
% S = P.char() is a compact representation of the polgyon in human
% readable form.
ss = '';
for i=1:length(p)
if p(i).n <= 4
if length(p) > 1
s = sprintf('%2d: ', i);
else
s = '';
end
v = p(i).vertices;
for k=1:p(i).n
s = strcat(s, sprintf('(%g,%g)', v(:,k)));
if k~=p(i).n
s = strcat(s, ', ');
end
end
else
s = sprintf('... %d vertices', p.n)
end
ss =strvcat(ss, s);
end
end
function display(p)
%Polygon.display Display polygon
%
% P.display() displays the polygon in a compact human readable form.
%
% See also Polygon.char.
loose = strcmp( get(0, 'FormatSpacing'), 'loose');
if loose
disp(' ');
end
disp([inputname(1), ' = '])
if loose
disp(' ');
end
disp(char(p))
if loose
disp(' ');
end
end
function plot(plist, varargin)
%Polygon.plot Draw polygon
%
% P.plot() draws the polygon P in the current plot.
%
% P.plot(LS) as above but pass the arguments LS to plot.
%
% Notes::
% - The polygon is added to the current plot.
opt.fill = [];
[opt,args] = tb_optparse(opt, varargin);
ish = ishold;
hold all
for p=plist
% for every polygon in the list
% get the vertices
X = p.vertices(1,:)';
Y = p.vertices(2,:)';
while true
% look for NaNs which indicate disjoint vertex sets
k = find(isnan(X));
if length(k) > 0
% if a NaN chop out the segment before and after
k = k(1);
x = X(1:k-1);
y = Y(1:k-1);
X = X(k+1:end);
Y = Y(k+1:end);
else
x = X; y = Y;
end
% close the polygon
x = [x; x(1)];
y = [y; y(1)];
if opt.fill
patch(x, y, opt.fill);
else
plot(x, y, args{:});
end
if length(k) == 0
break;
end
end
end
if ~ish
hold off
end
end
function a = area(p)
%Polygon.area Area of polygon
%
% A = P.area() is the area of the polygon.
%
% See also Polygon.moments.
a = p.moments(0, 0);
end
function m = moments(p, mp, mq)
%Polygon.moments Moments of polygon
%
% A = P.moments(p, q) is the pq'th moment of the polygon.
%
% See also Polygon.area, Polygon.centroid, mpq_poly.
m = mpq_poly(p.vertices, mp, mq);
end
function q = transform(p, T)
%Polygon.transform Transform polygon vertices
%
% P2 = P.transform(T) is a new Polygon object whose vertices have
% been transformed by the SE(2) homgoeneous transformation T (3x3).
if length(T) == 3
T = se2(T);
end
q = Polygon( homtrans(T, p.vertices) );
end
function f = inside(p, points)
%Polygon.inside Test if points are inside polygon
%
% IN = P.inside(P) tests if points given by columns of P (2xN) are inside
% the polygon. The corresponding elements of IN (1xN) are either true or
% false.
f = inpolygon(points(1,:), points(2,:), p.x, p.y);
end
function c = centroid(p)
%Polygon.centroid Centroid of polygon
%
% X = P.centroid() is the centroid of the polygon.
%
% See also Polygon.moments.
c = [p.moments(1,0) p.moments(0,1)] / p.area();
end
function r = perimeter(p)
%Polygon.perimeter Perimeter of polygon
%
% L = P.perimeter() is the perimeter of the polygon.
p = sum(sqrt(diff(p.x).^2+diff(p.y).^2));
end
function f = intersect(p, plist)
%Polygon.intersect Intersection of polygon with list of polygons
%
% I = P.intersect(PLIST) indicates whether or not the Polygon P
% intersects with
%
% i(j) = 1 if p intersects polylist(j), else 0.
% Based on ISINTPL
% Copyright (c) 1995 by Kirill K. Pankratov,
% 06/20/95, 08/25/95
f = [];
for q=plist
f = [f isintpl(p.x, p.y, q.x, q.y)];
end
end
function f = intersect_line(p, l)
%Polygon.intersect_line Intersection of polygon and line segment
%
% I = P.intersect_line(L) is the intersection points of a polygon P with
% the line segment L=[x1 x2; y1 y2]. I (2xN) has one column per
% intersection, each column is [x y]'.
f = [];
% find intersections
for i=1:p.n
in = mod(i, p.n)+1;
xv = [p.x(i); p.x(in)];
yv = [p.y(i); p.y(in)];
intsec = iscross(xv, yv, l(1,:)', l(2,:)');
if intsec
[x,y] = intsecl(xv, yv, l(1,:)', l(2,:)');
f = [f [x;y]];
end
end
end
function r = difference(p, q)
%Polygon.difference Difference of polygons
%
% D = P.difference(Q) is polygon P minus polygon Q.
%
% Notes::
% - If polygons P and Q are not intersecting, returns
% coordinates of P.
% - If the result D is not simply connected or consists of
% several polygons, resulting vertex list will contain NaNs.
% POLYDIFF Difference of 2 polygons.
% [XO,YO] = POLYDIFF(X1,Y1,X2,Y2) Calculates polygon(s) P
% of difference of polygons P1 and P1 with coordinates
% X1, Y1 and X2, Y2.
% The resulting polygon(s) is a set of all points which belong
% to P1 but not to to P2: P = P1 & ~P2.
% The input polygons must be non-self-intersecting and
% simply connected.
%
% If polygons P1, P2 are not intersecting, returns
% coordinates of the first polygon X1, X2.
% If the result P is not simply connected or consists of several
% polygons, resulting boundary consists of concatenated
% coordinates of these polygons, separated by NaN.
% Copyright (c) 1995 by Kirill K. Pankratov,
% 06/25/95
% Call POLYBOOL with flag=3
[xo,yo,ind] = polybool(p.x, p.y, q.x, q.y, 3);
r = Polygon([xo(:) yo(:)]');
end
function r = intersection(p, q)
%Polygon.intersection Intersection of polygons
%
% I = P.intersection(Q) is a Polygon representing the
% intersection of polygons P and Q.
%
% Notes::
% - If these polygons are not intersecting, returns empty polygon.
% - If intersection consist of several disjoint polygons
% (for non-convex P or Q) then vertices of I is the concatenation
% of the vertices of these polygons.
% POLYINTS Intersection of 2 polygons.
% [XO,YO] = POLYINTS(X1,Y1,X2,Y2) Calculates polygon(s)
% if intersection of polygons with coordinates X1, Y1
% and X2, Y2.
% The resulting polygon(s) is a set of all points which
% belong to both P1 and P2: P = P1 & P2.
% These polygons must be non-self-intersecting and
% simply connected.
%
% If these polygons are not intersecting, returns empty.
% If intersection consist of several disjoint polygons
% (for non-convex P1 or P2) output vectors XO, YO consist
% of concatenated cooddinates of these polygons,
% Copyright (c) 1995 by Kirill K. Pankratov,
% 06/25/95
% Call POLYBOOL with flag=1
[xo,yo,ind] = polybool(p.x, p.y, q.x, q.y, 1);
r = Polygon([xo(:) yo(:)]');
end
function r = union(p, q)
%Polygon.union Union of polygons
%
% I = P.union(Q) is a polygon representing the
% union of polygons P and Q.
%
% Notes::
% - If these polygons are not intersecting, returns a polygon with
% vertices of both polygons separated by NaNs.
% - If the result P is not simply connected (such as a polygon
% with a "hole") the resulting contour consist of counter-
% clockwise "outer boundary" and one or more clock-wise
% "inner boundaries" around "holes".
% POLYUNI Union of 2 polygons.
% [XO,YO] = POLYINT(X1,Y1,X2,Y2) Calculates polygon(s) P
% which is (are) union of polygons P1 and P2 with coordinates
% X1, Y1 and X2, Y2.
% The resulting polygon(s) is a set of all points which belong
% either to P1 or to P2: P = P1 | P2.
% The input polygons must be non-self-intersecting and
% simply connected.
%
% If polygons P1, P2 are not intersecting, returns
% coordinates of the both polygons separated by NaN.
% If both P1 and P2 are convex, their boundaries can have no
% more than 2 intersections. The result is also a convex
% polygon.
% If the result P is not simply connected (such as a polygon
% with a "hole") the resulting contour consist of counter-
% clockwise "outer boundary" and one or more clock-wise
% "inner boundaries" around "holes".
% Copyright (c) 1995 by Kirill K. Pankratov,
% 06/25/95
% Call POLYBOOL with flag=2 ..........
[xo,yo,ind] = polybool(p.x, p.y, q.x, q.y, 2);
r = Polygon([xo(:) yo(:)]');
end
function r = xor(p, q)
%Polygon.xor Exclusive or of polygons
%
% I = P.union(Q) is a polygon representing the
% exclusive-or of polygons P and Q.
%
% Notes::
% - If these polygons are not intersecting, returns a polygon with
% vertices of both polygons separated by NaNs.
% - If the result P is not simply connected (such as a polygon
% with a "hole") the resulting contour consist of counter-
% clockwise "outer boundary" and one or more clock-wise
% "inner boundaries" around "holes".
% POLYXOR Exclusive OR of 2 polygons.
% [XO,YO] = POLYXOR(X1,Y1,X2,Y2) Calculates polygon(s) P
% of difference of polygons P1 and P1 with coordinates
% X1, Y1 and X2, Y2.
% The resulting polygon(s) is a set of all points which belong
% either to P1 or to P2 but not to both:
% P = (P1 & ~P2) | (P2 & ~P1).
% The input polygons must be non-self-intersecting and
% simply connected.
%
% If polygons P1, P2 are not intersecting, returns
% coordinates of the both polygons separated by NaN.
% If the result P is not simply connected or consists of several
% polygons, resulting boundary consists of concatenated
% coordinates of these polygons, separated by NaN.
% Copyright (c) 1995 by Kirill K. Pankratov,
% 06/25/95
% Call POLYBOOL twice with flag=3
[xx,yy,ind] = polybool(p.x, p.y, q.x, q.y, 3);
xo = [xx; NaN]; yo = [yy; NaN];
[xx,yy,ind] = polybool(q.x, q.y, p.x, p.y, 3);
xo = [xo; xx]; yo = [yo; yy];
r = Polygon([xo(:) yo(:)]');
end
end % methods
end % classdef
function [is,in,un] = interval(x1,x2)
% Intersection and union of 2 intervals.
% [IS,IN,UN] = INTERVAL(X1,X2) calculates pair-wise
% intersection IN and union UN of N pairs of
% intervals with coordinates X1 and X2 (both are
% 2 by N vectors). Returns 1 by N boolean vector IS
% equal to 1 if intervals have non-empty intersection
% and 0 if they don't.
% Copyright (c) 1995 by Kirill K. Pankratov,
% 08/24/95
% Handle input ...........................
if nargin==0, help interval, return, end
if nargin==1
un = x1;
else
un = [x1; x2];
end
[in,un] = sort(un); % Sort both intervals together
un = un(1:2,:)-1;
is = sum(floor(un/2)); % Check for [0 0 1 1] or [1 1 0 0]
is = (is==1);
ii = find(in(2,:)==in(3,:));
is(ii) = .5*ones(size(ii));
% Extract intersection and union from sorted coordinates
if nargout>1
un = in([1 4],:);
in = in(2:3,:);
in(:,~is) = flipud(in(:,~is));
end
end
function [is,S] = iscross(x1,y1,x2,y2,tol)
% ISCROSS Finds whether pairs of lines cross each other
% [IS,S] = ISCROSS(X1,Y1,X2,Y2) where arguments X1, Y1,
% X2, Y2 are all 2 by N matrices are coordinates of
% ends of the pairs of line segments.
% Returns vector IS (1 by N) consisting of ones if
% corresponding pairs cross each other, zeros if they
% don't and .5 if an end of one line segment lies on
% another segment.
% Also returns a matrix S (4 by N) with each row
% consisting of cross products (double areas of
% corresponding triangles) built on the following points:
% (X2(1,:),Y2(1,:)),(X1(1,:),Y1(1,:)),(X2(2,:),Y2(2,:)),
% (X2(1,:),Y2(1,:)),(X1(2,:),Y1(2,:)),(X2(2,:),Y2(2,:))
% (X1(1,:),Y1(1,:)),(X2(1,:),Y2(1,:)),(X1(2,:),Y1(2,:))
% (X1(1,:),Y1(1,:)),(X2(2,:),Y2(2,:)),(X1(2,:),Y1(2,:))
% The signs of these 4 areas can be used to determine
% whether these lines and their continuations cross each
% other.
% [IS,S] = ISCROSS(X1,Y1,X2,Y2,TOL) uses tolerance TOL
% for detecting the crossings (default is 0).
% Copyright (c) 1995 by Kirill K. Pankratov
% 08/14/94, 05/18/95, 08/25/95
% Defaults and parameters .......................
tol_dflt = 0; % Tolerance for area calculation
is_chk = 1; % Check input arguments
% Handle input ..................................
if nargin==0, help iscross, return, end
if nargin<4 % Check if all 4 entered
error(' Not enough input arguments')
end
if nargin<5, tol = tol_dflt; end
if tol < 0, is_chk = 0; tol = 0; end
% Check the format of arguments .................
if is_chk
[x1,y1,x2,y2] = linechk(x1,y1,x2,y2);
end
len = size(x1,2);
o2 = ones(2,1);
% Find if the ranges of pairs of segments intersect
[isx,S,A] = interval(x1,x2);
scx = diff(A);
[isy,S,A] = interval(y1,y2);
scy = diff(A);
is = isx & isy;
% If S values are not needed, extract only those pairs
% which have intersecting ranges ..............
if nargout < 2
isx = find(is); % Indices of pairs to be checked
% further
x1 = x1(:,isx);
x2 = x2(:,isx);
y1 = y1(:,isx);
y2 = y2(:,isx);
is = is(isx);
if isempty(is), is = zeros(1,len); return, end
scx = scx(isx);
scy = scy(isx);
end
% Rescale by ranges ...........................
x1 = x1.*scx(o2,:);
x2 = x2.*scx(o2,:);
y1 = y1.*scy(o2,:);
y2 = y2.*scy(o2,:);
% Calculate areas .............................
S = zeros(4,length(scx));
S(1,:) = (x2(1,:)-x1(1,:)).*(y2(2,:)-y1(1,:));
S(1,:) = S(1,:)-(x2(2,:)-x1(1,:)).*(y2(1,:)-y1(1,:));
S(2,:) = (x2(1,:)-x1(2,:)).*(y2(2,:)-y1(2,:));
S(2,:) = S(2,:)-(x2(2,:)-x1(2,:)).*(y2(1,:)-y1(2,:));
S(3,:) = (x1(1,:)-x2(1,:)).*(y1(2,:)-y2(1,:));
S(3,:) = S(3,:)-(x1(2,:)-x2(1,:)).*(y1(1,:)-y2(1,:));
S(4,:) = (x1(1,:)-x2(2,:)).*(y1(2,:)-y2(2,:));
S(4,:) = S(4,:)-(x1(2,:)-x2(2,:)).*(y1(1,:)-y2(2,:));
% Find if they cross each other ...............
is = (S(1,:).*S(2,:)<=0)&(S(3,:).*S(4,:)<=0);
% Find very close to intersection
isy = min(abs(S));
ii = find(isy<=tol & is);
is(ii) = .5*ones(size(ii));
% Output
if nargout < 2
isy = zeros(1,len);
isy(isx) = is;
is = isy;
else
isy = scx.*scy;
ii = find(~isy);
isy(ii) = ones(size(ii));
S = S./isy(ones(4,1),:);
end
end
function [xo,yo,ind] = polybool(x1,y1,x2,y2,flag)
% [XO,YO] = POLYBOOL(X1,Y1,X2,Y2,FLAG)
% calulates results of Boolean operations on
% a pair of polygons.
% FLAG Specifies the type of the operation:
% 1 - Intersection (P1 & P2)
% 2 - Union (P1 | P2)
% 3 - Difference (P1 & ~P2)
% Copyright (c) 1995 by Kirill K. Pankratov,
% 06/25/95, 09/07/95
% This program calls the following functions:
% AREA, ISINTPL, ISCROSS, INTSECL.
% Algorithm:
% 1. Check boundary contour directions (area).
% For intersection and union make all
% counter-clockwise. For difference make the second
% contour clock-wise.
% 2. Calculate matrix of intersections (function ISINTPL).
% Quick exit if no intersections.
% 3. For intersecting segments calculate intersection
% coordinates (function INTSECL).
% 4. Sort intersections along both contours.
% 5. Calculate sign of cross-product between intersectiong
% segments. This will give which contour goes "in" and
% "out" at intersections.
%
% 6. Start with first intersection:
% Determine direction to go ("in" for intersection,
% "out" for union).
% Move until next intersection, switch polygons at each
% intersection until coming to the initial point.
% If not all intersections are encountered, the
% resulting polygon is disjoint. Separate output
% coordinates by NaN and repeat procedure until all
% intersections are counted.
% Default for flag
flag_dflt = 1; % 1- intersec., 2-union, 3 - diff.
% Handle input
if nargin==0, help polybool, return, end
if nargin < 4
error(' Not enough input arguments')
end
if nargin<5, flag = flag_dflt; end
x1 = x1(:); y1 = y1(:);
x2 = x2(:); y2 = y2(:);
l1 = length(x1);
l2 = length(x2);
% Check areas and reverse if negative
nn1 = area(x1,y1);
if nn1<0, x1 = flipud(x1); y1 = flipud(y1); end
nn2 = area(x2,y2);
if (nn2<0 & flag<3) | (nn2>0 & flag==3)
x2 = flipud(x2); y2 = flipud(y2);
end
% If both polygons are identical ........
if l1==l2
if all(x1==x2) & all(y1==y2)
if flag<3, xo = x1; yo = y1; ind = 1:l1;
else, xo = []; yo = []; ind = []; end
return
end
end
% Calculate matrix of intersections .....
[is,C] = isintpl(x1,y1,x2,y2);
is = any(any(C));
% Quick exit if no intersections ........
if ~is
if flag==1 % Intersection
xo=[]; yo = [];
elseif flag==2 % Union
xo = [x1; nan; x2];
yo = [y1; nan; y2];
elseif flag==3 % Difference
xo = x1; yo = y1;
end
return
end
% Mark intersections with unique numbers
i1 = find(C);
ni = length(i1);
C(i1) = 1:ni;
% Close polygon contours
x1 = [x1; x1(1)]; y1 = [y1; y1(1)];
x2 = [x2; x2(1)]; y2 = [y2; y2(1)];
l1 = length(x1); l2 = length(x2);
% Calculate intersections themselves
[i1,i2,id] = find(C);
xs1 = [x1(i1) x1(i1+1)]'; ys1 = [y1(i1) y1(i1+1)]';
xs2 = [x2(i2) x2(i2+1)]'; ys2 = [y2(i2) y2(i2+1)]';
% Call INTSECL ............................
[xint,yint] = intsecl(xs1,ys1,xs2,ys2);
% For sements belonging to the same line
% find interval of intersection ...........
ii = find(xint==inf);
if ~isempty(ii)
[is,inx] = interval(xs1(:,ii),xs2(:,ii));
[is,iny] = interval(ys1(:,ii),ys2(:,ii));
xint(ii) = mean(inx);
yint(ii) = mean(iny);
end
% Coordinate differences of intersecting segments
xs1 = diff(xs1); ys1 = diff(ys1);
xs2 = diff(xs2); ys2 = diff(ys2);
% Calculate cross-products
cp = xs1.*ys2-xs2.*ys1;
cp = cp>0;
if flag==2, cp=~cp; end % Reverse if union
cp(ii) = 2*ones(size(ii));
% Sort intersections along the contours
ind = (xint-x1(i1)').^2+(yint-y1(i1)').^2;
ind = ind./(xs1.^2+ys1.^2);
cnd = min(ind(ind>0));
ind = ind+i1'+i2'/(ni+1)*cnd*0;
[xo,ii] = sort(ind);
xs1 = id(ii);
[xo,ind] = sort(xs1);
ind = rem(ind,ni)+1;
xs1 = xs1(ind);
ind = (xint-x2(i2)').^2+(yint-y2(i2)').^2;
ind = ind./(xs2.^2+ys2.^2);
cnd = min(ind(ind>0));
[xo,ii] = sort(i2'+ind+i1'/(ni+1)*cnd*0);
xs2 = id(ii);
[xo,ind] = sort(xs2);
ind = rem(ind,ni)+1;
xs2 = xs2(ind);
% Combine coordinates in one vector
x1 = [x1; x2]; y1 = [y1; y2];
% Find max. possible length of a chain
xo = find(any(C'));
xo = diff([xo xo(1)+l1]);
mlen(1) = max(xo);
xo = find(any(C));
xo = diff([xo xo(1)+l2]);
mlen(2) = max(xo);
% Check if multiple intersections in one segment
xo = diff([i1 i2]);
is_1 = ~all(all(xo));
% Begin counting intersections *********************
% Initialization ..................
int = zeros(size(xint));
nn = 1; % First intersection
nn1 = i1(nn); nn2 = i2(nn);
b = cp(nn);
is2 = b==2;
xo = []; yo = []; ind = [];
closed = 0;
% Proceed until all intersections are counted
while ~closed % begin counting `````````````````````0
% If contour closes, find new starting point
if int(nn) & ~all(int)
ii = find(int);
C(id(ii)) = zeros(size(ii));
nn = min(find(~int)); % Next intersection
nn1 = i1(nn);
nn2 = i2(nn);
xo = [xo; nan]; % Separate by NaN
yo = [yo; nan];
ind = [ind; nan];
% Choose direction ......
b = cp(nn);
end
% Add current intersection ......
xo = [xo; xint(nn)];
yo = [yo; yint(nn)];
ind = [ind; 0];
int(nn) = 1;
closed = all(int);
% Find next segment
% Indices for next intersection
if ~b, nn = xs1(nn);
else, nn = xs2(nn);
end
if ~b, pt0 = nn1; else, pt0 = nn2; end
nn1 = i1(nn);
nn2 = i2(nn);
if b, pt = nn2; else, pt = nn1; end
if b, pt0 = pt0+l1; pt = pt+l1; end
ii = (pt0+1:pt);
% Go through the beginning ..............
cnd = pt<pt0 | (pt==pt0 & is_1 & flag>1);
if cnd
if ~b, ii = [pt0+1:l1 1:pt];
else, ii = [pt0+1:l1+l2 l1+1:pt];
end
end
len = length(ii);
cnd = b & len>mlen(2);
cnd = cnd | (~b & len>mlen(1));
if is2 | cnd, ii=[]; end
% Add new segment
xo = [xo; x1(ii)];
yo = [yo; y1(ii)];
ind = [ind; ii'];
% Switch direction
if cp(nn)==2, b = ~b; is2 = 1;
else, b = cp(nn); is2 = 0;
end
end % End while (all intersections) '''''''''''''''0
% Remove coincident successive points
ii = find(~diff(xo) & ~diff(yo));
xo(ii) = []; yo(ii) = []; ind(ii) = [];
% Remove points which are
ii = find(isnan(xo));
if ~isempty(ii)
i2 = ones(size(xo));
ii = [ii; length(xo)+1];
i1 = find(diff(ii)==3);
i1 = ii(i1);
i1 = [i1; i1+1; i1+2];
i2(i1) = zeros(size(i1));
i1 = find(diff(ii)==2);
i1 = ii(i1);
i1 = [i1; i1+1];
i2(i1) = zeros(size(i1));
xo = xo(i2); yo = yo(i2); ind = ind(i2);
end
end
function [xo,yo] = intsecpl(xv,yv,xl,yl,trace)
% INTSECPL Intersection of a polygon and a line.
% [XI,YI] = INTSECPL(XV,YV,XL,YL) calculates
% intersections XI, YI of a polygon with vertices XV,
% YV and a line specified by pairs of end coordinates
% XL = [XL0 XL1], YL = [YL0 YL1]. Line is assumed to
% continue beyond the range of end points.
% INTSECPL(XV,YV,[A B]) uses another specification for
% a line: Y = A*X+B.
%
% If a line does not intersect polygon, returns empty
% XI, YI.
% For convex polygon maximum number of intersections is
% 2, for non-convex polygons multiple intersections are
% possible.
%
% INTSECPL(XV,YV,XL,YL) by itself or
% [XI,YI] = INTSECPL(XV,YV,XL,YL,1) plots polygon,
% a line segment and intersection segment(s)
% (part(s) of the same line inside the polygon).
% Copyright (c) 1995 by Kirill K. Pankratov,
% 06/25/95, 08/27/95, 09/27/95
% Calls ISCROSS, INTSECL programs.
% Defaults and parameters .................................
tol = 1e-14; % Tolerance
marg = tol; % Margins for polygon frame
is_ab = 0; % Default A*X+B mode
% Handle input ............................................
if nargin==0, help intsecpl, return, end
if nargin < 3
error(' Not enough input arguments')
end
if nargin<5, trace = 0; end
if nargin==4 % Check if 4-th arg is trace
if max(size(yl))==1, trace = yl; is_ab = 1; end
end
if nargin==3, is_ab = 1; end
trace = trace | nargin<2;
if length(xv)~=length(yv)
error(' Vectors X, Y must have the same size')
end
% Auxillary ...........
xv = [xv(:); xv(1)];
yv = [yv(:); yv(1)];
ii = find(abs(diff(xv))<tol & abs(diff(yv))<tol);
xv(ii) = []; yv(ii) = [];
nv = length(xv);
ov = ones(nv-1,1);
% Polygon frame
lim = [min(xv)-marg max(xv)+marg min(yv)-marg max(yv)+marg];
% Estimate for diameter
d = sqrt((lim(2)-lim(1)).^2+(lim(4)-lim(3)).^2);
% Form line segment depending on how line is specified
if is_ab % A*X+B mode ...................
xl = xl(:);
if length(xl)<2
error(' Line is specified by at least two parameters')
end
a = xl(1); b = xl(2);
xl = [lim(1)-1 lim(2)+1];