-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
AbstractNPC.java
509 lines (451 loc) · 15.8 KB
/
AbstractNPC.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
package net.citizensnpcs.api.npc;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.metadata.FixedMetadataValue;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.ai.GoalController;
import net.citizensnpcs.api.ai.SimpleGoalController;
import net.citizensnpcs.api.ai.speech.SimpleSpeechController;
import net.citizensnpcs.api.ai.speech.SpeechController;
import net.citizensnpcs.api.event.DespawnReason;
import net.citizensnpcs.api.event.NPCAddTraitEvent;
import net.citizensnpcs.api.event.NPCCloneEvent;
import net.citizensnpcs.api.event.NPCRemoveByCommandSenderEvent;
import net.citizensnpcs.api.event.NPCRemoveEvent;
import net.citizensnpcs.api.event.NPCRemoveTraitEvent;
import net.citizensnpcs.api.event.NPCTeleportEvent;
import net.citizensnpcs.api.persistence.PersistenceLoader;
import net.citizensnpcs.api.trait.Trait;
import net.citizensnpcs.api.trait.trait.MobType;
import net.citizensnpcs.api.trait.trait.Speech;
import net.citizensnpcs.api.util.Colorizer;
import net.citizensnpcs.api.util.DataKey;
import net.citizensnpcs.api.util.MemoryDataKey;
import net.citizensnpcs.api.util.Messaging;
import net.citizensnpcs.api.util.Placeholders;
import net.citizensnpcs.api.util.SpigotUtil;
public abstract class AbstractNPC implements NPC {
private final GoalController goalController = new SimpleGoalController();
private final int id;
private final MetadataStore metadata = new SimpleMetadataStore() {
@Override
public void remove(String key) {
super.remove(key);
if (getEntity() != null) {
getEntity().removeMetadata(key, CitizensAPI.getPlugin());
}
}
@Override
public void set(String key, Object data) {
super.set(key, data);
if (getEntity() != null) {
getEntity().setMetadata(key, new FixedMetadataValue(CitizensAPI.getPlugin(), data));
}
}
@Override
public void setPersistent(String key, Object data) {
super.setPersistent(key, data);
if (getEntity() != null) {
getEntity().setMetadata(key, new FixedMetadataValue(CitizensAPI.getPlugin(), data));
}
}
};
private String name;
private final NPCRegistry registry;
private final List<String> removedTraits = Lists.newArrayList();
private final List<Runnable> runnables = Lists.newArrayList();
private final SpeechController speechController = new SimpleSpeechController(this);
protected final Map<Class<? extends Trait>, Trait> traits = Maps.newHashMap();
private final UUID uuid;
protected AbstractNPC(UUID uuid, int id, String name, NPCRegistry registry) {
this.uuid = uuid;
this.id = id;
this.registry = registry;
this.name = name;
CitizensAPI.getTraitFactory().addDefaultTraits(this);
}
@Override
public void addRunnable(Runnable runnable) {
this.runnables.add(runnable);
}
@Override
public void addTrait(Class<? extends Trait> clazz) {
addTrait(getTraitFor(clazz));
}
@Override
public void addTrait(Trait trait) {
if (trait == null) {
Messaging.severe("Cannot register a null trait. Was it registered properly?");
return;
}
if (trait.getNPC() == null) {
trait.linkToNPC(this);
}
// if an existing trait is being replaced, we need to remove the
// currently registered runnable to avoid conflicts
Class<? extends Trait> clazz = trait.getClass();
Trait replaced = traits.get(clazz);
Bukkit.getPluginManager().registerEvents(trait, CitizensAPI.getPlugin());
traits.put(clazz, trait);
if (isSpawned()) {
trait.onSpawn();
}
if (trait.isRunImplemented()) {
if (replaced != null) {
runnables.remove(replaced);
}
runnables.add(trait);
}
Bukkit.getPluginManager().callEvent(new NPCAddTraitEvent(this, trait));
}
@Override
public NPC clone() {
return copy();
}
@Override
public NPC copy() {
NPC copy = registry.createNPC(getOrAddTrait(MobType.class).getType(), getFullName());
DataKey key = new MemoryDataKey();
save(key);
copy.load(key);
for (Trait trait : copy.getTraits()) {
trait.onCopy();
}
Bukkit.getPluginManager().callEvent(new NPCCloneEvent(this, copy));
return copy;
}
@Override
public MetadataStore data() {
return this.metadata;
}
@Override
public boolean despawn() {
return despawn(DespawnReason.PLUGIN);
}
@Override
public void destroy() {
Bukkit.getPluginManager().callEvent(new NPCRemoveEvent(this));
runnables.clear();
for (Trait trait : traits.values()) {
HandlerList.unregisterAll(trait);
trait.onRemove();
}
traits.clear();
goalController.clear();
registry.deregister(this);
}
@Override
public void destroy(CommandSender source) {
Bukkit.getPluginManager().callEvent(new NPCRemoveByCommandSenderEvent(this, source));
destroy();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
AbstractNPC other = (AbstractNPC) obj;
if (uuid == null) {
if (other.uuid != null) {
return false;
}
} else if (!uuid.equals(other.uuid)) {
return false;
}
return true;
}
@Override
public GoalController getDefaultGoalController() {
return goalController;
}
@Override
public SpeechController getDefaultSpeechController() {
// TODO: Remove in future versions.
// This is here to add the Speech trait to any existing NPCs
// that were created pre-SpeechController, if invoked.
if (!hasTrait(Speech.class)) {
addTrait(Speech.class);
}
return speechController;
}
protected EntityType getEntityType() {
return isSpawned() ? getEntity().getType() : getOrAddTrait(MobType.class).getType();
}
@Override
public String getFullName() {
int nameLength = SpigotUtil.getMaxNameLength(getEntityType());
String replaced = Placeholders.replace(Colorizer.parseColors(name), null, this);
if (replaced.length() > nameLength) {
Messaging.severe("ID", id, "created with name length greater than " + nameLength + ", truncating", replaced,
"to", replaced.substring(0, nameLength));
replaced = replaced.substring(0, nameLength);
}
return replaced;
}
@Override
public int getId() {
return id;
}
@Override
public String getName() {
return Colorizer.stripColors(name);
}
@Override
public <T extends Trait> T getOrAddTrait(Class<T> clazz) {
Trait trait = traits.get(clazz);
if (trait == null) {
trait = getTraitFor(clazz);
addTrait(trait);
}
return clazz.cast(trait);
}
@Override
public NPCRegistry getOwningRegistry() {
return registry;
}
@Override
@Deprecated
public <T extends Trait> T getTrait(Class<T> clazz) {
return getOrAddTrait(clazz);
}
protected Trait getTraitFor(Class<? extends Trait> clazz) {
return CitizensAPI.getTraitFactory().getTrait(clazz);
}
@Override
public <T extends Trait> T getTraitNullable(Class<T> clazz) {
return clazz.cast(traits.get(clazz));
}
@Override
public Iterable<Trait> getTraits() {
return traits.values();
}
@Override
public UUID getUniqueId() {
return uuid;
}
@Override
public int hashCode() {
return 31 + uuid.hashCode();
}
@Override
public boolean hasTrait(Class<? extends Trait> trait) {
return traits.containsKey(trait);
}
@Override
public boolean isFlyable() {
return data().get(NPC.FLYABLE_METADATA, false);
}
@Override
public boolean isProtected() {
return data().get(NPC.DEFAULT_PROTECTED_METADATA, true);
}
@Override
public void load(final DataKey root) {
name = root.getString("name");
metadata.loadFrom(root.getRelative("metadata"));
String traitNames = root.getString("traitnames");
Set<DataKey> keys = Sets.newHashSet(root.getRelative("traits").getSubKeys());
Iterables.addAll(keys, Iterables.transform(Splitter.on(',').split(traitNames), new Function<String, DataKey>() {
@Override
public DataKey apply(String input) {
return root.getRelative("traits." + input);
}
}));
DataKey locationKey = root.getRelative("traits.location");
if (locationKey.keyExists()) {
loadTraitFromKey(locationKey);
keys.remove(locationKey);
}
for (DataKey key : keys) {
loadTraitFromKey(key);
}
}
private void loadTraitFromKey(DataKey traitKey) {
Class<? extends Trait> clazz = CitizensAPI.getTraitFactory().getTraitClass(traitKey.name());
Trait trait;
if (hasTrait(clazz)) {
trait = getTraitNullable(clazz);
} else {
trait = CitizensAPI.getTraitFactory().getTrait(clazz);
if (trait == null) {
Messaging.severeTr("citizens.notifications.trait-load-failed", traitKey.name(), getId());
return;
}
addTrait(trait);
}
try {
PersistenceLoader.load(trait, traitKey);
trait.load(traitKey);
} catch (Throwable ex) {
if (Messaging.isDebugging()) {
ex.printStackTrace();
}
Messaging.logTr("citizens.notifications.trait-load-failed", traitKey.name(), getId());
}
}
@Override
public void removeTrait(Class<? extends Trait> traitClass) {
Trait trait = traits.remove(traitClass);
if (trait != null) {
Bukkit.getPluginManager().callEvent(new NPCRemoveTraitEvent(this, trait));
removedTraits.add(trait.getName());
if (trait.isRunImplemented()) {
runnables.remove(trait);
}
HandlerList.unregisterAll(trait);
trait.onRemove();
}
}
@Override
public boolean requiresNameHologram() {
return getEntityType() != EntityType.ARMOR_STAND
&& ((name.length() > 16 && getEntityType() == EntityType.PLAYER)
|| data().get(NPC.ALWAYS_USE_NAME_HOLOGRAM_METADATA, false) || name.contains("&x")
|| name.contains("§x") || !Placeholders.replace(name, null, this).equals(name));
}
@Override
public void save(DataKey root) {
if (!metadata.get(NPC.SHOULD_SAVE_METADATA, true))
return;
metadata.saveTo(root.getRelative("metadata"));
root.setString("name", name);
root.setString("uuid", uuid.toString());
// Save all existing traits
StringBuilder traitNames = new StringBuilder();
for (Trait trait : traits.values()) {
DataKey traitKey = root.getRelative("traits." + trait.getName());
trait.save(traitKey);
try {
PersistenceLoader.save(trait, traitKey);
} catch (Throwable t) {
Messaging.log("PersistenceLoader failed for", trait);
t.printStackTrace();
continue;
}
removedTraits.remove(trait.getName());
traitNames.append(trait.getName() + ",");
}
if (traitNames.length() > 0) {
root.setString("traitnames", traitNames.substring(0, traitNames.length() - 1));
} else {
root.setString("traitnames", "");
}
for (String name : removedTraits) {
root.removeKey("traits." + name);
}
removedTraits.clear();
}
@Override
public void setAlwaysUseNameHologram(boolean use) {
data().setPersistent(NPC.ALWAYS_USE_NAME_HOLOGRAM_METADATA, use);
}
@Override
public void setFlyable(boolean flyable) {
data().setPersistent(NPC.FLYABLE_METADATA, flyable);
}
@Override
public void setName(String name) {
this.name = name;
if (!isSpawned())
return;
Entity bukkitEntity = getEntity();
if (bukkitEntity instanceof LivingEntity) {
((LivingEntity) bukkitEntity).setCustomName(getFullName());
}
if (bukkitEntity.getType() == EntityType.PLAYER && !requiresNameHologram()) {
Location old = bukkitEntity.getLocation();
despawn(DespawnReason.PENDING_RESPAWN);
spawn(old);
}
}
@Override
public void setProtected(boolean isProtected) {
data().setPersistent(NPC.DEFAULT_PROTECTED_METADATA, isProtected);
}
@Override
public void setUseMinecraftAI(boolean use) {
data().setPersistent(NPC.USE_MINECRAFT_AI_METADATA, use);
}
private void teleport(final Entity entity, Location location, int delay) {
final Entity passenger = entity.getPassenger();
entity.eject();
if (!location.getWorld().equals(entity.getWorld())) {
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), new Runnable() {
@Override
public void run() {
entity.teleport(location);
}
}, delay++);
} else {
entity.teleport(location);
}
if (passenger == null)
return;
teleport(passenger, location, delay++);
Runnable task = new Runnable() {
@Override
public void run() {
entity.setPassenger(passenger);
}
};
if (!location.getWorld().equals(entity.getWorld())) {
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), task, delay);
} else {
task.run();
}
}
@Override
public void teleport(Location location, TeleportCause cause) {
if (!isSpawned())
return;
NPCTeleportEvent event = new NPCTeleportEvent(this, location);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled())
return;
Entity entity = getEntity();
while (entity.getVehicle() != null) {
entity = entity.getVehicle();
}
location.getBlock().getChunk();
teleport(entity, location, 5);
}
protected void unloadEvents() {
runnables.clear();
for (Trait trait : traits.values()) {
HandlerList.unregisterAll(trait);
}
traits.clear();
goalController.clear();
}
public void update() {
for (int i = 0; i < runnables.size(); ++i) {
runnables.get(i).run();
}
if (isSpawned()) {
goalController.run();
}
}
@Override
public boolean useMinecraftAI() {
return data().get(NPC.USE_MINECRAFT_AI_METADATA, false);
}
}