org.spongepowered.api.entity.living.Living Java Examples

The following examples show how to use org.spongepowered.api.entity.living.Living. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PlayerInteractListener.java    From EagleFactions with MIT License 6 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onEntityInteract(final InteractEntityEvent event, @Root final Player player)
{
    final Entity targetEntity = event.getTargetEntity();
    final Optional<Vector3d> optionalInteractionPoint = event.getInteractionPoint();

    if((targetEntity instanceof Living) && !(targetEntity instanceof ArmorStand))
        return;

    final Vector3d blockPosition = optionalInteractionPoint.orElseGet(() -> targetEntity.getLocation().getPosition());
    final Location<World> location = new Location<>(targetEntity.getWorld(), blockPosition);
    boolean canInteractWithEntity = super.getPlugin().getProtectionManager().canInteractWithBlock(location, player, true).hasAccess();
    if(!canInteractWithEntity)
    {
        event.setCancelled(true);
        return;
    }
}
 
Example #2
Source File: SpongeDeathListener.java    From Plan with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Listener
public void onEntityDeath(DestructEntityEvent.Death event) {
    long time = System.currentTimeMillis();
    Living dead = event.getTargetEntity();

    if (dead instanceof Player) {
        // Process Death
        SessionCache.getCachedSession(dead.getUniqueId()).ifPresent(Session::died);
    }

    try {
        Optional<EntityDamageSource> optDamageSource = event.getCause().first(EntityDamageSource.class);
        if (optDamageSource.isPresent()) {
            EntityDamageSource damageSource = optDamageSource.get();
            Entity killerEntity = damageSource.getSource();
            handleKill(time, dead, killerEntity);
        }
    } catch (Exception e) {
        errorLogger.log(L.ERROR, e, ErrorContext.builder().related(event, dead).build());
    }
}
 
Example #3
Source File: MobSpawnExecutor.java    From EssentialCmds with MIT License 6 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	int amount = ctx.<Integer> getOne("amount").get();
	EntityType type = ctx.<EntityType> getOne("mob").get();

	if (src instanceof Player)
	{
		Player player = (Player) src;

		if (!Living.class.isAssignableFrom(type.getEntityClass()))
		{
			player.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "The mob type you inputted is not a living entity."));
			return CommandResult.success();
		}

		this.spawnEntity(getSpawnLocFromPlayerLoc(player).add(0, 1, 0), player, type, amount);
		player.sendMessage(Text.of(TextColors.GREEN, "Success! ", TextColors.YELLOW, "Spawned mob(s)!"));
	}
	else
	{
		src.sendMessage(Text.of(TextColors.DARK_RED, "Error! ", TextColors.RED, "Must be an in-game player to use /mobspawn!"));
	}

	return CommandResult.success();
}
 
Example #4
Source File: CommandHandlers.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
public static void handleKillWorld(CommandSource sender, World world, EntityType type) {
    int killed = 0;
    int total = 0;
    int living = 0;
    for (Entity e : world.getEntities().stream().filter(entity ->
            !(entity instanceof Player) &&
                    ((entity instanceof Living && type == null) || entity.getType().equals(type))
    ).collect(Collectors.toList())) {
        total++;
        if (RedProtect.get().rm.getTopRegion(e.getLocation(), CommandHandlers.class.getName()) == null) {
            e.remove();
            killed++;
        } else if (e instanceof Living && type == null) {
            living++;
        } else if (e.getType().equals(type)) {
            living++;
        }
    }
    RedProtect.get().lang.sendMessage(sender, "cmdmanager.kill", new Replacer[]{
            new Replacer("{total}", String.valueOf(total)),
            new Replacer("{living}", String.valueOf(living)),
            new Replacer("{killed}", String.valueOf(killed)),
            new Replacer("{world}", world.getName())
    });
}
 
Example #5
Source File: EntityEventHandler.java    From GriefDefender with MIT License 5 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onEntityCollideEntity(CollideEntityEvent event) {
    if (!GDFlags.COLLIDE_ENTITY || event instanceof CollideEntityEvent.Impact) {
        return;
    }
    //if (GriefDefenderPlugin.isSourceIdBlacklisted(ClaimFlag.ENTITY_COLLIDE_ENTITY.toString(), event.getSource(), event.getEntities().get(0).getWorld().getProperties())) {
    //    return;
    //}

    Object rootCause = event.getCause().root();
    final boolean isRootEntityItemFrame = rootCause instanceof ItemFrame;
    if (!isRootEntityItemFrame) {
        return;
    }

    GDTimings.ENTITY_COLLIDE_EVENT.startTimingIfSync();
    event.filterEntities(new Predicate<Entity>() {
        @Override
        public boolean test(Entity entity) {
            // Avoid living entities breaking itemframes
            if (isRootEntityItemFrame && entity instanceof Living) {
                return false;
            }

            return true;
        }
    });
    GDTimings.ENTITY_COLLIDE_EVENT.stopTimingIfSync();
}
 
Example #6
Source File: PlayerInteractListener.java    From EagleFactions with MIT License 5 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onItemUse(final InteractItemEvent event, @Root final Player player)
{
    if (event.getItemStack() == ItemStackSnapshot.NONE)
        return;

    final Vector3d interactionPoint = event.getInteractionPoint().orElse(player.getLocation().getPosition());
    Location<World> location = new Location<>(player.getWorld(), interactionPoint);

    //Handle hitting entities
    boolean hasHitEntity = event.getContext().containsKey(EventContextKeys.ENTITY_HIT);
    if(hasHitEntity)
    {
        final Entity hitEntity = event.getContext().get(EventContextKeys.ENTITY_HIT).get();
        if (hitEntity instanceof Living && !(hitEntity instanceof ArmorStand))
            return;

        location = hitEntity.getLocation();
    }

    final ProtectionResult protectionResult = super.getPlugin().getProtectionManager().canUseItem(location, player, event.getItemStack(), true);
    if (!protectionResult.hasAccess())
    {
        event.setCancelled(true);
        return;
    }
}
 
Example #7
Source File: SpongeDeathListener.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void handleKill(long time, Living dead, Entity killerEntity) {
    Runnable processor = null;
    UUID victimUUID = getUUID(dead);
    if (killerEntity instanceof Player) {
        processor = handlePlayerKill(time, victimUUID, (Player) killerEntity);
    } else if (killerEntity instanceof Wolf) {
        processor = handleWolfKill(time, victimUUID, (Wolf) killerEntity);
    } else if (killerEntity instanceof Projectile) {
        processor = handleProjectileKill(time, victimUUID, (Projectile) killerEntity);
    }
    if (processor != null) {
        processing.submit(processor);
    }
}
 
Example #8
Source File: BloodModule.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public void onInit(GameInitializationEvent event) {
    //Config
    TypeSerializers.getDefaultSerializers().registerType(TypeToken.of(BloodEffect.class), new BloodEffect.BloodEffectSerializer());
    config = new RawModuleConfig("blood");
    //Check if all entity types are in the config
    CommentedConfigurationNode node = config.get();
    boolean modified = false;
    //For every entitytype, if it doesnt exist in the config add it
    for (EntityType type : Sponge.getRegistry().getAllOf(CatalogTypes.ENTITY_TYPE)) {
        if (!Living.class.isAssignableFrom(type.getEntityClass())) {
            continue;
        }
        //If entitytype is not in config
        if (node.getNode("types", type.getId(), "enabled").getValue() == null) {
            modified = true;
            CommentedConfigurationNode typenode = node.getNode("types", type.getId());
            try {
                typenode.setValue(TypeToken.of(BloodEffect.class), BloodEffects.DEFAULT);
            } catch (ObjectMappingException e) {
                ErrorLogger.log(e, "Failed to set default blood effect.");
            }
        }
    }
    if (modified) {
        config.save(node);
    }
    //Load blood effects from config
    BloodEffects.reload();
    //Listeners
    Sponge.getEventManager().registerListeners(UltimateCore.get(), new BloodListener());
}
 
Example #9
Source File: EventUtil.java    From Prism with MIT License 5 votes vote down vote up
/**
 * Reject certain events which can only be identified
 * by the change + cause signature.
 *
 * @param a BlockType original
 * @param b BlockType replacement
 * @param cause Cause chain from event
 * @return boolean If should be rejected
 */
public static boolean rejectPlaceEventIdentity(BlockType a, BlockType b, Cause cause) {
    // Things that eat grass...
    if (a.equals(BlockTypes.GRASS) && b.equals(BlockTypes.DIRT)) {
        return cause.first(Living.class).isPresent();
    }

    // Grass-like "Grow" events
    if (a.equals(BlockTypes.DIRT) && b.equals(BlockTypes.GRASS)) {
        return cause.first(BlockSnapshot.class).isPresent();
    }

    // If no entity at fault, we don't care about placement that didn't affect anything
    if (!cause.first(Entity.class).isPresent()) {
        return (a.equals(BlockTypes.AIR));
    }

    // Natural flow/fire.
    // Note: This only allows tracking on the source block set by a player using
    // buckets, or items to set fires. Blocks broken by water, lava or fire are still logged as usual.
    // Full flow/fire tracking would be hard on the database and is generally unnecessary.
    if (!cause.first(Player.class).isPresent()) {
        return (a.equals(BlockTypes.AIR) && (b.equals(BlockTypes.FLOWING_LAVA) || b.equals(BlockTypes.FLOWING_WATER)) ||
        b.equals(BlockTypes.FIRE));
    }

    return false;
}
 
Example #10
Source File: PlayerEventHandler.java    From GriefDefender with MIT License 4 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onPlayerInteractEntity(InteractEntityEvent.Secondary event, @First Player player) {
    if (!GDFlags.INTERACT_ENTITY_SECONDARY || !GriefDefenderPlugin.getInstance().claimsEnabledForWorld(player.getWorld().getUniqueId())) {
        return;
    }

    final Entity targetEntity = event.getTargetEntity();
    final HandType handType = event.getHandType();
    final ItemStack itemInHand = player.getItemInHand(handType).orElse(ItemStack.empty());
    final Object source = player;
    if (GriefDefenderPlugin.isTargetIdBlacklisted(Flags.INTERACT_ENTITY_SECONDARY.getName(), targetEntity, player.getWorld().getProperties())) {
        return;
    }

    GDTimings.PLAYER_INTERACT_ENTITY_SECONDARY_EVENT.startTimingIfSync();
    final Location<World> location = targetEntity.getLocation();
    final GDClaim claim = this.dataStore.getClaimAt(location);
    final GDPlayerData playerData = this.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    if (targetEntity instanceof Living && targetEntity.get(Keys.TAMED_OWNER).isPresent()) {
        final UUID ownerID = targetEntity.get(Keys.TAMED_OWNER).get().orElse(null);
        if (ownerID != null) {
            // always allow owner to interact with their pets
            if (player.getUniqueId().equals(ownerID) || playerData.canIgnoreClaim(claim)) {
                if (playerData.petRecipientUniqueId != null) {
                    targetEntity.offer(Keys.TAMED_OWNER, Optional.of(playerData.petRecipientUniqueId));
                    playerData.petRecipientUniqueId = null;
                    GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().COMMAND_PET_CONFIRMATION);
                    event.setCancelled(true);
                }
                GDTimings.PLAYER_INTERACT_ENTITY_SECONDARY_EVENT.stopTimingIfSync();
                return;
            }
            // If pet protection is enabled, deny the interaction
            if (GriefDefenderPlugin.getActiveConfig(player.getWorld().getProperties()).getConfig().claim.protectTamedEntities) {
                final GDPermissionUser user = PermissionHolderCache.getInstance().getOrCreateUser(ownerID);
                final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.CLAIM_PROTECTED_ENTITY,
                        ImmutableMap.of(
                        "player", user.getName()));
                GriefDefenderPlugin.sendMessage(player, message);
                event.setCancelled(true);
                GDTimings.PLAYER_INTERACT_ENTITY_SECONDARY_EVENT.stopTimingIfSync();
                return;
            }
        }
    }

    if (playerData.canIgnoreClaim(claim)) {
        GDTimings.PLAYER_INTERACT_ENTITY_SECONDARY_EVENT.stopTimingIfSync();
        return;
    }

    Tristate result = GDPermissionManager.getInstance().getFinalPermission(event, location, claim, Flags.INTERACT_ENTITY_SECONDARY, source, targetEntity, player, TrustTypes.ACCESSOR, true);
    if (result == Tristate.TRUE && targetEntity instanceof ArmorStand) {
        result = GDPermissionManager.getInstance().getFinalPermission(event, location, claim, Flags.INTERACT_INVENTORY, source, targetEntity, player, TrustTypes.CONTAINER, false);
    }
    if (result == Tristate.FALSE) {
        event.setCancelled(true);
        this.sendInteractEntityDenyMessage(itemInHand, targetEntity, claim, player, handType);
        GDTimings.PLAYER_INTERACT_ENTITY_SECONDARY_EVENT.stopTimingIfSync();
    }
}
 
Example #11
Source File: SpongeDeathListener.java    From Plan with GNU Lesser General Public License v3.0 4 votes vote down vote up
private UUID getUUID(Living dead) {
    if (dead instanceof Player) {
        return dead.getUniqueId();
    }
    return null;
}
 
Example #12
Source File: PlayerEventHandler.java    From GriefPrevention with MIT License 4 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onPlayerInteractEntity(InteractEntityEvent.Secondary event, @First Player player) {
    if (!GPFlags.INTERACT_ENTITY_SECONDARY || !GriefPreventionPlugin.instance.claimsEnabledForWorld(player.getWorld().getProperties())) {
        return;
    }

    final Entity targetEntity = event.getTargetEntity();
    final HandType handType = event.getHandType();
    final ItemStack itemInHand = player.getItemInHand(handType).orElse(ItemStack.empty());
    final Object source = !itemInHand.isEmpty() ? itemInHand : player;
    if (GriefPreventionPlugin.isTargetIdBlacklisted(ClaimFlag.INTERACT_ENTITY_SECONDARY.toString(), targetEntity, player.getWorld().getProperties())) {
        return;
    }

    GPTimings.PLAYER_INTERACT_ENTITY_SECONDARY_EVENT.startTimingIfSync();
    Location<World> location = targetEntity.getLocation();
    GPClaim claim = this.dataStore.getClaimAt(location);
    GPPlayerData playerData = this.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());

    // if entity is living and has an owner, apply special rules
    if (targetEntity instanceof Living) {
        EntityBridge spongeEntity = (EntityBridge) targetEntity;
        Optional<User> owner = ((OwnershipTrackedBridge) spongeEntity).tracked$getOwnerReference();
        if (owner.isPresent()) {
            UUID ownerID = owner.get().getUniqueId();
            // if the player interacting is the owner or an admin in ignore claims mode, always allow
            if (player.getUniqueId().equals(ownerID) || playerData.canIgnoreClaim(claim)) {
                // if giving away pet, do that instead
                if (playerData.petGiveawayRecipient != null) {
                    SpongeEntityType spongeEntityType = (SpongeEntityType) ((Entity) spongeEntity).getType();
                    if (spongeEntityType.equals(EntityTypes.UNKNOWN) || !spongeEntityType.getModId().equalsIgnoreCase("minecraft")) {
                        final Text message = GriefPreventionPlugin.instance.messageData.commandPetInvalid
                                .apply(ImmutableMap.of(
                                "type", spongeEntityType.getId())).build();
                        GriefPreventionPlugin.sendMessage(player, message);
                        playerData.petGiveawayRecipient = null;
                        GPTimings.PLAYER_INTERACT_ENTITY_SECONDARY_EVENT.stopTimingIfSync();
                        return;
                    }
                    ((Entity) spongeEntity).setCreator(playerData.petGiveawayRecipient.getUniqueId());
                    if (targetEntity instanceof EntityTameable) {
                        EntityTameable tameable = (EntityTameable) targetEntity;
                        tameable.setOwnerId(playerData.petGiveawayRecipient.getUniqueId());
                    } else if (targetEntity instanceof EntityHorse) {
                        EntityHorse horse = (EntityHorse) targetEntity;
                        horse.setOwnerUniqueId(playerData.petGiveawayRecipient.getUniqueId());
                        horse.setHorseTamed(true);
                    }
                    playerData.petGiveawayRecipient = null;
                    GriefPreventionPlugin.sendMessage(player, GriefPreventionPlugin.instance.messageData.commandPetConfirmation.toText());
                    event.setCancelled(true);
                    this.sendInteractEntityDenyMessage(itemInHand, targetEntity, claim, player, handType);
                }
                GPTimings.PLAYER_INTERACT_ENTITY_SECONDARY_EVENT.stopTimingIfSync();
                return;
            }
        }
    }

    if (playerData.canIgnoreClaim(claim)) {
        GPTimings.PLAYER_INTERACT_ENTITY_SECONDARY_EVENT.stopTimingIfSync();
        return;
    }

    Tristate result = GPPermissionHandler.getClaimPermission(event, location, claim, GPPermissions.INTERACT_ENTITY_SECONDARY, source, targetEntity, player, TrustType.ACCESSOR, true);
    if (result == Tristate.TRUE && targetEntity instanceof ArmorStand) {
        result = GPPermissionHandler.getClaimPermission(event, location, claim, GPPermissions.INVENTORY_OPEN, source, targetEntity, player, TrustType.CONTAINER, false);
    }
    if (result == Tristate.FALSE) {
        event.setCancelled(true);
        this.sendInteractEntityDenyMessage(itemInHand, targetEntity, claim, player, handType);
        GPTimings.PLAYER_INTERACT_ENTITY_SECONDARY_EVENT.stopTimingIfSync();
    }
}