-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
SentinelTrait.java
2155 lines (1979 loc) · 78.9 KB
/
SentinelTrait.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 org.mcmonkey.sentinel;
import com.google.common.base.Function;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.ai.Navigator;
import net.citizensnpcs.api.ai.TeleportStuckAction;
import net.citizensnpcs.api.ai.speech.SpeechContext;
import net.citizensnpcs.api.event.DespawnReason;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.persistence.Persist;
import net.citizensnpcs.api.persistence.PersistenceLoader;
import net.citizensnpcs.api.persistence.Persister;
import net.citizensnpcs.api.trait.Trait;
import net.citizensnpcs.api.trait.trait.Owner;
import net.citizensnpcs.api.trait.trait.Spawned;
import net.citizensnpcs.api.util.DataKey;
import net.citizensnpcs.trait.CurrentLocation;
import net.citizensnpcs.trait.waypoint.WanderWaypointProvider;
import net.citizensnpcs.trait.waypoint.Waypoint;
import net.citizensnpcs.trait.waypoint.WaypointProvider;
import net.citizensnpcs.trait.waypoint.Waypoints;
import net.citizensnpcs.util.NMS;
import net.citizensnpcs.util.PlayerAnimation;
import org.bukkit.*;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.*;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import org.mcmonkey.sentinel.commands.SentinelCommand;
import org.mcmonkey.sentinel.events.SentinelChaseEndEvent;
import org.mcmonkey.sentinel.events.SentinelChaseNewTargetEvent;
import org.mcmonkey.sentinel.events.SentinelCombatStateChangeEvent;
import org.mcmonkey.sentinel.events.SentinelWantsToPathEvent;
import org.mcmonkey.sentinel.targeting.SentinelTarget;
import org.mcmonkey.sentinel.targeting.SentinelTargetLabel;
import org.mcmonkey.sentinel.targeting.SentinelTargetList;
import org.mcmonkey.sentinel.targeting.SentinelTargetingHelper;
import org.mcmonkey.sentinel.utilities.SentinelNMSHelper;
import org.mcmonkey.sentinel.utilities.SentinelVersionCompat;
import java.util.*;
/**
* The main Sentinel trait.
*/
public class SentinelTrait extends Trait {
/**
* Constant: the smallest health value that can be given to an NPC.
*/
public static final double healthMin = 0.01;
/**
* Constant: the maximum attack rate value (in ticks).
*/
public static final int attackRateMax = 2000;
/**
* Constant: the maximum heal rate value (in ticks).
*/
public static final int healRateMax = 2000;
/**
* Helper for targeting logic.
*/
public SentinelTargetingHelper targetingHelper;
/**
* Helper for items.
*/
public SentinelItemHelper itemHelper;
/**
* Helper for weapons.
*/
public SentinelWeaponHelper weaponHelper;
/**
* Helper for attacking.
*/
public SentinelAttackHelper attackHelper;
/**
* Constructs the Sentinel Trait object - should only be called by the Citizens API internal functionality.
* To add Sentinel to an NPC, use {@code npc.addTrait(SentinelTrait.class)}.
*/
public SentinelTrait() {
super("sentinel");
targetingHelper = new SentinelTargetingHelper();
itemHelper = new SentinelItemHelper();
weaponHelper = new SentinelWeaponHelper();
attackHelper = new SentinelAttackHelper();
targetingHelper.setTraitObject(this);
itemHelper.setTraitObject(this);
weaponHelper.setTraitObject(this);
attackHelper.setTraitObject(this);
}
/**
* Statistics value: how long (in ticks) this NPC has ever been in the world, in total.
*/
@Persist("stats_ticksSpawned")
public long stats_ticksSpawned = 0;
/**
* Statistics value: how many times this NPC has spawned into the world.
*/
@Persist("stats_timesSpawned")
public long stats_timesSpawned = 0;
/**
* Statistics value: how many arrows this NPC has fired.
*/
@Persist("stats_arrowsFired")
public long stats_arrowsFired = 0;
/**
* Statistics value: how many potions this NPC has thrown.
*/
@Persist("stats_potionsThrow")
public long stats_potionsThrown = 0;
/**
* Statistics value: how many fireballs this NPC has fired.
*/
@Persist("stats_fireballsFired")
public long stats_fireballsFired = 0;
/**
* Statistics value: how many snowballs this NPC has thrown.
*/
@Persist("stats_snowballsThrown")
public long stats_snowballsThrown = 0;
/**
* Statistics value: how many eggs this NPC has thrown.
*/
@Persist("stats_eggsThrown")
public long stats_eggsThrown = 0;
/**
* Statistics value: how many skulls this NPC has thrown.
*/
@Persist("stats_skullsThrown")
public long stats_skullsThrown = 0;
/**
* Statistics value: how many llama spits this NPC has spit.
*/
@Persist("stats_llamaSpitShot")
public long stats_llamaSpitShot = 0;
/**
* Statistics value: how many shulker bullets this NPC has shot.
*/
@Persist("stats_shulkerBulletsShot")
public long stats_shulkerBulletsShot = 0;
/**
* Statistics value: how many evoker fangs this NPC has spawned.
*/
@Persist("stats_evokerFangsSpawned")
public long stats_evokerFangsSpawned = 0;
/**
* Statistics value: how many pearls this NPC has used.
*/
@Persist("stats_pearlsUsed")
public long stats_pearlsUsed = 0;
/**
* Statistics value: how many times this NPC has punched a target.
*/
@Persist("stats_punches")
public long stats_punches = 0;
/**
* Statistics value: how many attacks this NPC has attempted.
*/
@Persist("stats_attackAttempts")
public long stats_attackAttempts = 0;
/**
* Statistics value: how much damage this NPC has taken.
*/
@Persist("stats_damageTaken")
public double stats_damageTaken = 0;
/**
* Statistics value: how much damage this NPC has given.
*/
@Persist("stats_damageGiven")
public double stats_damageGiven = 0;
/**
* Updater for older Sentinel saves (up to 1.7.2)
*/
@Override
public void load(final DataKey key) {
new BukkitRunnable() {
@Override
public void run() {
updateOld(key);
}
}.runTaskLater(SentinelPlugin.instance, 1);
}
@Override
public void save(DataKey key) {
for (DataKey subkey : key.getSubKeys()) {
if (subkey.name().equals("targets")
|| subkey.name().equals("ignores")
|| subkey.name().endsWith("Targets")
|| subkey.name().endsWith("Ignores")) {
key.removeKey(subkey.name());
}
}
}
/**
* Updater for older Sentinel saves (up to 1.7.2)
*/
public void updateOld(DataKey key) {
for (DataKey subkey : key.getSubKeys()) {
if (subkey.name().equals("targets")) {
for (DataKey listEntry : subkey.getSubKeys()) {
allTargets.targets.add(listEntry.getRaw("").toString());
}
allTargets.recalculateTargetsCache();
}
else if (subkey.name().equals("ignores")) {
for (DataKey listEntry : subkey.getSubKeys()) {
allIgnores.targets.add(listEntry.getRaw("").toString());
}
allIgnores.recalculateTargetsCache();
}
if (subkey.name().endsWith("Targets")) {
allTargets.updateOld(subkey, subkey.name().substring(0, subkey.name().length() - "Targets".length()));
}
else if (subkey.name().endsWith("Ignores")) {
allIgnores.updateOld(subkey, subkey.name().substring(0, subkey.name().length() - "Ignores".length()));
}
}
}
@Persist("allTargets")
public SentinelTargetList allTargets = new SentinelTargetList();
@Persist("allIgnores")
public SentinelTargetList allIgnores = new SentinelTargetList();
@Persist("allAvoids")
public SentinelTargetList allAvoids = new SentinelTargetList();
public static class SentinelTargetListPersister implements Persister<SentinelTargetList> {
@Override
public SentinelTargetList create(DataKey dataKey) {
SentinelTargetList list = PersistenceLoader.load(new SentinelTargetList(), dataKey);
list.init();
return list;
}
@Override
public void save(SentinelTargetList o, DataKey dataKey) {
PersistenceLoader.save(o, dataKey);
}
}
static {
PersistenceLoader.registerPersistDelegate(SentinelTargetList.class, SentinelTargetListPersister.class);
}
/**
* Adds a new target (by target description string).
*/
public void addTarget(String target) {
new SentinelTargetLabel(target).addToList(allTargets);
}
/**
* Adds a new ignore (by target description string).
*/
public void addIgnore(String target) {
new SentinelTargetLabel(target).addToList(allIgnores);
}
/**
* Adds a new avoid-target (by target description string).
*/
public void addAvoid(String target) {
new SentinelTargetLabel(target).addToList(allAvoids);
}
/**
* Removes a target (by target description string).
*/
public void removeTarget(String target) {
new SentinelTargetLabel(target).removeFromList(allTargets);
}
/**
* Removes an ignore (by target description string).
*/
public void removeIgnore(String target) {
new SentinelTargetLabel(target).removeFromList(allIgnores);
}
/**
* Removes an avoid-target (by target description string).
*/
public void removeAvoid(String target) {
new SentinelTargetLabel(target).removeFromList(allAvoids);
}
/**
* How far to stay from avoid targets.
*/
@Persist
public double avoidRange = 10.0;
/**
* Maximum range to trigger attacks from.
*/
@Persist("range")
public double range = 20.0;
/**
* The NPC's damage value (-1 means automatically calculated from weapon, anything else is equal to the HP lost by an unarmored target).
*/
@Persist("damage")
public double damage = -1.0;
/**
* The NPC's armor value (-1 means automatically calculated from equipment, 0 means no armor and 1 means invincible armor... decimals between 0 and 1 are normal).
*/
@Persist("armor")
public double armor = -1.0;
/**
* The NPC's maximum health (NOT its current health when the NPC is spawned and injured).
*/
@Persist("health")
public double health = 20.0;
/**
* Whether the NPC chases targets when using ranged weapons.
*/
@Persist("ranged_chase")
public boolean rangedChase = false;
/**
* Whether the NPC chases targets when using melee weapons.
*/
@Persist("close_chase")
public boolean closeChase = true;
/**
* Whether the NPC cannot be harmed (true = no harm, false = receives damage normally).
*/
@Persist("invincible")
public boolean invincible = false;
/**
* Whether the NPC should be protected from damage by ignore targets.
*/
@Persist ("protected")
public boolean protectFromIgnores = false;
/**
* Whether the NPC "fights back" against attacks (targets anyone that damages it).
*/
@Persist("fightback")
public boolean fightback = true;
/**
* Whether the NPC runs away when attacked.
*/
@Persist("runaway")
public boolean runaway = false;
/**
* How long (in ticks) between using melee attacks.
*/
@Persist("attackRate")
public int attackRate = 30;
/**
* How long (in ticks) between firing ranged shots.
*/
@Persist("attackRateRanged")
public int attackRateRanged = 30;
/**
* How long (in ticks) before the NPC heals by 1 HP (when damaged).
*/
@Persist("healRate")
public int healRate = 100;
/**
* Upper 64 bits of the guarded player's UUID.
*/
@Persist("guardingUpper")
public long guardingUpper = 0;
/**
* Lower 64 bits of the guarded player's UUID.
*/
@Persist("guardingLower")
public long guardingLower = 0;
/**
* ID of an NPC to guard, if any.
*/
@Persist("guardedNPC")
public int guardedNPC = -1;
/**
* Whether the NPC needs ammo to fire ranged weapons (otherwise, infinite ammo).
*/
@Persist("needsAmmo")
public boolean needsAmmo = false;
/**
* Whether to protect NPC arrow shots from damaging targets that weren't meant to be hit.
*/
@Persist("safeShot")
public boolean safeShot = true;
/**
* How long (in ticks) after death before the NPC respawns.
*/
@Persist("respawnTime")
public long respawnTime = 100;
/**
* The maximum distance from a guard point the NPC can run (when chasing a target).
*/
@Persist("chaseRange")
public double chaseRange = 100;
/**
* The NPC's respawn location (null = respawn where the NPC died at).
*/
@Persist("spawnPoint")
public Location spawnPoint = null;
/**
* The NPC's avoid return point (null = just run away).
*/
@Persist("avoidReturnPoint")
public Location avoidReturnPoint = null;
/**
* What the NPC drops when dead.
*/
@Persist("drops")
public ArrayList<ItemStack> drops = new ArrayList<>();
/**
* Chances of item drops, matched to the 'drops' list.
*/
@Persist("dropChances")
public ArrayList<Double> dropChances = new ArrayList<>();
/**
* Whether mob targets killed by the NPC can drop items.
*/
@Persist("enemyDrops")
public boolean enemyDrops = false;
/**
* How long (in ticks) to retain an enemy target when out-of-view.
*/
@Persist("enemyTargetTime")
public long enemyTargetTime = 0;
/**
* How fast the NPC moves when chasing (1 = normal speed).
*/
@Persist("speed")
public double speed = 1;
/**
* The text to warn enemy players with (empty string = no greeting).
*/
@Persist("warning_text")
public String warningText = "";
/**
* The text to greet friendly players with (empty string = no greeting).
*/
@Persist("greeting_text")
public String greetingText = "";
/**
* The range this NPC gives greetings or warnings at.
*/
@Persist("greet_range")
public double greetRange = 10;
/**
* The rate in ticks this NPC gives greetings or warnings at.
*/
@Persist("greet_rate")
public int greetRate = 100;
/**
* Whether this NPC automatically switches weapons.
*/
@Persist("autoswitch")
public boolean autoswitch = false;
/**
* The name of the squad this NPC is in (null for no squad).
*/
@Persist("squad")
public String squad = null;
/**
* The NPC's accuracy value (0 = perfectly accurate).
*/
@Persist("accuracy")
public double accuracy = 0;
/**
* Whether this NPC should have 'realistic' targeting.
*/
@Persist("realistic")
public boolean realistic = false;
/**
* Whether this NPC should ignore Line of Sight requirement. If set true, the NPC can see targets through walls.
*/
@Persist("ignore_los")
public boolean ignoreLOS = false;
/**
* How far this NPC's punches can reach.
*/
@Persist("reach")
public double reach = 3;
/**
* How far this NPC is willing to fire projectiles.
*/
@Persist("projectileRange")
public double projectileRange = 100;
/**
* Minimum distance before choosing a new point (relative to guarded player).
*/
@Persist("guard_distance_minimum")
public double guardDistanceMinimum = 7;
/**
* Maximum possible distance of point to choose (relative to the guarded player).
*/
@Persist("guard_selection_range")
public double guardSelectionRange = 4;
@Persist("retain_target")
public boolean retainTarget = false;
/**
* Map of weapon material names to custom damage amount.
*/
@Persist("weapon_damage_map")
public HashMap<String, Double> weaponDamage = new HashMap<>();
/**
* Map of held weapon material names to redirect 'work like' material names.
*/
@Persist("weapon_redirect_map")
public HashMap<String, String> weaponRedirects = new HashMap<>();
/**
* If set 'true', the NPC will never teleport through Sentinel logic.
* When enabling this, you should set the Citizens "stuckAction" NavigatorParameter to "null" as well.
*/
@Persist("disable_teleporting")
public boolean disableTeleporting = false;
/**
* Ticks before a new target is properly noticed.
* 0 = no slowdown applied.
*/
@Persist("reaction_slowdown")
public int reactionSlowdown = 0;
/**
* Whether the NPC can receive knockback.
*/
@Persist("allow_knockback")
public boolean allowKnockback = true;
/**
* The name of a WorldGuard region this Sentinel must stay within (if any).
*/
@Persist("worldguard_region")
public String worldguardRegion = null;
/**
* How much XP to drop when the NPC dies.
*/
@Persist("death_xp")
public int deathXP = 0;
/**
* Cache object, refer to 'worldguardRegion'.
*/
public Object worldguardRegionCache = null;
/**
* The target entity this NPC is chasing (if any).
*/
public LivingEntity chasing = null;
/**
* Whether the NPC is currently trying to block with a shield.
*/
public boolean isBlocking = false;
/**
* Causes the NPC to start blocking with a shield (if it has one).
*/
public void startBlocking() {
if (!npc.isSpawned() || !(getLivingEntity() instanceof Player) || !itemHelper.hasShield() || shieldAxeCooldown > stats_ticksSpawned) {
if (isBlocking) {
stopBlocking();
}
return;
}
if (SentinelPlugin.debugMe && !isBlocking) {
debug("I'm scared! I'll block with my shield!");
}
isBlocking = true;
PlayerAnimation.START_USE_OFFHAND_ITEM.play((Player) getLivingEntity());
autoSpeedModifier();
}
/**
* Causes the NPC to stop blocking with a shield (if it has one).
*/
public void stopBlocking() {
if (!isBlocking) {
return;
}
if (SentinelPlugin.debugMe) {
debug("I'll put my shield down.");
}
isBlocking = false;
if (!npc.isSpawned() || !(getLivingEntity() instanceof Player) || !itemHelper.hasShield()) {
return;
}
PlayerAnimation.STOP_USE_ITEM.play((Player) getLivingEntity());
autoSpeedModifier();
}
/**
* Sets the NPC's local parameter speed modifier to its proper current value.
*/
public void autoSpeedModifier() {
if (!getNPC().getNavigator().isNavigating()) {
return;
}
double speedMod = isBlocking ? 0.6 : 1.0;
getNPC().getNavigator().getLocalParameters().speedModifier((float) (speed * speedMod));
}
/**
* Gets the UUID of the player this Sentinel is set to be guarding.
* Null indicates not guarding anyone.
*/
public UUID getGuarding() {
if (guardedNPC >= 0) {
NPC npc = CitizensAPI.getNPCRegistry().getById(guardedNPC);
if (npc != null) {
return npc.getUniqueId();
}
}
if (guardingLower == 0 && guardingUpper == 0) {
return null;
}
return new UUID(guardingUpper, guardingLower);
}
/**
* Sets the NPC to be guarding an NPC.
* -1 indicates not guarding anyone.
*/
public void setGuarding(int npcID) {
guardingUpper = 0;
guardingLower = 0;
guardedNPC = npcID;
}
/**
* Sets the NPC to be guarding an entity.
* Null indicates not guarding anyone.
*/
public void setGuarding(UUID uuid) {
guardedNPC = -1;
if (uuid == null) {
guardingUpper = 0;
guardingLower = 0;
}
else {
guardingUpper = uuid.getMostSignificantBits();
guardingLower = uuid.getLeastSignificantBits();
}
}
/**
* Internally tracks whether the damage enforcement system can be used (protects against infinite loops).
*/
private boolean canEnforce = false;
private static EntityDamageEvent.DamageModifier[] modifiersToZero = new EntityDamageEvent.DamageModifier[]{
EntityDamageEvent.DamageModifier.HARD_HAT, EntityDamageEvent.DamageModifier.BLOCKING,
EntityDamageEvent.DamageModifier.RESISTANCE, EntityDamageEvent.DamageModifier.MAGIC,
EntityDamageEvent.DamageModifier.ABSORPTION
};
/**
* How long ago (in ticks) the NPC was last burned.
*/
public int ticksSinceLastBurn = 0;
/**
* Called when this sentinel gets hurt.
*/
public void whenImHurt(EntityDamageEvent event) {
if (SentinelPlugin.debugMe) {
debug("I'm hurt! By " + event.getCause().name() + " for " + event.getFinalDamage() + " hp");
}
switch (event.getCause()) {
case FIRE:
case FIRE_TICK:
case LAVA:
case MELTING:
if (ticksSinceLastBurn <= 20) {
event.setDamage(0);
event.setCancelled(true);
return;
}
ticksSinceLastBurn = 0;
break;
}
}
/**
* When the shield can next be used (based on tick timer), if it has been disabled via axe strike.
*/
public long shieldAxeCooldown = 0;
/**
* Returns a boolean indicating whether a hit from the given damager should be blocked by a shield.
*/
public boolean hitIsBlocked(Entity damager) {
if (!isBlocking) {
return false;
}
if (!itemHelper.hasShield()) {
isBlocking = false;
return false;
}
if (!SentinelUtilities.isLookingTowards(getLivingEntity().getEyeLocation(), damager.getLocation(), 45, 45)) {
return false;
}
if (SentinelVersionCompat.v1_14 && damager instanceof Arrow && ((Arrow) damager).getPierceLevel() > 0) {
return false;
}
if (stats_ticksSpawned < shieldAxeCooldown) {
return false;
}
ItemStack held = damager instanceof LivingEntity ? SentinelUtilities.getHeldItem((LivingEntity) damager) : null;
if (held != null && SentinelVersionCompat.AXE_MATERIALS.contains(held.getType())) {
if (!(damager instanceof Player) || ((Player) damager).isSprinting() || SentinelUtilities.random.nextInt(4) == 1) {
shieldAxeCooldown = stats_ticksSpawned + (20 * 5);
}
}
return true;
}
private static Vector VECTOR_ZERO = new Vector(0, 0, 0);
private boolean hasShownFreshInitWarn = false;
/**
* Called when this sentinel gets attacked, to correct the armor handling.
*/
public void whenAttacksAreHappeningToMe(EntityDamageByEntityEvent event) {
if (event.isCancelled()) {
return;
}
if (!getNPC().isSpawned()) {
return;
}
// Init notice: Only show maximum of once, within 5 minutes of creation, if default fightback is on,
// if the attacker is the owning player, who still has the NPC selected, and the ignore list is unmodified
// Essentially just a giant heuristic for *new user wants to test the NPC on themself but doesn't know there's a default ignore protection check*
if (!hasShownFreshInitWarn && stats_ticksSpawned < 20 * 60 * 5 && fightback
&& event.getDamager() instanceof Player && npc.getOrAddTrait(Owner.class).isOwnedBy(event.getDamager().getUniqueId())
&& CitizensAPI.getDefaultNPCSelector().getSelected(event.getDamager()) == npc) {
hasShownFreshInitWarn = true;
if (allIgnores.totalTargetsCount() == 1 && allIgnores.targetsProcessed.contains(SentinelTarget.OWNER)) {
event.getDamager().sendMessage(SentinelCommand.prefixGood + "Notice: if this is your first time setting up this NPC, don't forget to use "
+ SentinelCommand.colorEmphasis + "/sentinel removeignore owner" + SentinelCommand.colorBasic
+ " once you're done configuring the NPC, if you want it to be able to attack you.");
}
}
double armorLevel = getArmor(getLivingEntity());
if (hitIsBlocked(event.getDamager())) {
armorLevel = (1.0 - armorLevel) * 0.5 + armorLevel;
}
if (!event.isApplicable(EntityDamageEvent.DamageModifier.ARMOR)) {
event.setDamage(EntityDamageEvent.DamageModifier.BASE, (1.0 - armorLevel) * event.getDamage(EntityDamageEvent.DamageModifier.BASE));
}
else {
event.setDamage(EntityDamageEvent.DamageModifier.ARMOR, -armorLevel * event.getDamage(EntityDamageEvent.DamageModifier.BASE));
}
for (EntityDamageEvent.DamageModifier modifier : modifiersToZero) {
if (event.isApplicable(modifier)) {
event.setDamage(modifier, 0);
}
}
if (!allowKnockback) {
getLivingEntity().setVelocity(VECTOR_ZERO);
Bukkit.getScheduler().scheduleSyncDelayedTask(SentinelPlugin.instance, () -> {
if (npc.isSpawned()) {
getLivingEntity().setVelocity(VECTOR_ZERO);
}
}, 1);
}
}
/**
* Called when this sentinel attacks something, to correct damage handling.
*/
public void whenAttacksAreHappeningFromMe(EntityDamageByEntityEvent event) {
if (event.isCancelled()) {
return;
}
if (!npc.isSpawned()) {
return;
}
if (SentinelPlugin.debugMe) {
debug("Damage from me to " + event.getEntityType().name() + " of cause " + event.getCause().name());
}
// NPCs can mis-invoke sweep damage - this is never a wanted/intended effect, so discard it asap.
if (SentinelVersionCompat.v1_9 && event.getCause() == EntityDamageEvent.DamageCause.ENTITY_SWEEP_ATTACK) {
debug("Discard sweep damage");
event.setCancelled(true);
return;
}
if (SentinelPlugin.instance.alternateDamage) {
if (canEnforce) {
canEnforce = false;
whenAttacksHappened(event);
if (!event.isCancelled()) {
((LivingEntity) event.getEntity()).damage(event.getFinalDamage());
if (event.getEntity() instanceof LivingEntity) {
weaponHelper.knockback((LivingEntity) event.getEntity(), 1f);
}
}
if (SentinelPlugin.debugMe) {
debug("enforce damage value to " + event.getFinalDamage());
}
}
else {
debug("refuse damage enforcement");
}
event.setDamage(0);
event.setCancelled(true);
return;
}
double damage = getDamage(false);
if (SentinelPlugin.debugMe) {
debug("correct base damage to " + damage);
}
event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage);
}
/**
* Called when this sentinel attacks something with a projectile, to correct damage handling.
*/
public void whenAttacksAreHappeningFromMyArrow(EntityDamageByEntityEvent event) {
if (event.isCancelled()) {
return;
}
if (!npc.isSpawned()) {
return;
}
if (SentinelPlugin.debugMe) {
debug("Damage from my projectile to " + event.getEntityType().name() + " of cause " + event.getCause().name());
}
if (SentinelPlugin.instance.alternateDamage) {
if (canEnforce) {
canEnforce = false;
whenAttacksHappened(event);
if (!event.isCancelled()) {
((LivingEntity) event.getEntity()).damage(getDamage(true));
if (event.getEntity() instanceof LivingEntity) {
weaponHelper.knockback((LivingEntity) event.getEntity(), 1f);
}
}
if (SentinelPlugin.debugMe) {
debug("enforce damage value to " + getDamage(true));
}
}
else {
if (SentinelPlugin.debugMe) {
debug("refuse damage enforcement");
}
}
event.setDamage(0);
event.setCancelled(true);
return;
}
double dam = getDamage(true);
if (damage < 0 && SentinelUtilities.approxEquals(dam, 1)) { // Allow default damage through for custom / external weapons
return;
}
double modder = event.getDamage(EntityDamageEvent.DamageModifier.BASE);
double rel = modder == 0.0 ? 1.0 : dam / modder;
event.setDamage(EntityDamageEvent.DamageModifier.BASE, dam);
for (EntityDamageEvent.DamageModifier mod : EntityDamageEvent.DamageModifier.values()) {
if (mod != EntityDamageEvent.DamageModifier.BASE && event.isApplicable(mod)) {
event.setDamage(mod, event.getDamage(mod) * rel);
if (SentinelPlugin.debugMe) {
debug("Set damage for " + mod + " to " + event.getDamage(mod));
}
}
}
}
private EntityDamageByEntityEvent damageDeDup = null;
public void whenAttacksHappened(EntityDamageByEntityEvent event) {
if (!npc.isSpawned()) {
return;
}
if (event.isCancelled()) {
return;
}
if (event == damageDeDup) {
return;
}
damageDeDup = event;
Entity damager = event.getDamager();
LivingEntity projectileSource = null;
if (damager instanceof Projectile) {
ProjectileSource source = ((Projectile) damager).getShooter();
if (source instanceof LivingEntity) {
projectileSource = (LivingEntity) source;
damager = projectileSource;
}
}
boolean isMe = event.getEntity().getUniqueId().equals(getLivingEntity().getUniqueId());
if (isMe && (SentinelPlugin.instance.protectFromIgnores || protectFromIgnores)) {
if (damager instanceof LivingEntity && targetingHelper.isIgnored((LivingEntity) damager)) {
event.setCancelled(true);
return;
}
else if (projectileSource != null && targetingHelper.isIgnored(projectileSource)) {
event.setCancelled(true);
return;
}
}
boolean isKilling = event.getEntity() instanceof LivingEntity && event.getFinalDamage() >= ((LivingEntity) event.getEntity()).getHealth();
boolean isFriend = getGuarding() != null && SentinelUtilities.uuidEquals(event.getEntity().getUniqueId(), getGuarding());
boolean attackerIsMe = damager.getUniqueId().equals(getLivingEntity().getUniqueId());
if (projectileSource != null && projectileSource.getUniqueId().equals(getLivingEntity().getUniqueId())) {
attackerIsMe = true;
}
if (isMe || isFriend) {
if (attackerIsMe) {
if (SentinelPlugin.debugMe) {
debug("Ignoring damage I did to " + (isMe ? "myself." : "my friend."));
}
event.setCancelled(true);
return;
}
if (getGuarding() != null && SentinelUtilities.uuidEquals(damager.getUniqueId(), getGuarding())) {
if (isMe && SentinelPlugin.instance.noGuardDamage) {
debug("Ignoring damage from the player we're guarding.");
event.setCancelled(true);
}
return;
}
if (isMe) {