use of org.spongepowered.api.event.entity.item.ItemMergeItemEvent in project LanternServer by LanternPowered.
the class LanternItem method combineItemStacks.
@Nullable
private CombineData combineItemStacks(int pickupDelay, int despawnDelay) {
// Remove items with no item stack
final ItemStackSnapshot itemStackSnapshot1 = get(Keys.REPRESENTED_ITEM).orElse(null);
if (itemStackSnapshot1 == null || itemStackSnapshot1.isEmpty()) {
remove();
return null;
}
final int max = itemStackSnapshot1.getType().getMaxStackQuantity();
int quantity1 = itemStackSnapshot1.getQuantity();
// Check if the stack is already at it's maximum size
if (quantity1 >= max) {
return null;
}
final CauseStack causeStack = CauseStack.current();
final CauseStack.Frame frame = causeStack.pushCauseFrame();
frame.pushCause(this);
// Search for surrounding items
final Set<Entity> entities = getWorld().getIntersectingEntities(getBoundingBox().get().expand(0.6, 0.0, 0.6), entity -> entity != this && entity instanceof LanternItem);
ItemStack itemStack1 = null;
for (Entity entity : entities) {
final int pickupDelay1 = entity.get(Keys.PICKUP_DELAY).orElse(0);
if (pickupDelay1 == NO_PICKUP_DELAY) {
continue;
}
final ItemStackSnapshot itemStackSnapshot2 = entity.get(Keys.REPRESENTED_ITEM).get();
int quantity2 = itemStackSnapshot2.getQuantity();
// make sure that the stacks can be merged
if (quantity2 >= max || !LanternItemStack.areSimilar(itemStackSnapshot1, itemStackSnapshot2)) {
continue;
}
// Call the merge event
final ItemMergeItemEvent event = SpongeEventFactory.createItemMergeItemEvent(causeStack.getCurrentCause(), (Item) entity, this);
Sponge.getEventManager().post(event);
if (event.isCancelled()) {
continue;
}
// Merge the items
quantity1 += quantity2;
if (quantity1 > max) {
quantity2 = quantity1 - max;
quantity1 = max;
// Create a new stack and offer it back the entity
final ItemStack itemStack2 = itemStackSnapshot2.createStack();
itemStack2.setQuantity(quantity2);
// The snapshot can be wrapped
entity.offer(Keys.REPRESENTED_ITEM, LanternItemStackSnapshot.wrap(itemStack2));
} else {
// The other entity is completely drained and will be removed
entity.offer(Keys.REPRESENTED_ITEM, ItemStackSnapshot.NONE);
entity.remove();
}
// The item stack has changed
if (itemStack1 == null) {
itemStack1 = itemStackSnapshot1.createStack();
}
itemStack1.setQuantity(quantity1);
// When merging items, also merge the pickup and despawn delays
pickupDelay = Math.max(pickupDelay, pickupDelay1);
despawnDelay = Math.max(despawnDelay, entity.get(Keys.DESPAWN_DELAY).orElse(NO_DESPAWN_DELAY));
// The stack is already full, stop here
if (quantity1 == max) {
break;
}
}
causeStack.popCauseFrame(frame);
if (itemStack1 != null) {
offer(Keys.REPRESENTED_ITEM, LanternItemStackSnapshot.wrap(itemStack1));
return new CombineData(pickupDelay, despawnDelay);
}
return null;
}
Aggregations