-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclipper_float.pas
More file actions
4909 lines (4527 loc) · 147 KB
/
Copy pathclipper_float.pas
File metadata and controls
4909 lines (4527 loc) · 147 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
unit clipper_float;
(*******************************************************************************
* *
* Author : Angus Johnson *
* Version : 6.1.3 (float) - Experimental *
* Date : 16 January 2014 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2014 *
* *
* License: *
* Use, modification & distribution is subject to Boost Software License Ver 1. *
* http://www.boost.org/LICENSE_1_0.txt *
* *
* Attributions: *
* The code in this library is an extension of Bala Vatti's clipping algorithm: *
* "A generic solution to polygon clipping" *
* Communications of the ACM, Vol 35, Issue 7 (July 1992) PP 56-63. *
* http://portal.acm.org/citation.cfm?id=129906 *
* *
* Computer graphics and geometric modeling: implementation and algorithms *
* By Max K. Agoston *
* Springer; 1 edition (January 4, 2005) *
* http://books.google.com/books?q=vatti+clipping+agoston *
* *
* See also: *
* "Polygon Offsetting by Computing Winding Numbers" *
* Paper no. DETC2005-85513 PP. 565-575 *
* ASME 2005 International Design Engineering Technical Conferences *
* and Computers and Information in Engineering Conference (IDETC/CIE2005) *
* September 24-28, 2005 , Long Beach, California, USA *
* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *
* *
*******************************************************************************)
{$DEFINE TYPES2}
//use_xyz: adds a Z member to FPoint (with only a minor cost to performance)
{.$DEFINE use_xyz}
//use_lines: Enables line clipping. Adds a very minor cost to performance.
{.$DEFINE use_lines}
//use_deprecated: Enables support for the obsolete OffsetPaths() function
//which has been replace with the ClipperOffset class.
{$DEFINE use_deprecated}
{$IFDEF FPC}
{$DEFINE INLINING}
{$ELSE}
{$IFDEF ConditionalExpressions}
{$IF CompilerVersion >= 18} //Delphi 2007
//Inline has been supported since D2005.
//However D2005 and D2006 have an Inline codegen bug (QC41166).
//http://www.thedelphigeek.com/2007/02/nasty-inline-codegen-bug-in-bds-2006.html
{$DEFINE INLINING}
{$IFEND}
{$ENDIF}
{$ENDIF}
interface
uses
{$IFDEF TYPES2}Types0, Types2, {$ENDIF}
SysUtils, Types, Classes, Math;
const
def_arc_tolerance = 0.25;
type
PFPoint = ^TFPoint;
{$IFDEF TYPES2}
{$IFDEF use_xyz}
TFPoint = T3DPoint;
TPath = TArrayOf3DPoint;
TPaths = TArrayOfArrayOf3DPoint;
{$ELSE}
TFPoint = TDPoint;
TPath = TArrayOfDPoint;
TPaths = TArrayOfArrayOfDPoint;
{$ENDIF}
TDoublePoint = TDPoint;
TArrayOfDoublePoint = TArrayOfDPoint;
//TFRect = Types2.TDRect;
{$ELSE}
{$IFDEF use_xyz}
TFPoint = record X, Y: Double; Z: Int64; end;
{$ELSE}
TFPoint = record X, Y: Double; end;
{$ENDIF}
TDoublePoint = record X, Y: Double; end;
TArrayOfDoublePoint = array of TDoublePoint;
TPath = array of TFPoint;
TPaths = array of TPath;
{$ENDIF}
TFRect = record Left, Top, Right, Bottom: Double; end;
{$IFDEF use_xyz}
TZFillCallback = procedure (const Pt1, Pt2: TFPoint; var Pt: TFPoint);
{$ENDIF}
TInitOption = (ioReverseSolution, ioStrictlySimple, ioPreserveCollinear);
TInitOptions = set of TInitOption;
TClipType = (ctIntersection, ctUnion, ctDifference, ctXor);
TPolyType = (ptSubject, ptClip);
//By far the most widely used winding rules for polygon filling are
//EvenOdd & NonZero (GDI, GDI+, XLib, OpenGL, Cairo, AGG, Quartz, SVG, Gr32)
//Others rules include Positive, Negative and ABS_GTR_EQ_TWO (only in OpenGL)
//see http://glprogramming.com/red/chapter11.html
TPolyFillType = (pftEvenOdd, pftNonZero, pftPositive, pftNegative);
//TJoinType & TEndType are used by OffsetPaths()
TJoinType = (jtSquare, jtRound, jtMiter);
TEndType = (etClosedPolygon, etClosedLine,
etOpenButt, etOpenSquare, etOpenRound, etSingle); //and etSingle still to come
{$IFDEF use_deprecated}
TEndType_ = (etClosed, etButt = 2, etSquare, etRound);
{$ENDIF}
TPolyNode = class;
TArrayOfPolyNode = array of TPolyNode;
TPolyNode = class
private
FPath : TPath;
FParent : TPolyNode;
FIndex : Integer;
FCount : Integer;
FBuffLen : Integer;
FIsOpen : Boolean;
FChilds : TArrayOfPolyNode;
FJoinType: TJoinType; //used by ClipperOffset only
FEndType : TEndType; //used by ClipperOffset only
function GetChild(Index: Integer): TPolyNode;
function IsHoleNode: boolean;
procedure AddChild(PolyNode: TPolyNode);
function GetNextSiblingUp: TPolyNode;
public
function GetNext: TPolyNode;
property ChildCount: Integer read FCount;
property Childs[index: Integer]: TPolyNode read GetChild;
property Parent: TPolyNode read FParent;
property IsHole: Boolean read IsHoleNode;
property IsOpen: Boolean read FIsOpen;
property Contour: TPath read FPath;
end;
TPolyTree = class(TPolyNode)
private
FAllNodes: TArrayOfPolyNode; //container for ALL PolyNodes
function GetTotal: Integer;
public
procedure Clear;
function GetFirst: TPolyNode;
destructor Destroy; override;
property Total: Integer read GetTotal;
end;
//the definitions below are used internally ...
TEdgeSide = (esLeft, esRight);
TDirection = (dRightToLeft, dLeftToRight);
POutPt = ^TOutPt;
PEdge = ^TEdge;
TEdge = record
Bot : TFPoint; //bottom
Curr : TFPoint; //current (ie relative to bottom of current scanbeam)
Top : TFPoint; //top
Delta: TFPoint;
Dx : Double; //inverse of slope
PolyType : TPolyType;
Side : TEdgeSide;
WindDelta: Integer; //1 or -1 depending on winding direction
WindCnt : Integer;
WindCnt2 : Integer; //winding count of the opposite PolyType
OutIdx : Integer;
Next : PEdge;
Prev : PEdge;
NextInLML: PEdge;
PrevInAEL: PEdge;
NextInAEL: PEdge;
PrevInSEL: PEdge;
NextInSEL: PEdge;
end;
PEdgeArray = ^TEdgeArray;
TEdgeArray = array[0.. MaxInt div sizeof(TEdge) -1] of TEdge;
PScanbeam = ^TScanbeam;
TScanbeam = record
Y : Double;
Next: PScanbeam;
end;
PIntersectNode = ^TIntersectNode;
TIntersectNode = record
Edge1: PEdge;
Edge2: PEdge;
Pt : TFPoint;
end;
PLocalMinima = ^TLocalMinima;
TLocalMinima = record
Y : Double;
LeftBound : PEdge;
RightBound: PEdge;
Next : PLocalMinima;
end;
POutRec = ^TOutRec;
TOutRec = record
Idx : Integer;
BottomPt : POutPt;
IsHole : Boolean;
IsOpen : Boolean;
//The 'FirstLeft' field points to the OutRec representing the polygon
//immediately to the left of the current OutRec's polygon. When a polygon is
//contained within another polygon, the polygon immediately to its left will
//either be its owner polygon or a sibling also contained by the same outer
//polygon. By storing this field, it's easy to sort polygons into a tree
//structure which reflects the parent/child relationships of all polygons.
FirstLeft : POutRec;
Pts : POutPt;
PolyNode : TPolyNode;
end;
TOutPt = record
Idx : Integer;
Pt : TFPoint;
Next : POutPt;
Prev : POutPt;
end;
PJoin = ^TJoin;
TJoin = record
OutPt1 : POutPt;
OutPt2 : POutPt;
OffPt : TFPoint; //offset point (provides slope of common edges)
end;
TClipperBase = class
private
FEdgeList : TList;
FLmList : PLocalMinima; //localMinima list
FCurrLm : PLocalMinima; //current localMinima node
FHasOpenPaths : Boolean;
procedure DisposeLocalMinimaList;
procedure DisposePolyPts(PP: POutPt);
procedure InsertLocalMinima(Lm: PLocalMinima);
function ProcessBound(E: PEdge; IsClockwise: Boolean): PEdge;
protected
FPreserveCollinear : Boolean;
procedure Reset; virtual;
procedure PopLocalMinima;
property CurrentLm: PLocalMinima read FCurrLm;
property HasOpenPaths: Boolean read FHasOpenPaths;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Clear; virtual;
function AddPath(const Path: TPath; PolyType: TPolyType; Closed: Boolean): Boolean;
function AddPaths(const Paths: TPaths; PolyType: TPolyType; Closed: Boolean): Boolean;
//PreserveCollinear: Prevents removal of 'inner' vertices when three or
//more vertices are collinear in solution polygons.
property PreserveCollinear: Boolean
read FPreserveCollinear write FPreserveCollinear;
end;
TClipper = class(TClipperBase)
private
FPolyOutList : TList;
FJoinList : TList;
FGhostJoinList : TList;
FIntersectList : TList;
FClipType : TClipType;
FScanbeam : PScanbeam; //scanbeam list
FActiveEdges : PEdge; //active Edge list
FSortedEdges : PEdge; //used for temporary sorting
FClipFillType : TPolyFillType;
FSubjFillType : TPolyFillType;
FExecuteLocked : Boolean;
FReverseOutput : Boolean;
FStrictSimple : Boolean;
FUsingPolyTree : Boolean;
{$IFDEF use_xyz}
FZFillCallback : TZFillCallback;
{$ENDIF}
procedure DisposeScanbeamList;
procedure InsertScanbeam(const Y: Double);
function PopScanbeam: Double;
procedure SetWindingCount(Edge: PEdge);
function IsEvenOddFillType(Edge: PEdge): Boolean;
function IsEvenOddAltFillType(Edge: PEdge): Boolean;
procedure AddEdgeToSEL(Edge: PEdge);
procedure CopyAELToSEL;
procedure InsertLocalMinimaIntoAEL(const BotY: Double);
procedure SwapPositionsInAEL(E1, E2: PEdge);
procedure SwapPositionsInSEL(E1, E2: PEdge);
procedure ProcessHorizontal(HorzEdge: PEdge; IsTopOfScanbeam: Boolean);
procedure ProcessHorizontals(IsTopOfScanbeam: Boolean);
function ProcessIntersections(const BotY, TopY: Double): Boolean;
procedure BuildIntersectList(const BotY, TopY: Double);
procedure ProcessIntersectList;
procedure DeleteFromAEL(E: PEdge);
procedure DeleteFromSEL(E: PEdge);
procedure IntersectEdges(E1,E2: PEdge;
const Pt: TFPoint; Protect: Boolean = False);
procedure DoMaxima(E: PEdge);
procedure UpdateEdgeIntoAEL(var E: PEdge);
function FixupIntersectionOrder: Boolean;
procedure ProcessEdgesAtTopOfScanbeam(const TopY: Double);
function IsContributing(Edge: PEdge): Boolean;
function CreateOutRec: POutRec;
function AddOutPt(E: PEdge; const Pt: TFPoint): POutPt;
procedure AddLocalMaxPoly(E1, E2: PEdge; const Pt: TFPoint);
function AddLocalMinPoly(E1, E2: PEdge; const Pt: TFPoint): POutPt;
function GetOutRec(Idx: integer): POutRec;
procedure AppendPolygon(E1, E2: PEdge);
procedure DisposeAllOutRecs;
procedure DisposeOutRec(Index: Integer);
procedure DisposeIntersectNodes;
function BuildResult: TPaths;
function BuildResult2(PolyTree: TPolyTree): Boolean;
procedure FixupOutPolygon(OutRec: POutRec);
procedure SetHoleState(E: PEdge; OutRec: POutRec);
procedure AddJoin(Op1, Op2: POutPt; const OffPt: TFPoint);
procedure ClearJoins;
procedure AddGhostJoin(OutPt: POutPt; const OffPt: TFPoint);
procedure ClearGhostJoins;
function JoinPoints(Jr: PJoin; OutRec1, OutRec2: POutRec): Boolean;
procedure FixupFirstLefts1(OldOutRec, NewOutRec: POutRec);
procedure FixupFirstLefts2(OldOutRec, NewOutRec: POutRec);
procedure DoSimplePolygons;
procedure JoinCommonEdges;
procedure FixHoleLinkage(OutRec: POutRec);
protected
procedure Reset; override;
function ExecuteInternal: Boolean; virtual;
public
function Execute(clipType: TClipType;
out solution: TPaths;
subjFillType: TPolyFillType = pftEvenOdd;
clipFillType: TPolyFillType = pftEvenOdd): Boolean; overload;
function Execute(clipType: TClipType;
out PolyTree: TPolyTree;
subjFillType: TPolyFillType = pftEvenOdd;
clipFillType: TPolyFillType = pftEvenOdd): Boolean; overload;
constructor Create(InitOptions: TInitOptions = []); reintroduce; overload;
destructor Destroy; override;
procedure Clear; override;
//ReverseSolution: reverses the default orientation
property ReverseSolution: Boolean read FReverseOutput write FReverseOutput;
//StrictlySimple: when false (the default) solutions are 'weakly' simple
property StrictlySimple: Boolean read FStrictSimple write FStrictSimple;
{$IFDEF use_xyz}
property ZFillFunction: TZFillCallback read FZFillCallback write FZFillCallback;
{$ENDIF}
end;
TClipperOffset = class
private
FDelta: Double;
FSinA, FSin, FCos: Extended;
FMiterLim, FStepsPerRad: Double;
FNorms: TArrayOfDoublePoint;
FSolution: TPaths;
FOutPos: Integer;
FInP: TPath;
FOutP: TPath;
FLowest: TPoint; //X = Path index, Y = Path offset (to lowest point)
FPolyNodes: TPolyNode;
FMiterLimit: Double;
FArcTolerance: Double;
procedure AddPoint(const Pt: TFPoint);
procedure DoSquare(J, K: Integer);
procedure DoMiter(J, K: Integer; R: Double);
procedure DoRound(J, K: Integer);
procedure OffsetPoint(J: Integer;
var K: Integer; JoinType: TJoinType);
procedure FixOrientations;
procedure DoOffset(Delta: Double);
public
constructor Create(MiterLimit: Double = 2; ArcTolerance: Double = def_arc_tolerance);
destructor Destroy; override;
procedure AddPath(const Path: TPath; JoinType: TJoinType; EndType: TEndType);
procedure AddPaths(const Paths: TPaths; JoinType: TJoinType; EndType: TEndType);
procedure Clear;
procedure Execute(out solution: TPaths; Delta: Double); overload;
procedure Execute(out solution: TPolyTree; Delta: Double); overload;
property MiterLimit: double read FMiterLimit write FMiterLimit;
property ArcTolerance: double read FArcTolerance write FArcTolerance;
end;
function Orientation(const Pts: TPath): Boolean; overload;
function Area(const Pts: TPath): Double; overload;
function GetBounds(const polys: TPaths): TFRect;
{$IFDEF use_xyz}
function FPoint(const X, Y: Double; Z: Int64 = 0): TFPoint;
{$ELSE}
function FPoint(const X, Y: Double): TFPoint;
{$ENDIF}
function ReversePath(const Pts: TPath): TPath;
function ReversePaths(const Pts: TPaths): TPaths;
{$IFDEF use_deprecated}
function OffsetPaths(const Polys: TPaths; const Delta: Double;
JoinType: TJoinType = jtSquare; EndType: TEndType_ = etClosed;
Limit: Double = 0): TPaths;
{$ENDIF}
//SimplifyPolygon converts a self-intersecting polygon into a simple polygon.
function SimplifyPolygon(const Poly: TPath; FillType: TPolyFillType = pftEvenOdd): TPaths;
function SimplifyPolygons(const Polys: TPaths; FillType: TPolyFillType = pftEvenOdd): TPaths;
//CleanPolygon removes adjacent vertices closer than the specified distance.
function CleanPolygon(const Poly: TPath; Distance: double = 1.415): TPath;
function CleanPolygons(const Polys: TPaths; Distance: double = 1.415): TPaths;
function MinkowskiSum(const Base, Path: TPath; IsClosed: Boolean = true): TPaths;
function MinkowskiDiff(const Base, Path: TPath; IsClosed: Boolean = true): TPaths;
function PolyTreeToPaths(PolyTree: TPolyTree): TPaths;
function ClosedPathsFromPolyTree(PolyTree: TPolyTree): TPaths;
function OpenPathsFromPolyTree(PolyTree: TPolyTree): TPaths;
implementation
const
Horizontal: Double = -3.4e+38;
Unassigned : Integer = -1;
Skip : Integer = -2; //flag for the edge that closes an open path
Two_Pi : double = 2 * PI;
//The SlopesEqual function places the most limits on coordinate values
//So, to avoid overflow errors, they must not exceed the following values...
//Also, if all coordinates are within +/-LoRange, then calculations will be
//faster. Otherwise using Int128 math will render the library ~10-15% slower.
resourcestring
rsDoMaxima = 'DoMaxima error';
rsUpdateEdgeIntoAEL = 'UpdateEdgeIntoAEL error';
rsHorizontal = 'ProcessHorizontal error';
rsInvalidInt = 'Coordinate exceeds range bounds';
rsIntersect = 'Intersection error';
rsOpenPath = 'AddPath: Open paths must be subject.';
rsOpenPath2 = 'AddPath: Open paths have been disabled.';
rsOpenPath3 = 'Error: TPolyTree struct is need for open path clipping.';
rsPolylines = 'Error intersecting polylines';
rsClipperOffset = 'Error: No PolyTree assigned';
//------------------------------------------------------------------------------
// TPolyNode methods ...
//------------------------------------------------------------------------------
function TPolyNode.GetChild(Index: Integer): TPolyNode;
begin
if (Index < 0) or (Index >= FCount) then
raise Exception.Create('TPolyNode range error: ' + inttostr(Index));
Result := FChilds[Index];
end;
//------------------------------------------------------------------------------
procedure TPolyNode.AddChild(PolyNode: TPolyNode);
begin
if FCount = FBuffLen then
begin
Inc(FBuffLen, 16);
SetLength(FChilds, FBuffLen);
end;
PolyNode.FParent := self;
PolyNode.FIndex := FCount;
FChilds[FCount] := PolyNode;
Inc(FCount);
end;
//------------------------------------------------------------------------------
function TPolyNode.IsHoleNode: boolean;
var
Node: TPolyNode;
begin
Result := True;
Node := FParent;
while Assigned(Node) do
begin
Result := not Result;
Node := Node.FParent;
end;
end;
//------------------------------------------------------------------------------
function TPolyNode.GetNext: TPolyNode;
begin
if FCount > 0 then
Result := FChilds[0] else
Result := GetNextSiblingUp;
end;
//------------------------------------------------------------------------------
function TPolyNode.GetNextSiblingUp: TPolyNode;
begin
if not Assigned(FParent) then //protects against TPolyTree.GetNextSiblingUp()
Result := nil
else if FIndex = FParent.FCount -1 then
Result := FParent.GetNextSiblingUp
else
Result := FParent.Childs[FIndex +1];
end;
//------------------------------------------------------------------------------
// TPolyTree methods ...
//------------------------------------------------------------------------------
destructor TPolyTree.Destroy;
begin
Clear;
inherited;
end;
//------------------------------------------------------------------------------
procedure TPolyTree.Clear;
var
I: Integer;
begin
for I := 0 to high(FAllNodes) do FAllNodes[I].Free;
FAllNodes := nil;
FBuffLen := 16;
SetLength(FChilds, FBuffLen);
FCount := 0;
end;
//------------------------------------------------------------------------------
function TPolyTree.GetFirst: TPolyNode;
begin
if FCount > 0 then
Result := FChilds[0] else
Result := nil;
end;
//------------------------------------------------------------------------------
function TPolyTree.GetTotal: Integer;
begin
Result := length(FAllNodes);
end;
//------------------------------------------------------------------------------
// Miscellaneous Functions ...
//------------------------------------------------------------------------------
function PointCount(Pts: POutPt): Integer;
var
P: POutPt;
begin
Result := 0;
if not Assigned(Pts) then Exit;
P := Pts;
repeat
Inc(Result);
P := P.Next;
until P = Pts;
end;
//------------------------------------------------------------------------------
{$IFDEF use_xyz}
function FPoint(const X, Y: Double; Z: Int64 = 0): TFPoint;
begin
Result.X := X;
Result.Y := Y;
Result.Z := Z;
end;
//------------------------------------------------------------------------------
{$ELSE}
function FPoint(const X, Y: Double): TFPoint;
begin
Result.X := X;
Result.Y := Y;
end;
//------------------------------------------------------------------------------
{$ENDIF}
//------------------------------------------------------------------------------
function Area(const Pts: TPath): Double;
var
I, J, Cnt: Integer;
D: Double;
begin
Result := 0.0;
Cnt := Length(Pts);
if (Cnt < 3) then Exit;
J := cnt - 1;
for I := 0 to Cnt -1 do
begin
D := (Pts[j].X + Pts[i].X);
Result := Result + D * (Pts[j].Y - Pts[i].Y);
J := I;
end;
Result := -Result * 0.5;
end;
//------------------------------------------------------------------------------
function Area(OutRec: POutRec): Double; overload;
var
Op: POutPt;
D, D2: Double;
begin
D := 0;
Op := OutRec.Pts;
if Assigned(Op) then
repeat
D2 := Op.Prev.Pt.X + Op.Pt.X;
D := D + D2 * (Op.Prev.Pt.Y - Op.Pt.Y);
Op := Op.Next;
until Op = OutRec.Pts;
Result := D * 0.5;
end;
//------------------------------------------------------------------------------
function Orientation(const Pts: TPath): Boolean;
begin
Result := Area(Pts) >= 0;
end;
//------------------------------------------------------------------------------
function ReversePath(const Pts: TPath): TPath;
var
I, HighI: Integer;
begin
HighI := high(Pts);
SetLength(Result, HighI +1);
for I := 0 to HighI do
Result[I] := Pts[HighI - I];
end;
//------------------------------------------------------------------------------
function ReversePaths(const Pts: TPaths): TPaths;
var
I, J, highJ: Integer;
begin
I := length(Pts);
SetLength(Result, I);
for I := 0 to I -1 do
begin
highJ := high(Pts[I]);
SetLength(Result[I], highJ+1);
for J := 0 to highJ do
Result[I][J] := Pts[I][highJ - J];
end;
end;
//------------------------------------------------------------------------------
function GetBounds(const polys: TPaths): TFRect;
var
I,J,Len: Integer;
begin
Len := Length(polys);
I := 0;
while (I < Len) and (Length(polys[I]) = 0) do inc(I);
if (I = Len) then
begin
with Result do begin Left := 0; Top := 0; Right := 0; Bottom := 0; end;
Exit;
end;
Result.Left := polys[I][0].X;
Result.Right := Result.Left;
Result.Top := polys[I][0].Y;
Result.Bottom := Result.Top;
for I := I to Len -1 do
for J := 0 to High(polys[I]) do
begin
if polys[I][J].X < Result.Left then Result.Left := polys[I][J].X
else if polys[I][J].X > Result.Right then Result.Right := polys[I][J].X;
if polys[I][J].Y < Result.Top then Result.Top := polys[I][J].Y
else if polys[I][J].Y > Result.Bottom then Result.Bottom := polys[I][J].Y;
end;
end;
//------------------------------------------------------------------------------
function PointInPolygon (const pt: TFPoint; ops: POutPt): Integer;
var
d,d2,d3: Double;
opStart: POutPt;
begin
//returns 0 if false, +1 if true, -1 if pt ON polygon boundary
//http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf
//nb: if poly bounds are known, test them first before calling this function.
result := 0;
opStart := ops;
repeat
if (ops.Next.Pt.Y = pt.Y) then
begin
if (ops.Next.Pt.X = pt.X) or ((ops.Pt.Y = pt.Y) and
((ops.Next.Pt.X > pt.X) = (ops.Pt.X < pt.X))) then
begin
result := -1;
Exit;
end;
end;
if ((ops.Pt.Y < pt.Y) <> (ops.Next.Pt.Y < pt.Y)) then
begin
if (ops.Pt.X >= pt.X) then
begin
if (ops.Next.Pt.X > pt.X) then
result := 1 - result
else
begin
d2 := (ops.Pt.X - pt.X);
d3 := (ops.Next.Pt.X - pt.X);
d := d2 * (ops.Next.Pt.Y - pt.Y) - d3 * (ops.Pt.Y - pt.Y);
if (d = 0) then begin result := -1; Exit; end;
if ((d > 0) = (ops.Next.Pt.Y > ops.Pt.Y)) then
result := 1 - result;
end;
end else
begin
if (ops.Next.Pt.X > pt.X) then
begin
d2 := (ops.Pt.X - pt.X);
d3 := (ops.Next.Pt.X - pt.X);
d := d2 * (ops.Next.Pt.Y - pt.Y) - d3 * (ops.Pt.Y - pt.Y);
if (d = 0) then begin result := -1; Exit; end;
if ((d > 0) = (ops.Next.Pt.Y > ops.Pt.Y)) then
result := 1 - result;
end;
end;
end;
ops := ops.Next;
until ops = opStart;
end;
//---------------------------------------------------------------------------
function Poly2ContainsPoly1(OutPt1, OutPt2: POutPt): Boolean;
var
res: integer;
op: POutPt;
begin
op := OutPt1;
repeat
res := PointInPolygon(op.Pt, OutPt2);
if (res >= 0) then
begin
Result := res <> 0;
Exit;
end;
op := op.Next;
until op = OutPt1;
Result := true; //all points on line => result = true
end;
//---------------------------------------------------------------------------
{$OVERFLOWCHECKS OFF}
function IsAlmostEqual(val1, val2: Double): Boolean;
var
i1: Int64 absolute val1;
i2: Int64 absolute val2;
const
MinInt64: Int64 = -9223372036854775808;
begin
//http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
//https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
if (i1 < 0) then i1 := MinInt64 + (-i1); //cumbersome but ...
if (i2 < 0) then i2 := MinInt64 + (-i2); //avoids int overflow
result := abs(i1 - i2) <= 10000;
end;
//---------------------------------------------------------------------------
{$OVERFLOWCHECKS ON}
function PointsEqual(const P1, P2: TFPoint): Boolean;
{$IFDEF INLINING} inline; {$ENDIF}
begin
Result := IsAlmostEqual(P1.X, P2.X) and IsAlmostEqual(P1.Y, P2.Y);
end;
//------------------------------------------------------------------------------
function SlopesEqual(E1, E2: PEdge): Boolean; overload;
begin
Result :=
IsAlmostEqual(E1.Delta.Y * E2.Delta.X, E1.Delta.X * E2.Delta.Y);
end;
//---------------------------------------------------------------------------
function SlopesEqual(const Pt1, Pt2, Pt3: TFPoint): Boolean; overload;
begin
Result :=
IsAlmostEqual((Pt1.Y-Pt2.Y)*(Pt2.X-Pt3.X), (Pt1.X-Pt2.X)*(Pt2.Y-Pt3.Y));
end;
//---------------------------------------------------------------------------
(*****************************************************************************
* Dx: 0(90 ) Slope: 0 = Dx: -inf *
* | Slope: 0.5 = Dx: -2 *
* +inf (180 ) <--- o ---> -inf (0 ) Slope: 2.0 = Dx: -0.5 *
* Slope: inf = Dx: 0 *
*****************************************************************************)
function GetDx(const Pt1, Pt2: TFPoint): Double;
begin
if (Pt1.Y = Pt2.Y) then Result := Horizontal
else Result := (Pt2.X - Pt1.X)/(Pt2.Y - Pt1.Y);
end;
//---------------------------------------------------------------------------
procedure SetDx(E: PEdge); {$IFDEF INLINING} inline; {$ENDIF}
begin
E.Delta.X := (E.Top.X - E.Bot.X);
E.Delta.Y := (E.Top.Y - E.Bot.Y);
if E.Delta.Y = 0 then E.Dx := Horizontal
else E.Dx := E.Delta.X/E.Delta.Y;
end;
//---------------------------------------------------------------------------
procedure SwapSides(Edge1, Edge2: PEdge);
var
Side: TEdgeSide;
begin
Side := Edge1.Side;
Edge1.Side := Edge2.Side;
Edge2.Side := Side;
end;
//------------------------------------------------------------------------------
procedure SwapPolyIndexes(Edge1, Edge2: PEdge);
var
OutIdx: Integer;
begin
OutIdx := Edge1.OutIdx;
Edge1.OutIdx := Edge2.OutIdx;
Edge2.OutIdx := OutIdx;
end;
//------------------------------------------------------------------------------
function TopX(Edge: PEdge; const currentY: Double): Double;
begin
if currentY = Edge.Top.Y then Result := Edge.Top.X
else if Edge.Top.X = Edge.Bot.X then Result := Edge.Bot.X
else Result := Edge.Bot.X + Edge.Dx*(currentY - Edge.Bot.Y);
end;
//------------------------------------------------------------------------------
{$IFDEF use_xyz}
Procedure SetZ(var Pt: TFPoint; E: PEdge; ZFillFunc: TZFillCallback);
begin
Pt.Z := 0;
if assigned(ZFillFunc) then
begin
//put the 'preferred' point as first parameter ...
if E.OutIdx < 0 then
ZFillFunc(E.Bot, E.Top, Pt) //outside a path so presume entering ...
else
ZFillFunc(E.Top, E.Bot, Pt); //inside a path so presume exiting ...
end;
end;
//------------------------------------------------------------------------------
{$ENDIF}
function IntersectPoint(Edge1, Edge2: PEdge; out ip: TFPoint): Boolean;
var
B1,B2,M: Double;
begin
{$IFDEF use_xyz}
ip.Z := 0;
{$ENDIF}
//nb: with very large coordinate values, it's possible for SlopesEqual() to
//return false but for the edge.Dx value be equal due to double precision
//rounding ...
if SlopesEqual(Edge1, Edge2) or (edge1.Dx = edge2.Dx) then
begin
//parallel edges, but nevertheless prepare to force the intersection
//since Edge2.Curr.X < Edge1.Curr.X ...
if Edge2.Bot.Y > Edge1.Bot.Y then
ip := Edge2.Bot else
ip := Edge1.Bot;
Result := False;
Exit;
end;
if Edge1.Delta.X = 0 then
begin
ip.X := Edge1.Bot.X;
if Edge2.Dx = Horizontal then
ip.Y := Edge2.Bot.Y
else
begin
with Edge2^ do B2 := Bot.Y - (Bot.X/Dx);
ip.Y := ip.X/Edge2.Dx + B2;
end;
end
else if Edge2.Delta.X = 0 then
begin
ip.X := Edge2.Bot.X;
if Edge1.Dx = Horizontal then
ip.Y := Edge1.Bot.Y
else
begin
with Edge1^ do B1 := Bot.Y - (Bot.X/Dx);
ip.Y := ip.X/Edge1.Dx + B1;
end;
end else
begin
with Edge1^ do B1 := Bot.X - Bot.Y * Dx;
with Edge2^ do B2 := Bot.X - Bot.Y * Dx;
M := (B2-B1)/(Edge1.Dx - Edge2.Dx);
ip.Y := M;
if Abs(Edge1.Dx) < Abs(Edge2.Dx) then
ip.X := Edge1.Dx * M + B1 else
ip.X := Edge2.Dx * M + B2;
end;
//The precondition - E.Curr.X > eNext.Curr.X - indicates that the two edges do
//intersect below TopY (and hence below the tops of either Edge). However,
//when edges are almost parallel, rounding errors may cause False positives -
//indicating intersections when there really aren't any. Also, floating point
//imprecision can incorrectly place an intersect point beyond/above an Edge.
//Therfore, further adjustment to IP is warranted ...
if (ip.Y < Edge1.Top.Y) or (ip.Y < Edge2.Top.Y) then
begin
//Find the lower top of the two edges and compare X's at this Y.
//If Edge1's X is greater than Edge2's X then it's fair to assume an
//intersection really has occurred...
if (Edge1.Top.Y > Edge2.Top.Y) then
ip.Y := edge1.Top.Y else
ip.Y := edge2.Top.Y;
if Abs(Edge1.Dx) < Abs(Edge2.Dx) then
ip.X := TopX(Edge1, ip.Y) else
ip.X := TopX(Edge2, ip.Y);
end;
Result := True;
end;
//------------------------------------------------------------------------------
procedure ReversePolyPtLinks(PP: POutPt);
var
Pp1,Pp2: POutPt;
begin
if not Assigned(PP) then Exit;
Pp1 := PP;
repeat
Pp2:= Pp1.Next;
Pp1.Next := Pp1.Prev;
Pp1.Prev := Pp2;
Pp1 := Pp2;
until Pp1 = PP;
end;
//------------------------------------------------------------------------------
function Pt2IsBetweenPt1AndPt3(const Pt1, Pt2, Pt3: TFPoint): Boolean;
begin
//nb: assumes collinearity.
if PointsEqual(Pt1, Pt3) or PointsEqual(Pt1, Pt2) or PointsEqual(Pt3, Pt2) then
Result := False
else if (Pt1.X <> Pt3.X) then
Result := (Pt2.X > Pt1.X) = (Pt2.X < Pt3.X)
else
Result := (Pt2.Y > Pt1.Y) = (Pt2.Y < Pt3.Y);
end;
//------------------------------------------------------------------------------
function GetOverlap(const A1, A2, B1, B2: Double; out Left, Right: Double): Boolean;
begin
if (A1 < A2) then
begin
if (B1 < B2) then begin Left := Max(A1,B1); Right := Min(A2,B2); end
else begin Left := Max(A1,B2); Right := Min(A2,B1); end;
end else
begin
if (B1 < B2) then begin Left := Max(A2,B1); Right := Min(A1,B2); end
else begin Left := Max(A2,B2); Right := Min(A1,B1); end
end;
Result := Left < Right;
end;
//------------------------------------------------------------------------------
procedure UpdateOutPtIdxs(OutRec: POutRec);
var
op: POutPt;
begin
op := OutRec.Pts;
repeat
op.Idx := OutRec.Idx;
op := op.Prev;
until op = OutRec.Pts;
end;
//------------------------------------------------------------------------------
procedure ReverseHorizontal(E: PEdge);
var