-
Notifications
You must be signed in to change notification settings - Fork 0
/
areaMapper.js
8991 lines (7528 loc) · 404 KB
/
areaMapper.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
// Github: https://github.com/RandallDavis/roll20-areaMapper
// By: Rand Davis
// Contact: https://app.roll20.net/users/163846/rand
var APIAreaMapper = APIAreaMapper || (function() {
/* core - begin */
var version = 1.104,
areaSchemaVersion = 1.0,
buttonBackgroundColor = '#CC1869',
buttonGreyedColor = '#8D94A9',
buttonHighlightLinkColor = '#D6F510',
buttonHighlightInactiveColor = '#858789',
buttonHighlightActiveColor = '#1810F5',
buttonHighlightPositiveColor = '#29FF4D',
buttonHighlightNegativeColor = '#8629FF',
mainBackgroundColor = '#3D8FE1',
headerBackgroundColor = '#386EA5',
notificationBackgroundColor = '#64EED7',
lockedTagColor = '#E5DB50',
trappedTagColor = '#E2274C',
hiddenTagColor = '#277EE2',
attachedObjectTagColor = '#AD17CB',
closedDoorAlertPic = 'https://s3.amazonaws.com/files.d20.io/images/8543193/5XhwOpMaBUS_5B444UNC5Q/thumb.png?1427665106',
openDoorAlertPic = 'https://s3.amazonaws.com/files.d20.io/images/8543205/QBOWp1MHHlJCrPWn9kcVqQ/thumb.png?1427665124',
closedTrapdoorAlertPic = 'https://s3.amazonaws.com/files.d20.io/images/10471466/8E3rn1V_OHhwMl-iRTJfrg/thumb.png?1435585449',
openTrapdoorAlertPic = 'https://s3.amazonaws.com/files.d20.io/images/10471460/hf8vQVv5-Bm8ipSvG2kTBA/thumb.png?1435585410',
closedLightsourceAlertPic = 'https://s3.amazonaws.com/files.d20.io/images/2875450/tlPEO3pChVDm5lOR6UgWDg/thumb.png?1390730143',
openLightsourceAlertPic = 'https://s3.amazonaws.com/files.d20.io/images/90119/NeWRJzrmjUyLOdGD_MoN2A/thumb.png?1341838869',
padlockAlertPic = 'https://s3.amazonaws.com/files.d20.io/images/8546285/bdyuCfZSGRXr3qrVkcPkAg/thumb.png?1427673372',
skullAlertPic = 'https://s3.amazonaws.com/files.d20.io/images/8779089/aM1ujMQboacuc2fEMFk7Eg/thumb.png?1428784948',
wallThickness = 14,
wallLengthExtension = 12,
doorThickness = 20,
doorLengthExtension = -26,
lightRadiusAlterAmount = 3,
defaultBrightLight = 20,
defaultDimLight = 10,
blueprintFloorPolygonColor = '#A3E1E4',
blueprintEdgeWallGapsPathColor = '#D13583',
blueprintInnerWallsPathColor = '#3535D1',
blueprintDoorPathColor = '#EC9B10',
blueprintChestPathColor = '#F7F247',
blueprintTrapdoorPathColor = '#56C029',
blueprintLightsourcePathColor = '#A520D5',
/*
When this is true, the script runs toBack() on objects as a workaround for the Roll20 API bug
https://app.roll20.net/forum/post/1986741/api-z-order-with-newly-created-objects-tofront-and-toback-is-broken/#post-1986741
*/
zOrderWorkaround = true,
checkInstall = function() {
log('-=> Area Mapper v'+version+' <=-');
if(!_.has(state, 'APIAreaMapper')) {
log('APIAreaMapper: No APIAreaMapper state found. Creating it.');
state.APIAreaMapper = {
assets: {
schemaVersion: 0
},
areas: {
schemaVersion: 0
}
};
}
if(state.APIAreaMapper.assets && state.APIAreaMapper.assets.schemaVersion < 1.0) {
log('APIAreaMapper: Creating assets in state.');
state.APIAreaMapper.assets = {
schemaVersion: 1.0,
floorAssets: [
['https://s3.amazonaws.com/files.d20.io/images/48971/thumb.jpg?1340229647',0,0,1,1,0,0],
['https://s3.amazonaws.com/files.d20.io/images/224431/2KRtd2Vic84zocexdHKSDg/thumb.jpg?1348140031',0,0,1,1,0,0],
['https://s3.amazonaws.com/files.d20.io/images/170063/-IZTPfD81DHYpTbzvEUyAQ/thumb.png?1345800193',0,0,1,1,0,0],
['https://s3.amazonaws.com/files.d20.io/images/30830/thumb.png?1339416039',0,0,1,1,0,0],
['https://s3.amazonaws.com/files.d20.io/images/2830294/BaNT6qoN5O0WRiY3TS0azA/thumb.png?1390392180',0,0,1,1,0,0]
],
wallAssets: [
[['https://s3.amazonaws.com/files.d20.io/images/9585786/x1-hhxavuLoUjMsgA5vYdA/thumb.png?1432007204',0,1,0.8360173141910751,0.9705901479276444,0,0],
['https://s3.amazonaws.com/files.d20.io/images/7068/thumb.png?1336366825',0,0,1.2399379256250003,1.3534965970312505,0,-4]],
[['https://s3.amazonaws.com/files.d20.io/images/452469/9KJ1s2PJhuMbDICeYETXZQ/thumb.png?1355660278',0,0,3.386354940899389,1.0605,0,5],
['https://s3.amazonaws.com/files.d20.io/images/7068/thumb.png?1336366825',0,0,1.2399379256250003,1.3534965970312505,0,-4]]
],
doorAssets: [
[['https://s3.amazonaws.com/files.d20.io/images/6951/thumb.png?1336359665',0,0,1.2775092847093634,1.3807018786315788,0,-2],
['https://s3.amazonaws.com/files.d20.io/images/7068/thumb.png?1336366825',0,0,1.2399379256250003,1.3534965970312505,0,-4]]
],
chestAssets: [
[['https://s3.amazonaws.com/files.d20.io/images/7962/thumb.png?1336489213',0,0,1.1025,0.9523809523809523,0,-2],
['https://s3.amazonaws.com/files.d20.io/images/2839308/_RR8niUb3sTQgLSoxDhM4g/thumb.png?1390469385',0,0,1,1.0396039603960396,0,-1]]
]
};
}
if(state.APIAreaMapper.assets && state.APIAreaMapper.assets.schemaVersion < 1.1) {
log('APIAreaMapper: Adding assets to state.');
state.APIAreaMapper.assets.schemaVersion = 1.1;
state.APIAreaMapper.assets.trapdoorAssets = [
[['https://s3.amazonaws.com/files.d20.io/images/5770/thumb.png?1336266346',0,0,1.2387463105442005,1.2387463105442005,3,-1],
['https://s3.amazonaws.com/files.d20.io/images/5338/thumb.png?1336255241',0,0,1.20462921707625,1.328103711826566,0,0]],
[['https://s3.amazonaws.com/files.d20.io/images/7678/thumb.png?1336442415',0,0,1.0721353521070098,1.08285670562808,0,0],
['https://s3.amazonaws.com/files.d20.io/images/13947/thumb.png?1337763612',0,0,1,1,0,0]]
];
}
//correct asset properties:
if(state.APIAreaMapper.assets && state.APIAreaMapper.assets.schemaVersion < 1.2) {
log('APIAreaMapper: Altering default asset properties.');
state.APIAreaMapper.assets.schemaVersion = 1.2;
state.APIAreaMapper.assets.wallAssets.forEach(function(w) {
switch(w[0]) {
case 'https://s3.amazonaws.com/files.d20.io/images/7068/thumb.png?1336366825':
w[6] = -1;
break;
case 'https://s3.amazonaws.com/files.d20.io/images/452469/9KJ1s2PJhuMbDICeYETXZQ/thumb.png?1355660278':
w[6] = 2;
break;
default:
break;
}
}, this);
state.APIAreaMapper.assets.doorAssets.forEach(function(w) {
switch(w[0]) {
case 'https://s3.amazonaws.com/files.d20.io/images/6951/thumb.png?1336359665':
w[6] = -1;
break;
case 'https://s3.amazonaws.com/files.d20.io/images/7068/thumb.png?1336366825':
w[6] = -1;
break;
default:
break;
}
}, this);
}
if(state.APIAreaMapper.assets && state.APIAreaMapper.assets.schemaVersion < 1.3) {
log('APIAreaMapper: Adding assets to state.');
state.APIAreaMapper.assets.schemaVersion = 1.3;
state.APIAreaMapper.assets.lightsourceAssets = [
[['https://s3.amazonaws.com/files.d20.io/images/2875450/tlPEO3pChVDm5lOR6UgWDg/thumb.png?1390730143',0,0,1.1046221254112045,1.0936852726843609,-2,-2,0,0], //light values are ignored
['https://s3.amazonaws.com/files.d20.io/images/90119/NeWRJzrmjUyLOdGD_MoN2A/thumb.png?1341838869',0,0,1.2775092847093632,1.7103393581163142,1,-3,defaultBrightLight,defaultDimLight]],
[['https://s3.amazonaws.com/files.d20.io/images/298002/jOpj2xv9xXKpoQ9YKnDMQw/thumb.png?1350560695',180,0,1,1.0201,2,0,0,0], //light values are ignored
['https://s3.amazonaws.com/files.d20.io/images/45074/thumb.png?1340020826',180,0,2.1828745883819374,2.0997174612054823,4,-5,defaultBrightLight,defaultDimLight]],
[['https://s3.amazonaws.com/files.d20.io/images/298003/ulsp7PmK0xkhPc5NX6bZRw/thumb.png?1350560697',180,0,0.8795078309355354,1.030301,7,1,0,0], //light values are ignored
['https://s3.amazonaws.com/files.d20.io/images/45074/thumb.png?1340020826',180,0,2.0809280095213754,2.1207146358175373,6,-5,defaultBrightLight,defaultDimLight]]
];
}
if(state.APIAreaMapper.areas && state.APIAreaMapper.areas.schemaVersion !== areaSchemaVersion) {
log('APIAreaMapper: Resetting area state.');
state.APIAreaMapper.areas = {
schemaVersion: areaSchemaVersion,
areas: [],
areaInstances: []
};
}
resetTemporaryState();
},
resetTemporaryState = function() {
hideAssetManagementModal();
delete state.APIAreaMapper.tempIgnoreDrawingEvents;
delete state.APIAreaMapper.tempIgnoreAttachedObjectEvents;
delete state.APIAreaMapper.recordAreaMode;
delete state.APIAreaMapper.playerId;
delete state.APIAreaMapper.playerName;
delete state.APIAreaMapper.uiWindow;
delete state.APIAreaMapper.falseSelection;
delete state.APIAreaMapper.chestReposition;
delete state.APIAreaMapper.trapdoorReposition;
delete state.APIAreaMapper.lightsourceReposition;
delete state.APIAreaMapper.assetManagement;
//reset the handout:
if(state.APIAreaMapper.handoutUi) {
state.APIAreaMapper.uiWindow = 'mainMenu';
followUpAction = [];
followUpAction.refresh = true;
processFollowUpAction(followUpAction);
}
},
inheritPrototype = function(childObject, parentObject) {
var copyOfParent = Object.create(parentObject.prototype);
copyOfParent.constructor = childObject;
childObject.prototype = copyOfParent;
},
typedObject = function() {
this._type = [];
};
typedObject.prototype = {
constructor: typedObject,
isType: function(type) {
var found = false;
this._type.forEach(function(typeValue) {
if(type == typeValue) {
found = true;
return;
}
});
return found;
},
getProperty: function(property) {
if(!property) {
throw new Error('No property specified in getProperty().');
}
if('undefined' === typeof(this['_' + property])) {
return null;
}
return this['_' + property];
},
setProperty: function(property, value) {
if(!property) {
throw new Error('No property specified in setProperty().');
}
switch(property) {
default:
throw new Error(property + ' is unknown in setProperty().');
break;
}
},
initializeCollectionProperty: function(property) {
if(!property) {
throw new Error('No property specified in initializeCollectionProperty().');
}
switch(property) {
default:
throw new Error(property + ' is unknown in initializeCollectionProperty().');
break;
}
}
};
/* core - end */
/* polygon logic - begin */
//note: this is a simple, non-polymorphic datatype for performance purposes:
var point = function(x, y) {
this.x = x;
this.y = y;
this.equals = function(comparedPoint) {
return (this.x === comparedPoint.x && this.y === comparedPoint.y);
};
},
//angle object to simplify comparisons with epsilons:
//note: this is a simple, non-polymorphic datatype for performance purposes:
angle = function(radians) {
this.radians = radians;
this.equals = function(comparedRadians) {
return Math.round(this.radians * 10000) == Math.round(comparedRadians * 10000);
};
this.lessThan = function(comparedRadians) {
return Math.round(this.radians * 10000) < Math.round(comparedRadians * 10000);
};
this.greaterThan = function(comparedRadians) {
return Math.round(this.radians * 10000) > Math.round(comparedRadians * 10000);
};
this.subtract = function(subtractedRadians) {
return new angle(((this.radians - subtractedRadians) + (2 * Math.PI) + 0.000001) % (2 * Math.PI));
};
},
//segment between points a and b:
//note: this is a simple, non-polymorphic datatype for performance purposes:
segment = function(a, b) {
this.a = a;
this.b = b;
this.equals = function(comparedSegment) {
return (this.a.equals(comparedSegment.a) && this.b.equals(comparedSegment.b))
|| (this.a.equals(comparedSegment.b) && this.b.equals(comparedSegment.a));
};
this.length = function() {
var xDist = this.b.x - this.a.x;
var yDist = this.b.y - this.a.y;
return Math.sqrt((xDist * xDist) + (yDist * yDist));
};
this.midpoint = function() {
return new point(this.a.x + ((this.b.x - this.a.x) / 2), this.a.y + ((this.b.y - this.a.y) / 2));
};
//return an angle with respect to a specfic endpoint:
this.angle = function(p) {
var radians = (Math.atan2(this.b.y - this.a.y, this.b.x - this.a.x) + (2 * Math.PI)) % (2 * Math.PI);
if(this.b.x === p.x && this.b.y === p.y) {
//use angle with respect to b:
radians = (radians + (Math.PI)) % (2 * Math.PI);
}
return new angle(radians);
};
this.angleDegrees = function(p) {
return this.angle(p).radians * 180 / Math.PI;
};
},
pointIntersectsSegment = function(s, p) {
//boxing logic:
var xMin = Math.min(s.a.x, s.b.x);
var yMin = Math.min(s.a.y, s.b.y);
var xMax = Math.max(s.a.x, s.b.x);
var yMax = Math.max(s.a.y, s.b.y);
if(p.x < Math.min(s.a.x, s.b.x)
|| p.y < Math.min(s.a.y, s.b.y)
|| p.x > Math.max(s.a.x, s.b.x)
|| p.y > Math.max(s.a.y, s.b.y)) {
return null;
}
//test to see if p is on the line created by s:
var m = (s.b.y - s.a.y) / (s.b.x - s.a.x);
var b = s.a.y - (m * s.a.x);
return (Math.abs(p.y - ((m * p.x) + b)) < 0.0001);
},
//this is a modified version of https://gist.github.com/Joncom/e8e8d18ebe7fe55c3894
segmentsIntersect = function(s1, s2) {
//exclude segments with shared endpoints:
if(s1.a.equals(s2.a) || s1.a.equals(s2.b) || s1.b.equals(s2.a) || s1.b.equals(s2.b)) {
return null;
}
var s1_x = s1.b.x - s1.a.x;
var s1_y = s1.b.y - s1.a.y;
var s2_x = s2.b.x - s2.a.x;
var s2_y = s2.b.y - s2.a.y;
var s = (-s1_y * (s1.a.x - s2.a.x) + s1_x * (s1.a.y - s2.a.y)) / (-s2_x * s1_y + s1_x * s2_y);
var t = (s2_x * (s1.a.y - s2.a.y) - s2_y * (s1.a.x - s2.a.x)) / (-s2_x * s1_y + s1_x * s2_y);
if(s >= 0 && s <= 1 && t >= 0 && t <= 1) {
return new point(s1.a.x + (t * s1_x), s1.a.y + (t * s1_y));
}
return null;
},
path = function() {
typedObject.call(this);
this._type.push('path');
this.points = []; //don't use getter/setter mechanism for the purpose of efficiency
this.segments = []; //don't use getter/setter mechanism for the purpose of efficiency
};
inheritPrototype(path, typedObject);
path.prototype.getPointIndex = function(p) {
for(var i = 0; i < this.points.length; i++) {
if(p.equals(this.points[i][0])) {
return i;
}
}
return;
};
path.prototype.getSegmentIndex = function(s) {
for(var i = 0; i < this.segments.length; i++) {
if(s.equals(this.segments[i])) {
return i;
}
}
return;
};
path.prototype.addPoint = function(p) {
var index = this.getPointIndex(p);
if('undefined' === typeof(index)) {
//add point and return its index:
return this.points.push([p, []]) - 1;
}
return index;
};
path.prototype.removeSegment = function(s) {
var iS = this.getSegmentIndex(s);
//remove segment from points:
for(var pI = this.points.length - 1; pI >= 0; pI--) {
for(var i = 0; i < this.points[pI][1].length; i++) {
if(this.points[pI][1][i] === iS) {
//remove the segment reference:
this.points[pI][1].splice(i, 1);
//fix i since an item was deleted:
i--;
} else if(this.points[pI][1][i] > iS) {
//decrement segment index references, since a segment is being removed:
this.points[pI][1][i]--;
}
}
}
//remove segment from segments:
this.segments.splice(iS, 1);
};
path.prototype.convertRawPathToPath = function(rawPath, top, left, isFromEvent) {
var pathPoints = [],
rawPathParsed = JSON.parse(rawPath);
//if the path is from an event, the top/left is relative to the height/width of the path and needs to be corrected:
if(isFromEvent) {
var maxX = 0,
maxY = 0;
rawPathParsed.forEach(function(pRaw) {
//TODO: handle types other than M and L:
var p = new point(pRaw[1], pRaw[2]);
pathPoints.push(p);
//find the height and width as we loop through the points:
maxX = Math.max(maxX, p.x);
maxY = Math.max(maxY, p.y);
}, this);
//fix top/left:
top -= maxY / 2;
left -= maxX / 2;
//apply corrected top/left offsets to points:
pathPoints.forEach(function(p) {
p.x += left;
p.y += top;
}, this);
}
//if the path isn't from an event, the top/left can be interpreted literally and can be applied while creating the points:
else {
rawPathParsed.forEach(function(pRaw) {
//TODO: handle types other than M and L:
pathPoints.push(new point(pRaw[1] + left, pRaw[2] + top));
}, this);
}
return pathPoints;
};
path.prototype.addRawPath = function(rawPath, top, left, isFromEvent) {
var pathPoints = this.convertRawPathToPath(rawPath, top, left, isFromEvent);
return this.addPointsPath(pathPoints);
};
path.prototype.addPointsPath = function(pathPoints) {
if(!(pathPoints && pathPoints.length > 1)) {
return;
}
var hadIntersections = false;
var pStart, //start point
pPrior; //prior point
pathPoints.forEach(function(pCurrent) {
var iCurrent = this.addPoint(pCurrent); //index of current point
if(pPrior) {
var result = this.addSegment(new segment(pPrior, pCurrent));
if(result) {
hadIntersections = hadIntersections || result.hadIntersections;
}
} else {
pStart = pCurrent;
}
pPrior = pCurrent;
}, this);
//if this is a polygon (broken polymorphism because it would be better to do multiple inheritence), close the polygon if it isn't closed already:
if(this.isType('polygon')) {
if(!pPrior.equals(pStart)) {
var result = this.addSegment(new segment(pPrior, pStart));
if(result) {
hadIntersections = hadIntersections || result.hadIntersections;
}
}
}
/*
If prior to calling this method, only a simple polygon was stored, and then another simple polygon
is added, whether or not there were intersections reveals something about the interrelation of
the two polygons that is useful for some algorithms. If two simple polygons don't intersect, then
either they are siblings, or one is completely contained within the other. This is detected in
this method because it would lead to redundant processing to do it elsewhere.
*/
var returnObject = [];
returnObject.hadIntersections = hadIntersections;
return returnObject;
};
/*
A simple path has gauranteed properties. Each point can have one or an even number of segments. Only a point
at the beginning or end of the path can have one segment, and if one of them has one, then both must. If a point
has more than two segments, then it is an intersection point. Segments are ordered such that they can be
traversed to find a walkable points path.
If all points have an even number of segments, then it is a simple polygon and the first and last points
have a shared segment.
*/
var simplePath = function() {
path.call(this);
this._type.push('simplePath');
};
inheritPrototype(simplePath, path);
//adds the segment to the tail of the path:
simplePath.prototype.addSegment = function(s) {
if(!s.a.equals(s.b)) {
if(this.segments.length == 0) {
//there are no segments, so insert this and establish orientation from s.a -> s.b:
var sI = this.segments.push(s) - 1;
var pAI = this.addPoint(s.a);
var pBI = this.addPoint(s.b);
this.points[pAI][1].push(sI);
this.points[pBI][1].push(sI);
} else {
//fix the segment's orientation:
var sFixed =
new segment(
this.segments[this.segments.length - 1].b,
this.segments[this.segments.length - 1].b.equals(s.a)
? s.b
: s.a
);
var sI = this.segments.push(sFixed) - 1;
var pAI = this.getPointIndex(sFixed.a);
var pBI = this.addPoint(sFixed.b);
this.points[pAI][1].push(sI);
this.points[pBI][1].push(sI);
}
}
};
//breaks a segment at the specified point:
simplePath.prototype.breakSegment = function(s, p) {
if(!s.a.equals(p) && !s.b.equals(p)) {
//get current indexes:
var sI = this.getSegmentIndex(s);
var pAI = this.getPointIndex(s.a);
var pBI = this.getPointIndex(s.b);
//increment the references to all segments that are about to be shifted to the right:
this.points.forEach(function(p2) {
for(var i = 0; i < p2[1].length; i++) {
if(p2[1][i] > sI) {
p2[1][i]++;
}
}
}, this);
//add the new point:
var pI = this.addPoint(p);
//splice in the right side of the broken segment:
this.segments.splice(sI + 1, 0, new segment(p, this.segments[sI].b));
//modify the left side of the broken segment:
this.segments[sI].b = p;
//increment point s.b's segment reference:
this.points[pBI][1][this.points[pBI][1].indexOf(sI)]++;
//register the broken segments in point p:
this.points[pI][1].push(sI);
this.points[pI][1].push(sI + 1);
}
};
//returns points in walking order:
simplePath.prototype.getPointsPath = function() {
if(!(this.segments && this.segments.length > 0)) {
return;
}
var pointsPath = [];
pointsPath.push(this.segments[0].a);
this.segments.forEach(function(s) {
pointsPath.push(s.b);
}, this);
return pointsPath;
};
//returns a raw path aligned at (0,0) with top/left offsets:
simplePath.prototype.getRawPath = function() {
if(!(this.segments && this.segments.length > 0)) {
return;
}
//get a walkable path in the proper orientation:
var pointsPath = this.getPointsPath();
var minX = pointsPath[0].x;
var minY = pointsPath[0].y;
var maxX = pointsPath[0].x;
var maxY = pointsPath[0].y;
pointsPath.forEach(function(p) {
minX = Math.min(minX, p.x);
minY = Math.min(minY, p.y);
maxX = Math.max(maxX, p.x);
maxY = Math.max(maxY, p.y);
}, this);
var rawPath = '[[\"M\",' + (pointsPath[0].x - minX) + ',' + (pointsPath[0].y - minY) + ']';
for(var i = 1; i < pointsPath.length; i++) {
rawPath += ',[\"L\",' + (pointsPath[i].x - minX) + ',' + (pointsPath[i].y - minY) + ']';
}
//if this is a polygon, close the path:
if(this.isType('polygon' && !pointsPath[0].equals(pointsPath[pointsPath.length - 1]))) {
rawPath += ',[\"L\",' + (pointsPath[0].x - minX) + ',' + (pointsPath[0].y - minY) + ']';
}
rawPath += ']';
var returnObject = [];
returnObject.rawPath = rawPath;
returnObject.top = minY;
returnObject.left = minX;
returnObject.width = maxX - minX;
returnObject.height = maxY - minY;
return returnObject;
};
//takes an array of path points that are gauranteed to intersect this path and returns paths that weren't intersected:
//note: this handles simple polygon logic as well
simplePath.prototype.removePathIntersections = function(intersectingPaths) {
//Stuff this path's points into a data structure that has proper path order, but allows for tagging. Don't do tagging on this.points because it could get persisted when the points are saved.
var taggedPointsPath = [];
this.getPointsPath().forEach(function(p) {
taggedPointsPath.push([p, [false, false, false]]); //this consists of the point, whether or not there are intersections on it, if it's the start of an intersection, and if it's the end of an intersection
}, this);
var getTaggedPointsPathPointIndex = function(taggedPointsPath, p) {
for(var i = 0; i < taggedPointsPath.length; i++) {
if(taggedPointsPath[i][0].equals(p)) {
return i;
}
}
return null;
};
var breakSegmentIfPointNotFound = function(taggedPointsPath, p) {
if(getTaggedPointsPathPointIndex(taggedPointsPath, p) === null) {
for(var i = 0 + 1; i < taggedPointsPath.length; i++) {
var s = new segment(taggedPointsPath[i - 1][0], taggedPointsPath[i][0]);
if(pointIntersectsSegment(s, p)) {
taggedPointsPath.splice(i, 0, [p, [false, false, false]]);
return;
}
}
}
};
//break any intersections on this path with critical points on intersecting paths:
intersectingPaths.forEach(function(ip) {
breakSegmentIfPointNotFound(taggedPointsPath, ip[0]);
breakSegmentIfPointNotFound(taggedPointsPath, ip[1]);
breakSegmentIfPointNotFound(taggedPointsPath, ip[ip.length - 1]);
}, this);
var fullyIntersected = false;
//apply intersection tags to this path:
intersectingPaths.forEach(function(ip) {
//test that ip is long enough to be used:
if(ip.length < 2) {
return;
}
//test that the first, second, and last points from ip are all on this path, and the first and second are adjacent:
var iFirst = getTaggedPointsPathPointIndex(taggedPointsPath, ip[0]);
var iSecond = getTaggedPointsPathPointIndex(taggedPointsPath, ip[1]);
var iLast = getTaggedPointsPathPointIndex(taggedPointsPath, ip[ip.length - 1]);
//if orientation is 1, the paths have the same orientation; otherwise, the orientation will be -1, if the orientation is anything else, the first and second points are not adjacent:
var orientation;
//if this is a polygon and one of the points is at index 0, handle edge cases where the adjacent point is wrapped around; skip the last point in the polygon because it's redundant to the first point:
if(this.isType('polygon')) {
if(iFirst === 0 && iSecond === taggedPointsPath.length - 2) {
orientation = -1;
} else if(iSecond === 0 && iFirst === taggedPointsPath.length - 2) {
orientation = 1;
} else {
orientation = iSecond - iFirst;
}
} else {
orientation = iSecond - iFirst;
}
//abs(orientation) will normally be 1, as iFirst should be ajacent to iSecond. Give it an additional threshold in case there is a merge occurring where intersecting paths overlap.
if(iFirst === null || iSecond === null || iLast === null
|| Math.abs(orientation) === 0
|| Math.abs(orientation) > 3) {
return;
}
//remove the grace from orientation so that it can be used for stepping:
orientation = (orientation > 0) ? 1 : -1;
//as a special case, mark all as intersected if ip is a polygon (we already know it's of > 0 length):
if(iFirst === iLast) {
fullyIntersected = true;
return;
}
//tag the points on this path as intersected that span between the first and last points exclusive:
for(var i = iFirst + 1; i !== iLast; i = (i + orientation) % taggedPointsPath.length) {
//mark this point as intersected:
taggedPointsPath[i][1][0] = true;
//clobber any other intersecting paths' endpoints:
taggedPointsPath[i][1][1] = false;
taggedPointsPath[i][1][2] = false;
}
//tag this path with the endpoints of the intersecing path, with respect to this path's orientation:
//respect other intersecting paths' endpoints as if the new endpoints were clobbered:
if(orientation > 0) {
if(!taggedPointsPath[iFirst][1][0]) {
taggedPointsPath[iFirst][1][1] = true;
}
if(!taggedPointsPath[iLast][1][0]) {
taggedPointsPath[iLast][1][2] = true;
}
} else {
if(!taggedPointsPath[iFirst][1][0]) {
taggedPointsPath[iFirst][1][2] = true;
}
if(!taggedPointsPath[iLast][1][0]) {
taggedPointsPath[iLast][1][1] = true;
}
}
//tag the endpoints:
taggedPointsPath[iFirst][1][0] = true;
taggedPointsPath[iLast][1][0] = true;
}, this);
if(fullyIntersected) {
return [];
}
var survivingPaths = [];
var initialPath = [];
var currentPath = initialPath;
//determine the surviving paths that evaded intersection:
for(var i = 0; i < taggedPointsPath.length; i++) {
if(!taggedPointsPath[i][1][0]) {
//add the current point:
currentPath.push(taggedPointsPath[i][0]);
} else {
//handle start of intersections:
if(taggedPointsPath[i][1][1]) {
//close off the current path:
if(currentPath.length) {
currentPath.push(taggedPointsPath[i][0]);
survivingPaths.push(currentPath);
currentPath = [];
}
}
//handle end of intersections:
if(taggedPointsPath[i][1][2]) {
//begin a new current path:
currentPath.push(taggedPointsPath[i][0]);
}
}
}
/*
The initial path is special in that it might need to be prepended, but we won't know until we complete the circuit.
It will be prepended if: this path is a polygon, the initial path begins at point index 0, the initial path doesn't
complete the circuit without intersections, and the final point of this path is not intersected.
*/
//prepend to initialPath if necessary:
if(this.isType('polygon')
&& !taggedPointsPath[0][1][0]
&& currentPath !== initialPath
&& currentPath.length > 0) {
survivingPaths[0] = currentPath.concat(survivingPaths[0]);
}
//include currentPath:
else {
if(currentPath.length > 1) {
survivingPaths.push(currentPath);
}
}
return survivingPaths;
}
var complexPath = function() {
path.call(this);
this._type.push('complexPath');
};
inheritPrototype(complexPath, path);
//returns whether or not there were intersections, because this is useful information for certain algorithms:
complexPath.prototype.addSegment = function(s) {
//note: it's illogical to return a segment's index, because it might have been broken into pieces:
//note: it's inconvient to do early detection of the segment being new, because of segment breaking:
//don't add the segment if it's of 0 length:
if(s.a.equals(s.b)) {
return;
}
var newSegments = [];
var brokenSegments = [];
var intersectingSegments = [];
newSegments.push(s);
//find segments that the new segment intersects:
this.segments.forEach(function(seg) {
if(segmentsIntersect(s, seg)) {
intersectingSegments.push(seg);
}
}, this);
//break segment against all intersecting segments and remove intersecting segments:
intersectingSegments.forEach(function(seg) {
//loop through new segments to look for intersections:
for(var i = 0; i < newSegments.length; i++) {
//because we're breaking new segments, we have to retest for intersection:
var intersectionPoint = segmentsIntersect(newSegments[i], seg);
if(intersectionPoint) {
//create broken segments out of old segment that was intersected:
brokenSegments.push(new segment(seg.a, intersectionPoint));
brokenSegments.push(new segment(intersectionPoint, seg.b));
//remove the segment that was intersected from the graph:
this.removeSegment(seg);
//create new broken segments:
newSegments.unshift(new segment(newSegments[i].a, intersectionPoint));
newSegments.unshift(new segment(intersectionPoint, newSegments[i + 1].b));
//remove the new segment that was just broken:
newSegments.splice(i + 2, 1);
//adjust the loop to bypass the broken newSegments that were already tested against seg:
i++;
}
}
}, this);
var hadIntersections = false;
//add old broken segments:
brokenSegments.forEach(function(seg) {
if(!seg.a.equals(seg.b)) {
hadIntersections = true;
var iS = this.segments.push(seg) - 1;
var iPa = this.addPoint(seg.a);
var iPb = this.addPoint(seg.b);
this.points[iPa][1].push(iS);
this.points[iPb][1].push(iS);
}
}, this);
//add new segments:
newSegments.forEach(function(seg) {
if(!seg.a.equals(seg.b)) {
var iS = this.segments.push(seg) - 1;
var iPa = this.addPoint(seg.a);
var iPb = this.addPoint(seg.b);
this.points[iPa][1].push(iS);
this.points[iPb][1].push(iS);
}
}, this);
//create a return object with specific fields, so that the return values aren't misconstrued to be something more intuitive:
var returnObject = [];
returnObject.hadIntersections = hadIntersections;
return returnObject;
};
var simplePolygon = function() {
simplePath.call(this);
this._type.push('polygon');
this._type.push('simplePolygon');
};
inheritPrototype(simplePolygon, simplePath);
//tests if the point is inside the polygon:
simplePolygon.prototype.hasInsidePoint = function(p) {
//use an arbitrarily long horizontal segment that goes into negatives (because of relative coordinates):
var horizontalSegment = new segment(new point(-1000000000, p.y), new point(1000000000, p.y));
//count the intersecting points that appear to the left of the point in question:
var pointsOnLeft = 0;
//find segments that intersect the point horizontally:
this.segments.forEach(function(s) {
//find a naturally occurring intersection point:
var intersectingPoint = segmentsIntersect(horizontalSegment, s);
//if there was no natural intersection point, test for a segment endpoint hitting the horizontal segment:
if(!intersectingPoint) {
/*
If an endpoint on the segment is on the horizontal segment, count it as an intersecting segment if it is angling down from
that point's perspective. This will result in two segments traveling through the horizontal segment to register as odd, and
will ignore any horizontal segments that are overlapping the horizontal segment.
*/
if(s.a.y === p.y && s.b.y - s.a.y > 0) {
intersectingPoint = s.a;
} else if(s.b.y === p.y && s.a.y - s.b.y > 0) {
intersectingPoint = s.b;
}
}
if(intersectingPoint && intersectingPoint.x < p.x) {
pointsOnLeft++;
}
}, this);
//there will be an even number of intersections; if the point in question is between an odd number of intersections, it's inside the polygon:
return (pointsOnLeft % 2 === 1);
};
//only tests segment's endpoints:
simplePolygon.prototype.hasInsideSegment = function(s) {
return (this.hasInsidePoint(s.a) && this.hasInsidePoint(s.b));
};
simplePolygon.prototype.hasInsideEntirePath = function(sp) {