forked from username2234/airmash_bot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker.js
2682 lines (2591 loc) · 90.4 KB
/
worker.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
const {
Worker, MessageChannel, MessagePort, isMainThread, parentPort
} = require('worker_threads');
var log_enabled = false;
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 19);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
var DiagonalMovement = {
Always: 1,
Never: 2,
IfAtMostOneObstacle: 3,
OnlyWhenNoObstacles: 4
};
module.exports = DiagonalMovement;
/***/ }),
/* 1 */
/***/ (function(module, exports) {
/**
* Backtrace according to the parent records and return the path.
* (including both start and end nodes)
* @param {Node} node End node
* @return {Array<Array<number>>} the path
*/
function backtrace(node) {
var path = [[node.x, node.y]];
while (node.parent) {
node = node.parent;
path.push([node.x, node.y]);
}
return path.reverse();
}
exports.backtrace = backtrace;
/**
* Backtrace from start and end node, and return the path.
* (including both start and end nodes)
* @param {Node}
* @param {Node}
*/
function biBacktrace(nodeA, nodeB) {
var pathA = backtrace(nodeA), pathB = backtrace(nodeB);
return pathA.concat(pathB.reverse());
}
exports.biBacktrace = biBacktrace;
/**
* Compute the length of the path.
* @param {Array<Array<number>>} path The path
* @return {number} The length of the path
*/
function pathLength(path) {
var i, sum = 0, a, b, dx, dy;
for (i = 1; i < path.length; ++i) {
a = path[i - 1];
b = path[i];
dx = a[0] - b[0];
dy = a[1] - b[1];
sum += Math.sqrt(dx * dx + dy * dy);
}
return sum;
}
exports.pathLength = pathLength;
/**
* Given the start and end coordinates, return all the coordinates lying
* on the line formed by these coordinates, based on Bresenham's algorithm.
* http://en.wikipedia.org/wiki/Bresenham's_line_algorithm#Simplification
* @param {number} x0 Start x coordinate
* @param {number} y0 Start y coordinate
* @param {number} x1 End x coordinate
* @param {number} y1 End y coordinate
* @return {Array<Array<number>>} The coordinates on the line
*/
function interpolate(x0, y0, x1, y1) {
var abs = Math.abs, line = [], sx, sy, dx, dy, err, e2;
dx = abs(x1 - x0);
dy = abs(y1 - y0);
sx = (x0 < x1) ? 1 : -1;
sy = (y0 < y1) ? 1 : -1;
err = dx - dy;
while (true) {
line.push([x0, y0]);
if (x0 === x1 && y0 === y1) {
break;
}
e2 = 2 * err;
if (e2 > -dy) {
err = err - dy;
x0 = x0 + sx;
}
if (e2 < dx) {
err = err + dx;
y0 = y0 + sy;
}
}
return line;
}
exports.interpolate = interpolate;
/**
* Given a compressed path, return a new path that has all the segments
* in it interpolated.
* @param {Array<Array<number>>} path The path
* @return {Array<Array<number>>} expanded path
*/
function expandPath(path) {
var expanded = [], len = path.length, coord0, coord1, interpolated, interpolatedLen, i, j;
if (len < 2) {
return expanded;
}
for (i = 0; i < len - 1; ++i) {
coord0 = path[i];
coord1 = path[i + 1];
interpolated = interpolate(coord0[0], coord0[1], coord1[0], coord1[1]);
interpolatedLen = interpolated.length;
for (j = 0; j < interpolatedLen - 1; ++j) {
expanded.push(interpolated[j]);
}
}
expanded.push(path[len - 1]);
return expanded;
}
exports.expandPath = expandPath;
/**
* Smoothen the give path.
* The original path will not be modified; a new path will be returned.
* @param {PF.Grid} grid
* @param {Array<Array<number>>} path The path
*/
function smoothenPath(grid, path) {
var len = path.length, x0 = path[0][0], // path start x
y0 = path[0][1], // path start y
x1 = path[len - 1][0], // path end x
y1 = path[len - 1][1], // path end y
sx, sy, // current start coordinate
ex, ey, // current end coordinate
newPath, i, j, coord, line, testCoord, blocked;
sx = x0;
sy = y0;
newPath = [[sx, sy]];
for (i = 2; i < len; ++i) {
coord = path[i];
ex = coord[0];
ey = coord[1];
line = interpolate(sx, sy, ex, ey);
blocked = false;
for (j = 1; j < line.length; ++j) {
testCoord = line[j];
if (!grid.isWalkableAt(testCoord[0], testCoord[1])) {
blocked = true;
break;
}
}
if (blocked) {
lastValidCoord = path[i - 1];
newPath.push(lastValidCoord);
sx = lastValidCoord[0];
sy = lastValidCoord[1];
}
}
newPath.push([x1, y1]);
return newPath;
}
exports.smoothenPath = smoothenPath;
/**
* Compress a path, remove redundant nodes without altering the shape
* The original path is not modified
* @param {Array<Array<number>>} path The path
* @return {Array<Array<number>>} The compressed path
*/
function compressPath(path) {
// nothing to compress
if (path.length < 3) {
return path;
}
var compressed = [], sx = path[0][0], // start x
sy = path[0][1], // start y
px = path[1][0], // second point x
py = path[1][1], // second point y
dx = px - sx, // direction between the two points
dy = py - sy, // direction between the two points
lx, ly, ldx, ldy, sq, i;
// normalize the direction
sq = Math.sqrt(dx * dx + dy * dy);
dx /= sq;
dy /= sq;
// start the new path
compressed.push([sx, sy]);
for (i = 2; i < path.length; i++) {
// store the last point
lx = px;
ly = py;
// store the last direction
ldx = dx;
ldy = dy;
// next point
px = path[i][0];
py = path[i][1];
// next direction
dx = px - lx;
dy = py - ly;
// normalize
sq = Math.sqrt(dx * dx + dy * dy);
dx /= sq;
dy /= sq;
// if the direction has changed, store the point
if (dx !== ldx || dy !== ldy) {
compressed.push([lx, ly]);
}
}
// store the last point
compressed.push([px, py]);
return compressed;
}
exports.compressPath = compressPath;
/***/ }),
/* 2 */,
/* 3 */
/***/ (function(module, exports) {
/**
* @namespace PF.Heuristic
* @description A collection of heuristic functions.
*/
module.exports = {
/**
* Manhattan distance.
* @param {number} dx - Difference in x.
* @param {number} dy - Difference in y.
* @return {number} dx + dy
*/
manhattan: function (dx, dy) {
return dx + dy;
},
/**
* Euclidean distance.
* @param {number} dx - Difference in x.
* @param {number} dy - Difference in y.
* @return {number} sqrt(dx * dx + dy * dy)
*/
euclidean: function (dx, dy) {
return Math.sqrt(dx * dx + dy * dy);
},
/**
* Octile distance.
* @param {number} dx - Difference in x.
* @param {number} dy - Difference in y.
* @return {number} sqrt(dx * dx + dy * dy) for grids
*/
octile: function (dx, dy) {
var F = Math.SQRT2 - 1;
return (dx < dy) ? F * dx + dy : F * dy + dx;
},
/**
* Chebyshev distance.
* @param {number} dx - Difference in x.
* @param {number} dy - Difference in y.
* @return {number} max(dx, dy)
*/
chebyshev: function (dx, dy) {
return Math.max(dx, dy);
}
};
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(23);
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
/**
* @author imor / https://github.com/imor
*/
var Heap = __webpack_require__(4);
var Util = __webpack_require__(1);
var Heuristic = __webpack_require__(3);
var DiagonalMovement = __webpack_require__(0);
/**
* Base class for the Jump Point Search algorithm
* @param {object} opt
* @param {function} opt.heuristic Heuristic function to estimate the distance
* (defaults to manhattan).
*/
function JumpPointFinderBase(opt) {
opt = opt || {};
this.heuristic = opt.heuristic || Heuristic.manhattan;
this.trackJumpRecursion = opt.trackJumpRecursion || false;
}
/**
* Find and return the path.
* @return {Array<Array<number>>} The path, including both start and
* end positions.
*/
JumpPointFinderBase.prototype.findPath = function (startX, startY, endX, endY, grid) {
var openList = this.openList = new Heap(function (nodeA, nodeB) {
return nodeA.f - nodeB.f;
}), startNode = this.startNode = grid.getNodeAt(startX, startY), endNode = this.endNode = grid.getNodeAt(endX, endY), node;
this.grid = grid;
// set the `g` and `f` value of the start node to be 0
startNode.g = 0;
startNode.f = 0;
// push the start node into the open list
openList.push(startNode);
startNode.opened = true;
// while the open list is not empty
while (!openList.empty()) {
// pop the position of node which has the minimum `f` value.
node = openList.pop();
node.closed = true;
if (node === endNode) {
return Util.expandPath(Util.backtrace(endNode));
}
this._identifySuccessors(node);
}
// fail to find the path
return [];
};
/**
* Identify successors for the given node. Runs a jump point search in the
* direction of each available neighbor, adding any points found to the open
* list.
* @protected
*/
JumpPointFinderBase.prototype._identifySuccessors = function (node) {
var grid = this.grid, heuristic = this.heuristic, openList = this.openList, endX = this.endNode.x, endY = this.endNode.y, neighbors, neighbor, jumpPoint, i, l, x = node.x, y = node.y, jx, jy, dx, dy, d, ng, jumpNode, abs = Math.abs, max = Math.max;
neighbors = this._findNeighbors(node);
for (i = 0, l = neighbors.length; i < l; ++i) {
neighbor = neighbors[i];
jumpPoint = this._jump(neighbor[0], neighbor[1], x, y);
if (jumpPoint) {
jx = jumpPoint[0];
jy = jumpPoint[1];
jumpNode = grid.getNodeAt(jx, jy);
if (jumpNode.closed) {
continue;
}
// include distance, as parent may not be immediately adjacent:
d = Heuristic.octile(abs(jx - x), abs(jy - y));
ng = node.g + d; // next `g` value
if (!jumpNode.opened || ng < jumpNode.g) {
jumpNode.g = ng;
jumpNode.h = jumpNode.h || heuristic(abs(jx - endX), abs(jy - endY));
jumpNode.f = jumpNode.g + jumpNode.h;
jumpNode.parent = node;
if (!jumpNode.opened) {
openList.push(jumpNode);
jumpNode.opened = true;
}
else {
openList.updateItem(jumpNode);
}
}
}
}
};
module.exports = JumpPointFinderBase;
/***/ }),
/* 6 */
/***/ (function(module, exports) {
/**
* A node in grid.
* This class holds some basic information about a node and custom
* attributes may be added, depending on the algorithms' needs.
* @constructor
* @param {number} x - The x coordinate of the node on the grid.
* @param {number} y - The y coordinate of the node on the grid.
* @param {boolean} [walkable] - Whether this node is walkable.
*/
function Node(x, y, walkable) {
/**
* The x coordinate of the node on the grid.
* @type number
*/
this.x = x;
/**
* The y coordinate of the node on the grid.
* @type number
*/
this.y = y;
/**
* Whether this node can be walked through.
* @type boolean
*/
this.walkable = (walkable === undefined ? true : walkable);
}
module.exports = Node;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
var Heap = __webpack_require__(4);
var Util = __webpack_require__(1);
var Heuristic = __webpack_require__(3);
var DiagonalMovement = __webpack_require__(0);
/**
* A* path-finder. Based upon https://github.com/bgrins/javascript-astar
* @constructor
* @param {Object} opt
* @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed.
* Deprecated, use diagonalMovement instead.
* @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching
* block corners. Deprecated, use diagonalMovement instead.
* @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement.
* @param {function} opt.heuristic Heuristic function to estimate the distance
* (defaults to manhattan).
* @param {number} opt.weight Weight to apply to the heuristic to allow for
* suboptimal paths, in order to speed up the search.
*/
function AStarFinder(opt) {
opt = opt || {};
this.allowDiagonal = opt.allowDiagonal;
this.dontCrossCorners = opt.dontCrossCorners;
this.heuristic = opt.heuristic || Heuristic.manhattan;
this.weight = opt.weight || 1;
this.diagonalMovement = opt.diagonalMovement;
if (!this.diagonalMovement) {
if (!this.allowDiagonal) {
this.diagonalMovement = DiagonalMovement.Never;
}
else {
if (this.dontCrossCorners) {
this.diagonalMovement = DiagonalMovement.OnlyWhenNoObstacles;
}
else {
this.diagonalMovement = DiagonalMovement.IfAtMostOneObstacle;
}
}
}
// When diagonal movement is allowed the manhattan heuristic is not
//admissible. It should be octile instead
if (this.diagonalMovement === DiagonalMovement.Never) {
this.heuristic = opt.heuristic || Heuristic.manhattan;
}
else {
this.heuristic = opt.heuristic || Heuristic.octile;
}
}
/**
* Find and return the the path.
* @return {Array<Array<number>>} The path, including both start and
* end positions.
*/
AStarFinder.prototype.findPath = function (startX, startY, endX, endY, grid) {
var openList = new Heap(function (nodeA, nodeB) {
return nodeA.f - nodeB.f;
}), startNode = grid.getNodeAt(startX, startY), endNode = grid.getNodeAt(endX, endY), heuristic = this.heuristic, diagonalMovement = this.diagonalMovement, weight = this.weight, abs = Math.abs, SQRT2 = Math.SQRT2, node, neighbors, neighbor, i, l, x, y, ng;
// set the `g` and `f` value of the start node to be 0
startNode.g = 0;
startNode.f = 0;
// push the start node into the open list
openList.push(startNode);
startNode.opened = true;
// while the open list is not empty
while (!openList.empty()) {
// pop the position of node which has the minimum `f` value.
node = openList.pop();
node.closed = true;
// if reached the end position, construct the path and return it
if (node === endNode) {
return Util.backtrace(endNode);
}
// get neigbours of the current node
neighbors = grid.getNeighbors(node, diagonalMovement);
for (i = 0, l = neighbors.length; i < l; ++i) {
neighbor = neighbors[i];
if (neighbor.closed) {
continue;
}
x = neighbor.x;
y = neighbor.y;
// get the distance between current node and the neighbor
// and calculate the next g score
ng = node.g + ((x - node.x === 0 || y - node.y === 0) ? 1 : SQRT2);
// check if the neighbor has not been inspected yet, or
// can be reached with smaller cost from the current node
if (!neighbor.opened || ng < neighbor.g) {
neighbor.g = ng;
neighbor.h = neighbor.h || weight * heuristic(abs(x - endX), abs(y - endY));
neighbor.f = neighbor.g + neighbor.h;
neighbor.parent = node;
if (!neighbor.opened) {
openList.push(neighbor);
neighbor.opened = true;
}
else {
// the neighbor can be reached with smaller cost.
// Since its f value has been updated, we have to
// update its position in the open list
openList.updateItem(neighbor);
}
}
} // end for each neighbor
} // end while not open list empty
// fail to find the path
return [];
};
module.exports = AStarFinder;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
var Heap = __webpack_require__(4);
var Util = __webpack_require__(1);
var Heuristic = __webpack_require__(3);
var DiagonalMovement = __webpack_require__(0);
/**
* A* path-finder.
* based upon https://github.com/bgrins/javascript-astar
* @constructor
* @param {Object} opt
* @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed.
* Deprecated, use diagonalMovement instead.
* @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching
* block corners. Deprecated, use diagonalMovement instead.
* @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement.
* @param {function} opt.heuristic Heuristic function to estimate the distance
* (defaults to manhattan).
* @param {number} opt.weight Weight to apply to the heuristic to allow for
* suboptimal paths, in order to speed up the search.
*/
function BiAStarFinder(opt) {
opt = opt || {};
this.allowDiagonal = opt.allowDiagonal;
this.dontCrossCorners = opt.dontCrossCorners;
this.diagonalMovement = opt.diagonalMovement;
this.heuristic = opt.heuristic || Heuristic.manhattan;
this.weight = opt.weight || 1;
if (!this.diagonalMovement) {
if (!this.allowDiagonal) {
this.diagonalMovement = DiagonalMovement.Never;
}
else {
if (this.dontCrossCorners) {
this.diagonalMovement = DiagonalMovement.OnlyWhenNoObstacles;
}
else {
this.diagonalMovement = DiagonalMovement.IfAtMostOneObstacle;
}
}
}
//When diagonal movement is allowed the manhattan heuristic is not admissible
//It should be octile instead
if (this.diagonalMovement === DiagonalMovement.Never) {
this.heuristic = opt.heuristic || Heuristic.manhattan;
}
else {
this.heuristic = opt.heuristic || Heuristic.octile;
}
}
/**
* Find and return the the path.
* @return {Array<Array<number>>} The path, including both start and
* end positions.
*/
BiAStarFinder.prototype.findPath = function (startX, startY, endX, endY, grid) {
var cmp = function (nodeA, nodeB) {
return nodeA.f - nodeB.f;
}, startOpenList = new Heap(cmp), endOpenList = new Heap(cmp), startNode = grid.getNodeAt(startX, startY), endNode = grid.getNodeAt(endX, endY), heuristic = this.heuristic, diagonalMovement = this.diagonalMovement, weight = this.weight, abs = Math.abs, SQRT2 = Math.SQRT2, node, neighbors, neighbor, i, l, x, y, ng, BY_START = 1, BY_END = 2;
// set the `g` and `f` value of the start node to be 0
// and push it into the start open list
startNode.g = 0;
startNode.f = 0;
startOpenList.push(startNode);
startNode.opened = BY_START;
// set the `g` and `f` value of the end node to be 0
// and push it into the open open list
endNode.g = 0;
endNode.f = 0;
endOpenList.push(endNode);
endNode.opened = BY_END;
// while both the open lists are not empty
while (!startOpenList.empty() && !endOpenList.empty()) {
// pop the position of start node which has the minimum `f` value.
node = startOpenList.pop();
node.closed = true;
// get neigbours of the current node
neighbors = grid.getNeighbors(node, diagonalMovement);
for (i = 0, l = neighbors.length; i < l; ++i) {
neighbor = neighbors[i];
if (neighbor.closed) {
continue;
}
if (neighbor.opened === BY_END) {
return Util.biBacktrace(node, neighbor);
}
x = neighbor.x;
y = neighbor.y;
// get the distance between current node and the neighbor
// and calculate the next g score
ng = node.g + ((x - node.x === 0 || y - node.y === 0) ? 1 : SQRT2);
// check if the neighbor has not been inspected yet, or
// can be reached with smaller cost from the current node
if (!neighbor.opened || ng < neighbor.g) {
neighbor.g = ng;
neighbor.h = neighbor.h ||
weight * heuristic(abs(x - endX), abs(y - endY));
neighbor.f = neighbor.g + neighbor.h;
neighbor.parent = node;
if (!neighbor.opened) {
startOpenList.push(neighbor);
neighbor.opened = BY_START;
}
else {
// the neighbor can be reached with smaller cost.
// Since its f value has been updated, we have to
// update its position in the open list
startOpenList.updateItem(neighbor);
}
}
} // end for each neighbor
// pop the position of end node which has the minimum `f` value.
node = endOpenList.pop();
node.closed = true;
// get neigbours of the current node
neighbors = grid.getNeighbors(node, diagonalMovement);
for (i = 0, l = neighbors.length; i < l; ++i) {
neighbor = neighbors[i];
if (neighbor.closed) {
continue;
}
if (neighbor.opened === BY_START) {
return Util.biBacktrace(neighbor, node);
}
x = neighbor.x;
y = neighbor.y;
// get the distance between current node and the neighbor
// and calculate the next g score
ng = node.g + ((x - node.x === 0 || y - node.y === 0) ? 1 : SQRT2);
// check if the neighbor has not been inspected yet, or
// can be reached with smaller cost from the current node
if (!neighbor.opened || ng < neighbor.g) {
neighbor.g = ng;
neighbor.h = neighbor.h ||
weight * heuristic(abs(x - startX), abs(y - startY));
neighbor.f = neighbor.g + neighbor.h;
neighbor.parent = node;
if (!neighbor.opened) {
endOpenList.push(neighbor);
neighbor.opened = BY_END;
}
else {
// the neighbor can be reached with smaller cost.
// Since its f value has been updated, we have to
// update its position in the open list
endOpenList.updateItem(neighbor);
}
}
} // end for each neighbor
} // end while not open list empty
// fail to find the path
return [];
};
module.exports = BiAStarFinder;
/***/ }),
/* 9 */,
/* 10 */,
/* 11 */,
/* 12 */,
/* 13 */,
/* 14 */,
/* 15 */,
/* 16 */,
/* 17 */,
/* 18 */,
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var botNavigation_1 = __webpack_require__(20);
var botNavigation = new botNavigation_1.BotNavigation();
//onmessage = function (event) {
parentPort.on('message',function (event) {
//var args = event.data;
var args = event;
var action = args[0];
//var pm = self.postMessage; // typescript binding is not helping here
botNavigation.setLogFunction(log);
botNavigation.setSignalAliveFunction(signalAlive);
try {
if (action === "findPath") {
var myPos = args[1];
var otherPos = args[2];
var requestID = args[3];
var path = botNavigation.findPath(myPos, otherPos, requestID);
// callback
//pm(["findPath", path, requestID]);
parentPort.postMessage(["findPath", path, requestID]);
}
else if (action === "setMountains") {
var mountains = args[1];
botNavigation.setMountains(mountains);
//pm(["READY"]);
parentPort.postMessage(["READY"]);
}
else {
//pm(["ERROR", "unknown action " + action]);
parentPort.postMessage(["ERROR", "unknown action " + action]);
}
}
catch (err) {
log("worker error:" + err.message + "\n" + err.stack);
//pm(["ERROR"]);
var requestID = args[3];
parentPort.postMessage(["ERROR", requestID]);
}
function log(what) {
//pm(["LOG", what]);
//console.log("CC" + what);
}
function signalAlive() {
//pm(["SIGNAL_ALIVE"]);
parentPort.postMessage(["SIGNAL_ALIVE"]);
}
});
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var pathfinding_1 = __webpack_require__(21);
var navConfig = {
// map is -16352 to 16352 in the x direction and -8160 to 8160 in the y-direction
mapProperties: { left: -16352, top: -8160, right: 16352, bottom: 8160 },
maxGridLength: 2500,
marginStep: 500,
scale: 0.1
};
var BotNavigation = /** @class */ (function () {
function BotNavigation() {
}
BotNavigation.prototype.setLogFunction = function (logFunction) {
this.log = logFunction;
};
BotNavigation.prototype.setSignalAliveFunction = function (signalAlive) {
this.signalAlive = signalAlive;
};
BotNavigation.prototype.setMountains = function (mountains) {
this.mountains = mountains.map(function (m) {
return {
x: m.x * navConfig.scale,
y: m.y * navConfig.scale,
size: m.size * navConfig.scale,
};
});
};
BotNavigation.prototype.getGrid = function (width, height, left, top) {
var grid = new pathfinding_1.Grid(Math.ceil(width), Math.ceil(height));
this.mountains.forEach(function (mountain) {
if (mountain.x < left - mountain.size || mountain.x > left + width + mountain.size) {
return;
}
if (mountain.y < top - mountain.size || mountain.y > top + height + mountain.size) {
return;
}
// remove walkability of this mountain
var mountainLeft = mountain.x - mountain.size;
var mountainRight = mountain.x + mountain.size;
var mountainTop = mountain.y - mountain.size;
var mountainBottom = mountain.y + mountain.size;
for (var i = mountainLeft; i <= mountainRight; i++) {
for (var j = mountainTop; j <= mountainBottom; j++) {
var gridX = Math.floor(i - left);
var gridY = Math.floor(j - top);
if (gridX < 0 || gridX >= width || gridY < 0 || gridY >= height) {
continue;
}
grid.setWalkableAt(gridX, gridY, false);
}
}
});
return grid;
};
BotNavigation.prototype.isValid = function (pos) {
var margin = 32 * navConfig.scale;
return pos.x > navConfig.mapProperties.left * navConfig.scale + margin &&
pos.x < navConfig.mapProperties.right * navConfig.scale - margin &&
pos.y > navConfig.mapProperties.top * navConfig.scale + margin &&
pos.y < navConfig.mapProperties.bottom * navConfig.scale - margin;
};
BotNavigation.prototype.scale = function (pos) {
if (pos.scale) {
// has already been scaled
return pos;
}
return {
x: pos.x * navConfig.scale,
y: pos.y * navConfig.scale,
scale: navConfig.scale
};
};
BotNavigation.prototype.findPath = function (myPos, otherPos, requestID, margin) {
if (margin === void 0) { margin = 0; }
this.signalAlive();
myPos = this.scale(myPos);
otherPos = this.scale(otherPos);
if (!this.isValid(myPos)) {
var posLog = "";
if (myPos) {
posLog = myPos.x + "," + myPos.y;
}
if (log_enabled) this.log("myPos " + posLog + " is not valid for " + requestID);
return [];
}
if (!this.isValid(otherPos)) {
var posLog = "";
if (otherPos) {
posLog = otherPos.x + "," + otherPos.y;
}
if (log_enabled) this.log("otherPos " + posLog + " is not valid for " + requestID);
return [];
}
var halvarin = margin / 2;
var gridLeft;
var gridWidth = Math.min(navConfig.maxGridLength, Math.abs(otherPos.x - myPos.x) + margin);
if (otherPos.x > myPos.x) {
gridLeft = myPos.x - halvarin;
}
else {
gridLeft = myPos.x - gridWidth + 1 + halvarin;
}
if (gridLeft < navConfig.mapProperties.left * navConfig.scale) {
gridLeft = navConfig.mapProperties.left * navConfig.scale;
}
if (gridLeft + gridWidth > navConfig.mapProperties.right * navConfig.scale) {
gridLeft = navConfig.mapProperties.right * navConfig.scale - gridWidth - 1;
}
var gridTop;
var gridHeight = Math.min(navConfig.maxGridLength, Math.abs(otherPos.y - myPos.y) + margin);
if (otherPos.y > myPos.y) {
gridTop = myPos.y - halvarin;
}
else {
gridTop = myPos.y - gridHeight + 1 + halvarin;
}
if (gridTop < navConfig.mapProperties.top * navConfig.scale) {
gridTop = navConfig.mapProperties.top * navConfig.scale;
}
if (gridTop + gridHeight > navConfig.mapProperties.bottom * navConfig.scale) {
gridTop = navConfig.mapProperties.bottom * navConfig.scale - gridHeight - 1;
}
// get grid with mountains
var grid = this.getGrid(gridWidth, gridHeight, gridLeft, gridTop);
var BestFirstFinder2 = pathfinding_1.BestFirstFinder; // @types definitions are not correct
var finder = new BestFirstFinder2({
allowDiagonal: true
});
var fromX = Math.floor(myPos.x - gridLeft);
var fromY = Math.floor(myPos.y - gridTop);
var toX = otherPos.x - gridLeft;
var toY = otherPos.y - gridTop;
// target may not be "visible" in our grid
if (toX < 0) {
toX = 0;
}
if (toX >= gridWidth) {
toX = gridWidth - 1;
}
var searchDirection = 1;
if (toY < 0) {
toY = 0;
}
if (toY >= gridHeight) {
toY = gridHeight - 1;
searchDirection = -1;
}
toX = Math.floor(toX);
toY = Math.floor(toY);
// prevent to round to an unwalkable place: go up or down until a walkable place was found
while (!grid.isWalkableAt(toX, toY) && toY > 0 && toY < gridHeight - 1) {
toY += searchDirection;
}
while (!grid.isWalkableAt(fromX, fromY) && fromY > 0 && fromY < gridHeight - 1) {
fromY += searchDirection;
}
//fix?
if (toX < 0) {
toX = 0;
}
if (toX >= gridWidth) {
toX = gridWidth - 1;
}
if (fromX < 0) {
fromX = 0;
}
if (fromX >= gridWidth) {
fromX = gridWidth - 1;
}
if (toY < 0) {