/
DijkstraMap.java
3403 lines (3181 loc) · 161 KB
/
DijkstraMap.java
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
package squidpony.performance.alternate;
import squidpony.GwtCompatibility;
import squidpony.annotation.GwtIncompatible;
import squidpony.squidai.Threat;
import squidpony.squidgrid.*;
import squidpony.squidmath.*;
import java.util.*;
/**
* An alternative to AStarSearch when you want to fully explore a search space, or when you want a gradient floodfill.
* If you can't remember how to spell this, just remember: Does It Just Know Stuff? That's Really Awesome!
* Created by Tommy Ettinger on 4/4/2015.
*/
public class DijkstraMap {
/**
* The type of heuristic to use.
*/
public enum Measurement {
/**
* The distance it takes when only the four primary directions can be
* moved in. The default.
*/
MANHATTAN,
/**
* The distance it takes when diagonal movement costs the same as
* cardinal movement.
*/
CHEBYSHEV,
/**
* The distance it takes as the crow flies. This will NOT affect movement cost when calculating a path,
* only the preferred squares to travel to (resulting in drastically more reasonable-looking paths).
*/
EUCLIDEAN
}
/**
* This affects how distance is measured on diagonal directions vs. orthogonal directions. MANHATTAN should form a
* diamond shape on a featureless map, while CHEBYSHEV and EUCLIDEAN will form a square. EUCLIDEAN does not affect
* the length of paths, though it will change the DijkstraMap's gradientMap to have many non-integer values, and
* that in turn will make paths this finds much more realistic and smooth (favoring orthogonal directions unless a
* diagonal one is a better option).
*/
public Measurement measurement = Measurement.MANHATTAN;
/**
* Stores which parts of the map are accessible and which are not. Should not be changed unless the actual physical
* terrain has changed. You should call initialize() with a new map instead of changing this directly.
*/
public double[][] physicalMap;
/**
* The frequently-changing values that are often the point of using this class; goals will have a value of 0, and
* any cells that can have a character reach a goal in n steps will have a value of n. Cells that cannot be
* entered because they are solid will have a very high value equal to the WALL constant in this class, and cells
* that cannot be entered because they cannot reach a goal will have a different very high value equal to the
* DARK constant in this class.
*/
public double[][] gradientMap;
/**
* A 2D array of modifiers to apply to the perceived safety of an area; modifiers go up when deteriorate() is
* called, which makes the cells specified in that method call more dangerous (usually because staying in one place
* is perceived as risky).
*/
public double[][] safetyMap;
/**
* This stores the entry cost multipliers for each cell; that is, a value of 1.0 is a normal, unmodified cell, but
* a value of 0.5 can be entered easily (two cells of its cost can be entered for the cost of one 1.0 cell), and a
* value of 2.0 can only be entered with difficulty (one cell of its cost can be entered for the cost of two 1.0
* cells). Unlike the measurement field, this does affect the length of paths, as well as the numbers assigned
* to gradientMap during a scan. The values for walls are identical to the value used by gradientMap, that is, this
* class' WALL static final field. Floors, however, are never given FLOOR as a value, and default to 1.0 .
*/
public double[][] costMap = null;
/**
* Height of the map. Exciting stuff. Don't change this, instead call initialize().
*/
public int height;
/**
* Width of the map. Exciting stuff. Don't change this, instead call initialize().
*/
public int width;
/**
* The latest path that was obtained by calling findPath(). It will not contain the value passed as a starting
* cell; only steps that require movement will be included, and so if the path has not been found or a valid
* path toward a goal is impossible, this ArrayList will be empty.
*/
public ArrayList<Coord> path = new ArrayList<>();
/**
* Goals are always marked with 0.
*/
public static final double GOAL = 0.0;
/**
* Floor cells, which include any walkable cell, are marked with a high number equal to 999200.0 .
*/
public static final double FLOOR = 999200.0;
/**
* Walls, which are solid no-entry cells, are marked with a high number equal to 999500.0 .
*/
public static final double WALL = 999500.0;
/**
* This is used to mark cells that the scan couldn't reach, and these dark cells are marked with a high number
* equal to 999800.0 .
*/
public static final double DARK = 999800.0;
/**
* Goals that pathfinding will seek out. The Double value should almost always be 0.0 , the same as the static GOAL
* constant in this class.
*/
public LinkedHashMap<Coord, Double> goals;
private LinkedHashMap<Coord, Double> fresh, closed, open;
/**
* The RNG used to decide which one of multiple equally-short paths to take.
*/
public RNG rng;
private int frustration = 0;
public Coord[][] targetMap;
private boolean initialized = false;
private int mappedCount = 0;
public int getMappedCount() {
return mappedCount;
}
/**
* Construct a DijkstraMap without a level to actually scan. If you use this constructor, you must call an
* initialize() method before using this class.
*/
public DijkstraMap() {
rng = new RNG(new LightRNG());
path = new ArrayList<>();
goals = new LinkedHashMap<>();
fresh = new LinkedHashMap<>();
closed = new LinkedHashMap<>();
open = new LinkedHashMap<>();
}
/**
* Construct a DijkstraMap without a level to actually scan. This constructor allows you to specify an RNG before
* it is ever used in this class. If you use this constructor, you must call an initialize() method before using
* any other methods in the class.
*/
public DijkstraMap(RNG random) {
rng = random;
path = new ArrayList<>();
goals = new LinkedHashMap<>();
fresh = new LinkedHashMap<>();
closed = new LinkedHashMap<>();
open = new LinkedHashMap<>();
}
/**
* Used to construct a DijkstraMap from the output of another.
*
* @param level
*/
public DijkstraMap(final double[][] level) {
rng = new RNG(new LightRNG());
path = new ArrayList<>();
goals = new LinkedHashMap<>();
fresh = new LinkedHashMap<>();
closed = new LinkedHashMap<>();
open = new LinkedHashMap<>();
initialize(level);
}
/**
* Used to construct a DijkstraMap from the output of another, specifying a distance calculation.
*
* @param level
* @param measurement
*/
public DijkstraMap(final double[][] level, Measurement measurement) {
rng = new RNG(new LightRNG());
this.measurement = measurement;
path = new ArrayList<>();
goals = new LinkedHashMap<>();
fresh = new LinkedHashMap<>();
closed = new LinkedHashMap<>();
open = new LinkedHashMap<>();
initialize(level);
}
/**
* Constructor meant to take a char[][] returned by DungeonGen.generate(), or any other
* char[][] where '#' means a wall and anything else is a walkable tile. If you only have
* a map that uses box-drawing characters, use DungeonUtility.linesToHashes() to get a
* map that can be used here.
*
* @param level
*/
public DijkstraMap(final char[][] level) {
rng = new RNG(new LightRNG());
path = new ArrayList<>();
goals = new LinkedHashMap<>();
fresh = new LinkedHashMap<>();
closed = new LinkedHashMap<>();
open = new LinkedHashMap<>();
initialize(level);
}
/**
* Constructor meant to take a char[][] returned by DungeonGen.generate(), or any other
* char[][] where '#' means a wall and anything else is a walkable tile. If you only have
* a map that uses box-drawing characters, use DungeonUtility.linesToHashes() to get a
* map that can be used here. Also takes an RNG that ensures predictable path choices given
* otherwise identical inputs and circumstances.
*
* @param level
* @param rng The RNG to use for certain decisions; only affects find* methods like findPath, not scan.
*/
public DijkstraMap(final char[][] level, RNG rng) {
this.rng = rng;
path = new ArrayList<>();
goals = new LinkedHashMap<>();
fresh = new LinkedHashMap<>();
closed = new LinkedHashMap<>();
open = new LinkedHashMap<>();
initialize(level);
}
/**
* Constructor meant to take a char[][] returned by DungeonGen.generate(), or any other
* char[][] where one char means a wall and anything else is a walkable tile. If you only have
* a map that uses box-drawing characters, use DungeonUtility.linesToHashes() to get a
* map that can be used here. You can specify the character used for walls.
*
* @param level
*/
public DijkstraMap(final char[][] level, char alternateWall) {
rng = new RNG(new LightRNG());
path = new ArrayList<>();
goals = new LinkedHashMap<>();
fresh = new LinkedHashMap<>();
closed = new LinkedHashMap<>();
open = new LinkedHashMap<>();
initialize(level, alternateWall);
}
/**
* Constructor meant to take a char[][] returned by DungeonGen.generate(), or any other
* char[][] where '#' means a wall and anything else is a walkable tile. If you only have
* a map that uses box-drawing characters, use DungeonUtility.linesToHashes() to get a
* map that can be used here. This constructor specifies a distance measurement.
*
* @param level
* @param measurement
*/
public DijkstraMap(final char[][] level, Measurement measurement) {
rng = new RNG(new LightRNG());
path = new ArrayList<>();
this.measurement = measurement;
goals = new LinkedHashMap<>();
fresh = new LinkedHashMap<>();
closed = new LinkedHashMap<>();
open = new LinkedHashMap<>();
initialize(level);
}
/**
* Constructor meant to take a char[][] returned by DungeonGen.generate(), or any other
* char[][] where '#' means a wall and anything else is a walkable tile. If you only have
* a map that uses box-drawing characters, use DungeonUtility.linesToHashes() to get a
* map that can be used here. Also takes a distance measurement and an RNG that ensures
* predictable path choices given otherwise identical inputs and circumstances.
*
* @param level
* @param rng The RNG to use for certain decisions; only affects find* methods like findPath, not scan.
*/
public DijkstraMap(final char[][] level, Measurement measurement, RNG rng) {
this.rng = rng;
path = new ArrayList<>();
this.measurement = measurement;
goals = new LinkedHashMap<>();
fresh = new LinkedHashMap<>();
closed = new LinkedHashMap<>();
open = new LinkedHashMap<>();
initialize(level);
}
/**
* Used to initialize or re-initialize a DijkstraMap that needs a new PhysicalMap because it either wasn't given
* one when it was constructed, or because the contents of the terrain have changed permanently (not if a
* creature moved; for that you pass the positions of creatures that block paths to scan() or findPath() ).
*
* @param level
* @return
*/
public DijkstraMap initialize(final double[][] level) {
width = level.length;
height = level[0].length;
gradientMap = new double[width][height];
safetyMap = new double[width][height];
physicalMap = new double[width][height];
costMap = new double[width][height];
targetMap = new Coord[width][height];
for (int x = 0; x < width; x++) {
System.arraycopy(level[x], 0, gradientMap[x], 0, height);
System.arraycopy(level[x], 0, physicalMap[x], 0, height);
Arrays.fill(costMap[x], 1.0);
}
initialized = true;
return this;
}
/**
* Used to initialize or re-initialize a DijkstraMap that needs a new PhysicalMap because it either wasn't given
* one when it was constructed, or because the contents of the terrain have changed permanently (not if a
* creature moved; for that you pass the positions of creatures that block paths to scan() or findPath() ).
*
* @param level
* @return
*/
public DijkstraMap initialize(final char[][] level) {
width = level.length;
height = level[0].length;
gradientMap = new double[width][height];
safetyMap = new double[width][height];
physicalMap = new double[width][height];
costMap = new double[width][height];
targetMap = new Coord[width][height];
for (int x = 0; x < width; x++) {
Arrays.fill(costMap[x], 1.0);
for (int y = 0; y < height; y++) {
double t = (level[x][y] == '#') ? WALL : FLOOR;
gradientMap[x][y] = t;
physicalMap[x][y] = t;
}
}
initialized = true;
return this;
}
/**
* Used to initialize or re-initialize a DijkstraMap that needs a new PhysicalMap because it either wasn't given
* one when it was constructed, or because the contents of the terrain have changed permanently (not if a
* creature moved; for that you pass the positions of creatures that block paths to scan() or findPath() ). This
* initialize() method allows you to specify an alternate wall char other than the default character, '#' .
*
* @param level
* @param alternateWall
* @return
*/
public DijkstraMap initialize(final char[][] level, char alternateWall) {
width = level.length;
height = level[0].length;
gradientMap = new double[width][height];
safetyMap = new double[width][height];
physicalMap = new double[width][height];
costMap = new double[width][height];
targetMap = new Coord[width][height];
for (int x = 0; x < width; x++) {
Arrays.fill(costMap[x], 1.0);
for (int y = 0; y < height; y++) {
double t = (level[x][y] == alternateWall) ? WALL : FLOOR;
gradientMap[x][y] = t;
physicalMap[x][y] = t;
}
}
initialized = true;
return this;
}
/**
* Used to initialize the entry cost modifiers for games that require variable costs to enter squares. This expects
* a char[][] of the same exact dimensions as the 2D array that was used to previously initialize() this
* DijkstraMap, treating the '#' char as a wall (impassable) and anything else as having a normal cost to enter.
* The costs can be accessed later by using costMap directly (which will have a valid value when this does not
* throw an exception), or by calling setCost().
*
* @param level a 2D char array that uses '#' for walls
* @return this DijkstraMap for chaining.
*/
public DijkstraMap initializeCost(final char[][] level) {
if (!initialized) throw new IllegalStateException("DijkstraMap must be initialized first!");
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
costMap[x][y] = (level[x][y] == '#') ? WALL : 1.0;
}
}
return this;
}
/**
* Used to initialize the entry cost modifiers for games that require variable costs to enter squares. This expects
* a char[][] of the same exact dimensions as the 2D array that was used to previously initialize() this
* DijkstraMap, treating the '#' char as a wall (impassable) and anything else as having a normal cost to enter.
* The costs can be accessed later by using costMap directly (which will have a valid value when this does not
* throw an exception), or by calling setCost().
* <p/>
* This method allows you to specify an alternate wall char other than the default character, '#' .
*
* @param level a 2D char array that uses alternateChar for walls.
* @param alternateWall a char to use to represent walls.
* @return this DijkstraMap for chaining.
*/
public DijkstraMap initializeCost(final char[][] level, char alternateWall) {
if (!initialized) throw new IllegalStateException("DijkstraMap must be initialized first!");
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
costMap[x][y] = (level[x][y] == alternateWall) ? WALL : 1.0;
}
}
return this;
}
/**
* Used to initialize the entry cost modifiers for games that require variable costs to enter squares. This expects
* a double[][] of the same exact dimensions as the 2D array that was used to previously initialize() this
* DijkstraMap, using the exact values given in costs as the values to enter cells, even if they aren't what this
* class would assign normally -- walls and other impassable values should be given WALL as a value, however.
* The costs can be accessed later by using costMap directly (which will have a valid value when this does not
* throw an exception), or by calling setCost().
* <p/>
* This method should be slightly more efficient than the other initializeCost methods.
*
* @param costs a 2D double array that already has the desired cost values
* @return this DijkstraMap for chaining.
*/
public DijkstraMap initializeCost(final double[][] costs) {
if (!initialized) throw new IllegalStateException("DijkstraMap must be initialized first!");
costMap = new double[width][height];
for (int x = 0; x < width; x++) {
System.arraycopy(costs[x], 0, costMap[x], 0, height);
}
return this;
}
/**
* Gets the appropriate DijkstraMap.Measurement to pass to a constructor if you already have a Radius.
* Matches SQUARE or CUBE to CHEBYSHEV, DIAMOND or OCTAHEDRON to MANHATTAN, and CIRCLE or SPHERE to EUCLIDEAN.
*
* @param radius the Radius to find the corresponding Measurement for
* @return a DijkstraMap.Measurement that matches radius; SQUARE to CHEBYSHEV, DIAMOND to MANHATTAN, etc.
*/
public static Measurement findMeasurement(Radius radius) {
if (radius.equals2D(Radius.SQUARE))
return DijkstraMap.Measurement.CHEBYSHEV;
else if (radius.equals2D(Radius.DIAMOND))
return DijkstraMap.Measurement.MANHATTAN;
else
return DijkstraMap.Measurement.EUCLIDEAN;
}
/**
* Gets the appropriate Radius corresponding to a DijkstraMap.Measurement.
* Matches CHEBYSHEV to SQUARE, MANHATTAN to DIAMOND, and EUCLIDEAN to CIRCLE.
*
* @param measurement the Measurement to find the corresponding Radius for
* @return a DijkstraMap.Measurement that matches radius; CHEBYSHEV to SQUARE, MANHATTAN to DIAMOND, etc.
*/
public static Radius findRadius(Measurement measurement) {
switch (measurement) {
case CHEBYSHEV:
return Radius.SQUARE;
case EUCLIDEAN:
return Radius.CIRCLE;
default:
return Radius.DIAMOND;
}
}
/**
* Resets the gradientMap to its original value from physicalMap.
*/
public void resetMap() {
if (!initialized) return;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
gradientMap[x][y] = physicalMap[x][y];
}
}
}
/**
* Resets the targetMap (which is only assigned in the first place if you use findTechniquePath() ).
*/
public void resetTargetMap() {
if (!initialized) return;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
targetMap[x][y] = null;
}
}
}
/**
* Resets the targetMap (which is only assigned in the first place if you use findTechniquePath() ).
*/
public void resetSafetyMap() {
if (!initialized) return;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
safetyMap[x][y] = 0.0;
}
}
}
/**
* Resets this DijkstraMap to a state with no goals, no discovered path, and no changes made to gradientMap
* relative to physicalMap.
*/
public void reset() {
resetMap();
resetTargetMap();
goals.clear();
path.clear();
closed.clear();
fresh.clear();
open.clear();
frustration = 0;
}
/**
* Marks a cell as a goal for pathfinding, unless the cell is a wall or unreachable area (then it does nothing).
*
* @param x
* @param y
*/
public void setGoal(int x, int y) {
if (!initialized) return;
if (physicalMap[x][y] > FLOOR) {
return;
}
goals.put(Coord.get(x, y), GOAL);
}
/**
* Marks a cell as a goal for pathfinding, unless the cell is a wall or unreachable area (then it does nothing).
*
* @param pt
*/
public void setGoal(Coord pt) {
if (!initialized) return;
if (physicalMap[pt.x][pt.y] > FLOOR) {
return;
}
goals.put(pt, GOAL);
}
/**
* Marks a cell's cost for pathfinding as cost, unless the cell is a wall or unreachable area (then it always sets
* the cost to the value of the WALL field).
*
* @param pt
* @param cost
*/
public void setCost(Coord pt, double cost) {
if (!initialized) return;
if (physicalMap[pt.x][pt.y] > FLOOR) {
costMap[pt.x][pt.y] = WALL;
return;
}
costMap[pt.x][pt.y] = cost;
}
/**
* Marks a cell's cost for pathfinding as cost, unless the cell is a wall or unreachable area (then it always sets
* the cost to the value of the WALL field).
*
* @param x
* @param y
* @param cost
*/
public void setCost(int x, int y, double cost) {
if (!initialized) return;
if (physicalMap[x][y] > FLOOR) {
costMap[x][y] = WALL;
return;
}
costMap[x][y] = cost;
}
/**
* Marks a specific cell in gradientMap as completely impossible to enter.
*
* @param x
* @param y
*/
public void setOccupied(int x, int y) {
if (!initialized) return;
gradientMap[x][y] = WALL;
}
/**
* Reverts a cell to the value stored in the original state of the level as known by physicalMap.
*
* @param x
* @param y
*/
public void resetCell(int x, int y) {
if (!initialized) return;
gradientMap[x][y] = physicalMap[x][y];
}
/**
* Reverts a cell to the value stored in the original state of the level as known by physicalMap.
*
* @param pt
*/
public void resetCell(Coord pt) {
if (!initialized) return;
gradientMap[pt.x][pt.y] = physicalMap[pt.x][pt.y];
}
/**
* Used to remove all goals and undo any changes to gradientMap made by having a goal present.
*/
public void clearGoals() {
if (!initialized)
return;
for (Coord entry : goals.keySet()) {
resetCell(entry);
}
goals.clear();
}
protected void setFresh(int x, int y, double counter) {
if (!initialized) return;
gradientMap[x][y] = counter;
fresh.put(Coord.get(x, y), counter);
}
protected void setFresh(final Coord pt, double counter) {
if (!initialized) return;
gradientMap[pt.x][pt.y] = counter;
fresh.put(pt, counter);
}
/**
* Used in conjunction with methods that depend on finding cover, like findCoveredAttackPath(), this method causes
* specified risky points to be considered less safe, and will encourage a pathfinder to keep moving toward a goal
* instead of just staying in cover forever (or until an enemy moves around the cover and ambushes the pathfinder).
* Typically, you call deteriorate() with the current Coord position of the pathfinder and any Coords they stayed at
* earlier along a path, and you do this once every turn or once every few turns, depending on how aggressively the
* pathfinder should seek a goal.
*
* @param riskyPoints a List of Coord that should be considered more risky to stay at with each call.
* @return the current safetyMap.
*/
public double[][] deteriorate(List<Coord> riskyPoints) {
return deteriorate(riskyPoints.toArray(new Coord[riskyPoints.size()]));
}
/**
* Used in conjunction with methods that depend on finding cover, like findCoveredAttackPath(), this method causes
* specified risky points to be considered less safe, and will encourage a pathfinder to keep moving toward a goal
* instead of just staying in cover forever (or until an enemy moves around the cover and ambushes the pathfinder).
* Typically, you call deteriorate() with the current Coord position of the pathfinder and any Coords they stayed at
* earlier along a path, and you do this once every turn or once every few turns, depending on how aggressively the
* pathfinder should seek a goal.
*
* @param riskyPoints a vararg or array of Coord that should be considered more risky to stay at with each call.
* @return the current safetyMap.
*/
public double[][] deteriorate(Coord... riskyPoints) {
if (!initialized)
return null;
Coord c;
for (int i = 0; i < riskyPoints.length; i++) {
c = riskyPoints[i];
safetyMap[c.x][c.y] += 1.0;
}
return safetyMap;
}
/**
* Used in conjunction with methods that depend on finding cover, like findCoveredAttackPath(), this method causes
* specified safer points to be considered more safe, and will make a pathfinder more likely to enter those places
* if they were considered dangerous earlier (due to calling deteriorate()).
* <p/>
* Typically, you call relax() with previous Coords a pathfinder stayed at that should be safer now than they were
* at some previous point in time, and you might do this when no one has been attacked in a while or when the AI is
* sure that a threat has been neutralized or no longer threatens a safer point.
*
* @param saferPoints a List of Coord that should be considered less risky to stay at with each call.
* @return the current safetyMap.
*/
public double[][] relax(List<Coord> saferPoints) {
return relax(saferPoints.toArray(new Coord[saferPoints.size()]));
}
/**
* Used in conjunction with methods that depend on finding cover, like findCoveredAttackPath(), this method causes
* specified safer points to be considered more safe, and will make a pathfinder more likely to enter those places
* if they were considered dangerous earlier (due to calling deteriorate()).
* <p/>
* Typically, you call relax() with previous Coords a pathfinder stayed at that should be safer now than they were
* at some previous point in time, and you might do this when no one has been attacked in a while or when the AI is
* sure that a threat has been neutralized or no longer threatens a safer point.
*
* @param saferPoints a vararg or array of Coord that should be considered less risky to stay at with each call.
* @return the current safetyMap.
*/
public double[][] relax(Coord... saferPoints) {
if (!initialized)
return null;
Coord c;
for (int i = 0; i < saferPoints.length; i++) {
c = saferPoints[i];
safetyMap[c.x][c.y] -= 1.0;
if (safetyMap[c.x][c.y] < 0.0)
safetyMap[c.x][c.y] = 0.0;
}
return safetyMap;
}
/**
* Recalculate the Dijkstra map and return it. Cells that were marked as goals with setGoal will have
* a value of 0, the cells adjacent to goals will have a value of 1, and cells progressively further
* from goals will have a value equal to the distance from the nearest goal. The exceptions are walls,
* which will have a value defined by the WALL constant in this class, and areas that the scan was
* unable to reach, which will have a value defined by the DARK constant in this class (typically,
* these areas should not be used to place NPCs or items and should be filled with walls). This uses the
* current measurement.
*
* @param impassable A Set of Position keys representing the locations of enemies or other moving obstacles to a
* path that cannot be moved through; this can be null if there are no such obstacles.
* @return A 2D double[width][height] using the width and height of what this knows about the physical map.
*/
public double[][] scan(Set<Coord> impassable) {
if (!initialized) return null;
if (impassable == null)
impassable = new LinkedHashSet<>();
LinkedHashMap<Coord, Double> blocking = new LinkedHashMap<>(impassable.size());
for (Coord pt : impassable) {
blocking.put(pt, WALL);
}
closed.putAll(blocking);
for (Map.Entry<Coord, Double> entry : goals.entrySet()) {
if (closed.containsKey(entry.getKey()))
closed.remove(entry.getKey());
gradientMap[entry.getKey().x][entry.getKey().y] = entry.getValue();
}
double currentLowest = 999000;
LinkedHashMap<Coord, Double> lowest = new LinkedHashMap<>();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (gradientMap[x][y] > FLOOR && !goals.containsKey(Coord.get(x, y)))
closed.put(Coord.get(x, y), physicalMap[x][y]);
else if (gradientMap[x][y] < currentLowest) {
currentLowest = gradientMap[x][y];
lowest.clear();
lowest.put(Coord.get(x, y), currentLowest);
} else if (gradientMap[x][y] == currentLowest) {
lowest.put(Coord.get(x, y), currentLowest);
}
}
}
int numAssigned = lowest.size();
mappedCount = goals.size();
open.putAll(lowest);
Direction[] dirs = (measurement == Measurement.MANHATTAN) ? Direction.CARDINALS : Direction.OUTWARDS;
while (numAssigned > 0) {
// ++iter;
numAssigned = 0;
for (Map.Entry<Coord, Double> cell : open.entrySet()) {
for (int d = 0; d < dirs.length; d++) {
Coord adj = cell.getKey().translate(dirs[d].deltaX, dirs[d].deltaY);
if (adj.x < 0 || adj.y < 0 || width <= adj.x || height <= adj.y)
/* Outside the map */
continue;
double h = heuristic(dirs[d]);
if (!closed.containsKey(adj) && !open.containsKey(adj) && gradientMap[cell.getKey().x][cell.getKey().y] + h * costMap[adj.x][adj.y] < gradientMap[adj.x][adj.y]) {
setFresh(adj, cell.getValue() + h * costMap[adj.x][adj.y]);
++numAssigned;
++mappedCount;
}
}
}
// closed.putAll(open);
open = new LinkedHashMap<>(fresh);
fresh.clear();
}
closed.clear();
open.clear();
double[][] gradientClone = new double[width][height];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (gradientMap[x][y] == FLOOR) {
gradientMap[x][y] = DARK;
}
}
System.arraycopy(gradientMap[x], 0, gradientClone[x], 0, height);
}
return gradientClone;
}
/**
* Recalculate the Dijkstra map up to a limit and return it. Cells that were marked as goals with setGoal will have
* a value of 0, the cells adjacent to goals will have a value of 1, and cells progressively further
* from goals will have a value equal to the distance from the nearest goal. If a cell would take more steps to
* reach than the given limit, it will have a value of DARK if it was passable instead of the distance. The
* exceptions are walls, which will have a value defined by the WALL constant in this class, and areas that the scan
* was unable to reach, which will have a value defined by the DARK constant in this class. This uses the
* current measurement.
*
* @param limit The maximum number of steps to scan outward from a goal.
* @param impassable A Set of Position keys representing the locations of enemies or other moving obstacles to a
* path that cannot be moved through; this can be null if there are no such obstacles.
* @return A 2D double[width][height] using the width and height of what this knows about the physical map.
*/
public double[][] partialScan(int limit, Set<Coord> impassable) {
if (!initialized) return null;
if (impassable == null)
impassable = new LinkedHashSet<>();
LinkedHashMap<Coord, Double> blocking = new LinkedHashMap<>(impassable.size());
for (Coord pt : impassable) {
blocking.put(pt, WALL);
}
closed.putAll(blocking);
for (Map.Entry<Coord, Double> entry : goals.entrySet()) {
if (closed.containsKey(entry.getKey()))
closed.remove(entry.getKey());
gradientMap[entry.getKey().x][entry.getKey().y] = entry.getValue();
}
double currentLowest = 999000;
LinkedHashMap<Coord, Double> lowest = new LinkedHashMap<>();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (gradientMap[x][y] > FLOOR && !goals.containsKey(Coord.get(x, y)))
closed.put(Coord.get(x, y), physicalMap[x][y]);
else if (gradientMap[x][y] < currentLowest) {
currentLowest = gradientMap[x][y];
lowest.clear();
lowest.put(Coord.get(x, y), currentLowest);
} else if (gradientMap[x][y] == currentLowest) {
lowest.put(Coord.get(x, y), currentLowest);
}
}
}
int numAssigned = lowest.size();
mappedCount = goals.size();
open.putAll(lowest);
Direction[] dirs = (measurement == Measurement.MANHATTAN) ? Direction.CARDINALS : Direction.OUTWARDS;
int iter = 0;
while (numAssigned > 0 && iter < limit) {
// ++iter;
numAssigned = 0;
for (Map.Entry<Coord, Double> cell : open.entrySet()) {
for (int d = 0; d < dirs.length; d++) {
Coord adj = cell.getKey().translate(dirs[d].deltaX, dirs[d].deltaY);
double h = heuristic(dirs[d]);
if (!closed.containsKey(adj) && !open.containsKey(adj) && gradientMap[cell.getKey().x][cell.getKey().y] + h * costMap[adj.x][adj.y] < gradientMap[adj.x][adj.y]) {
setFresh(adj, cell.getValue() + h * costMap[adj.x][adj.y]);
++numAssigned;
++mappedCount;
}
}
}
// closed.putAll(open);
open = new LinkedHashMap<>(fresh);
fresh.clear();
++iter;
}
closed.clear();
open.clear();
double[][] gradientClone = new double[width][height];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (gradientMap[x][y] == FLOOR) {
gradientMap[x][y] = DARK;
}
}
System.arraycopy(gradientMap[x], 0, gradientClone[x], 0, height);
}
return gradientClone;
}
/**
* Recalculate the Dijkstra map until it reaches a Coord in targets, then returns the first target found.
* This uses the current measurement.
*
* @param start the cell to use as the origin for finding the nearest target
* @param targets the Coords that this is trying to find; it will stop once it finds one
* @return the Coord that it found first.
*/
public Coord findNearest(Coord start, Set<Coord> targets) {
if (!initialized) return null;
if (targets == null)
return null;
if (targets.contains(start))
return start;
resetMap();
Coord start2 = start;
int xShift = width / 8, yShift = height / 8;
while (physicalMap[start.x][start.y] >= WALL && frustration < 50) {
start2 = Coord.get(Math.min(Math.max(1, start.x + rng.nextInt(1 + xShift * 2) - xShift), width - 2),
Math.min(Math.max(1, start.y + rng.nextInt(1 + yShift * 2) - yShift), height - 2));
}
if (closed.containsKey(start2))
closed.remove(start2);
gradientMap[start2.x][start2.y] = 0.0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (gradientMap[x][y] > FLOOR && !goals.containsKey(Coord.get(x, y)))
closed.put(Coord.get(x, y), physicalMap[x][y]);
}
}
int numAssigned = 1;
mappedCount = 1;
open.put(start2, 0.0);
Direction[] dirs = (measurement == Measurement.MANHATTAN) ? Direction.CARDINALS : Direction.OUTWARDS;
while (numAssigned > 0) {
// ++iter;
numAssigned = 0;
for (Map.Entry<Coord, Double> cell : open.entrySet()) {
for (int d = 0; d < dirs.length; d++) {
Coord adj = cell.getKey().translate(dirs[d].deltaX, dirs[d].deltaY);
double h = heuristic(dirs[d]);
if (!closed.containsKey(adj) && !open.containsKey(adj) &&
gradientMap[cell.getKey().x][cell.getKey().y] + h * costMap[adj.x][adj.y] < gradientMap[adj.x][adj.y]) {
setFresh(adj, cell.getValue() + h * costMap[adj.x][adj.y]);
++numAssigned;
++mappedCount;
if (targets.contains(adj)) {
fresh.clear();
closed.clear();
open.clear();
return adj;
}
}
}
}
// closed.putAll(open);
open = new LinkedHashMap<>(fresh);
fresh.clear();
}
closed.clear();
open.clear();
return null;
}
/**
* Recalculate the Dijkstra map until it reaches a Coord in targets, then returns the first target found.
* This uses the current measurement.
*
* @param start the cell to use as the origin for finding the nearest target
* @param targets the Coords that this is trying to find; it will stop once it finds one
* @return the Coord that it found first.
*/
public Coord findNearest(Coord start, Coord... targets) {
LinkedHashSet<Coord> tgts = new LinkedHashSet<>(targets.length);
Collections.addAll(tgts, targets);
return findNearest(start, tgts);
}
/**
* If you have a target or group of targets you want to pathfind to without scanning the full map, this can be good.
* It may find sub-optimal paths in the presence of costs to move into cells. It is useful when you want to move in
* a straight line to a known nearby goal.
*
* @param start your starting location
* @param targets an array or vararg of Coords to pathfind to the nearest of
* @return an ArrayList of Coord that goes from a cell adjacent to start and goes to one of the targets. Copy of path.
*/
public ArrayList<Coord> findShortcutPath(Coord start, Coord... targets) {
if (targets.length == 0) {
path.clear();
return new ArrayList<>(path);
}
Coord currentPos = findNearest(start, targets);
while (true) {
if (frustration > 500) {
path.clear();
break;
}
double best = gradientMap[currentPos.x][currentPos.y];
final Direction[] dirs = appendDir(shuffleDirs(rng), Direction.NONE);