Search in sources :

Example 6 with Projectile

use of org.spongepowered.api.entity.projectile.Projectile in project RedProtect by FabioZumbi12.

the class RPPlayerListener method onEntityDamageEvent.

@Listener(order = Order.FIRST, beforeModifications = true)
public void onEntityDamageEvent(DamageEntityEvent e) {
    // victim
    Entity e1 = e.getTargetEntity();
    // damager
    Entity e2 = null;
    if (e.getCause().first(IndirectEntityDamageSource.class).isPresent()) {
        e2 = e.getCause().first(IndirectEntityDamageSource.class).get().getSource();
        RedProtect.get().logger.debug("player", "RPLayerListener: Is DamageEntityEvent event. Damager " + e2.getType().getName());
    }
    Player damager = null;
    if (e2 instanceof Projectile) {
        Projectile proj = (Projectile) e2;
        if (proj.getShooter() instanceof Player) {
            damager = (Player) proj.getShooter();
        }
    } else if (e2 instanceof Player) {
        damager = (Player) e2;
    }
    Location<World> l = e1.getLocation();
    Region r = RedProtect.get().rm.getTopRegion(l);
    if (r == null) {
        return;
    }
    RedProtect.get().logger.debug("player", "RPLayerListener: Is DamageEntityEvent event. Victim " + e1.getType().getName());
    if (damager instanceof Player) {
        if (e1 instanceof Hanging && !r.canBuild(damager)) {
            RPLang.sendMessage(damager, "entitylistener.region.cantinteract");
            e.setCancelled(true);
            return;
        }
        if (e1 instanceof Player && r.flagExists("pvp") && !r.canPVP(damager)) {
            RPLang.sendMessage(damager, "entitylistener.region.cantpvp");
            e.setCancelled(true);
            return;
        }
    }
    // return if not player
    if (!(e1 instanceof Player)) {
        return;
    }
    Player play = (Player) e.getTargetEntity();
    if (RedProtect.get().tpWait.contains(play.getName())) {
        RedProtect.get().tpWait.remove(play.getName());
        RPLang.sendMessage(play, RPLang.get("cmdmanager.region.tpcancelled"));
    }
    if (r != null && !r.canPlayerDamage()) {
        e.setCancelled(true);
    }
    // execute on health
    if (r.cmdOnHealth(play)) {
        RedProtect.get().logger.debug("player", "Cmd on healt: true");
    }
    if (!r.canDeath() && play.get(Keys.HEALTH).get() <= 1) {
        e.setCancelled(true);
    }
    // deny damagecauses
    List<String> Causes = RedProtect.get().cfgs.getStringList("server-protection.deny-playerdeath-by");
    if (e.getCause().containsType(DamageSource.class) && Causes.size() > 0) {
        DamageType damagec = e.getCause().first(DamageSource.class).get().getType();
        for (String cause : Causes) {
            if (damagec.getName().equalsIgnoreCase(cause)) {
                e.setCancelled(true);
            }
        }
    }
}
Also used : Entity(org.spongepowered.api.entity.Entity) Player(org.spongepowered.api.entity.living.player.Player) DamageSource(org.spongepowered.api.event.cause.entity.damage.source.DamageSource) IndirectEntityDamageSource(org.spongepowered.api.event.cause.entity.damage.source.IndirectEntityDamageSource) Hanging(org.spongepowered.api.entity.hanging.Hanging) Region(br.net.fabiozumbi12.RedProtect.Sponge.Region) IndirectEntityDamageSource(org.spongepowered.api.event.cause.entity.damage.source.IndirectEntityDamageSource) World(org.spongepowered.api.world.World) DamageType(org.spongepowered.api.event.cause.entity.damage.DamageType) Projectile(org.spongepowered.api.entity.projectile.Projectile) Listener(org.spongepowered.api.event.Listener)

Example 7 with Projectile

use of org.spongepowered.api.entity.projectile.Projectile in project RedProtect by FabioZumbi12.

the class EntityListener method onEntityDamage.

@Listener(order = Order.FIRST, beforeModifications = true)
public void onEntityDamage(DamageEntityEvent e, @First Entity e2) {
    Entity e1 = e.getTargetEntity();
    Location<World> loc = e1.getLocation();
    Player damager = null;
    if (e2 instanceof Projectile) {
        Projectile proj = (Projectile) e2;
        if (proj.getShooter() instanceof Player) {
            damager = (Player) proj.getShooter();
        }
    } else if (e2 instanceof Player) {
        damager = (Player) e2;
    }
    Region r1 = RedProtect.get().getRegionManager().getTopRegion(loc, this.getClass().getName());
    if (r1 == null) {
        // global flags
        if (e1 instanceof ArmorStand) {
            if (e2 instanceof Player) {
                if (!RedProtect.get().getConfigManager().globalFlagsRoot().worlds.get(loc.getExtent().getName()).build) {
                    e.setCancelled(true);
                    return;
                }
            }
        }
        return;
    }
    if (e1 instanceof ArmorStand) {
        if (!r1.canBuild(damager)) {
            e.setCancelled(true);
            RedProtect.get().getLanguageManager().sendMessage(damager, "blocklistener.region.cantbreak");
        }
    }
}
Also used : Entity(org.spongepowered.api.entity.Entity) Player(org.spongepowered.api.entity.living.player.Player) Region(br.net.fabiozumbi12.RedProtect.Sponge.Region) World(org.spongepowered.api.world.World) Projectile(org.spongepowered.api.entity.projectile.Projectile) Listener(org.spongepowered.api.event.Listener)

Example 8 with Projectile

use of org.spongepowered.api.entity.projectile.Projectile in project SpongeCommon by SpongePowered.

the class EntityTickPhaseState method unwind.

@SuppressWarnings("unchecked")
@Override
public void unwind(EntityTickContext phaseContext) {
    final Entity tickingEntity = phaseContext.getSource(Entity.class).orElseThrow(TrackingUtil.throwWithContext("Not ticking on an Entity!", phaseContext));
    final Optional<User> creator = phaseContext.getOwner();
    final Optional<User> notifier = phaseContext.getNotifier();
    final User entityCreator = notifier.orElseGet(() -> creator.orElse(null));
    try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
        Sponge.getCauseStackManager().pushCause(tickingEntity);
        phaseContext.addNotifierAndOwnerToCauseStack();
        phaseContext.getCapturedEntitySupplier().acceptAndClearIfNotEmpty(entities -> {
            final List<Entity> experience = new ArrayList<Entity>(entities.size());
            final List<Entity> nonExp = new ArrayList<Entity>(entities.size());
            final List<Entity> breeding = new ArrayList<Entity>(entities.size());
            final List<Entity> projectile = new ArrayList<Entity>(entities.size());
            for (Entity entity : entities) {
                if (entity instanceof EntityXPOrb) {
                    experience.add(entity);
                } else if (tickingEntity instanceof Ageable && tickingEntity.getClass() == entity.getClass()) {
                    breeding.add(entity);
                } else if (entity instanceof Projectile) {
                    projectile.add(entity);
                } else {
                    nonExp.add(entity);
                }
            }
            if (!experience.isEmpty()) {
                Sponge.getCauseStackManager().addContext(EventContextKeys.SPAWN_TYPE, InternalSpawnTypes.EXPERIENCE);
                if (EntityUtil.isEntityDead(tickingEntity)) {
                    if (tickingEntity instanceof EntityLivingBase) {
                        CombatEntry entry = ((EntityLivingBase) tickingEntity).getCombatTracker().getBestCombatEntry();
                        if (entry != null) {
                            if (entry.damageSrc != null) {
                                Sponge.getCauseStackManager().addContext(EventContextKeys.LAST_DAMAGE_SOURCE, (DamageSource) entry.damageSrc);
                            }
                        }
                    }
                }
                final SpawnEntityEvent event = SpongeEventFactory.createSpawnEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), experience);
                if (!SpongeImpl.postEvent(event)) {
                    for (Entity entity : event.getEntities()) {
                        if (entityCreator != null) {
                            EntityUtil.toMixin(entity).setCreator(entityCreator.getUniqueId());
                        }
                        EntityUtil.getMixinWorld(entity).forceSpawnEntity(entity);
                    }
                }
                Sponge.getCauseStackManager().removeContext(EventContextKeys.LAST_DAMAGE_SOURCE);
            }
            if (!breeding.isEmpty()) {
                Sponge.getCauseStackManager().addContext(EventContextKeys.SPAWN_TYPE, InternalSpawnTypes.BREEDING);
                if (tickingEntity instanceof EntityAnimal) {
                    final EntityPlayer playerInLove = ((EntityAnimal) tickingEntity).getLoveCause();
                    if (playerInLove != null) {
                        Sponge.getCauseStackManager().addContext(EventContextKeys.PLAYER, (Player) playerInLove);
                    }
                }
                SpawnEntityEvent event = SpongeEventFactory.createSpawnEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), breeding);
                if (!SpongeImpl.postEvent(event)) {
                    for (Entity entity : event.getEntities()) {
                        if (entityCreator != null) {
                            EntityUtil.toMixin(entity).setCreator(entityCreator.getUniqueId());
                        }
                        EntityUtil.getMixinWorld(entity).forceSpawnEntity(entity);
                    }
                }
                Sponge.getCauseStackManager().removeContext(EventContextKeys.PLAYER);
            }
            if (!projectile.isEmpty()) {
                Sponge.getCauseStackManager().addContext(EventContextKeys.SPAWN_TYPE, InternalSpawnTypes.PROJECTILE);
                final SpawnEntityEvent event = SpongeEventFactory.createSpawnEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), projectile);
                SpongeImpl.postEvent(event);
                if (!event.isCancelled()) {
                    for (Entity entity : event.getEntities()) {
                        if (entityCreator != null) {
                            entity.setCreator(entityCreator.getUniqueId());
                        }
                        EntityUtil.getMixinWorld(entity).forceSpawnEntity(entity);
                    }
                }
            }
            Sponge.getCauseStackManager().addContext(EventContextKeys.SPAWN_TYPE, InternalSpawnTypes.PASSIVE);
            final SpawnEntityEvent event = SpongeEventFactory.createSpawnEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), nonExp);
            SpongeImpl.postEvent(event);
            if (!event.isCancelled()) {
                for (Entity entity : event.getEntities()) {
                    if (entityCreator != null) {
                        entity.setCreator(entityCreator.getUniqueId());
                    }
                    EntityUtil.getMixinWorld(entity).forceSpawnEntity(entity);
                }
            }
        });
        phaseContext.getCapturedItemsSupplier().acceptAndClearIfNotEmpty(entities -> {
            final ArrayList<Entity> capturedEntities = new ArrayList<>();
            for (EntityItem entity : entities) {
                capturedEntities.add(EntityUtil.fromNative(entity));
            }
            Sponge.getCauseStackManager().addContext(EventContextKeys.SPAWN_TYPE, InternalSpawnTypes.DROPPED_ITEM);
            final DropItemEvent.Custom event = SpongeEventFactory.createDropItemEventCustom(Sponge.getCauseStackManager().getCurrentCause(), capturedEntities);
            SpongeImpl.postEvent(event);
            if (!event.isCancelled()) {
                for (Entity entity : event.getEntities()) {
                    if (entityCreator != null) {
                        EntityUtil.toMixin(entity).setCreator(entityCreator.getUniqueId());
                    }
                    EntityUtil.getMixinWorld(entity).forceSpawnEntity(entity);
                }
            }
        });
        phaseContext.getCapturedBlockSupplier().acceptAndClearIfNotEmpty(blockSnapshots -> TrackingUtil.processBlockCaptures(blockSnapshots, this, phaseContext));
        phaseContext.getBlockItemDropSupplier().acceptIfNotEmpty(map -> {
            final List<BlockSnapshot> capturedBlocks = phaseContext.getCapturedBlocks();
            for (BlockSnapshot snapshot : capturedBlocks) {
                final BlockPos blockPos = ((IMixinLocation) (Object) snapshot.getLocation().get()).getBlockPos();
                final Collection<EntityItem> entityItems = map.get(blockPos);
                if (!entityItems.isEmpty()) {
                    Sponge.getCauseStackManager().pushCause(snapshot);
                    Sponge.getCauseStackManager().addContext(EventContextKeys.SPAWN_TYPE, InternalSpawnTypes.DROPPED_ITEM);
                    final List<Entity> items = entityItems.stream().map(EntityUtil::fromNative).collect(Collectors.toList());
                    final DropItemEvent.Destruct event = SpongeEventFactory.createDropItemEventDestruct(Sponge.getCauseStackManager().getCurrentCause(), items);
                    SpongeImpl.postEvent(event);
                    if (!event.isCancelled()) {
                        for (Entity entity : event.getEntities()) {
                            creator.ifPresent(user -> entity.setCreator(user.getUniqueId()));
                            EntityUtil.getMixinWorld(entity).forceSpawnEntity(entity);
                        }
                    }
                    Sponge.getCauseStackManager().popCause();
                }
            }
        });
        phaseContext.getCapturedItemStackSupplier().acceptAndClearIfNotEmpty(drops -> {
            final List<EntityItem> items = drops.stream().map(drop -> drop.create(EntityUtil.getMinecraftWorld(tickingEntity))).collect(Collectors.toList());
            Sponge.getCauseStackManager().addContext(EventContextKeys.SPAWN_TYPE, InternalSpawnTypes.DROPPED_ITEM);
            final List<Entity> entities = (List<Entity>) (List<?>) items;
            if (!entities.isEmpty()) {
                DropItemEvent.Custom event = SpongeEventFactory.createDropItemEventCustom(Sponge.getCauseStackManager().getCurrentCause(), entities);
                SpongeImpl.postEvent(event);
                if (!event.isCancelled()) {
                    for (Entity droppedItem : event.getEntities()) {
                        EntityUtil.getMixinWorld(droppedItem).forceSpawnEntity(droppedItem);
                    }
                }
            }
        });
        this.fireMovementEvents(EntityUtil.toNative(tickingEntity));
    }
}
Also used : SpongeImpl(org.spongepowered.common.SpongeImpl) EntityItemFrame(net.minecraft.entity.item.EntityItemFrame) EventContextKeys(org.spongepowered.api.event.cause.EventContextKeys) ExplosionContext(org.spongepowered.common.event.tracking.phase.general.ExplosionContext) Vector3d(com.flowpowered.math.vector.Vector3d) DropItemEvent(org.spongepowered.api.event.item.inventory.DropItemEvent) DamageSource(org.spongepowered.api.event.cause.entity.damage.source.DamageSource) ArrayList(java.util.ArrayList) EntityXPOrb(net.minecraft.entity.item.EntityXPOrb) CombatEntry(net.minecraft.util.CombatEntry) TrackingUtil(org.spongepowered.common.event.tracking.TrackingUtil) Ageable(org.spongepowered.api.entity.living.Ageable) EntityHanging(net.minecraft.entity.EntityHanging) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Transaction(org.spongepowered.api.data.Transaction) Nullable(javax.annotation.Nullable) EntityItem(net.minecraft.entity.item.EntityItem) User(org.spongepowered.api.entity.living.player.User) IMixinLocation(org.spongepowered.common.interfaces.world.IMixinLocation) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) Collection(java.util.Collection) Sponge(org.spongepowered.api.Sponge) BlockPos(net.minecraft.util.math.BlockPos) SpawnEntityEvent(org.spongepowered.api.event.entity.SpawnEntityEvent) IProjectile(net.minecraft.entity.IProjectile) InternalSpawnTypes(org.spongepowered.common.registry.type.event.InternalSpawnTypes) Entity(org.spongepowered.api.entity.Entity) Collectors(java.util.stream.Collectors) BlockChange(org.spongepowered.common.world.BlockChange) EntityUtil(org.spongepowered.common.entity.EntityUtil) EntityAnimal(net.minecraft.entity.passive.EntityAnimal) List(java.util.List) EntityLivingBase(net.minecraft.entity.EntityLivingBase) EntityPlayer(net.minecraft.entity.player.EntityPlayer) Transform(org.spongepowered.api.entity.Transform) World(org.spongepowered.api.world.World) VecHelper(org.spongepowered.common.util.VecHelper) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) Projectile(org.spongepowered.api.entity.projectile.Projectile) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) MoveEntityEvent(org.spongepowered.api.event.entity.MoveEntityEvent) Entity(org.spongepowered.api.entity.Entity) User(org.spongepowered.api.entity.living.player.User) ArrayList(java.util.ArrayList) CombatEntry(net.minecraft.util.CombatEntry) Ageable(org.spongepowered.api.entity.living.Ageable) CauseStackManager(org.spongepowered.api.event.CauseStackManager) BlockPos(net.minecraft.util.math.BlockPos) ArrayList(java.util.ArrayList) List(java.util.List) EntityAnimal(net.minecraft.entity.passive.EntityAnimal) EntityItem(net.minecraft.entity.item.EntityItem) DropItemEvent(org.spongepowered.api.event.item.inventory.DropItemEvent) IMixinLocation(org.spongepowered.common.interfaces.world.IMixinLocation) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) SpawnEntityEvent(org.spongepowered.api.event.entity.SpawnEntityEvent) IProjectile(net.minecraft.entity.IProjectile) Projectile(org.spongepowered.api.entity.projectile.Projectile) EntityLivingBase(net.minecraft.entity.EntityLivingBase) EntityPlayer(net.minecraft.entity.player.EntityPlayer) EntityXPOrb(net.minecraft.entity.item.EntityXPOrb)

Example 9 with Projectile

use of org.spongepowered.api.entity.projectile.Projectile in project RedProtect by FabioZumbi12.

the class RPGlobalListener method onEntityDamageEntity.

@Listener(order = Order.FIRST, beforeModifications = true)
public void onEntityDamageEntity(DamageEntityEvent e) {
    Entity e1 = e.getTargetEntity();
    Entity e2;
    RedProtect.get().logger.debug("entity", "RPGlobalListener: DamageEntityEvent - e1: " + e1.getType().getName());
    Region r = RedProtect.get().rm.getTopRegion(e1.getLocation());
    if (e1 instanceof Living && !(e1 instanceof Monster)) {
        if (r == null && RedProtect.get().cfgs.getGlobalFlag(e1.getWorld().getName(), "invincible")) {
            e.setCancelled(true);
        }
    }
    if (e.getCause().first(Living.class).isPresent()) {
        e2 = e.getCause().first(Living.class).get();
        RedProtect.get().logger.debug("entity", "RPGlobalListener: DamageEntityEvent - Is DamageEntityEvent event. Damager " + e2.getType().getName());
    } else {
        return;
    }
    RedProtect.get().logger.debug("entity", "RPGlobalListener: DamageEntityEvent - e1: " + e1.getType().getName() + " - e2: " + e2.getType().getName());
    Location<World> loc = e1.getLocation();
    Region r1 = RedProtect.get().rm.getTopRegion(loc);
    if (r1 != null) {
        return;
    }
    if (e2 instanceof Projectile) {
        Projectile proj = (Projectile) e2;
        if (proj.getShooter() instanceof Entity) {
            e2 = (Entity) proj.getShooter();
        }
        if (!(e2 instanceof Player)) {
            if (e1 instanceof Hanging || e1 instanceof ArmorStand) {
                if (!RedProtect.get().cfgs.getGlobalFlag(e1.getWorld().getName(), "entity-block-damage")) {
                    e.setCancelled(true);
                    return;
                }
            }
        }
    }
    if (e2 instanceof Creeper || e2 instanceof PrimedTNT || e2 instanceof TNTMinecart) {
        if (e1 instanceof Player) {
            if (!RedProtect.get().cfgs.getGlobalFlag(e1.getWorld().getName(), "explosion-entity-damage")) {
                e.setCancelled(true);
                return;
            }
        }
        if (e1 instanceof Animal || e1 instanceof Villager || e1 instanceof Golem || e1 instanceof Ambient) {
            if (!RedProtect.get().cfgs.getGlobalFlag(e1.getWorld().getName(), "explosion-entity-damage")) {
                e.setCancelled(true);
                return;
            }
        }
        if (e1 instanceof Monster) {
            if (!RedProtect.get().cfgs.getGlobalFlag(e1.getWorld().getName(), "explosion-entity-damage")) {
                e.setCancelled(true);
                return;
            }
        }
        if (e1 instanceof Hanging || e1 instanceof ArmorStand) {
            if (!RedProtect.get().cfgs.getGlobalFlag(e1.getWorld().getName(), "entity-block-damage")) {
                e.setCancelled(true);
                return;
            }
        }
    }
    if (e2 instanceof Player) {
        Player p = (Player) e2;
        if (e1 instanceof Player) {
            if (!e1.equals(e2) && !RedProtect.get().cfgs.getGlobalFlag(e1.getWorld().getName(), "pvp") && !p.hasPermission("redprotect.world.bypass")) {
                e.setCancelled(true);
                return;
            }
        }
        if (e1 instanceof Animal || e1 instanceof Villager || e1 instanceof Golem || e1 instanceof Ambient) {
            if (!RedProtect.get().cfgs.getGlobalFlag(e1.getWorld().getName(), "player-hurt-passives") && !p.hasPermission("redprotect.world.bypass")) {
                e.setCancelled(true);
                return;
            }
        }
        if (e1 instanceof Monster) {
            if (!RedProtect.get().cfgs.getGlobalFlag(e1.getWorld().getName(), "player-hurt-monsters") && !p.hasPermission("redprotect.world.bypass")) {
                e.setCancelled(true);
                return;
            }
        }
        if (e1 instanceof Boat || e1 instanceof Minecart) {
            if (!RedProtect.get().cfgs.getGlobalFlag(e1.getWorld().getName(), "use-minecart") && !p.hasPermission("redprotect.world.bypass")) {
                e.setCancelled(true);
                return;
            }
        }
        if (e1 instanceof Hanging || e1 instanceof ArmorStand) {
            if (!RedProtect.get().cfgs.getGlobalFlag(e1.getWorld().getName(), "entity-block-damage") && !p.hasPermission("redprotect.world.bypass")) {
                e.setCancelled(true);
                return;
            }
        }
    }
}
Also used : PrimedTNT(org.spongepowered.api.entity.explosive.PrimedTNT) Entity(org.spongepowered.api.entity.Entity) Player(org.spongepowered.api.entity.living.player.Player) Living(org.spongepowered.api.entity.living.Living) Creeper(org.spongepowered.api.entity.living.monster.Creeper) TNTMinecart(org.spongepowered.api.entity.vehicle.minecart.TNTMinecart) Minecart(org.spongepowered.api.entity.vehicle.minecart.Minecart) World(org.spongepowered.api.world.World) Projectile(org.spongepowered.api.entity.projectile.Projectile) Golem(org.spongepowered.api.entity.living.golem.Golem) Ambient(org.spongepowered.api.entity.living.Ambient) ArmorStand(org.spongepowered.api.entity.living.ArmorStand) Hanging(org.spongepowered.api.entity.hanging.Hanging) TNTMinecart(org.spongepowered.api.entity.vehicle.minecart.TNTMinecart) Animal(org.spongepowered.api.entity.living.animal.Animal) Monster(org.spongepowered.api.entity.living.monster.Monster) Villager(org.spongepowered.api.entity.living.Villager) Region(br.net.fabiozumbi12.RedProtect.Sponge.Region) Boat(org.spongepowered.api.entity.vehicle.Boat) Listener(org.spongepowered.api.event.Listener)

Example 10 with Projectile

use of org.spongepowered.api.entity.projectile.Projectile in project SpongeCommon by SpongePowered.

the class ProjectileTest method registerCommand.

@Listener
public void registerCommand(final RegisterCommandEvent<Command.Parameterized> event) {
    final Parameter.Value<EntityType<@NonNull ?>> entityTypeParameter = Parameter.registryElement(new TypeToken<EntityType<?>>() {
    }, (ctx) -> Sponge.game(), RegistryTypes.ENTITY_TYPE, "minecraft", "sponge").key("type").build();
    final Parameter.Value<Boolean> targetParameter = Parameter.bool().key("target").optional().build();
    final Command.Parameterized launchCommand = Command.builder().addParameters(entityTypeParameter, targetParameter).executor(context -> {
        final Player player = context.cause().first(Player.class).orElseThrow(() -> new CommandException(Component.text("Only a player can execute this command")));
        final EntityType<?> entityType = context.requireOne(entityTypeParameter);
        final Optional<Projectile> launched;
        if (context.one(targetParameter).orElse(false)) {
            final Collection<? extends Entity> nearbyEntities = player.nearbyEntities(10, entity -> entity instanceof Living && entity != player);
            if (nearbyEntities.isEmpty()) {
                return CommandResult.error(Component.text("No entity to target nearby"));
            }
            final Entity target = nearbyEntities.iterator().next();
            launched = player.launchProjectileTo((EntityType<Projectile>) entityType, target);
            if (launched.isPresent()) {
                player.sendMessage(Identity.nil(), Component.text("Launched projectile to " + RegistryTypes.ENTITY_TYPE.keyFor(Sponge.game(), target.type()).asString()));
                return CommandResult.success();
            }
        } else {
            launched = player.launchProjectile((EntityType<Projectile>) entityType);
            if (launched.isPresent()) {
                player.sendMessage(Identity.nil(), Component.text("Launched projectile"));
                return CommandResult.success();
            }
        }
        throw new CommandException(Component.text("Could not launch projectile"));
    }).build();
    event.register(this.plugin, launchCommand, "launch");
    final Command.Parameterized launchToMeCommand = Command.builder().addParameter(entityTypeParameter).executor(context -> {
        final Player player = context.cause().first(Player.class).orElseThrow(() -> new CommandException(Component.text("Only a player can execute this command")));
        final Collection<? extends ProjectileSource> nearbyProjectileSources = (Collection<? extends ProjectileSource>) player.nearbyEntities(10, entity -> entity instanceof ProjectileSource);
        if (nearbyProjectileSources.isEmpty()) {
            return CommandResult.error(Component.text("No projectile source nearby"));
        }
        final ProjectileSource projectileSource = nearbyProjectileSources.iterator().next();
        final EntityType<?> entityType = context.requireOne(entityTypeParameter);
        final Optional<? extends Projectile> launched = projectileSource.launchProjectileTo((EntityType<Projectile>) entityType, player);
        final EntityType<?> type = ((Entity) projectileSource).type();
        if (launched.isPresent()) {
            final EntityType<?> launchedType = launched.get().type();
            player.sendMessage(Identity.nil(), Component.text().append(Component.text("You made a ")).append(Component.text(RegistryTypes.ENTITY_TYPE.keyFor(Sponge.game(), type).asString())).append(Component.text(" shoot a ")).append(Component.text(RegistryTypes.ENTITY_TYPE.keyFor(Sponge.game(), launchedType).asString())).append(Component.text(" at you")).build());
            return CommandResult.success();
        }
        throw new CommandException(Component.text().append(Component.text("Could not launch a ")).append(Component.text(RegistryTypes.ENTITY_TYPE.keyFor(Sponge.game(), type).asString())).append(Component.text(" from a ")).append(Component.text(RegistryTypes.ENTITY_TYPE.keyFor(Sponge.game(), entityType).asString())).append(Component.text(" at you")).build());
    }).build();
    event.register(this.plugin, launchToMeCommand, "launchtome");
    final Parameter.Value<ServerLocation> dispenserParameter = Parameter.location().key("dispenser").build();
    final Command.Parameterized triggerDispenserCommand = Command.builder().addParameters(dispenserParameter, entityTypeParameter).executor(context -> {
        final Player player = context.cause().first(Player.class).orElseThrow(() -> new CommandException(Component.text("Only a player can execute this command")));
        final BlockEntity dispenser = context.requireOne(dispenserParameter).blockEntity().orElse(null);
        if (dispenser == null) {
            return CommandResult.error(Component.text("Could not find dispenser"));
        }
        final EntityType<?> entityType = context.requireOne(entityTypeParameter);
        final Optional<? extends Projectile> launched = ((Dispenser) dispenser).launchProjectile((EntityType<Projectile>) entityType);
        if (launched.isPresent()) {
            launched.get().offer(Keys.SHOOTER, player);
            player.sendMessage(Identity.nil(), Component.text().append(Component.text("The dispenser launched a ")).append(Component.text(RegistryTypes.ENTITY_TYPE.keyFor(Sponge.game(), launched.get().type()).asString())).build());
            return CommandResult.success();
        }
        return CommandResult.error(Component.text().append(Component.text("Could not make the dispenser launch a ")).append(Component.text(RegistryTypes.ENTITY_TYPE.keyFor(Sponge.game(), entityType).asString())).build());
    }).build();
    event.register(this.plugin, triggerDispenserCommand, "triggerdispenser");
}
Also used : BlockEntity(org.spongepowered.api.block.entity.BlockEntity) NonNull(org.checkerframework.checker.nullness.qual.NonNull) Command(org.spongepowered.api.command.Command) ServerWorld(org.spongepowered.api.world.server.ServerWorld) Inject(com.google.inject.Inject) EntityTypes(org.spongepowered.api.entity.EntityTypes) Parameter(org.spongepowered.api.command.parameter.Parameter) Component(net.kyori.adventure.text.Component) InteractBlockEvent(org.spongepowered.api.event.block.InteractBlockEvent) LinkedList(java.util.LinkedList) Living(org.spongepowered.api.entity.living.Living) RegisterCommandEvent(org.spongepowered.api.event.lifecycle.RegisterCommandEvent) CommandResult(org.spongepowered.api.command.CommandResult) Plugin(org.spongepowered.plugin.builtin.jvm.Plugin) LoadableModule(org.spongepowered.test.LoadableModule) Identity(net.kyori.adventure.identity.Identity) Collection(java.util.Collection) Sponge(org.spongepowered.api.Sponge) TypeToken(io.leangen.geantyref.TypeToken) Entity(org.spongepowered.api.entity.Entity) ProjectileSource(org.spongepowered.api.projectile.source.ProjectileSource) RegistryTypes(org.spongepowered.api.registry.RegistryTypes) Dispenser(org.spongepowered.api.block.entity.carrier.Dispenser) Keys(org.spongepowered.api.data.Keys) Vector3d(org.spongepowered.math.vector.Vector3d) PluginContainer(org.spongepowered.plugin.PluginContainer) CommandContext(org.spongepowered.api.command.parameter.CommandContext) EntityType(org.spongepowered.api.entity.EntityType) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) Projectile(org.spongepowered.api.entity.projectile.Projectile) Queue(java.util.Queue) Listener(org.spongepowered.api.event.Listener) CommandException(org.spongepowered.api.command.exception.CommandException) First(org.spongepowered.api.event.filter.cause.First) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) ServerLocation(org.spongepowered.api.world.server.ServerLocation) BlockEntity(org.spongepowered.api.block.entity.BlockEntity) Entity(org.spongepowered.api.entity.Entity) Player(org.spongepowered.api.entity.living.player.Player) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Optional(java.util.Optional) ServerLocation(org.spongepowered.api.world.server.ServerLocation) Living(org.spongepowered.api.entity.living.Living) CommandException(org.spongepowered.api.command.exception.CommandException) Projectile(org.spongepowered.api.entity.projectile.Projectile) EntityType(org.spongepowered.api.entity.EntityType) Command(org.spongepowered.api.command.Command) NonNull(org.checkerframework.checker.nullness.qual.NonNull) Parameter(org.spongepowered.api.command.parameter.Parameter) Collection(java.util.Collection) ProjectileSource(org.spongepowered.api.projectile.source.ProjectileSource) BlockEntity(org.spongepowered.api.block.entity.BlockEntity) Listener(org.spongepowered.api.event.Listener)

Aggregations

Projectile (org.spongepowered.api.entity.projectile.Projectile)15 Entity (org.spongepowered.api.entity.Entity)13 Player (org.spongepowered.api.entity.living.player.Player)12 Listener (org.spongepowered.api.event.Listener)11 World (org.spongepowered.api.world.World)9 Region (br.net.fabiozumbi12.RedProtect.Sponge.Region)8 Hanging (org.spongepowered.api.entity.hanging.Hanging)6 Living (org.spongepowered.api.entity.living.Living)4 Animal (org.spongepowered.api.entity.living.animal.Animal)4 Golem (org.spongepowered.api.entity.living.golem.Golem)4 Monster (org.spongepowered.api.entity.living.monster.Monster)4 ArrayList (java.util.ArrayList)3 Collection (java.util.Collection)3 ProjectileSource (org.spongepowered.api.entity.projectile.source.ProjectileSource)3 Boat (org.spongepowered.api.entity.vehicle.Boat)3 Minecart (org.spongepowered.api.entity.vehicle.minecart.Minecart)3 Vector3d (com.flowpowered.math.vector.Vector3d)2 List (java.util.List)2 Optional (java.util.Optional)2 Nullable (javax.annotation.Nullable)2