-
-
Notifications
You must be signed in to change notification settings - Fork 294
/
LookClose.java
394 lines (345 loc) · 12.8 KB
/
LookClose.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
package net.citizensnpcs.trait;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.potion.PotionEffectType;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.citizensnpcs.Settings.Setting;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.event.NPCLookCloseChangeTargetEvent;
import net.citizensnpcs.api.persistence.Persist;
import net.citizensnpcs.api.trait.Trait;
import net.citizensnpcs.api.trait.TraitName;
import net.citizensnpcs.api.util.DataKey;
import net.citizensnpcs.trait.RotationTrait.PacketRotationSession;
import net.citizensnpcs.util.NMS;
import net.citizensnpcs.util.Util;
/**
* Persists the /npc lookclose metadata
*
*/
@TraitName("lookclose")
public class LookClose extends Trait implements Toggleable {
@Persist("disablewhilenavigating")
private boolean disableWhileNavigating = Setting.DISABLE_LOOKCLOSE_WHILE_NAVIGATING.asBoolean();
@Persist("enabled")
private boolean enabled = Setting.DEFAULT_LOOK_CLOSE.asBoolean();
@Persist
private boolean enableRandomLook = Setting.DEFAULT_RANDOM_LOOK_CLOSE.asBoolean();
@Persist("headonly")
private boolean headOnly;
@Persist("linkedbody")
private boolean linkedBody;
private Player lookingAt;
@Persist("perplayer")
private boolean perPlayer;
@Persist
private int randomLookDelay = Setting.DEFAULT_RANDOM_LOOK_DELAY.asTicks();
@Persist
private float[] randomPitchRange = { 0, 0 };
@Persist
private boolean randomSwitchTargets;
@Persist
private float[] randomYawRange = { 0, 360 };
private double range = Setting.DEFAULT_LOOK_CLOSE_RANGE.asDouble();
@Persist("realisticlooking")
private boolean realisticLooking = Setting.DEFAULT_REALISTIC_LOOKING.asBoolean();
private final Map<UUID, PacketRotationSession> sessions = Maps.newHashMapWithExpectedSize(4);
private int t;
@Persist("targetnpcs")
private boolean targetNPCs;
public LookClose() {
super("lookclose");
}
private boolean canSee(Player player) {
if (player == null || !player.isValid())
return false;
return realisticLooking && npc.getEntity() instanceof LivingEntity
? ((LivingEntity) npc.getEntity()).hasLineOfSight(player)
: true;
}
/**
* Returns whether the target can be seen. Will use realistic line of sight if {@link #setRealisticLooking(boolean)}
* is true.
*/
public boolean canSeeTarget() {
return canSee(lookingAt);
}
public boolean disableWhileNavigating() {
return disableWhileNavigating;
}
/**
* Finds a new look-close target
*/
public void findNewTarget() {
if (perPlayer) {
lookingAt = null;
RotationTrait rotationTrait = npc.getOrAddTrait(RotationTrait.class);
Set<UUID> seen = Sets.newHashSet();
for (Player player : getNearbyPlayers()) {
PacketRotationSession session = sessions.get(player.getUniqueId());
if (session == null) {
sessions.put(player.getUniqueId(),
session = rotationTrait.createPacketSession(
rotationTrait.getGlobalParameters().clone().linkedBody(linkedBody)
.headOnly(headOnly).uuidFilter(player.getUniqueId()).persist(true)));
}
session.getSession().rotateToFace(player);
seen.add(player.getUniqueId());
}
for (Iterator<UUID> iterator = sessions.keySet().iterator(); iterator.hasNext();) {
UUID uuid = iterator.next();
if (!seen.contains(uuid)) {
rotationTrait.resetPlayerToPhysicalSession(uuid);
iterator.remove();
}
}
return;
} else if (sessions.size() > 0) {
RotationTrait rotationTrait = npc.getOrAddTrait(RotationTrait.class);
for (UUID uuid : sessions.keySet()) {
rotationTrait.resetPlayerToPhysicalSession(uuid);
}
sessions.clear();
}
if (lookingAt != null && !isValid(lookingAt)) {
NPCLookCloseChangeTargetEvent event = new NPCLookCloseChangeTargetEvent(npc, lookingAt, null);
Bukkit.getPluginManager().callEvent(event);
if (event.getNewTarget() != null && isValid(event.getNewTarget())) {
lookingAt = event.getNewTarget();
} else {
lookingAt = null;
}
}
Player old = lookingAt;
if (lookingAt != null) {
if (randomSwitchTargets && t <= 0) {
List<Player> options = getNearbyPlayers();
if (options.size() > 0) {
lookingAt = options.get(Util.getFastRandom().nextInt(options.size()));
t = randomLookDelay;
}
}
} else {
double min = Double.MAX_VALUE;
Location npcLoc = npc.getStoredLocation();
for (Player player : getNearbyPlayers()) {
double dist = player.getLocation().distance(npcLoc);
if (dist > min) {
continue;
}
min = dist;
lookingAt = player;
}
}
if (old != lookingAt) {
NPCLookCloseChangeTargetEvent event = new NPCLookCloseChangeTargetEvent(npc, old, lookingAt);
Bukkit.getPluginManager().callEvent(event);
if (lookingAt != event.getNewTarget() && event.getNewTarget() != null && !isValid(event.getNewTarget()))
return;
lookingAt = event.getNewTarget();
}
}
private List<Player> getNearbyPlayers() {
List<Player> options = Lists.newArrayList();
Location npcLoc = npc.getStoredLocation();
Iterable<Player> nearby = targetNPCs
? npc.getEntity().getNearbyEntities(range, range, range).stream()
.filter(e -> e.getType() == EntityType.PLAYER && e.getWorld() == npcLoc.getWorld())
.map(e -> (Player) e).collect(Collectors.toList())
: CitizensAPI.getLocationLookup().getNearbyPlayers(npcLoc, range);
for (Player player : nearby) {
if (player == lookingAt || !targetNPCs && CitizensAPI.getNPCRegistry().getNPC(player) != null) {
continue;
}
if (player.getLocation().getWorld() != npcLoc.getWorld() || isInvisible(player)) {
continue;
}
options.add(player);
}
return options;
}
public int getRandomLookDelay() {
return randomLookDelay;
}
public float[] getRandomLookPitchRange() {
return randomPitchRange;
}
public float[] getRandomLookYawRange() {
return randomYawRange;
}
public double getRange() {
return range;
}
public Player getTarget() {
return lookingAt;
}
public boolean isEnabled() {
return enabled;
}
public boolean isHeadOnly() {
return headOnly;
}
private boolean isInvisible(Player player) {
return player.getGameMode() == GameMode.SPECTATOR || player.hasPotionEffect(PotionEffectType.INVISIBILITY)
|| isPluginVanished(player) || !canSee(player);
}
private boolean isPluginVanished(Player player) {
for (MetadataValue meta : player.getMetadata("vanished")) {
if (meta.asBoolean())
return true;
}
return false;
}
public boolean isRandomLook() {
return enableRandomLook;
}
private boolean isValid(Player entity) {
return entity.isOnline() && entity.isValid() && entity.getWorld() == npc.getEntity().getWorld()
&& entity.getLocation().distance(npc.getStoredLocation()) <= range && !isInvisible(entity);
}
@Override
public void load(DataKey key) {
range = key.getDouble("range");
}
/**
* Enables/disables the trait
*/
public void lookClose(boolean lookClose) {
enabled = lookClose;
}
@Override
public void onDespawn() {
NPCLookCloseChangeTargetEvent event = new NPCLookCloseChangeTargetEvent(npc, lookingAt, null);
Bukkit.getPluginManager().callEvent(event);
if (event.getNewTarget() != null && isValid(event.getNewTarget())) {
lookingAt = event.getNewTarget();
} else {
lookingAt = null;
}
}
private void randomLook() {
float pitch = isEqual(randomPitchRange) ? randomPitchRange[0]
: Util.getFastRandom().doubles(randomPitchRange[0], randomPitchRange[1]).iterator().next().floatValue();
float yaw = isEqual(randomYawRange) ? randomYawRange[0]
: Util.getFastRandom().doubles(randomYawRange[0], randomYawRange[1]).iterator().next().floatValue();
npc.getOrAddTrait(RotationTrait.class).getPhysicalSession().rotateToHave(yaw, pitch);
}
@Override
public void run() {
if (!npc.isSpawned()) {
lookingAt = null;
return;
}
if (enableRandomLook) {
if (!npc.getNavigator().isNavigating() && lookingAt == null && t <= 0) {
randomLook();
t = randomLookDelay;
}
}
t--;
if (!enabled || npc.getNavigator().isNavigating() && disableWhileNavigating()) {
lookingAt = null;
return;
}
findNewTarget();
if (npc.getNavigator().isNavigating() || npc.getNavigator().isPaused()) {
npc.getNavigator().setPaused(lookingAt != null);
}
if (lookingAt == null)
return;
RotationTrait rot = npc.getOrAddTrait(RotationTrait.class);
rot.getGlobalParameters().headOnly(headOnly);
rot.getGlobalParameters().linkedBody(linkedBody);
rot.getPhysicalSession().rotateToFace(lookingAt);
if (npc.getEntity().getType().name().equals("SHULKER")) {
boolean wasSilent = npc.getEntity().isSilent();
npc.getEntity().setSilent(true);
NMS.setPeekShulker(npc.getEntity(),
100 - 4 * (int) Math.floor(npc.getStoredLocation().distanceSquared(lookingAt.getLocation())));
npc.getEntity().setSilent(wasSilent);
}
}
@Override
public void save(DataKey key) {
key.setDouble("range", range);
}
public void setDisableWhileNavigating(boolean set) {
disableWhileNavigating = set;
}
public void setHeadOnly(boolean headOnly) {
this.headOnly = headOnly;
}
public void setLinkedBody(boolean linkedBody) {
this.linkedBody = linkedBody;
}
public void setPerPlayer(boolean perPlayer) {
this.perPlayer = perPlayer;
}
/**
* Enables random looking - will look at a random {@link Location} every so often if enabled.
*/
public void setRandomLook(boolean enableRandomLook) {
this.enableRandomLook = enableRandomLook;
}
/**
* Sets the delay between random looking in ticks
*/
public void setRandomLookDelay(int delay) {
randomLookDelay = delay;
}
public void setRandomLookPitchRange(float min, float max) {
randomPitchRange = new float[] { min, max };
}
public void setRandomLookYawRange(float min, float max) {
randomYawRange = new float[] { min, max };
}
public void setRandomlySwitchTargets(boolean randomSwitchTargets) {
this.randomSwitchTargets = randomSwitchTargets;
}
/**
* Sets the maximum range in blocks to look at other Entities
*/
public void setRange(double range) {
this.range = range;
}
/**
* Enables/disables realistic looking (using line of sight checks). More computationally expensive.
*/
public void setRealisticLooking(boolean realistic) {
realisticLooking = realistic;
}
public void setTargetNPCs(boolean target) {
targetNPCs = target;
}
public boolean targetNPCs() {
return targetNPCs;
}
@Override
public boolean toggle() {
enabled = !enabled;
return enabled;
}
@Override
public String toString() {
return "LookClose{" + enabled + "}";
}
public boolean useRealisticLooking() {
return realisticLooking;
}
private static boolean isEqual(float[] array) {
return Math.abs(array[0] - array[1]) < 0.001;
}
}