-
-
Notifications
You must be signed in to change notification settings - Fork 302
/
LinearWaypointProvider.java
705 lines (631 loc) · 25.2 KB
/
LinearWaypointProvider.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
package net.citizensnpcs.trait.waypoint;
import java.util.AbstractList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.conversations.Conversation;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.util.Vector;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.citizensnpcs.Settings.Setting;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.ai.Goal;
import net.citizensnpcs.api.ai.GoalSelector;
import net.citizensnpcs.api.ai.Navigator;
import net.citizensnpcs.api.ai.event.CancelReason;
import net.citizensnpcs.api.ai.event.NavigatorCallback;
import net.citizensnpcs.api.astar.pathfinder.MinecraftBlockExaminer;
import net.citizensnpcs.api.command.CommandContext;
import net.citizensnpcs.api.command.CommandMessages;
import net.citizensnpcs.api.command.exception.CommandException;
import net.citizensnpcs.api.event.NPCDespawnEvent;
import net.citizensnpcs.api.event.NPCRemoveEvent;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.persistence.Persist;
import net.citizensnpcs.api.persistence.PersistenceLoader;
import net.citizensnpcs.api.util.DataKey;
import net.citizensnpcs.api.util.Messaging;
import net.citizensnpcs.editor.Editor;
import net.citizensnpcs.trait.waypoint.WaypointProvider.EnumerableWaypointProvider;
import net.citizensnpcs.trait.waypoint.triggers.TriggerEditPrompt;
import net.citizensnpcs.util.Messages;
import net.citizensnpcs.util.Util;
/**
* An ordered list of {@link Waypoint}s to walk between.
*/
public class LinearWaypointProvider implements EnumerableWaypointProvider {
private final Map<SourceDestinationPair, Iterable<Vector>> cachedPaths = Maps.newHashMap();
@Persist
private boolean cachePaths = Setting.DEFAULT_CACHE_WAYPOINT_PATHS.asBoolean();
private LinearWaypointGoal currentGoal;
@Persist
private boolean cycle = false;
private NPC npc;
private final List<Waypoint> waypoints = Lists.newArrayList();
public LinearWaypointProvider() {
}
public LinearWaypointProvider(NPC npc) {
this.npc = npc;
}
public void addWaypoint(Waypoint waypoint) {
waypoints.add(waypoint);
if (currentGoal != null) {
currentGoal.onProviderChanged();
}
}
public boolean cachePaths() {
return cachePaths;
}
@Override
public WaypointEditor createEditor(CommandSender sender, CommandContext args) {
if (args.hasFlag('h')) {
try {
if (args.getSenderLocation() != null) {
waypoints.add(new Waypoint(args.getSenderLocation()));
}
} catch (CommandException e) {
Messaging.sendError(sender, e.getMessage());
}
return null;
} else if (args.hasValueFlag("at")) {
try {
Location location = CommandContext.parseLocation(args.getSenderLocation(), args.getFlag("at"));
if (location != null) {
waypoints.add(new Waypoint(location));
}
} catch (CommandException e) {
Messaging.sendError(sender, e.getMessage());
}
return null;
} else if (args.hasFlag('c')) {
waypoints.clear();
cachedPaths.clear();
return null;
} else if (args.hasFlag('l')) {
if (waypoints.size() > 0) {
waypoints.remove(waypoints.size() - 1);
}
return null;
} else if (args.hasFlag('p')) {
setPaused(!isPaused());
return null;
} else if (args.hasFlag('k')) {
cachePaths = !cachePaths;
return null;
} else if (!(sender instanceof Player)) {
Messaging.sendErrorTr(sender, CommandMessages.MUST_BE_INGAME);
return null;
}
return new LinearWaypointEditor((Player) sender);
}
public boolean cycleWaypoints() {
return cycle;
}
public Waypoint getCurrentWaypoint() {
if (currentGoal != null && currentGoal.currentDestination != null) {
return currentGoal.currentDestination;
}
return null;
}
@Override
public boolean isPaused() {
return currentGoal == null ? false : currentGoal.isPaused();
}
@Override
public void load(DataKey key) {
for (DataKey root : key.getRelative("points").getIntegerSubKeys()) {
Waypoint waypoint = PersistenceLoader.load(Waypoint.class, root);
if (waypoint == null)
continue;
waypoints.add(waypoint);
}
}
@Override
public void onRemove() {
if (currentGoal == null)
return;
currentGoal.onProviderChanged();
npc.getDefaultGoalController().removeGoal(currentGoal);
currentGoal = null;
}
@Override
public void onSpawn(NPC npc) {
this.npc = npc;
if (currentGoal == null) {
currentGoal = new LinearWaypointGoal();
npc.getDefaultGoalController().addGoal(currentGoal, 1);
}
}
@Override
public void save(DataKey key) {
key.removeKey("points");
DataKey root = key.getRelative("points");
for (int i = 0; i < waypoints.size(); ++i) {
PersistenceLoader.save(waypoints.get(i), root.getRelative(i));
}
}
public void setCachePaths(boolean cachePaths) {
this.cachePaths = cachePaths;
if (currentGoal != null) {
currentGoal.onProviderChanged();
}
}
public void setCycle(boolean cycle) {
this.cycle = cycle;
if (currentGoal != null) {
currentGoal.onProviderChanged();
}
}
@Override
public void setPaused(boolean paused) {
if (currentGoal != null) {
currentGoal.setPaused(paused);
}
}
/**
* Returns the modifiable list of waypoints.
*/
@Override
public Iterable<Waypoint> waypoints() {
return new AbstractList<Waypoint>() {
@Override
public void add(int index, Waypoint waypoint) {
waypoints.add(index, waypoint);
mod();
}
@Override
public boolean add(Waypoint waypoint) {
boolean val = waypoints.add(waypoint);
mod();
return val;
}
@Override
public void clear() {
waypoints.clear();
mod();
}
@Override
public Waypoint get(int index) {
return waypoints.get(index);
}
private void mod() {
if (currentGoal != null) {
currentGoal.onProviderChanged();
}
}
@Override
public Waypoint remove(int index) {
Waypoint val = waypoints.remove(index);
mod();
return val;
}
@Override
public boolean remove(Object waypoint) {
boolean val = waypoints.remove(waypoint);
mod();
return val;
}
@Override
public Waypoint set(int index, Waypoint elem) {
Waypoint val = waypoints.set(index, elem);
mod();
return val;
}
@Override
public int size() {
return waypoints.size();
}
};
}
private class LinearWaypointEditor extends WaypointEditor {
Conversation conversation;
boolean editing = true;
EntityMarkers<Waypoint> markers;
private final Player player;
private Waypoint selectedWaypoint;
private boolean showingMarkers = true;
private LinearWaypointEditor(Player player) {
this.player = player;
this.markers = new EntityMarkers<Waypoint>();
}
@Override
public void begin() {
Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_BEGIN);
if (showingMarkers) {
createWaypointMarkers();
}
}
private void clearWaypoints() {
waypoints.clear();
onWaypointsModified();
markers.destroyMarkers();
Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_WAYPOINTS_CLEARED);
}
private void createWaypointMarkers() {
for (int i = 0; i < waypoints.size(); i++) {
markers.createMarker(waypoints.get(i), waypoints.get(i).getLocation());
}
}
@Override
public void end() {
if (!editing)
return;
editing = false;
if (conversation != null) {
conversation.abandon();
}
Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_END);
markers.destroyMarkers();
}
private String formatLoc(Location location) {
return String.format("[[%d]], [[%d]], [[%d]]", location.getBlockX(), location.getBlockY(),
location.getBlockZ());
}
@Override
public Waypoint getCurrentWaypoint() {
if (waypoints.size() == 0 || !editing) {
return null;
}
return selectedWaypoint == null ? waypoints.get(waypoints.size() - 1) : selectedWaypoint;
}
private Location getLastWaypoint() {
if (waypoints.size() <= 1)
return null;
return waypoints.get(waypoints.size() - 1).getLocation();
}
@EventHandler
public void onNPCDespawn(NPCDespawnEvent event) {
if (event.getNPC().equals(npc)) {
Editor.leave(player);
}
}
@EventHandler
public void onNPCRemove(NPCRemoveEvent event) {
if (event.getNPC().equals(npc)) {
Editor.leave(player);
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) {
if (!event.getPlayer().equals(player))
return;
String message = event.getMessage();
if (message.equalsIgnoreCase("triggers")) {
event.setCancelled(true);
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), () -> {
conversation = TriggerEditPrompt.start(player, LinearWaypointEditor.this);
conversation.addConversationAbandonedListener(e -> {
setPaused(false);
conversation = null;
});
setPaused(true);
});
} else if (message.equalsIgnoreCase("clear")) {
event.setCancelled(true);
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), new Runnable() {
@Override
public void run() {
clearWaypoints();
}
});
} else if (message.equalsIgnoreCase("toggle path") || message.equalsIgnoreCase("markers")) {
event.setCancelled(true);
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), () -> togglePath());
} else if (message.equalsIgnoreCase("cycle")) {
event.setCancelled(true);
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), () -> {
cycle = !cycle;
Messaging.sendTr(event.getPlayer(), cycle ? Messages.LINEAR_WAYPOINT_EDITOR_CYCLE_SET
: Messages.LINEAR_WAYPOINT_EDITOR_CYCLE_UNSET);
});
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
if (!event.getPlayer().equals(player) || event.getAction() == Action.PHYSICAL || !npc.isSpawned()
|| event.getPlayer().getWorld() != npc.getEntity().getWorld() || Util.isOffHand(event))
return;
if (event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_AIR) {
if (event.getClickedBlock() == null)
return;
event.setCancelled(true);
Location at = event.getClickedBlock().getLocation().add(0, 1, 0);
Location prev = getLastWaypoint();
if (prev != null && prev.getWorld() == at.getWorld()) {
double distance = at.distance(prev);
double maxDistance = npc.getNavigator().getDefaultParameters().range();
if (distance > maxDistance) {
Messaging.sendErrorTr(player, Messages.LINEAR_WAYPOINT_EDITOR_RANGE_EXCEEDED, distance,
maxDistance, ChatColor.RED);
return;
}
}
Waypoint element = new Waypoint(at);
int idx = waypoints.size();
if (waypoints.indexOf(selectedWaypoint) != -1) {
idx = waypoints.indexOf(selectedWaypoint);
waypoints.add(idx, element);
} else {
waypoints.add(element);
}
if (showingMarkers) {
markers.createMarker(element, element.getLocation().clone());
}
Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_ADDED_WAYPOINT, formatLoc(at), idx);
} else if (waypoints.size() > 0 && !event.getPlayer().isSneaking()) {
event.setCancelled(true);
Waypoint waypoint = removeWaypoint(waypoints.size() - 1);
if (waypoint.equals(selectedWaypoint)) {
selectedWaypoint = null;
}
Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_REMOVED_WAYPOINT, waypoints.size());
}
onWaypointsModified();
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if (!player.equals(event.getPlayer()) || !showingMarkers || Util.isOffHand(event))
return;
int slot = -1;
double minDistance = Double.MAX_VALUE;
for (int i = 0; i < waypoints.size(); i++) {
Waypoint waypoint = waypoints.get(i);
double distance = waypoint.getLocation()
.distanceSquared(event.getRightClicked().getLocation().add(0, -1, 0));
if (minDistance > distance) {
minDistance = distance;
slot = i;
}
}
if (slot == -1)
return;
if (selectedWaypoint != null && waypoints.get(slot) == selectedWaypoint) {
removeWaypoint(slot);
Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_REMOVED_WAYPOINT, waypoints.size());
return;
}
selectedWaypoint = waypoints.get(slot);
Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_SELECTED_WAYPOINT,
formatLoc(selectedWaypoint.getLocation()));
}
private void onWaypointsModified() {
if (currentGoal != null) {
currentGoal.onProviderChanged();
}
if (conversation != null && getCurrentWaypoint() != null) {
getCurrentWaypoint().describeTriggers(player);
}
}
private Waypoint removeWaypoint(int idx) {
Waypoint waypoint = waypoints.remove(idx);
if (showingMarkers) {
markers.removeMarker(waypoint);
}
if (waypoint == selectedWaypoint) {
selectedWaypoint = null;
}
return waypoint;
}
private void togglePath() {
showingMarkers = !showingMarkers;
if (showingMarkers) {
createWaypointMarkers();
Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_SHOWING_MARKERS);
} else {
markers.destroyMarkers();
Messaging.sendTr(player, Messages.LINEAR_WAYPOINT_EDITOR_NOT_SHOWING_MARKERS);
}
}
}
private class LinearWaypointGoal implements Goal {
private boolean ascending = true;
private final Location cachedLocation = new Location(null, 0, 0, 0);
private Waypoint currentDestination;
private Iterator<Waypoint> itr;
private boolean paused;
private GoalSelector selector;
private void ensureItr() {
if (itr == null) {
itr = getUnsafeIterator();
} else if (!itr.hasNext()) {
itr = getNewIterator();
}
}
private Navigator getNavigator() {
return npc.getNavigator();
}
private Iterator<Waypoint> getNewIterator() {
LinearWaypointsCompleteEvent event = new LinearWaypointsCompleteEvent(LinearWaypointProvider.this,
getUnsafeIterator());
Bukkit.getPluginManager().callEvent(event);
Iterator<Waypoint> next = event.getNextWaypoints();
return next;
}
private Iterator<Waypoint> getUnsafeIterator() {
if (cycle && ascending) {
ascending = false;
return new Iterator<Waypoint>() {
int idx = waypoints.size() - 1;
@Override
public boolean hasNext() {
return idx >= 0 && idx < waypoints.size();
}
@Override
public Waypoint next() {
return waypoints.get(idx--);
}
@Override
public void remove() {
waypoints.remove(Math.max(0, idx - 1));
}
};
} else {
ascending = true;
return new Iterator<Waypoint>() {
int idx = 0;
@Override
public boolean hasNext() {
return idx < waypoints.size();
}
@Override
public Waypoint next() {
return waypoints.get(idx++);
}
@Override
public void remove() {
waypoints.remove(Math.max(0, idx - 1));
}
};
}
}
public boolean isPaused() {
return paused;
}
public void onProviderChanged() {
itr = getUnsafeIterator();
if (currentDestination != null) {
if (selector != null) {
selector.finish();
}
if (npc != null && npc.getNavigator().isNavigating()) {
npc.getNavigator().cancelNavigation();
}
}
}
@Override
public void reset() {
currentDestination = null;
selector = null;
}
@Override
public void run(GoalSelector selector) {
if (!getNavigator().isNavigating()) {
selector.finish();
}
}
public void setPaused(boolean pause) {
paused = pause;
if (pause && currentDestination != null) {
selector.finish();
if (npc != null && npc.getNavigator().isNavigating()) {
npc.getNavigator().cancelNavigation();
}
}
}
@Override
public boolean shouldExecute(final GoalSelector selector) {
if (paused || currentDestination != null || !npc.isSpawned() || getNavigator().isNavigating()) {
return false;
}
ensureItr();
boolean shouldExecute = itr.hasNext();
if (!shouldExecute) {
return false;
}
this.selector = selector;
Waypoint next = itr.next();
final Location npcLoc = npc.getEntity().getLocation(cachedLocation);
if (npcLoc.getWorld() != next.getLocation().getWorld()
|| npcLoc.distance(next.getLocation()) < npc.getNavigator().getLocalParameters().distanceMargin()) {
return false;
}
currentDestination = next;
if (cachePaths) {
SourceDestinationPair key = new SourceDestinationPair(npcLoc, currentDestination);
Iterable<Vector> cached = cachedPaths.get(key);
if (cached != null) {
if (Iterables.size(cached) == 0 || !key.verify(npcLoc.getWorld(), cached)) {
cachedPaths.remove(key);
} else {
getNavigator().setTarget(cached);
}
}
}
if (!getNavigator().isNavigating()) {
getNavigator().setTarget(currentDestination.getLocation());
}
getNavigator().getLocalParameters().addSingleUseCallback(new NavigatorCallback() {
@Override
public void onCompletion(@Nullable CancelReason cancelReason) {
if (npc.isSpawned() && currentDestination != null
&& Util.locationWithinRange(npc.getStoredLocation(), currentDestination.getLocation(),
Setting.DEFAULT_DISTANCE_MARGIN.asDouble() + 1)) {
currentDestination.onReach(npc);
if (cachePaths && cancelReason == null) {
Iterable<Vector> path = getNavigator().getPathStrategy().getPath();
if (Iterables.size(path) > 0) {
cachedPaths.put(new SourceDestinationPair(npcLoc, currentDestination), path);
}
}
}
selector.finish();
}
});
return true;
}
}
private static class SourceDestinationPair {
private final Vector from;
private final Vector to;
public SourceDestinationPair(Location npcLoc, Waypoint to) {
this(new Vector(npcLoc.getBlockX(), npcLoc.getBlockY(), npcLoc.getBlockZ()), to.getLocation().toVector());
}
public SourceDestinationPair(Vector from, Vector to) {
this.from = from;
this.to = to;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
SourceDestinationPair other = (SourceDestinationPair) obj;
if (from == null) {
if (other.from != null) {
return false;
}
} else if (!from.equals(other.from)) {
return false;
}
if (to == null) {
if (other.to != null) {
return false;
}
} else if (!to.equals(other.to)) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = prime + ((from == null) ? 0 : from.hashCode());
return prime * result + ((to == null) ? 0 : to.hashCode());
}
public boolean verify(World world, Iterable<Vector> cached) {
for (Vector vector : cached) {
if (!MinecraftBlockExaminer
.canStandOn(world.getBlockAt(vector.getBlockX(), vector.getBlockY() - 1, vector.getBlockZ()))) {
return false;
}
}
return true;
}
}
}