-
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathSystemHandler.java
More file actions
917 lines (762 loc) · 37.9 KB
/
Copy pathSystemHandler.java
File metadata and controls
917 lines (762 loc) · 37.9 KB
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
package com.bgsoftware.wildstacker.handlers;
import com.bgsoftware.wildstacker.Locale;
import com.bgsoftware.wildstacker.WildStackerPlugin;
import com.bgsoftware.wildstacker.api.enums.EntityFlag;
import com.bgsoftware.wildstacker.api.enums.SpawnCause;
import com.bgsoftware.wildstacker.api.handlers.SystemManager;
import com.bgsoftware.wildstacker.api.loot.LootEntityAttributes;
import com.bgsoftware.wildstacker.api.loot.LootTable;
import com.bgsoftware.wildstacker.api.objects.StackedBarrel;
import com.bgsoftware.wildstacker.api.objects.StackedEntity;
import com.bgsoftware.wildstacker.api.objects.StackedItem;
import com.bgsoftware.wildstacker.api.objects.StackedObject;
import com.bgsoftware.wildstacker.api.objects.StackedSnapshot;
import com.bgsoftware.wildstacker.api.objects.StackedSpawner;
import com.bgsoftware.wildstacker.api.objects.UnloadedStackedBarrel;
import com.bgsoftware.wildstacker.api.objects.UnloadedStackedSpawner;
import com.bgsoftware.wildstacker.api.spawning.SpawnCondition;
import com.bgsoftware.wildstacker.database.Query;
import com.bgsoftware.wildstacker.hooks.DataSerializer_Default;
import com.bgsoftware.wildstacker.hooks.IDataSerializer;
import com.bgsoftware.wildstacker.loot.entity.EntityLootDataBuilder;
import com.bgsoftware.wildstacker.objects.WStackedBarrel;
import com.bgsoftware.wildstacker.objects.WStackedEntity;
import com.bgsoftware.wildstacker.objects.WStackedItem;
import com.bgsoftware.wildstacker.objects.WStackedSnapshot;
import com.bgsoftware.wildstacker.objects.WStackedSpawner;
import com.bgsoftware.wildstacker.objects.WUnloadedStackedBarrel;
import com.bgsoftware.wildstacker.objects.WUnloadedStackedSpawner;
import com.bgsoftware.wildstacker.tasks.ItemsMerger;
import com.bgsoftware.wildstacker.tasks.KillTask;
import com.bgsoftware.wildstacker.tasks.StackTask;
import com.bgsoftware.wildstacker.utils.GeneralUtils;
import com.bgsoftware.wildstacker.utils.ServerVersion;
import com.bgsoftware.wildstacker.utils.chunks.ChunkPosition;
import com.bgsoftware.wildstacker.utils.data.DataSerializer;
import com.bgsoftware.wildstacker.utils.data.structures.FastEnumMap;
import com.bgsoftware.wildstacker.utils.entity.EntityStorage;
import com.bgsoftware.wildstacker.utils.entity.EntityUtils;
import com.bgsoftware.wildstacker.utils.items.ItemUtils;
import com.bgsoftware.wildstacker.utils.legacy.Materials;
import com.bgsoftware.wildstacker.utils.pair.Pair;
import com.bgsoftware.wildstacker.utils.threads.Executor;
import com.google.common.base.Preconditions;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.inventory.ItemStack;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public final class SystemHandler implements SystemManager {
public static final int ENTITIES_STAGE = (1 << 0);
public static final int CHUNK_STAGE = (1 << 1);
public static final int CHUNK_FULL_STAGE = ENTITIES_STAGE | CHUNK_STAGE;
private final WildStackerPlugin plugin;
private final DataHandler dataHandler;
private final Set<UUID> itemsDisabledNames = new HashSet<>();
private final Set<UUID> entitiesDisabledNames = new HashSet<>();
private final FastEnumMap<EntityType, Set<SpawnCondition>> spawnConditions = new FastEnumMap<>(EntityType.class);
private final Map<String, SpawnCondition> spawnConditionsIds = new HashMap<>();
private boolean loadedData = false;
private IDataSerializer dataSerializer;
public SystemHandler(WildStackerPlugin plugin) {
this.plugin = plugin;
this.dataHandler = plugin.getDataHandler();
this.dataSerializer = new DataSerializer_Default(plugin);
//Start all required tasks
Executor.sync(() -> {
KillTask.start();
StackTask.start();
ItemsMerger.start();
}, 1L);
//Start the auto-clear
Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, this::performCacheClear, 100L, 100L);
//Start the auto-save
Bukkit.getScheduler().runTaskTimer(plugin, this::performCacheSave, 300L, 300L);
}
/*
* StackedObject's methods
*/
@Override
public void removeStackObject(StackedObject stackedObject) {
if (stackedObject instanceof StackedEntity) {
dataHandler.CACHED_ENTITIES.remove(((StackedEntity) stackedObject).getUniqueId());
((StackedEntity) stackedObject).clearFlags();
} else if (stackedObject instanceof StackedItem)
dataHandler.CACHED_ITEMS.remove(((StackedItem) stackedObject).getUniqueId());
else if (stackedObject instanceof StackedSpawner)
dataHandler.removeStackedSpawner((StackedSpawner) stackedObject);
else if (stackedObject instanceof StackedBarrel)
dataHandler.removeStackedBarrel((StackedBarrel) stackedObject);
markToBeUnsaved(stackedObject);
}
@Override
public StackedEntity getStackedEntity(LivingEntity livingEntity) {
StackedEntity stackedEntity = dataHandler.CACHED_ENTITIES.get(livingEntity.getUniqueId());
if (stackedEntity != null && stackedEntity.getLivingEntity() != null)
return stackedEntity;
if (!EntityUtils.isStackable(livingEntity))
throw new IllegalArgumentException("Cannot convert " + livingEntity.getType() + " into a stacked entity.");
//Entity wasn't found, creating a new object
stackedEntity = new WStackedEntity(livingEntity);
Pair<Integer, SpawnCause> entityData = dataHandler.CACHED_ENTITIES_RAW.remove(livingEntity.getUniqueId());
if (entityData != null) {
stackedEntity.setStackAmount(entityData.getKey(), false);
stackedEntity.setSpawnCause(entityData.getValue());
} else {
String cachedData = DataSerializer.deserializeData(stackedEntity.getCustomName());
try {
((WStackedEntity) stackedEntity).setSaveData(false);
if (!cachedData.isEmpty()) {
String[] dataSections = cachedData.split("-");
try {
stackedEntity.setStackAmount(Integer.parseInt(dataSections[0]), false);
} catch (Exception ignored) {
}
try {
stackedEntity.setSpawnCause(SpawnCause.valueOf(Integer.parseInt(dataSections[1])));
} catch (Exception ignored) {
}
try {
if (dataSections[2].equals("1"))
((WStackedEntity) stackedEntity).setNameTag();
} catch (Exception ignored) {
}
stackedEntity.setCustomName(DataSerializer.stripData(stackedEntity.getCustomName()));
} else {
dataSerializer.loadEntity(stackedEntity);
}
} finally {
((WStackedEntity) stackedEntity).setSaveData(true);
}
}
boolean shouldBeCached = stackedEntity.isCached() || stackedEntity.getStackAmount() > 1 ||
!stackedEntity.isDefaultUpgrade();
//A new entity was created. Let's see if we need to add him
if (shouldBeCached)
dataHandler.CACHED_ENTITIES.put(stackedEntity.getUniqueId(), stackedEntity);
boolean deadFlag = shouldBeCached ? dataHandler.CACHED_DEAD_ENTITIES.remove(livingEntity.getUniqueId()) :
dataHandler.CACHED_DEAD_ENTITIES.contains(livingEntity.getUniqueId());
if (deadFlag)
((WStackedEntity) stackedEntity).setDeadFlag(true);
return stackedEntity;
}
@Override
public StackedItem getStackedItem(Item item) {
StackedItem stackedItem = dataHandler.CACHED_ITEMS.get(item.getUniqueId());
if (stackedItem != null && stackedItem.getItem() != null)
return stackedItem;
//Item wasn't found, creating a new object.
stackedItem = new WStackedItem(item);
//Checks if the item still exists after a few ticks
Executor.sync(() -> {
if (item.isDead())
dataHandler.CACHED_ITEMS.remove(item.getUniqueId());
}, 10L);
//A new item was created. Let's see if we need to add him
if (stackedItem.isCached())
dataHandler.CACHED_ITEMS.put(stackedItem.getUniqueId(), stackedItem);
Integer entityData = dataHandler.CACHED_ITEMS_RAW.remove(item.getUniqueId());
if (entityData != null) {
stackedItem.setStackAmount(entityData, false);
} else {
String cachedData = DataSerializer.deserializeData(stackedItem.getCustomName());
try {
((WStackedItem) stackedItem).setSaveData(false);
if (!cachedData.isEmpty()) {
try {
stackedItem.setStackAmount(Integer.parseInt(cachedData), false);
} catch (Exception ignored) {
}
stackedItem.setCustomName(DataSerializer.stripData(stackedItem.getCustomName()));
} else {
dataSerializer.loadItem(stackedItem);
}
// We want to update the item's size if it's above max stack size.
// We do it here so item will not be saved.
if (stackedItem.getStackAmount() > stackedItem.getItemStack().getMaxStackSize())
stackedItem.setStackAmount(stackedItem.getStackAmount(), false);
} finally {
((WStackedItem) stackedItem).setSaveData(true);
}
}
return stackedItem;
}
@Override
public StackedSpawner getStackedSpawner(CreatureSpawner spawner) {
return getStackedSpawner(spawner.getLocation());
}
@Override
public StackedSpawner getStackedSpawner(Location location) {
StackedSpawner stackedSpawner = dataHandler.CACHED_SPAWNERS.get(location);
if (stackedSpawner != null)
return stackedSpawner;
//Spawner wasn't found, creating a new object
stackedSpawner = new WStackedSpawner((CreatureSpawner) location.getBlock().getState());
if (!dataHandler.CACHED_SPAWNERS_RAW.containsKey(location)) {
stackedSpawner.setNatural(true);
}
//A new spawner was created. Let's see if we need to add him
if (stackedSpawner.isCached())
dataHandler.addStackedSpawner(stackedSpawner);
return stackedSpawner;
}
@Override
public StackedBarrel getStackedBarrel(Block block) {
return getStackedBarrel(block == null ? null : block.getLocation());
}
@Override
public StackedBarrel getStackedBarrel(Location location) {
StackedBarrel stackedBarrel = dataHandler.CACHED_BARRELS.get(location);
if (stackedBarrel != null)
return stackedBarrel;
//Barrel wasn't found, creating a new object
stackedBarrel = new WStackedBarrel(location.getBlock(), ItemUtils.getFromBlock(location.getBlock()));
//A new barrel was created. Let's see if we need to add him
if (stackedBarrel.isCached())
dataHandler.addStackedBarrel(stackedBarrel);
return stackedBarrel;
}
@Override
public List<StackedEntity> getStackedEntities() {
return new ArrayList<>(dataHandler.CACHED_ENTITIES.values());
}
@Override
public List<StackedItem> getStackedItems() {
return new ArrayList<>(dataHandler.CACHED_ITEMS.values());
}
@Override
public List<StackedSpawner> getStackedSpawners() {
return (List<StackedSpawner>) dataHandler.CACHED_SPAWNERS.values();
}
@Override
public List<StackedSpawner> getStackedSpawners(Chunk chunk) {
return getStackedSpawners(chunk.getWorld(), chunk.getX(), chunk.getZ());
}
@Override
public List<StackedSpawner> getStackedSpawners(World world, int chunkX, int chunkZ) {
Set<StackedSpawner> chunkSpawners = dataHandler.CACHED_SPAWNERS_BY_CHUNKS.get(new ChunkPosition(world.getName(), chunkX, chunkZ));
return chunkSpawners == null ? new ArrayList<>() : new ArrayList<>(chunkSpawners);
}
@Override
public List<UnloadedStackedSpawner> getAllStackedSpawners() {
List<UnloadedStackedSpawner> spawners = new ArrayList<>();
dataHandler.CACHED_SPAWNERS.collect(spawners, WUnloadedStackedSpawner::new);
dataHandler.CACHED_SPAWNERS_RAW.collect(spawners);
return spawners;
}
@Override
public List<StackedBarrel> getStackedBarrels() {
return (List<StackedBarrel>) dataHandler.CACHED_BARRELS.values();
}
@Override
public List<StackedBarrel> getStackedBarrels(Chunk chunk) {
return getStackedBarrels(chunk.getWorld(), chunk.getX(), chunk.getZ());
}
@Override
public List<StackedBarrel> getStackedBarrels(World world, int chunkX, int chunkZ) {
Set<StackedBarrel> chunkBarrels = dataHandler.CACHED_BARRELS_BY_CHUNKS.get(new ChunkPosition(world.getName(), chunkX, chunkZ));
return chunkBarrels == null ? new ArrayList<>() : new ArrayList<>(chunkBarrels);
}
@Override
public List<UnloadedStackedBarrel> getAllStackedBarrels() {
List<UnloadedStackedBarrel> barrels = new ArrayList<>();
dataHandler.CACHED_BARRELS.collect(barrels, WUnloadedStackedBarrel::new);
dataHandler.CACHED_BARRELS_RAW.collect(barrels);
return barrels;
}
@Override
public boolean isStackedSpawner(Block block) {
return block != null && block.getType() == Materials.SPAWNER.toBukkitType() && isStackedSpawner(block.getLocation());
}
@Override
public boolean isStackedSpawner(Location location) {
return location != null && dataHandler.CACHED_SPAWNERS.containsKey(location);
}
@Override
public boolean isStackedBarrel(Block block) {
return block != null && block.getType() == Material.CAULDRON && isStackedBarrel(block.getLocation());
}
@Override
public boolean isStackedBarrel(Location location) {
return dataHandler.CACHED_BARRELS.containsKey(location);
}
@Override
public void performCacheClear() {
List<StackedObject> stackedObjects = dataHandler.getStackedObjects();
for (StackedObject stackedObject : stackedObjects) {
if (stackedObject instanceof StackedItem) {
StackedItem stackedItem = (StackedItem) stackedObject;
if (stackedItem.getItem() == null || (GeneralUtils.isChunkLoaded(stackedItem.getItem().getLocation()) && stackedItem.getItem().isDead()))
removeStackObject(stackedObject);
} else if (stackedObject instanceof StackedEntity) {
StackedEntity stackedEntity = (StackedEntity) stackedObject;
if (stackedEntity.getLivingEntity() == null || (
GeneralUtils.isChunkLoaded(stackedEntity.getLivingEntity().getLocation()) &&
(stackedEntity.getLivingEntity().isDead() && !hasImportantFlags(stackedEntity))) ||
!EntityUtils.isStackable(stackedEntity.getLivingEntity())) {
removeStackObject(stackedObject);
} else {
stackedEntity.updateNerfed();
}
} else if (stackedObject instanceof StackedSpawner) {
StackedSpawner stackedSpawner = (StackedSpawner) stackedObject;
if (GeneralUtils.isChunkLoaded(stackedSpawner.getLocation()) && !isStackedSpawner(stackedSpawner.getSpawner().getBlock())) {
removeStackObject(stackedObject);
}
} else if (stackedObject instanceof StackedBarrel) {
StackedBarrel stackedBarrel = (StackedBarrel) stackedObject;
Block block = stackedBarrel.getBlock();
if (GeneralUtils.isChunkLoaded(stackedBarrel.getLocation()) && !isStackedBarrel(block)) {
// In some versions, cauldron material can be WATER_CAULDRON.
// Instead of removing the barrel, we just want to set it to CAULDRON.
if (block.getType().name().equals("WATER_CAULDRON")) {
Executor.sync(() -> block.setType(Material.CAULDRON));
} else {
removeStackObject(stackedObject);
stackedBarrel.removeDisplayBlock();
}
}
}
}
}
@Override
public void performCacheSave() {
if (!Bukkit.isPrimaryThread()) {
Executor.sync(this::performCacheSave);
return;
}
Set<StackedObject> savedObjects = new HashSet<>(dataHandler.OBJECTS_TO_SAVE);
dataHandler.OBJECTS_TO_SAVE.clear();
savedObjects.forEach(stackedObject -> {
if (stackedObject instanceof StackedEntity) {
dataSerializer.saveEntity((StackedEntity) stackedObject);
} else if (stackedObject instanceof StackedItem) {
dataSerializer.saveItem((StackedItem) stackedObject);
} else if (stackedObject instanceof StackedSpawner) {
Query.SPAWNER_INSERT.getStatementHolder()
.setLocation(stackedObject.getLocation())
.setInt(stackedObject.getStackAmount())
.setInt(((WStackedSpawner) stackedObject).getUpgradeId())
.execute(true);
} else if (stackedObject instanceof StackedBarrel) {
Query.BARREL_INSERT.getStatementHolder()
.setLocation(stackedObject.getLocation())
.setInt(stackedObject.getStackAmount())
.setItemStack(((StackedBarrel) stackedObject).getBarrelItem(1))
.execute(true);
}
});
}
@Override
public void updateLinkedEntity(LivingEntity livingEntity, LivingEntity newLivingEntity) {
for (StackedSpawner stackedSpawner : getStackedSpawners()) {
LivingEntity linkedEntity = ((WStackedSpawner) stackedSpawner).getRawLinkedEntity();
if (linkedEntity != null && linkedEntity.equals(livingEntity))
stackedSpawner.setLinkedEntity(newLivingEntity);
}
}
@Override
public <T extends Entity> T spawnEntityWithoutStacking(Location location, Class<T> type) {
return spawnEntityWithoutStacking(location, type, SpawnCause.SPAWNER);
}
@Override
public <T extends Entity> T spawnEntityWithoutStacking(Location location, Class<T> type, CreatureSpawnEvent.SpawnReason spawnReason) {
return spawnEntityWithoutStacking(location, type, SpawnCause.valueOf(spawnReason));
}
@Override
public <T extends Entity> T spawnEntityWithoutStacking(Location location, Class<T> type, SpawnCause spawnCause) {
return spawnEntityWithoutStacking(location, type, spawnCause, null, null);
}
@Override
public StackedItem spawnItemWithAmount(Location location, ItemStack itemStack) {
return spawnItemWithAmount(location, itemStack, itemStack.getAmount());
}
@Override
public StackedItem spawnItemWithAmount(Location location, ItemStack itemStack, int amount) {
int limit = ItemUtils.canBeStacked(itemStack, location.getWorld()) ?
plugin.getSettings().itemsLimits.getOrDefault(itemStack.getType(), Integer.MAX_VALUE) :
itemStack.getMaxStackSize();
limit = limit < 1 ? Integer.MAX_VALUE : limit;
int amountOfItems = amount / limit;
int itemLimit = limit;
StackedItem lastDroppedItem = null;
for (int i = 0; i < amountOfItems; i++) {
itemStack = itemStack.clone();
itemStack.setAmount(Math.min(itemStack.getMaxStackSize(), itemLimit));
lastDroppedItem = plugin.getNMSEntities().createItem(location, itemStack, SpawnCause.CUSTOM, stackedItem -> {
if (plugin.getSettings().itemsStackingEnabled)
stackedItem.setStackAmount(itemLimit, stackedItem.isCached());
});
}
int leftOvers = amount % limit;
if (leftOvers > 0) {
itemStack = itemStack.clone();
itemStack.setAmount(Math.min(itemStack.getMaxStackSize(), leftOvers));
lastDroppedItem = plugin.getNMSEntities().createItem(location, itemStack, SpawnCause.CUSTOM, stackedItem -> {
if (plugin.getSettings().itemsStackingEnabled)
stackedItem.setStackAmount(leftOvers, stackedItem.isCached());
});
}
return lastDroppedItem;
}
@Override
public void spawnCorpse(StackedEntity stackedEntity) {
Class<? extends Entity> entityClass = stackedEntity.getType().getEntityClass();
if (entityClass == null)
return;
LivingEntity livingEntity = (LivingEntity) spawnEntityWithoutStacking(stackedEntity.getLocation(), entityClass, SpawnCause.CUSTOM, entity -> {
// Marking the entity as a corpse before the actual spawning
EntityStorage.setMetadata(entity, EntityFlag.CORPSE, true);
return true;
}, entity -> {
// Updating the entity values after the actual spawning
plugin.getNMSAdapter().updateEntity(stackedEntity.getLivingEntity(), (LivingEntity) entity);
});
if (livingEntity != null) {
Executor.sync(() -> {
plugin.getNMSEntities().playDeathSound(livingEntity);
livingEntity.setHealth(0);
Executor.sync(() -> EntityStorage.clearMetadata(livingEntity), 1L);
}, 2L);
}
}
@Override
public void performKillAll() {
performKillAll(false);
}
/*
* General methods
*/
@Override
public void performKillAll(boolean applyTaskFilter) {
performKillAll(entity -> true, item -> true, applyTaskFilter);
}
@Override
public void performKillAll(Predicate<Entity> entityPredicate, Predicate<Item> itemPredicate) {
performKillAll(entityPredicate, itemPredicate, false);
}
@Override
public void performKillAll(Predicate<Entity> entityPredicate, Predicate<Item> itemPredicate, boolean applyTaskFilter) {
if (!Bukkit.isPrimaryThread()) {
Executor.sync(() -> performKillAll(entityPredicate, itemPredicate, applyTaskFilter));
return;
}
List<Entity> entityList = new ArrayList<>();
for (World world : Bukkit.getWorlds()) {
if (!applyTaskFilter || plugin.getSettings().killTaskEntitiesWorlds.isEmpty() ||
plugin.getSettings().killTaskEntitiesWorlds.contains(world.getName())) {
for (Chunk chunk : world.getLoadedChunks()) {
entityList.addAll(Arrays.stream(chunk.getEntities())
.filter(entity -> entity instanceof LivingEntity).collect(Collectors.toList()));
}
}
if (!applyTaskFilter || plugin.getSettings().killTaskItemsWorlds.isEmpty() ||
plugin.getSettings().killTaskItemsWorlds.contains(world.getName())) {
for (Chunk chunk : world.getLoadedChunks()) {
entityList.addAll(Arrays.stream(chunk.getEntities())
.filter(entity -> entity instanceof Item).collect(Collectors.toList()));
}
}
}
Executor.async(() -> {
entityList.stream()
.filter(entity -> EntityUtils.isStackable(entity) && entityPredicate.test(entity) &&
(!applyTaskFilter || (GeneralUtils.containsOrEmpty(plugin.getSettings().killTaskEntitiesWhitelist, WStackedEntity.of(entity)) &&
!GeneralUtils.contains(plugin.getSettings().killTaskEntitiesBlacklist, WStackedEntity.of(entity)))))
.forEach(entity -> {
StackedEntity stackedEntity = WStackedEntity.of(entity);
if (!applyTaskFilter || (((plugin.getSettings().killTaskStackedEntities && stackedEntity.getStackAmount() > 1) ||
(plugin.getSettings().killTaskUnstackedEntities && stackedEntity.getStackAmount() <= 1)) && !stackedEntity.hasNameTag()))
stackedEntity.remove();
});
if (plugin.getSettings().killTaskStackedItems) {
entityList.stream()
.filter(entity -> ItemUtils.isStackable(entity) && ItemUtils.canPickup((Item) entity) && itemPredicate.test((Item) entity) &&
(!applyTaskFilter || (GeneralUtils.containsOrEmpty(plugin.getSettings().killTaskItemsWhitelist, ((Item) entity).getItemStack().getType()) &&
!plugin.getSettings().killTaskItemsBlacklist.contains(((Item) entity).getItemStack().getType()))))
.forEach(entity -> {
StackedItem stackedItem = WStackedItem.of(entity);
int maxStackSize = ((Item) entity).getItemStack().getMaxStackSize();
if (!applyTaskFilter || stackedItem.getStackAmount() > maxStackSize ||
(plugin.getSettings().killTaskUnstackedItems && stackedItem.getStackAmount() <= maxStackSize))
stackedItem.remove();
});
}
for (Player pl : Bukkit.getOnlinePlayers()) {
if (pl.isOp())
Locale.KILL_ALL_OPS.send(pl);
}
});
}
@Override
public LootTable getLootTable(LivingEntity livingEntity) {
return plugin.getLootHandler().getLootTable(livingEntity);
}
@Override
public LootEntityAttributes.Builder createLootContextBuilder(EntityType entityType) {
Preconditions.checkNotNull(entityType, "entityType parameter cannot be null.");
return new EntityLootDataBuilder(entityType);
}
@Override
public LootEntityAttributes.Builder createLootContextBuilder(StackedEntity stackedEntity) {
Preconditions.checkNotNull(stackedEntity, "stackedEntity parameter cannot be null.");
return new EntityLootDataBuilder(stackedEntity.getLivingEntity());
}
@Override
public LootEntityAttributes.Builder createLootContextBuilder(LivingEntity livingEntity) {
Preconditions.checkNotNull(livingEntity, "livingEntity parameter cannot be null.");
return new EntityLootDataBuilder(livingEntity);
}
@Override
public StackedSnapshot getStackedSnapshot(Chunk chunk, boolean loadData) {
return getStackedSnapshot(chunk);
}
@Override
public StackedSnapshot getStackedSnapshot(Chunk chunk) {
return getStackedSnapshot(chunk, StackedSnapshot.SnapshotOptions.LOAD_BARRELS,
StackedSnapshot.SnapshotOptions.LOAD_SPAWNERS);
}
@Override
public StackedSnapshot getStackedSnapshot(Chunk chunk, StackedSnapshot.SnapshotOptions... snapshotOptions) {
chunk.load(false);
return new WStackedSnapshot(chunk, snapshotOptions);
}
@Override
public boolean hasItemNamesToggledOff(Player player) {
return itemsDisabledNames.contains(player.getUniqueId());
}
@Override
public void toggleItemNames(Player player) {
// If the set contained the uuid (aka, the player had items toggled off), he will be removed and nothing else.
// If the set didn't contain the uuid, then the player will be added to it.
if (!itemsDisabledNames.remove(player.getUniqueId()))
itemsDisabledNames.add(player.getUniqueId());
}
@Override
public boolean hasEntityNamesToggledOff(Player player) {
return entitiesDisabledNames.contains(player.getUniqueId());
}
@Override
public void toggleEntityNames(Player player) {
// If the set contained the uuid (aka, the player had entities toggled off), he will be removed and nothing else.
// If the set didn't contain the uuid, then the player will be added to it.
if (!entitiesDisabledNames.remove(player.getUniqueId()))
entitiesDisabledNames.add(player.getUniqueId());
}
@Override
public void addSpawnCondition(SpawnCondition spawnCondition, EntityType... entityTypes) {
for (EntityType entityType : entityTypes)
spawnConditions.computeIfAbsent(entityType, new HashSet<>(1)).add(spawnCondition);
}
@Override
public Collection<SpawnCondition> getSpawnConditions(EntityType entityType) {
return Collections.unmodifiableSet(spawnConditions.getOrDefault(entityType, new HashSet<>()));
}
@Override
public void removeSpawnCondition(EntityType entityType, SpawnCondition spawnCondition) {
Set<SpawnCondition> spawnConditionSet = spawnConditions.get(entityType);
if (spawnConditionSet != null)
spawnConditionSet.remove(spawnCondition);
}
/*
* Loot loot methods
*/
@Override
public void clearSpawnConditions(EntityType entityType) {
spawnConditions.remove(entityType);
}
/*
* Names toggle methods
*/
@Override
public Optional<SpawnCondition> getSpawnCondition(String id) {
return Optional.ofNullable(spawnConditionsIds.get(id.toLowerCase()));
}
@Override
public SpawnCondition registerSpawnCondition(SpawnCondition spawnCondition) {
spawnConditionsIds.put(spawnCondition.getId().toLowerCase(), spawnCondition);
return spawnCondition;
}
public boolean isBarrelBlock(Material blockType, World world) {
return (plugin.getSettings().whitelistedBarrels.size() == 0 ||
plugin.getSettings().whitelistedBarrels.contains(blockType)) &&
!plugin.getSettings().blacklistedBarrels.contains(blockType) &&
!plugin.getSettings().barrelsDisabledWorlds.contains(world.getName());
}
public void markToBeSaved(StackedObject stackedObject) {
dataHandler.OBJECTS_TO_SAVE.add(stackedObject);
}
/*
* Spawn condition methods
*/
public void markToBeUnsaved(StackedObject stackedObject) {
dataHandler.OBJECTS_TO_SAVE.remove(stackedObject);
}
public void loadSpawners(Chunk chunk) {
ChunkPosition chunkPosition = new ChunkPosition(chunk);
Collection<UnloadedStackedSpawner> spawnersToLoad = dataHandler.CACHED_SPAWNERS_RAW.remove(chunkPosition);
for (UnloadedStackedSpawner unloadedStackedSpawner : spawnersToLoad) {
Location spawnerLocation = new Location(chunk.getWorld(), unloadedStackedSpawner.getX(),
unloadedStackedSpawner.getY(), unloadedStackedSpawner.getZ());
Block block = spawnerLocation.getBlock();
if (block.getType() == Materials.SPAWNER.toBukkitType()) {
WStackedSpawner stackedSpawner = new WStackedSpawner((CreatureSpawner) block.getState());
try {
stackedSpawner.setSaveData(false);
stackedSpawner.setUpgradeId(((WUnloadedStackedSpawner) unloadedStackedSpawner).getUpgradeId(), null, false);
stackedSpawner.setStackAmount(unloadedStackedSpawner.getStackAmount(), true);
dataHandler.addStackedSpawner(stackedSpawner);
} finally {
stackedSpawner.setSaveData(true);
}
}
}
if (plugin.getSettings().spawnersOverrideEnabled) {
plugin.getNMSSpawners().updateStackedSpawners(chunk);
}
}
public void loadBarrels(Chunk chunk) {
ChunkPosition chunkPosition = new ChunkPosition(chunk);
Collection<UnloadedStackedBarrel> barrelsToLoad = dataHandler.CACHED_BARRELS_RAW.remove(chunkPosition);
for (UnloadedStackedBarrel unloadedStackedBarrel : barrelsToLoad) {
Location barrelLocation = new Location(chunk.getWorld(), unloadedStackedBarrel.getX(),
unloadedStackedBarrel.getY(), unloadedStackedBarrel.getZ());
Block block = barrelLocation.getBlock();
if (block.getType() == Material.CAULDRON) {
WStackedBarrel stackedBarrel = new WStackedBarrel(block, unloadedStackedBarrel.getBarrelItem(1));
try {
stackedBarrel.setSaveData(false);
stackedBarrel.setStackAmount(unloadedStackedBarrel.getStackAmount(), true);
stackedBarrel.createDisplayBlock();
dataHandler.addStackedBarrel(stackedBarrel);
} finally {
stackedBarrel.setSaveData(true);
}
}
}
}
public void handleChunkLoad(Chunk chunk, int unloadStage) {
this.handleChunkLoad(chunk, unloadStage, Arrays.asList(chunk.getEntities()));
}
public void handleChunkLoad(Chunk chunk, int loadStage, List<Entity> loadedEntities) {
if (!this.loadedData)
return;
boolean isChunkLoad = (loadStage & CHUNK_STAGE) != 0;
boolean isEntitiesLoad = (loadStage & ENTITIES_STAGE) != 0;
boolean atLeast18 = ServerVersion.isAtLeast(ServerVersion.v1_8);
if (isChunkLoad) {
loadSpawners(chunk);
if (atLeast18)
loadBarrels(chunk);
}
if (isEntitiesLoad) {
for (Entity entity : loadedEntities) {
String customName = plugin.getNMSEntities().getCustomName(entity);
// Checking for too long names
if (customName != null && customName.length() > 256)
plugin.getNMSEntities().setCustomName(entity, customName.substring(0, 256));
// Remove display blocks of invalid barrels
if (atLeast18 && entity instanceof ArmorStand && customName != null &&
customName.equals("BlockDisplay") && !isStackedBarrel(entity.getLocation().getBlock())) {
Block block = entity.getLocation().getBlock();
if (block.getType() == Material.CAULDRON)
block.setType(Material.AIR);
entity.remove();
}
if (EntityUtils.isStackable(entity)) {
StackedEntity stackedEntity = WStackedEntity.of(entity);
stackedEntity.updateNerfed();
stackedEntity.updateName();
}
}
}
}
public void handleChunkUnload(Chunk chunk, int unloadStage) {
this.handleChunkUnload(chunk, unloadStage, Arrays.asList(chunk.getEntities()));
}
public void saveEntity(StackedEntity stackedEntity) {
dataSerializer.saveEntity(stackedEntity);
}
public void saveItem(StackedItem stackedItem) {
dataSerializer.saveItem(stackedItem);
}
public void handleChunkUnload(Chunk chunk, int unloadStage, List<Entity> unloadedEntities) {
if (!this.loadedData)
return;
boolean isChunkLoad = (unloadStage & CHUNK_STAGE) != 0;
boolean isEntitiesLoad = (unloadStage & ENTITIES_STAGE) != 0;
if (isEntitiesLoad) {
for (Entity entity : unloadedEntities) {
if (EntityUtils.isStackable(entity)) {
StackedEntity stackedEntity = dataHandler.CACHED_ENTITIES.remove(entity.getUniqueId());
if (stackedEntity != null) {
dataSerializer.saveEntity(stackedEntity);
stackedEntity.clearFlags();
}
} else if (entity instanceof Item) {
StackedItem stackedItem = dataHandler.CACHED_ITEMS.remove(entity.getUniqueId());
if (stackedItem != null)
dataSerializer.saveItem(stackedItem);
}
}
}
if (isChunkLoad) {
for (StackedSpawner stackedSpawner : getStackedSpawners(chunk)) {
dataHandler.removeStackedSpawner(stackedSpawner);
if (stackedSpawner.getStackAmount() > 1 || !stackedSpawner.isDefaultUpgrade()) {
dataHandler.CACHED_SPAWNERS_RAW.put(stackedSpawner.getLocation(), new WUnloadedStackedSpawner(stackedSpawner));
}
}
for (StackedBarrel stackedBarrel : getStackedBarrels(chunk)) {
dataHandler.removeStackedBarrel(stackedBarrel);
dataHandler.CACHED_BARRELS_RAW.put(stackedBarrel.getLocation(), new WUnloadedStackedBarrel(stackedBarrel));
stackedBarrel.removeDisplayBlock();
}
}
}
public void setDataLoaded() {
this.loadedData = true;
}
@Nullable
public <T extends Entity> T spawnEntityWithoutStacking(Location location, Class<T> type, SpawnCause spawnCause,
Predicate<Entity> beforeSpawnConsumer, Consumer<Entity> afterSpawnConsumer) {
return plugin.getNMSEntities().createEntity(location, type, spawnCause, entity -> {
EntityStorage.setMetadata(entity, EntityFlag.BYPASS_STACKING, true);
return beforeSpawnConsumer == null || beforeSpawnConsumer.test(entity);
}, afterSpawnConsumer);
}
/*
* Data serialization methods
*/
public void setDataSerializer(IDataSerializer dataSerializer) {
this.dataSerializer = dataSerializer;
}
private static boolean hasImportantFlags(StackedEntity stackedEntity) {
return stackedEntity.hasFlag(EntityFlag.DEAD_ENTITY) || stackedEntity.hasFlag(EntityFlag.ORIGINAL_AMOUNT);
}
}