-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPolygon.js
1829 lines (1578 loc) · 67.3 KB
/
Polygon.js
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 - javascript class for 2D polygons
Methods:
* constructor:
- Polygon - create a polygon instance
* polygon structural manipulation:
- remove - remove vertices given at certain indexes
- splice - remoce vertices found within two given indexes
- slice - return a new polygon built with vertices found within two given indexes
- push - push a new vertices at the end of the polygon
- unshift - push a new vertices at the begining of the polygon
- shift - retrive and remove first vertex
- pop - retrive and remove last vertex
- change - change a given vertex
- swap - swap between polygon X and Y properties
- append - append a given polygon at the end of current polygon
- insertPolygon - insert a polygon in a given index
- insertVertex - insert a vertex in a given index
- reverse - reverse polygon vertices
- sortCW - sort polygon vertices clockwise
* polygon information extraction
- getX - return an array of vertices X part
- getY - return an array of vertices Y part
- vertices - return two arrays of vertices location (X, Y)
- size - return number of vertices in polygon
- data - return polygon area, perimeter, centeroid, moments of inertia
and centroidal moments of inertia
- isClockWise - return true if polygon vertices are sorted clock wise
- maxSide - return index of first vertices (and the following vertices)
whos side is largest, and that side value
- minSide - return index of first vertices (and the following vertices)
whos side is smallest, and that side value
- maxAngle - return index of first vertices whos angle is smallest (sharpest edge)
and that angle value
- minAngle - return index of first vertices whos angle is largest (widest edge)
and thath angle value
- extent - return the bounding box of polygon [Xmin, Xmax, Ymin, Ymax]
(not necessarily the minimal bounding box)
- bottomVertex - return index of lowest vertex
- upperVertex - return index of highest vertex
- leftVertex - return index of "left-most" vertex
- rightVertex - return index of "right-most" vertex
* polygon geometric manipulation:
- rotate - rotate polygon certain degrees around a given point
- moveAlong - move polygon certain distance along a given directions
- moveBy - move polygon certain distance along the X and Y axis
- simplify - remove "reduceable" (= "less important") vertices
- sliceBox - remove all polygon vertices located within a given box [bottom left, upper right]
- sliceCircle - remove all polygon vertices located within a given circle [x, y, radius]
* polygon-point operation / information:
- inside - test if a given point is located within the polygon
- on - test if a given point is located on the polygon
- closest - return the polygon vertices closest to a given point
* polygon-line operation / information:
- lineIntersect - return a flag indicating if a line intersects the polygon
and a set of (x,y) intersection points
* polygon-polygon operation / information:
- intersect - perform intersection between two polygons (clipping polygon must be convex)
- union - perform union between two polygons (clipping polygon must be convex)
- isEqual - return true if two polygons are equal
* other methods:
- toString - return polygon as a human readable string
- convexHull - return a polygon which is the convex hull of current polygon
- radialFit - approximate polygon as a circle or an ellipse
Properties:
* accuracy - used to determine floating point equality tolerance
default: 1e-10
Notes:
- Polygon is always closed. Last vertex is connected to first vertex.
- Boolean operation (union, intersect) are allowed only if the "clipping" polygon is convex.
- methods convexHull and Simplify utilize recrusive functions.
- Polygon class use 'privileged' methods (a term used to describe closures within the constructor).
- The following polygon operations can be chained: remove, splice, push, unshift, change, swap,
append, insertPolygon, insertVertex, reverse, sortCW, sliceBox, sliceCircle, rotate, moveAlong,
moveBy, simplify.
Examples:
1) // create a star shaped polygon composed of 100 points
var _star = new Polygon({type: 'star', inner: 100, outer: 300, points: 100});
// remove all its 'inner circle' vertex and move it 50px to the right
_star.sliceCircle(0, 0, 200).moveBy(50, 0);
// fit a circle
var _circleFit = _star.radialFit('circle');
// check fitted circle error
console.log('fitted circle radius error is ' + (_circleFit[2] - 300) + '.\n' +
'fitted circle origin error in x is ' + (_circleFit[0] - 50) + '.\n' +
'fitted circle origin error in y is ' + (_circleFit[1]) + '.\n');
2) // create a hexagon
var _hex = new Polygon({type: 'regular', radius: 100, points: 6});
// rotate hexagon by 70 degrees and move it 95px in a 45 degrees bearing
_hex.rotate(0, 0, 70).moveAlong(45, 95);
// create a circle
var _circ = new Polygon({type: 'circle', radius: 45, points: 50});
// move circle 110px to the right
_circ.moveBy(110, 0);
// calcute circle and hexagon intersection
var _intersect = _hex.intersect(_circ);
// extract intersection geometrical properties
var _data = _intersect.data();
// console.log();
console.log('intersection polygon centeroid is (' + _data[0] + ', ' + _data[1] + ')\n' +
'intersection polygon perimeter is ' + _data[2] + '\n' +
'intersection polygon Ixx is ' + _data[3] + '\n' +
'intersection polygon Iyy is ' + _data[4] + '\n' +
'intersection polygon Ixy is ' + _data[5] + '\n' +
'intersection polygon centeroidal Ixx is ' + _data[6] + '\n' +
'intersection polygon centeroidal Iyy is ' + _data[7] + '\n' +
'intersection polygon centeroidal Ixy is ' + _data[8]);
3) // create two polygons
var subject = new Polygon({type: 'point', points: [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]]}),
cliper = new Polygon({type: 'point', points: [[100, 100], [300, 100], [300, 300], [100, 300]]});
// calculate their union
union = subject.union(cliper);
Dan I. Malta (malta.dan@gmail.com)
*/
// @constructor {Polygon class; privileged methods included}
// @param {object} the following types of object constructors are allowed:
// 1) regular polygon: (constructed around origin (0, 0), counter clockwise from X axis)
// {type: 'regular',
// radius: regular polygon distance from origin to vrtices,
// points: number of vertices
// }
// 2) circle: (constructed around origin (0, 0), counter clockwise from X axis)
// {type: 'circle',
// radius: circle radius,
// points: number of points along circle perimeter
// }
// 3) star: (constructed around origin (0, 0), counter clockwise from X axis)
// {type: 'star',
// inner: radius of star innver vertices,
// outer: radius of star outer vertices,
// points: number of star total vertices
// }
// 4) matrix: (polygon vertices are given as 2xN array)
// {type: 'matrix',
// matrix: a 2xN array at which first row is X part of vertices and
// second columns is Y part of vertices
// }
// 5) array: (polygon vertices are given as two equal size arrays)
// {type: 'array',
// x: an array holding X part of vertices,
// y: an array holding Y part of vertices
// }
// 6) point: (polygon vertices are given as a set of points enclosed in an array)
// {type: 'point',
// points: an array built in the following manner: [[x0, y0], [x1, y1],...,[xn, yn]]
// }
// @return {Polygon} construct polygon properties according to input arguments
function Polygon(xi_polygon) {
// @private
// @param {array} array
// @return {boolean} true if array holds only finite numbers
var _finite = function(xi_array) {
return xi_array.every(function(x) {return (isFinite(x));});
};
// @privileged
// @param {number} number
// @param {number} number
// @return {boolean} true if two input arguments are equal within accuracy property
this._equal = function(xi_a, xi_b) {
return (Math.abs(xi_a - xi_b) < this.accuracy);
};
// @privileged
// @param {array} input array
// @return {number} minimum number in array
this._min = function(xi_array) {
return Math.min.apply(Math, xi_array);
};
// @privileged
// @param {array} input array
// @return {number} maximum number in array
this._max = function(xi_array) {
return Math.max.apply(Math, xi_array);
};
// @privileged
// @param {number} a number
// @param {number} a number
// @return {number} pythagorean of two input arguments (overflow safe)
this._safePythag = function(xi_a, xi_b) {
if ((xi_a === 0) && (xi_b === 0)) {
return 0;
} else if (Math.abs(xi_a) >= Math.abs(xi_b)) {
return Math.abs(xi_a) * Math.sqrt(1 + Math.pow(Math.abs(xi_b / xi_a), 2));
} else {
return Math.abs(xi_b) * Math.sqrt(1 + Math.pow(Math.abs(xi_a / xi_b), 2));
}
};
// @privileged
// @param {array} an array
// @param {array} an array
// @return {array} the pythagorean of two input arguments
this._distance2 = function(xi_array1, xi_array2) {
return (xi_array1.map(function(x, i) {return (this._safePythag(x, xi_array2[i]));}));
};
// @privileged
// @param {array} array
// @return {array} array whos elements are the difference between each two consecutive elements in input array
// with closed polygon in mind
this._diff = function(xi_array) {
var xo_out = xi_array.map(function(x, i) {return ((i > 0) ? (x - xi_array[i - 1]) : (0));});
xo_out.splice(0,1);
xo_out.push(xi_array[0] - xi_array[xi_array.length - 1]);
return xo_out;
};
// @privileged
// @param {array} array [x0, ..., xn]
// @param {array} array [y0, ..., yn]
// @return {array} combined array [[x0, y0], ..., [xn, yn]]
this._toSet = function(xi_array1, xi_array2) {
var _i, _len, xo_out = [];
for (_i = 0, _len = xi_array1.length; _i < _len; _i++) {
xo_out.push([xi_array1[_i], xi_array2[_i]]);
}
return xo_out;
};
// locals
var _i, _angle, _delta, _finiteInput, _type;
// properties decleration (underscore to hint that they should not be approached directly)
this._X = []; // Xaxis value of polygon vertices
this._Y = []; // Yaxis value of polygon vertices
this.accuracy = 1e-10; // numeric calculation and floating point equality tolerance
// construct Polygon
if (!xi_polygon) {
this._X.push(0);
this._Y.push(0);
} else if (typeof xi_polygon === 'object') {
// housekeeping
_type = xi_polygon.type.toUpperCase();
// Polygon properties filled
if (/ARRAY|MATRIX|POINT|REGULAR|CIRCLE|STAR/.test(_type)) {
switch (_type) {
case 'ARRAY':
// test input arguments
_finiteInput = _finite(xi_polygon.x);
if (_finiteInput) {
_finiteInput = _finite(xi_polygon.y);
}
// assign them as Polygon properties
if (_finiteInput) {
this._X = xi_polygon.x.slice();
this._Y = xi_polygon.y.slice();
} else {
throw('Polygon input arguments must include finite numbers only.');
}
break;
case 'MATRIX':
// test input arguments
_finiteInput = _finite(xi_polygon.matrix[0]);
if (_finiteInput) {
_finiteInput = _finite(xi_polygon.matrix[1]);
}
// assign them as Polygon properties
if (_finiteInput) {
this._X = xi_polygon.matrix[0].slice();
this._Y = xi_polygon.matrix[1].slice();
} else {
throw('Polygon input arguments must include finite numbers only.');
}
break;
case 'POINT':
// test and assign inputs iteratively
for (_i in xi_polygon.points) {
if (isFinite(xi_polygon.points[_i][0])) {
this._X.push(xi_polygon.points[_i][0]);
} else {
throw('Polygon input arguments must include finite numbers only.');
}
if (isFinite(xi_polygon.points[_i][1])) {
this._Y.push(xi_polygon.points[_i][1]);
} else {
throw('Polygon input arguments must include finite numbers only.');
}
}
break;
case 'REGULAR':
case 'CIRCLE':
// housekeeping
xi_polygon.points = Math.abs(xi_polygon.points >>> 0);
xi_polygon.radius = Math.abs(xi_polygon.radius);
// circle / regular polygon delta angle
_angle = 2 * Math.PI / xi_polygon.points;
// construct circle / regular polygon (counter clockwise from X)
for (_i = 0; _i <= xi_polygon.points; _i++) {
this._X.push(xi_polygon.radius * Math.sin(_i * _angle));
this._Y.push(xi_polygon.radius * Math.cos(_i * _angle));
}
break;
case 'STAR':
// housekeeping
xi_polygon.points = Math.abs(xi_polygon.points) >>> 0;
xi_polygon.inner = Math.abs(xi_polygon.inner);
xi_polygon.outer = Math.abs(xi_polygon.outer);
// star outer/inner radius angle
_delta = Math.PI / xi_polygon.points;
_angle = 2 * _delta;
// construct star
for (_i = 0; _i <= xi_polygon.points; _i++) {
// outer
this._X.push(xi_polygon.outer * Math.sin(_i * _angle));
this._Y.push(xi_polygon.outer * Math.cos(_i * _angle));
// inner
this._X.push(xi_polygon.inner * Math.sin(_delta + _i * _angle));
this._Y.push(xi_polygon.inner * Math.cos(_delta + _i * _angle));
}
break;
}
} else {
throw('Polygon input object first argument is invalid');
}
} else {
throw('Polygon input is invalid.');
}
};
// @prototype {Polygon, public}
// @return {array} polygon vertices X part
Polygon.prototype.getX = function() {
return this._X;
};
// @prototype {Polygon, public}
// @return {array} polygon vertices Y part
Polygon.prototype.getY = function() {
return this._Y;
};
// @prototype {Polygon, public}
// @return {array} polygon vertices X part
// @return {array} polygon vertices Y part
Polygon.prototype.vertices = function() {
return [this._X, this._Y];
};
// @prototype {Polygon, public}
// @return {number} return number of vertices in polygon
Polygon.prototype.size = function() {
return this._X.length;
};
// @prototype {Polygon, public}
// @param {number | array} index of element | array filled with elements index
// @return {this} remove the vertices whos index is the {@code xi_index} from polygon
Polygon.prototype.remove = function(xi_index) {
// locals
var _i, _index, _len = xi_index.length || 0;
// remove vertices
if (_len === 0) {
_index = Math.abs(xi_index >>> 0);
if (_index <= this._X.length) {
// remove vertices
this._X.splice(_index, 1);
this._Y.splice(_index, 1);
}
} else {
for (_i = 0; _i < _len; _i++) {
_index = Math.abs(xi_index[_i] >>> 0);
if (_index <= this._X.length) {
// remove vertices
this._X.splice(_index, 1);
this._Y.splice(_index, 1);
}
}
}
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @param {number} start point of polygon vertices removal
// @param {number} end point of polygon vertices removal
// @return {this} starting at index @xi_start, remove vertices until @xi_end index
Polygon.prototype.splice = function(xi_start, xi_end) {
// housekeeping
xi_start = Math.abs(xi_start >>> 0);
xi_end = Math.abs(xi_end >>> 0);
// remove vertices
this._X.splice(xi_start, xi_end);
this._Y.splice(xi_start, xi_end);
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @param {number} start point of polygon vertices copy
// @param {number} end point of polygon vertices copy
// @return {Polygon} new Polygon whos vertices are the one found between the
// [@xi_start, @xi_end] indexes
Polygon.prototype.slice = function(xi_start, xi_end) {
// housekeeping
xi_start = Math.abs(xi_start >>> 0);
xi_end = Math.abs(xi_end >>> 0);
// remove vertices
return new Polygon({type: 'array',
x: this._X.slice(xi_start, xi_end),
y: this._Y.slice(xi_start, xi_end)
});
};
// @prototype {Polygon, public}
// @param {number} x value of a new vertices
// @param {number} y value of a new vertices
// @return {this} adds a new vertices at polygon end
Polygon.prototype.push = function(xi_x, xi_y) {
// add vertices
if ((isFinite(xi_x)) && (isFinite(xi_y))) {
this._X.push(xi_x);
this._Y.push(xi_y);
} else {
throw('Polygon.push input arguments must be finite numbers only.');
}
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @param {number} x value of a new vertices
// @param {number} y value of a new vertices
// @return {this} adds a new vertices at polygon start
Polygon.prototype.unshift = function(xi_x, xi_y) {
// add vertices
if ((isFinite(xi_x)) && (isFinite(xi_y))) {
this._X.unshift(xi_x);
this._Y.unshift(xi_y);
} else {
throw('Polygon.unshift input arguments must be finite numbers only.');
}
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @return {aray} remove first vertices from polygon and return them
Polygon.prototype.shift = function() {
// locals
var x = this._X.shift(), y = this._Y.shift();
// output
return [x, y];
};
// @prototype {Polygon, public}
// @return {} remove last vertices from polygon
Polygon.prototype.pop = function() {
// locals
var x = this._X.pop(), y = this._Y.pop();
// output
return [x, y];
};
// @prototype {Polygon, public}
// @param {number} index of vertice to change
// @param {number} new x value of vertices
// @param {number} new y value of vertices
// @return {this} polygon with a given vertix changed
Polygon.prototype.change = function(xi_index, xi_x, xi_y) {
// locals
var _index = Math.abs(xi_index >>> 0);
// change vertices value
if ((isFinite(xi_x)) && (isFinite(xi_y))) {
if (_index <= this._X.length) {
this._X[_index] = xi_x;
this._Y[_index] = xi_y;
}
} else {
throw('Polygon.change input arguments must be finite numbers only.');
}
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @return {this} polygon with X and Y properties swaped
Polygon.prototype.swap = function() {
var _y = this._Y.slice();
this._Y = this._X.slice();
this._X = _y.slice();
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @param {Polygon} polygon
// @return {this} given polygon is appended to this polygon
Polygon.prototype.append = function(xi_polygon) {
// append vertices
Array.prototype.push.apply(this._X, xi_polygon.getX());
Array.prototype.push.apply(this._Y, xi_polygon.getY());
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @param {number} index for inserted polygon
// @param {Polygon} polygon
// @return {this} this polygon with input polygon inserted in a specific index
// if index is larger then polygon size, it is inserted at the end
Polygon.prototype.insertPolygon = function(xi_index, xi_polygon) {
// local
var _index = xi_index >>> 0;
// insert polygon
if (_index < this._X.length) {
this._X.splice.apply(this._X,[_index, 0].concat(xi_polygon.getX()));
this._Y.splice.apply(this._Y, [_index, 0].concat(xi_polygon.getY()));
} else {
Array.prototype.push.apply(this._X, xi_polygon.getX());
Array.prototype.push.apply(this._Y, xi_polygon.getY());
}
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @param {number} index for inserted vertex
// @param {number} X part of new vertex
// @param {number} Y part of new vertex
// @return {this} this polygon with input vertex inserted in a specific index
// if index is larger then polygon size, it is inserted at the end
Polygon.prototype.insertVertex = function(xi_index, xi_x, xi_y) {
// local
var _index = xi_index >>> 0;
// insert vertex
if ((isFinite(xi_x)) && (isFinite(xi_y))) {
if (_index < this._X.length) {
this._X.splice.apply(this._X,[_index, 0].concat(xi_x));
this._Y.splice.apply(this._Y, [_index, 0].concat(xi_y));
} else {
this._X.push(xi_x);
this._Y.push(xi_y);
}
} else {
throw('Polygon.insertVertex input arguments must be finite numbers only.');
}
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @return {this} polygon vertices reversed
Polygon.prototype.reverse = function() {
this._X.reverse();
this._Y.reverse();
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @return {this} polygon vertices sorted clock-wise
Polygon.prototype.sortCW = function() {
// @param {number} Y
// @param {number} X
// @return {number} four quadrant inverse tangent of Y and X
// @brief Accuarcy is 1.4154620E-4, yet it is about 4 times faster then Math.atan2()
var _atan2 = function(xi_y, xi_x) {
// local
var _arg = xi_y / xi_x,
_arg2 = _arg * _arg,
_arg3 = _arg2 * _arg;
// output
return (1.570796326794897 * (_arg3 + _arg2 + 0.640388203202208 * _arg) /
(_arg3 + 1.640388203202208 * (_arg2 + _arg) + 1));
};
// locals
var _len = this.size(),
_Xmean = this._X.reduce(function(prev, x) {return (prev + x);}, 0) / _len,
_Ymean = this._Y.reduce(function(prev, x) {return (prev + x);}, 0) / _len,
_i, _temp, _angleZipped = [];
// vertices angle relative to polygon centroid
for (_i = 0; _i < _len; _i++) {
_angleZipped.push({angle: _atan2(this._Y[_i] - _Ymean, this._X[_i] - _Xmean),
x: this._X[_i],
y: this._Y[_i]}
);
}
// sort according to angle
_angleZipped.sort(function(x, y) {return (x.angle - y.angle);});
// unzip (x, y)
for (_i = 0; _i < _len; _i++) {
_temp = _angleZipped[_i];
this._X[_i] = _temp.x;
this._Y[_i] = _temp.y;
}
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @param {number} box bottom left X value (0 if input is not a finite number)
// @param {number} box bottom left Y value (0 if input is not a finite number)
// @param {number} box upper right X value (0 if input is not a finite number)
// @param {number} box upper right Y value (0 if input is not a finite number)
// @return {this} polygon with vertices located within input box are removed
Polygon.prototype.sliceBox = function(xi_xb, xi_yb, xi_xu, xi_yu) {
// @param {array} input array
// @param {number} left/bottom value
// @param {number} right/upper value
// @return {boolean} true if input is within boundaries
var _in = function(xi_array, xi_left, xi_right) {
return xi_array.map(function(x) {return ((x >= xi_left) && (x <= xi_right));});
};
// locals
var _len = this.size(),
_xIn = _in(this._X, (xi_xb || 0), (xi_xu || 0)),
_yIn = _in(this._Y, (xi_yb || 0), (xi_yu || 0));
// remove vertices
while (--_len >= 0) {
if (_xIn[_len] && _yIn[_len]) {
this._X.splice(_len, 1);
this._Y.splice(_len, 1);
}
}
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @param {number} circle center X value (0 if input is not finite)
// @param {number} circle center Y value (0 if input is not a finite number)
// @param {number} circle radius (1 if input is not a finite number)
// @return {this} polygon with vertices located within input circle are removed
Polygon.prototype.sliceCircle = function(xi_x, xi_y, xi_radius) {
// locals
var _len = this.size(),
_ix = xi_x || 0,
_iy = xi_y || 0,
_r2 = (xi_radius || 1) * xi_radius,
_xc = this._X.map(function(x) {return (x - _ix);}),
_yc = this._Y.map(function(x) {return (x - _iy);}),
_inCirc = _xc.map(function(x, i) {return (x * x + _yc[i] * _yc[i] <= _r2);});
// remove vertices
while (--_len >= 0) {
if (_inCirc[_len]) {
this._X.splice(_len, 1);
this._Y.splice(_len, 1);
}
}
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @return {number} area of polygon
// @return {number} centeroid of polygon (X)
// @return {number} centeroid of polygon (Y)
// @return {number} polygon perimeter
// @return {number} moment of inertia (X) - Ixx
// @return {number} moment of inertia (Y) - Iyy
// @return {number} moment of inertia (XY) - Ixy ( = Iyx)
// @return {number} centeroidal moment of inertia (X) - Iuu
// @return {number} centeroidal moment of inertia (Y) - Ivv
// @return {number} centeroidal moment of inertia (XY) - Iuv ( = Ivu)
Polygon.prototype.data = function() {
// @param {array} array
// @param {array} array
// @return {array} element wise sum of input argument (who must be the same size)
var _add = function(xi_array1, xi_array2) {
return xi_array1.map(function(x, i) {return (x + xi_array2[i]);});
};
// @param {array} input array
// @return {number} sum of input array elements
var _sum = function(xi_array) {
return xi_array.reduce(function(prev, x) {return (prev + x); }, 0);
};
// @param {array} input array
// @return {number} sqrt of all array elements
var _sqrt = function(xi_array) {
return xi_array.map(function(x) {return (Math.sqrt(x));});
};
// @param {array} input array
// @param {array} power
// @return {number} power of all elements array
var _pow = function(xi_array, xi_power) {
return xi_array.map(function(x) {return (Math.pow(x, xi_power));});
};
// @param {array} array
// @param {array} array
// @return {array} sum of dot operation between of two input argument (which must be of equal size)
var _dot2 = function(xi_array1, xi_array2) {
return xi_array1.reduce(function(prev, x, i) {return (prev + x * xi_array2[i]);}, 0);
};
// @param {array} array
// @param {array} array
// @param {array} array
// @return {array} sum of dot operation between of three input argument (which must be of equal size)
var _dot3 = function(xi_array1, xi_array2, ai_array3) {
return xi_array1.reduce(function(prev, x, i) {return (prev + x * xi_array2[i] * ai_array3[i]);}, 0);
};
// @param {array} array
// @param {array} array
// @param {array} array
// @param {array} array
// @return {array} sum of dot operation between of four input argument (which must be of equal size)
var _dot4 = function(xi_array1, xi_array2, ai_array3, xi_array4) {
return xi_array1.reduce(function(prev, x, i) {return (prev + x * xi_array2[i] *
ai_array3[i] * xi_array4[i]);}, 0);
};
// locals
var _xc, _yc, _Iuu, _Ivv, _Iuv,
_xm = (_sum(this._X) / this.size()),
_ym = (_sum(this._Y) / this.size()),
_x = this._X.map(function(x) {return (x - _xm);}),
_y = this._Y.map(function(x) {return (x - _ym);}),
_dx = this._diff(_x),
_dy = this._diff(_y),
_A = (_dot2(_y, _dx) - _dot2(_x, _dy)) / 2,
_Cx = (6 * _dot3(_x, _y, _dx) - 3 * _dot3(_x, _x, _dy) + 3 * _dot3(_y, _dx, _dx) + _dot3(_dx, _dx, _dy)) / 12,
_Cy = (3 * _dot3(_y, _y, _dx) - 6 * _dot3(_x, _y, _dy) - 3 * _dot3(_x, _dy, _dy) - _dot3(_dx, _dy, _dy)) / 12,
_Ixx = (2 * _dot4(_y, _y, _y, _dx) - 6 * _dot4(_x, _y, _y, _dy) - 6 * _dot4(_x, _y, _dy, _dy) +
-2 * _dot4(_x, _dy, _dy, _dy) - 2 * _dot4(_y, _dx, _dy, _dy) - _dot4(_dx, _dy, _dy, _dy)) / 12,
_Iyy = (6 * _dot4(_x, _x, _y, _dx) - 2 * _dot4(_x, _x, _x, _dy) + 6 * _dot4(_x, _y, _dx, _dx) +
2 * _dot4(_y, _dx, _dx, _dx) + 2 * _dot4(_x, _dx, _dx, _dy) + _dot4(_dx, _dx, _dx, _dy)) / 12,
_Ixy = (6 * _dot4(_x, _y, _y, _dx) - 6 * _dot4(_x, _x, _y, _dy) + 3 * _dot4(_y, _y, _dx, _dx) +
-3 * _dot4(_x, _x, _dy, _dy) + 2 * _dot4(_y, _dx, _dx, _dy) - 2 * _dot4(_x, _dx, _dy, _dy)) / 24,
_p = _sum(_sqrt(_add(_pow(_dx, 2), _pow(_dy, 2))));
// counter clockwise
if (_A < 0) {
_A = -_A;
_Cx = -_Cx;
_Cy = -_Cy;
_Ixx = -_Ixx;
_Iyy = -_Iyy;
_Ixy = -_Ixy;
}
// centroidal moments
_xc = _Cx / _A;
_yc = _Cy / _A;
_Iuu = _Ixx - _A * _yc * _yc;
_Ivv = _Iyy - _A * _xc * _xc;
_Iuv = _Ixy - _A * _xc * _yc;
// mean of vertices
_Cx = _xm + _Cx;
_Cy = _ym + _Cy;
_Ixx = _Iuu + _A * _Cy * _Cy;
_Iyy = _Ivv + _A * _Cx * _Cx;
_Ixy = _Iuv * _A * _Cx * _Cy;
// output
return [_A, _Cx, _Cy, _p, _Ixx, _Iyy, _Ixy, _Iuu, _Ivv, _Iuv];
};
// @prototype {Polygon, public}
// @param {number} rotation origin point X value (0 if input is not a finite number)
// @param {number} rotation origin point Y value (0 if input is not a finite number)
// @param {number} rotation angle (in degrees) (1 if input is not a finite number)
// @return {this} polygon vertices shall be rotated a given angle around the given coordinate
Polygon.prototype.rotate = function(xi_x, xi_y, xi_angle) {
// locals
var _i, _ix = xi_x || 0, _iy = xi_y || 0,
_angle = (xi_angle || 0) * Math.PI / 180,
_cos = Math.cos(_angle), _sin = Math.sin(_angle),
_dx = this._X.map(function(x) {return (x - _ix);}),
_dy = this._Y.map(function(x) {return (x - _iy);});
// edge numerics
if (this._equal(_cos, 1)) {
_cos = 1;
}
if (this._equal(_cos, 0)) {
_cos = 0;
}
if (this._equal(_sin, 1)) {
_sin = 1;
}
if (this._equal(_sin, 0)) {
_sin = 0;
}
// rotate polygon
this._X = this._X.map(function(x, i) {return (xi_x + _dx[i] * _cos - _dy[i] * _sin);});
this._Y = this._Y.map(function(x, i) {return (xi_y + _dx[i] * _sin + _dy[i] * _cos);});
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @param {number} movement direction (bearing; zero angle is along the Y axis)
// (0 if input is not a finite number)
// @param {number} movement distance (0 if input is not a finite number)
// @return {this} polygon vertices shall be moved a given distance along a given direction
Polygon.prototype.moveAlong = function(xi_angle, xi_distance) {
// locals
var _distance = xi_distance || 0,
_angle = xi_angle || 0,
_dy = _distance * Math.cos(_angle),
_dx = _distance * Math.sin(_angle);
// move polygon
this._X = this._X.map(function(x) {return (x + _dx);});
this._Y = this._Y.map(function(x) {return (x + _dy);});
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @param {number} movement along X axis (0 if input is not a finite number)
// @param {number} movement along Y axis (0 if input is not a finite number)
// @return {this} polygon vertices shall be moved a given distance along each axis
// according to input
Polygon.prototype.moveBy = function(xi_dx, xi_dy) {
// locals
var _dx = xi_dx || 0,
_dy = xi_dy || 0;
// move polygon
this._X = this._X.map(function(x) {return (x + _dx);});
this._Y = this._Y.map(function(x) {return (x + _dy);});
// output (for chaining purposes)
return this;
};
// @prototype {Polygon, public}
// @param {number} distance tolerance (0.1 if a finite number is not specified)
// @return {this} remove "reduceable" (= "less important") vertices from polygon according
// to their perpendicular distance from polygon segments
Polygon.prototype.simplify = function(xi_tolerance) {
// @param {array} two element array
// @param {array} two element array
// @return {array} difference between input arguments
var _diff2vec = function(xi_array1, xi_array2) {
return [xi_array1[0] - xi_array2[0], xi_array1[1] - xi_array2[1]];
};
// @param {array} two element array
// @param {array} two element array
// @return {number} inner product of two input arguments
var _dot2vec = function(xi_array1, xi_array2) {
return (xi_array1[0] * xi_array2[0] + xi_array1[1] * xi_array2[1]);
};
// @param {array} two element array
// @return {array} squared magnitude input arguments
var _mag2vec = function(xi_array) {
return (xi_array[0] * xi_array[0] + xi_array[1] * xi_array[1]);
};
// @param {array} two element array
// @return {array} magnitude of input arguments
var _norm2vec = function(xi_array) {
return Math.sqrt(_mag2vec(xi_array));
};
// @param {array} two element array
// @param {array} two element array
// @return {array} msquared magnitude of the difference between input arguments
var _magDiff2vec = function(xi_array1, xi_array2) {
return _mag2vec(_diff2vec(xi_array1, xi_array2));
};
// @param {number} simplification tolerance
// @param {array} polygon vertices
// @param {number} polygon sub-chain start index
// @param {number} polygon sub-chain end index
// @param/return {array} array to mark vertices which are not removed during simplification process.
// both a parameter and a return value due to function recurive character.
var _reduce = function(xi_tolerance, xi_vertices, xi_start, xi_end, xi_key ) {
// locals
var _iMax = xi_start,_maxDistSqr = 0, _tol = xi_tolerance * xi_tolerance,
_i, _length2, _proj, _dot, _dist, _w = [], _perpBase = [], _segment = [],
_direction = [];
// simplification needed?
if (xi_end <= xi_start + 1) {
return;
}
// segment characteristics
_segment = [xi_vertices[xi_start], xi_vertices[xi_end]];
_direction = _diff2vec(_segment[1], _segment[0]);
_length2 = _mag2vec(_direction,_direction);
// test all vertices distance from segment
for (_i = xi_start + 1; _i < xi_end; _i++) {
// distance
_w = _diff2vec(xi_vertices[_i], _segment[0]);
_dot = _dot2vec(_w, _direction);
if (_dot <= 0) {
_dist = _magDiff2vec(xi_vertices[_i], _segment[0]);
} else if ( _length2 <= _dot ) {
_dist = _magDiff2vec(xi_vertices[_i], _segment[1]);
} else {
_proj = _dot / _length2;
_perpBase = [_segment[0][0] + _proj * _direction[0],
_segment[0][1] + _proj * _direction[1]];
_dist = _magDiff2vec(xi_vertices[_i], _perpBase);
}
// max distance record
if (_dist <= _maxDistSqr) {
continue;
}
// new vertex
_iMax = _i;
_maxDistSqr = _dist;
}
// simplification tolerance
if (_maxDistSqr > _tol) {
// split polygon and cach vertex
xi_key[_iMax] = 1;
_reduce(xi_tolerance, xi_vertices, xi_start, _iMax, xi_key);
_reduce(xi_tolerance, xi_vertices, _iMax, xi_end, xi_key);
}
// no approximation required
return;
};
// locals
var _i, _m, _k = 1, _j = 0, _size, _tol = xi_tolerance || 0, _tol2 = _tol * _tol,
_thisVertices = [], _simplVertices = [], _vertices = [], _key = [];
// transform polygon to 1D array
for (_i = 0; _i < this.size(); _i++) {
_vertices = [this._X[_i], this._Y[_i]];
_thisVertices.push(_vertices);
}
_vertices = [];