net.minecraftforge.common.util.FakePlayer Java Examples

The following examples show how to use net.minecraftforge.common.util.FakePlayer. 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: ProtectionHandlers.java    From MyTown2 with The Unlicense 6 votes vote down vote up
@SubscribeEvent
public void onBucketFill(FillBucketEvent ev) {
    if(ev.entity.worldObj.isRemote || ev.isCanceled()) {
        return;
    }

    int x = (int) Math.floor(ev.target.blockX);
    int y = (int) Math.floor(ev.target.blockY);
    int z = (int) Math.floor(ev.target.blockZ);

    if(ev.entityPlayer instanceof FakePlayer) {
        if(!ProtectionManager.getFlagValueAtLocation(FlagType.FAKERS, ev.world.provider.dimensionId, x, y, z)) {
            ev.setCanceled(true);
        }
    } else {
        Resident res = MyTownUniverse.instance.getOrMakeResident(ev.entityPlayer);
        if(!ProtectionManager.hasPermission(res, FlagType.USAGE, ev.world.provider.dimensionId, x, y, z)) {
            ev.setCanceled(true);
        }
    }
}
 
Example #2
Source File: ToolUtility.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void applyHammerDrops(Random random, IBlockState blockState, List<ItemStack> drops, int fortuneLevel, EntityPlayer player) {
    ItemStack itemStack = new ItemStack(blockState.getBlock(), 1, blockState.getBlock().getMetaFromState(blockState));
    Recipe recipe = RecipeMaps.FORGE_HAMMER_RECIPES.findRecipe(Long.MAX_VALUE, Collections.singletonList(itemStack), Collections.emptyList(), 0);
    if (recipe != null && !recipe.getOutputs().isEmpty()) {
        drops.clear();
        for (ItemStack outputStack : recipe.getResultItemOutputs(Integer.MAX_VALUE, random, 0)) {
            outputStack = outputStack.copy();
            if (!(player instanceof FakePlayer) && OreDictUnifier.getPrefix(outputStack) == OrePrefix.crushed) {
                int growAmount = Math.round(outputStack.getCount() * random.nextFloat());
                if (fortuneLevel > 0) {
                    int i = Math.max(0, random.nextInt(fortuneLevel + 2) - 1);
                    growAmount += outputStack.getCount() * i;
                }
                outputStack.grow(growAmount);
            }
            drops.add(outputStack);
        }
    }
}
 
Example #3
Source File: CraftEventFactory.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
public static BlockBreakEvent callBlockBreakEvent(net.minecraft.world.World world, BlockPos pos, IBlockState state, EntityPlayerMP player) {
    Block bBlock = world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ());
    BlockBreakEvent bbe = new BlockBreakEvent(bBlock, player.getBukkitEntity());
    EntityPlayerMP playermp = player;
    net.minecraft.block.Block block = state.getBlock();
    if (!(playermp instanceof FakePlayer)) {
        boolean isSwordNoBreak = playermp.interactionManager.getGameType().isCreative() && !playermp.getHeldItemMainhand().isEmpty() && playermp.getHeldItemMainhand().getItem() instanceof ItemSword;
        if (!isSwordNoBreak) {
            int exp = 0;
            if (!(block == null || !player.canHarvestBlock(block.getDefaultState()) || block.canSilkHarvest(world, pos, block.getBlockState().getBaseState(), player) && EnchantmentHelper.getEnchantmentLevel(Enchantments.SILK_TOUCH, player.getHeldItemMainhand()) > 0)) {
                int bonusLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.FORTUNE, player.getHeldItemMainhand());
                exp = block.getExpDrop(state, world, pos, bonusLevel);
            }
            bbe.setExpToDrop(exp);
        } else {
            bbe.setCancelled(true);
        }
    }

    world.getServer().getPluginManager().callEvent(bbe);
    return bbe;
}
 
Example #4
Source File: ServerEventHandler.java    From Et-Futurum with The Unlicense 6 votes vote down vote up
@SubscribeEvent
public void entityHurtEvent(LivingHurtEvent event) {
	if (!EtFuturum.enableDmgIndicator)
		return;
	int amount = MathHelper.floor_float(Math.min(event.entityLiving.getHealth(), event.ammount) / 2F);
	if (amount <= 0)
		return;

	// If the attacker is a player spawn the hearts aligned and facing it
	if (event.source instanceof EntityDamageSource) {
		EntityDamageSource src = (EntityDamageSource) event.source;
		Entity attacker = src.getSourceOfDamage();
		if (attacker instanceof EntityPlayer && !(attacker instanceof FakePlayer)) {
			EntityPlayer player = (EntityPlayer) attacker;
			Vec3 look = player.getLookVec();
			look.rotateAroundY((float) Math.PI / 2);
			for (int i = 0; i < amount; i++) {
				double x = event.entityLiving.posX - amount * 0.35 * look.xCoord / 2 + i * 0.35 * look.xCoord;
				double y = event.entityLiving.posY + 1.5 + event.entityLiving.worldObj.rand.nextGaussian() * 0.05;
				double z = event.entityLiving.posZ - amount * 0.35 * look.zCoord / 2 + i * 0.35 * look.zCoord;
				EtFuturum.networkWrapper.sendToAllAround(new BlackHeartParticlesMessage(x, y, z), new TargetPoint(player.worldObj.provider.dimensionId, x, y, z, 64));
			}
		}
	}
}
 
Example #5
Source File: BlockUtils.java    From Wizardry with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Tries breaking a block safely and fires an event for it.
 *
 * @return Whether the block was successfully broken
 */
public static boolean breakBlock(@Nonnull World world, @Nonnull BlockPos pos, @Nullable IBlockState oldState, @Nonnull EntityPlayerMP player) {
	if (!world.isBlockLoaded(pos)) return false;

	if (!(player instanceof FakePlayer) && !hasEditPermission(pos, player)) return false;

	if (oldState == null) oldState = world.getBlockState(pos);

	BlockEvent.BreakEvent event = new BlockEvent.BreakEvent(world, pos, oldState, player);
	MinecraftForge.EVENT_BUS.post(event);

	if (event.isCanceled()) return false;

	TileEntity tile = world.getTileEntity(pos);
	Block block = oldState.getBlock();
	if (block.removedByPlayer(oldState, world, pos, player, true)) {
		block.onPlayerDestroy(world, pos, oldState);
		block.harvestBlock(world, player, pos, oldState, tile, player.getHeldItemMainhand());
		world.notifyBlockUpdate(pos, oldState, Blocks.AIR.getDefaultState(), 3);
	} else return false;

	return true;
}
 
Example #6
Source File: CraftEventFactory.java    From Thermos with GNU General Public License v3.0 6 votes vote down vote up
public static BlockBreakEvent callBlockBreakEvent(net.minecraft.world.World world, int x, int y, int z, net.minecraft.block.Block block, int blockMetadata, net.minecraft.entity.player.EntityPlayerMP player)
{
    org.bukkit.block.Block bukkitBlock = world.getWorld().getBlockAt(x, y, z);
    org.bukkit.event.block.BlockBreakEvent blockBreakEvent = new org.bukkit.event.block.BlockBreakEvent(bukkitBlock, ((EntityPlayerMP)player).getBukkitEntity());
    EntityPlayerMP playermp = (EntityPlayerMP)player;
    if (!(playermp instanceof FakePlayer))
    {
        if (!(playermp.theItemInWorldManager.getGameType().isAdventure() && !playermp.isCurrentToolAdventureModeExempt(x, y, z)) && !(playermp.theItemInWorldManager.getGameType().isCreative() && playermp.getHeldItem() != null && playermp.getHeldItem().getItem() instanceof ItemSword))
        {
            int exp = 0;
            if (!(block == null || !player.canHarvestBlock(block) || // Handle empty block or player unable to break block scenario
                    block.canSilkHarvest(world, player, x, y, z, blockMetadata) && EnchantmentHelper.getSilkTouchModifier(player))) // If the block is being silk harvested, the exp dropped is 0
            {
                int meta = block.getDamageValue(world, x, y, z);
                int bonusLevel = EnchantmentHelper.getFortuneModifier(player);
                exp = block.getExpDrop(world, meta, bonusLevel);
            }
            blockBreakEvent.setExpToDrop(exp);
        }
        else blockBreakEvent.setCancelled(true);
    }

    world.getServer().getPluginManager().callEvent(blockBreakEvent);
    return blockBreakEvent;
}
 
Example #7
Source File: MiscUtils.java    From Gadomancy with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean isPlayerFakeMP(EntityPlayerMP player) {
    if(player instanceof FakePlayer) return true;
    if(player.getClass() != EntityPlayerMP.class) return true;
    if(player.playerNetServerHandler == null) return true;
    try {
        player.getPlayerIP().length();
        player.playerNetServerHandler.netManager.getSocketAddress().toString();
    } catch (Exception exc) {
        return true;
    }
    if(MinecraftServer.getServer().getConfigurationManager().playerEntityList == null) return true;
    return !MinecraftServer.getServer().getConfigurationManager().playerEntityList.contains(player);
}
 
Example #8
Source File: ProtectionHandlers.java    From MyTown2 with The Unlicense 5 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onBlockTrample(BlockTrampleEvent ev) {
    if(ev.world.isRemote || ev.isCanceled())
        return;

    Entity entity = ev.entity;
    Resident res = null;

    if(!(entity instanceof EntityPlayer)) {
        // Protect from players ridding any entity
        if(entity.riddenByEntity != null && (entity.riddenByEntity instanceof EntityPlayer))
            entity = entity.riddenByEntity;
        // Protect from players jumping and leaving the horse in mid-air
        else
            res = ProtectionManager.getOwner(entity);
    }

    // Fake players are special
    if(entity instanceof FakePlayer) {
        if(!ProtectionManager.getFlagValueAtLocation(FlagType.FAKERS, ev.world.provider.dimensionId, ev.x, ev.y, ev.z)) {
            ev.setCanceled(true);
        }
    } else {
        // Will be null if we didn't find the player responsible for this trampling
        if(res == null) {
            res = MyTownUniverse.instance.getOrMakeResident(entity);
            // Will be null if it wasn't caused by a known player
            if(res == null)
                return;
        }

        // Trampling crops will break them and will modify the terrain
        if (!ProtectionManager.checkBlockBreak(ev.block)) {
            if(!ProtectionManager.hasPermission(res, FlagType.MODIFY, ev.world.provider.dimensionId, ev.x, ev.y, ev.z)) {
                ev.setCanceled(true);
            }
        }
    }
}
 
Example #9
Source File: ProtectionHandlers.java    From MyTown2 with The Unlicense 5 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onProjectileImpact(ProjectileImpactEvent ev) {
    if (ev.entity.worldObj.isRemote || ev.isCanceled()) {
        return;
    }

    EntityLivingBase firingEntity = ev.firingEntity;
    Resident owner = null;
    if (firingEntity instanceof EntityPlayerMP && !(firingEntity instanceof FakePlayer)) {
        owner = MyTownUniverse.instance.getOrMakeResident(firingEntity);
    }
    ProtectionManager.checkImpact(ev.entity, owner, ev.movingObjectPosition, ev);
}
 
Example #10
Source File: ProtectionHandlers.java    From MyTown2 with The Unlicense 5 votes vote down vote up
public void onAnyBlockPlacement(EntityPlayer player, BlockEvent.PlaceEvent ev) {
    if(ev.world.isRemote || ev.isCanceled()) {
        return;
    }

    if(player instanceof FakePlayer) {
        if(!ProtectionManager.getFlagValueAtLocation(FlagType.FAKERS, ev.world.provider.dimensionId, ev.x, ev.y, ev.z)) {
            ev.setCanceled(true);
        }
    } else {
        Resident res = MyTownUniverse.instance.getOrMakeResident(player);

        if (!MyTownUniverse.instance.blocks.contains(ev.world.provider.dimensionId, ev.x >> 4, ev.z >> 4)) {
            int range = Config.instance.placeProtectionRange.get();
            Volume placeBox = new Volume(ev.x-range, ev.y-range, ev.z-range, ev.x+range, ev.y+range, ev.z+range);

            if(!ProtectionManager.hasPermission(res, FlagType.MODIFY, ev.world.provider.dimensionId, placeBox)) {
                ev.setCanceled(true);
                return;
            }
        } else {
            if(!ProtectionManager.hasPermission(res, FlagType.MODIFY, ev.world.provider.dimensionId, ev.x, ev.y, ev.z)) {
                ev.setCanceled(true);
                return;
            }
        }

        if(ev.block instanceof ITileEntityProvider && ev.itemInHand != null) {
            TileEntity te = ((ITileEntityProvider) ev.block).createNewTileEntity(MinecraftServer.getServer().worldServerForDimension(ev.world.provider.dimensionId), ev.itemInHand.getItemDamage());
            if (te != null && ProtectionManager.isOwnable(te.getClass())) {
                ThreadPlacementCheck thread = new ThreadPlacementCheck(res, ev.x, ev.y, ev.z, ev.world.provider.dimensionId);
                activePlacementThreads++;
                thread.start();
            }
        }
    }
}
 
Example #11
Source File: TileEntityDrawbridge.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Nonnull
private FakePlayer getPlayer()
{
    if (this.fakePlayer == null)
    {
        int dim = this.getWorld().provider.getDimension();

        this.fakePlayer = FakePlayerFactory.get((WorldServer) this.getWorld(),
                new GameProfile(new UUID(dim, dim), Reference.MOD_ID + ":drawbridge"));
    }

    return this.fakePlayer;
}
 
Example #12
Source File: TileEntityDrawbridge.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Nullable
private IBlockState getPlacementStateForPosition(int position, World world, BlockPos pos, FakePlayer player, ItemStack stack)
{
    if (this.blockInfoTaken[position] != null)
    {
        return this.blockInfoTaken[position].getState();
    }

    // The Normal variant shouldn't place blocks into positions it didn't take them from,
    // unless it hasn't taken any blocks but was instead extended with inserted-only items.
    if ((this.isAdvanced() || this.numTaken == 0) &&
         stack.isEmpty() == false && stack.getItem() instanceof ItemBlock)
    {
        ItemBlock itemBlock = (ItemBlock) stack.getItem();
        Block block = itemBlock.getBlock();

        if (block != null && block != Blocks.AIR)
        {
            int meta = itemBlock.getMetadata(stack.getMetadata());
            player.rotationYaw = this.getFacing().getHorizontalAngle();

            return block.getStateForPlacement(world, pos, EnumFacing.UP, 0.5f, 1f, 0.5f, meta, player, EnumHand.MAIN_HAND);
        }
    }

    return null;
}
 
Example #13
Source File: ActivationRange.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
/**
 * These entities are excluded from Activation range checks.
 *
 * @param entity
 * @param world
 * @return boolean If it should always tick.
 */
public static boolean initializeEntityActivationState(Entity entity, SpigotWorldConfig config)
{
    // Cauldron start - another fix for Proxy Worlds
    if (config == null && DimensionManager.getWorld(0) != null)
    {
        config = DimensionManager.getWorld(0).spigotConfig;
    }
    else
    {
        return true;
    }
    // Cauldron end

    if ( ( entity.activationType == 3 && config.miscActivationRange == 0 )
            || ( entity.activationType == 2 && config.animalActivationRange == 0 )
            || ( entity.activationType == 1 && config.monsterActivationRange == 0 )
            || (entity instanceof EntityPlayer && !(entity instanceof FakePlayer)) // Cauldron
            || entity instanceof EntityThrowable
            || entity instanceof EntityDragon
            || entity instanceof EntityDragonPart
            || entity instanceof EntityWither
            || entity instanceof EntityFireball
            || entity instanceof EntityWeatherEffect
            || entity instanceof EntityTNTPrimed
            || entity instanceof EntityFallingBlock // PaperSpigot - Always tick falling blocks
            || entity instanceof EntityEnderCrystal
            || entity instanceof EntityFireworkRocket
            || entity instanceof EntityVillager
            // Cauldron start - force ticks for entities with superclass of Entity and not a creature/monster
            || (entity.getClass().getSuperclass() == Entity.class && !entity.isCreatureType(EnumCreatureType.creature, false)
            && !entity.isCreatureType(EnumCreatureType.ambient, false) && !entity.isCreatureType(EnumCreatureType.monster, false)
            && !entity.isCreatureType(EnumCreatureType.waterCreature, false)))
    {
        return true;
    }

    return false;
}
 
Example #14
Source File: BounceHandler.java    From Wizardry with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void addBounceHandler(EntityLivingBase entity, double bounce) {
	// only supports actual players as it uses the PlayerTick event
	if (!(entity instanceof EntityPlayer) || entity instanceof FakePlayer) {
		return;
	}
	BounceHandler handler = bouncingEntities.get(entity);
	if (handler == null) {
		// wasn't bouncing yet, register it
		MinecraftForge.EVENT_BUS.register(new BounceHandler(entity, bounce));
	} else if (bounce != 0) {
		// updated bounce if needed
		handler.bounce = bounce;
		handler.bounceTick = entity.ticksExisted;
	}
}
 
Example #15
Source File: BlockUtils.java    From Wizardry with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean placeBlock(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull EnumFacing facing, @Nonnull ItemStack stack) {
	if (!world.isBlockLoaded(pos)) return false;

	FakePlayer player = FakePlayerFactory.get((WorldServer) world, PLACER);
	player.moveToBlockPosAndAngles(pos, 0, -90);
	player.setHeldItem(EnumHand.MAIN_HAND, stack);
	player.setSneaking(true);

	if (!hasEditPermission(pos, player)) return false;

	EnumActionResult result = player.interactionManager.processRightClickBlock(
			player, world, stack, EnumHand.MAIN_HAND,
			pos, facing, 0, 0, 0);
	return result != EnumActionResult.FAIL;
}
 
Example #16
Source File: ToolUtility.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean applyTimberAxe(ItemStack itemStack, World world, BlockPos blockPos, EntityPlayer player) {
    if (player instanceof FakePlayer) {
        return false;
    }
    IBlockState blockState = world.getBlockState(blockPos);
    if(TreeChopTask.isLogBlock(blockState) == 1) {
        if(!world.isRemote) {
            EntityPlayerMP playerMP = (EntityPlayerMP) player;
            TreeChopTask treeChopTask = new TreeChopTask(blockPos, world, playerMP, itemStack);
            TaskScheduler.scheduleTask(world, treeChopTask);
        }
        return true;
    }
    return false;
}
 
Example #17
Source File: ToolJackHammer.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void onBlockDestroyed(ItemStack stack, World world, IBlockState state, BlockPos pos, EntityLivingBase entity) {
    if(entity instanceof EntityPlayer && !(entity instanceof FakePlayer)) {
        EntityPlayer entityPlayer = (EntityPlayer) entity;
        EnumFacing sideHit = ToolUtility.getSideHit(world, pos, entityPlayer);
        int damagePerBlockBreak = getToolDamagePerBlockBreak(stack);
        JackHammerMode jackHammerMode = MODE_SWITCH_BEHAVIOR.getModeFromItemStack(stack);
        EnumFacing horizontalFacing = entity.getHorizontalFacing();
        int xSizeExtend = (jackHammerMode.getHorizontalSize() - 1) / 2;
        int ySizeExtend = (jackHammerMode.getVerticalSize() - 1) / 2;
        for (int x = -xSizeExtend; x <= xSizeExtend; x++) {
            for (int y = -ySizeExtend; y <= ySizeExtend; y++) {
                //do not check center block - it's handled now
                if (x == 0 && y == 0) continue;
                BlockPos offsetPos = rotate(pos, x, y, sideHit, horizontalFacing);
                IBlockState blockState = world.getBlockState(offsetPos);
                if(world.isBlockModifiable(entityPlayer, offsetPos) &&
                    blockState.getBlock().canHarvestBlock(world, offsetPos, entityPlayer) &&
                    blockState.getPlayerRelativeBlockHardness(entityPlayer, world, offsetPos) > 0.0f &&
                    stack.canHarvestBlock(blockState)) {
                    GTUtility.harvestBlock(world, offsetPos, entityPlayer);
                    ((ToolMetaItem) stack.getItem()).damageItem(stack, damagePerBlockBreak, false);
                }
            }
        }
    }
}
 
Example #18
Source File: UIFactory.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
public final void openUI(E holder, EntityPlayerMP player) {
    if (player instanceof FakePlayer) {
        return;
    }
    ModularUI uiTemplate = createUITemplate(holder, player);
    uiTemplate.initWidgets();

    player.getNextWindowId();
    player.closeContainer();
    int currentWindowId = player.currentWindowId;

    PacketBuffer serializedHolder = new PacketBuffer(Unpooled.buffer());
    writeHolderToSyncData(serializedHolder, holder);
    int uiFactoryId = FACTORY_REGISTRY.getIDForObject(this);

    ModularUIContainer container = new ModularUIContainer(uiTemplate);
    container.windowId = currentWindowId;
    //accumulate all initial updates of widgets in open packet
    container.accumulateWidgetUpdateData = true;
    uiTemplate.guiWidgets.values().forEach(Widget::detectAndSendChanges);
    container.accumulateWidgetUpdateData = false;
    ArrayList<PacketUIWidgetUpdate> updateData = new ArrayList<>(container.accumulatedUpdates);
    container.accumulatedUpdates.clear();

    PacketUIOpen packet = new PacketUIOpen(uiFactoryId, serializedHolder, currentWindowId, updateData);
    NetworkHandler.channel.sendTo(NetworkHandler.packet2proxy(packet), player);

    container.addListener(player);
    player.openContainer = container;

    //and fire forge event only in the end
    MinecraftForge.EVENT_BUS.post(new PlayerContainerEvent.Open(player, container));
}
 
Example #19
Source File: GregFakePlayer.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static FakePlayer get(WorldServer world) {
    FakePlayer ret = GREGTECH_PLAYER != null ? GREGTECH_PLAYER.get() : null;
    if (ret == null) {
        ret = FakePlayerFactory.get(world, GREGTECH);
        GREGTECH_PLAYER = new WeakReference<>(ret);
    }
    return ret;
}
 
Example #20
Source File: PacketHandler.java    From MiningGadgets with MIT License 5 votes vote down vote up
public static void sendToAll(Object msg, World world) {
    //Todo Maybe only send to nearby players?
    for (PlayerEntity player : world.getPlayers()) {
        if (!(player instanceof FakePlayer))
            HANDLER.sendTo(msg, ((ServerPlayerEntity) player).connection.netManager, NetworkDirection.PLAY_TO_CLIENT);
    }
}
 
Example #21
Source File: PacketHandler.java    From MiningGadgets with MIT License 4 votes vote down vote up
public static void sendTo(Object msg, ServerPlayerEntity player) {
    if (!(player instanceof FakePlayer))
        HANDLER.sendTo(msg, player.connection.netManager, NetworkDirection.PLAY_TO_CLIENT);
}
 
Example #22
Source File: ItemBuildersWand.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void deleteArea(ItemStack stack, World world, EntityPlayer player, BlockPos posStart, BlockPos posEnd, boolean removeEntities)
{
    if (posStart == null || posEnd == null)
    {
        return;
    }

    if (player.getDistanceSq(posStart) > 160 * 160)
    {
        player.sendStatusMessage(new TextComponentTranslation("enderutilities.chat.message.areatoofar"), true);
        return;
    }

    if (this.isAreaWithinSizeLimit(posStart.subtract(posEnd), stack, player) == false)
    {
        player.sendStatusMessage(new TextComponentTranslation("enderutilities.chat.message.areatoolarge"), true);
        return;
    }

    // Set all blocks to air
    for (BlockPos.MutableBlockPos posMutable : BlockPos.getAllInBoxMutable(posStart, posEnd))
    {
        if (world.isAirBlock(posMutable) == false)
        {
            BlockUtils.setBlockToAirWithoutSpillingContents(world, posMutable, 2);
        }
    }

    // Remove pending block updates from within the area
    BlockPos posMin = PositionUtils.getMinCorner(posStart, posEnd);
    BlockPos posMax = PositionUtils.getMaxCorner(posStart, posEnd).add(1, 1, 1);
    StructureBoundingBox sbb = StructureBoundingBox.createProper(posMin.getX(), posMin.getY(), posMin.getZ(), posMax.getX(), posMax.getY(), posMax.getZ());
    world.getPendingBlockUpdates(sbb, true); // The boolean parameter indicates whether the entries will be removed

    // Remove all entities within the area
    int count = 0;

    if (removeEntities)
    {
        int x1 = Math.min(posStart.getX(), posEnd.getX());
        int y1 = Math.min(posStart.getY(), posEnd.getY());
        int z1 = Math.min(posStart.getZ(), posEnd.getZ());
        int x2 = Math.max(posStart.getX(), posEnd.getX());
        int y2 = Math.max(posStart.getY(), posEnd.getY());
        int z2 = Math.max(posStart.getZ(), posEnd.getZ());

        AxisAlignedBB bb = new AxisAlignedBB(x1, y1, z1, x2 + 1, y2 + 1, z2 + 1);
        List<Entity> entities = world.getEntitiesWithinAABBExcludingEntity(null, bb);

        for (Entity entity : entities)
        {
            if ((entity instanceof EntityPlayer) == false || entity instanceof FakePlayer)
            {
                entity.setDead();
                count++;
            }
        }

        if (count > 0)
        {
            player.sendStatusMessage(new TextComponentTranslation("enderutilities.chat.message.killedentitieswithcount", count), true);
        }
    }
}
 
Example #23
Source File: CraftPlayer.java    From Kettle with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cause) {
    Preconditions.checkArgument(location != null, "location");
    Preconditions.checkArgument(location.getWorld() != null, "location.world");
    location.checkFinite();
    EntityPlayerMP entity = getHandle();

    if (getHealth() == 0 || entity.isDead || entity instanceof FakePlayer) {
        return false;
    }

    if (entity.connection == null) {
        return false;
    }

    if (entity.isBeingRidden()) {
        return false;
    }

    // From = Players current Location
    Location from = this.getLocation();
    // To = Players new Location if Teleport is Successful
    Location to = location;
    // Create & Call the Teleport Event.
    PlayerTeleportEvent event = new PlayerTeleportEvent(this, from, to, cause);
    server.getPluginManager().callEvent(event);

    // Return False to inform the Plugin that the Teleport was unsuccessful/cancelled.
    if (event.isCancelled()) {
        return false;
    }

    // If this player is riding another entity, we must dismount before teleporting.
    entity.dismountRidingEntity();

    // Update the From Location
    from = event.getFrom();
    // Grab the new To Location dependent on whether the event was cancelled.
    to = event.getTo();
    // Grab the To and From World Handles.
    WorldServer fromWorld = ((CraftWorld) from.getWorld()).getHandle();
    WorldServer toWorld = ((CraftWorld) to.getWorld()).getHandle();

    // Close any foreign inventory
    if (getHandle().openContainer != getHandle().inventoryContainer) {
        getHandle().closeScreen();
    }

    // Check if the fromWorld and toWorld are the same.
    if (fromWorld == toWorld) {
        entity.connection.teleport(to);
    } else {
        server.getHandle().moveToWorld(entity, toWorld.dimension, true, to, true);
    }
    return true;
}
 
Example #24
Source File: TileEntityDrawbridge.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
private boolean extendOneBlock(int position, FakePlayer player, boolean playPistonSoundInsteadOfPlaceSound)
{
    final int invPosition = this.isAdvanced() ? position : 0;
    World world = this.getWorld();
    BlockPos pos = this.getPos().offset(this.getFacing(), position + 1);
    ItemStack stack = this.itemHandlerDrawbridge.getStackInSlot(invPosition);
    IBlockState placementState = this.getPlacementStateForPosition(position, world, pos, player, stack);

    if (placementState != null &&
        stack.isEmpty() == false &&
        world.isBlockLoaded(pos, world.isRemote == false) &&
        world.getBlockState(pos).getBlock().isReplaceable(world, pos) &&
        world.mayPlace(placementState.getBlock(), pos, true, EnumFacing.UP, null) &&
        ((playPistonSoundInsteadOfPlaceSound && world.setBlockState(pos, placementState)) ||
         (playPistonSoundInsteadOfPlaceSound == false && BlockUtils.setBlockStateWithPlaceSound(world, pos, placementState, 3))))
    {
        // This extract will also clear the blockInfoTaken, if the slot becomes empty.
        // This will prevent item duping exploits by swapping the item to something else
        // after the drawbridge has taken the state and TE data from the world for a given block.
        stack = this.itemHandlerDrawbridge.extractItem(invPosition, 1, false);

        this.blockStatesPlaced[position] = placementState;
        this.numPlaced++;

        NBTTagCompound nbt = this.getPlacementTileNBT(position, stack);

        if (nbt != null && placementState.getBlock().hasTileEntity(placementState))
        {
            TileUtils.createAndAddTileEntity(world, pos, nbt);
        }

        if (playPistonSoundInsteadOfPlaceSound)
        {
            world.playSound(null, pos, SoundEvents.BLOCK_PISTON_EXTEND, SoundCategory.BLOCKS, 0.5f, 0.8f);
        }

        return true;
    }
    else if (stack.isEmpty() == false)
    {
        this.failedPlacements++;
    }

    return false;
}
 
Example #25
Source File: TileEntityDrawbridge.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
private boolean retractOneBlock(int position, FakePlayer player, boolean takeNonPlaced, boolean playPistonSound)
{
    World world = this.getWorld();
    BlockPos pos = this.getPos().offset(this.getFacing(), position + 1);

    if (world.isBlockLoaded(pos, world.isRemote == false) == false)
    {
        return false;
    }

    IBlockState state = world.getBlockState(pos);

    if ((takeNonPlaced || state == this.blockStatesPlaced[position]) &&
        state.getBlock().isAir(state, world, pos) == false &&
        state.getBlockHardness(world, pos) >= 0f)
    {
        ItemStack stack = BlockUtils.getPickBlockItemStack(world, pos, player, EnumFacing.UP);

        if (stack.isEmpty() == false)
        {
            NBTTagCompound nbt = null;
            final int invPosition = this.isAdvanced() ? position : 0;

            if (state.getBlock().hasTileEntity(state))
            {
                TileEntity te = world.getTileEntity(pos);

                if (te != null)
                {
                    TileUtils.storeTileEntityInStack(stack, te, false);
                    nbt = te.writeToNBT(new NBTTagCompound());
                    NBTUtils.removePositionFromTileEntityNBT(nbt);
                }
            }

            if (this.itemHandlerDrawbridge.insertItem(invPosition, stack, false).isEmpty())
            {
                this.blockInfoTaken[position] = new BlockInfo(state, nbt);
                this.numTaken++;

                if (playPistonSound)
                {
                    world.playSound(null, pos, SoundEvents.BLOCK_PISTON_CONTRACT, SoundCategory.BLOCKS, 0.5f, 0.7f);
                }
                else
                {
                    BlockUtils.playBlockBreakSound(world, pos);
                }

                BlockUtils.setBlockToAirWithoutSpillingContents(world, pos);

                this.blockStatesPlaced[position] = null;

                return true;
            }
        }
    }

    return false;
}
 
Example #26
Source File: MyTownUniverse.java    From MyTown2 with The Unlicense 4 votes vote down vote up
public Resident getOrMakeResident(EntityPlayer player) {
    return getOrMakeResident(player.getPersistentID(), player.getDisplayName(), player instanceof FakePlayer);
}
 
Example #27
Source File: SafemodeHandler.java    From MyTown2 with The Unlicense 4 votes vote down vote up
/**
 * Kicks the given EntityPlayerMP if they dont have mytown.adm.safemode
 */
public static void kickPlayer(EntityPlayerMP pl) {
    if (!(pl instanceof FakePlayer)) {
        pl.playerNetServerHandler.kickPlayerFromServer(Config.instance.safeModeMsg.get());
    }
}
 
Example #28
Source File: ProtectionHandlers.java    From MyTown2 with The Unlicense 4 votes vote down vote up
@SuppressWarnings("unchecked")
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onPlayerBreaksBlock(BlockEvent.BreakEvent ev) {
    if(ev.world.isRemote || ev.isCanceled()) {
        return;
    }

    if(ev.getPlayer() instanceof FakePlayer) {
        if(!ProtectionManager.getFlagValueAtLocation(FlagType.FAKERS, ev.world.provider.dimensionId, ev.x, ev.y, ev.z)) {
            ev.setCanceled(true);
        }
    } else {
        Resident res = MyTownUniverse.instance.getOrMakeResident(ev.getPlayer());

        if (!MyTownUniverse.instance.blocks.contains(ev.world.provider.dimensionId, ev.x >> 4, ev.z >> 4)) {
            int range = Config.instance.placeProtectionRange.get();
            Volume breakBox = new Volume(ev.x-range, ev.y-range, ev.z-range, ev.x+range, ev.y+range, ev.z+range);

            if(!ProtectionManager.checkBlockBreak(ev.block)) {
                if(!ProtectionManager.hasPermission(res, FlagType.MODIFY, ev.world.provider.dimensionId, breakBox)) {
                    ev.setCanceled(true);
                    return;
                }
            }

        } else {
            if (!ProtectionManager.checkBlockBreak(ev.block)) {
                if(!ProtectionManager.hasPermission(res, FlagType.MODIFY, ev.world.provider.dimensionId, ev.x, ev.y, ev.z)) {
                    ev.setCanceled(true);
                    return;
                }
            }
        }

        if(ev.getPlayer().getHeldItem() != null) {
            ProtectionManager.checkBreakWithItem(ev.getPlayer().getHeldItem(), res, new BlockPos(ev.x, ev.y, ev.z, ev.world.provider.dimensionId), ev);
        }
    }

    if (!ev.isCanceled() && ev.block instanceof ITileEntityProvider) {
        TileEntity te = ((ITileEntityProvider) ev.block).createNewTileEntity(ev.world, ev.blockMetadata);
        if(te != null && ProtectionManager.isOwnable(te.getClass())) {
            te = ev.world.getTileEntity(ev.x, ev.y, ev.z);
            ownedTileEntities.remove(te);
            MyTown.instance.LOG.info("Removed te {}", te.toString());
        }
    }
}