Java Code Examples for org.spongepowered.api.entity.living.player.Player#getLocation()

The following examples show how to use org.spongepowered.api.entity.living.player.Player#getLocation() . 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: PlayerEventHandler.java    From GriefDefender with MIT License 6 votes vote down vote up
@Listener(order = Order.LAST, beforeModifications = true)
public void onPlayerPickupItem(ChangeInventoryEvent.Pickup.Pre event, @Root Player player) {
    if (!GDFlags.ITEM_PICKUP || !GriefDefenderPlugin.getInstance().claimsEnabledForWorld(player.getWorld().getUniqueId())) {
        return;
    }
    if (GriefDefenderPlugin.isTargetIdBlacklisted(Flags.ITEM_PICKUP.getName(), event.getTargetEntity(), player.getWorld().getProperties())) {
        return;
    }

    GDTimings.PLAYER_PICKUP_ITEM_EVENT.startTimingIfSync();
    final World world = player.getWorld();
    GDPlayerData playerData = this.dataStore.getOrCreatePlayerData(world, player.getUniqueId());
    Location<World> location = player.getLocation();
    GDClaim claim = this.dataStore.getClaimAtPlayer(playerData, location);
    if (GDPermissionManager.getInstance().getFinalPermission(event, location, claim, Flags.ITEM_PICKUP, player, event.getTargetEntity(), player, true) == Tristate.FALSE) {
        event.setCancelled(true);
    }

    GDTimings.PLAYER_PICKUP_ITEM_EVENT.stopTimingIfSync();
}
 
Example 2
Source File: ParameterRadius.java    From Prism with MIT License 6 votes vote down vote up
@Override
public Optional<CompletableFuture<?>> process(QuerySession session, String parameter, String value, Query query) {
    if (session.getCommandSource() instanceof Player) {
        Player player = (Player) session.getCommandSource();
        Location<World> location = player.getLocation();

        int radius = Integer.parseInt(value);
        int maxRadius = Prism.getInstance().getConfig().getLimitCategory().getMaximumRadius();

        // Enforce max radius unless player has override perms
        if (radius > maxRadius && !player.hasPermission("prism.override.radius")) {
            // @todo move this
            player.sendMessage(Format.subduedHeading(String.format("Limiting radius to maximum of %d", maxRadius)));
            radius = maxRadius;
        }

        session.setRadius(radius);

        query.addCondition(ConditionGroup.from(location, radius));
    }

    return Optional.empty();
}
 
Example 3
Source File: BlockListener.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onInteractBlock(InteractBlockEvent event, @First Player p) {
    BlockSnapshot b = event.getTargetBlock();
    Location<World> l;

    RedProtect.get().logger.debug(LogLevel.PLAYER, "BlockListener - Is InteractBlockEvent event");

    if (!b.getState().getType().equals(BlockTypes.AIR)) {
        l = b.getLocation().get();
        RedProtect.get().logger.debug(LogLevel.PLAYER, "BlockListener - Is InteractBlockEvent event. The block is " + b.getState().getType().getName());
    } else {
        l = p.getLocation();
    }

    Region r = RedProtect.get().rm.getTopRegion(l, this.getClass().getName());
    if (r != null) {
        ItemType itemInHand = RedProtect.get().getVersionHelper().getItemInHand(p);
        if (itemInHand.equals(ItemTypes.ARMOR_STAND) && !r.canBuild(p)) {
            RedProtect.get().lang.sendMessage(p, "blocklistener.region.cantbuild");
            event.setCancelled(true);
        }
    }
}
 
Example 4
Source File: RTPExecutor.java    From EssentialCmds with MIT License 6 votes vote down vote up
private Optional<Location<World>> randomLocation(Player player, int searchDiameter){
	Location<World> playerLocation = player.getLocation();
	//Adding world border support, otherwise you could murder players by using a location within the border.
	WorldBorder border = player.getWorld().getWorldBorder();
	Vector3d center = border.getCenter();
	double diameter = Math.min(border.getDiameter(), searchDiameter);
	double radius = border.getDiameter() / 2;
	Random rand = new Random();
	int x = (int) (rand.nextInt((int) (center.getX()+diameter)) - radius);
	int y = rand.nextInt(256);
	int z = rand.nextInt((int) (rand.nextInt((int) (center.getZ()+diameter)) - radius));

	Location<World> randLocation = new Location<World>(playerLocation.getExtent(), x, y, z);
	TeleportHelper teleportHelper = Sponge.getGame().getTeleportHelper();
	return teleportHelper.getSafeLocation(randLocation);
}
 
Example 5
Source File: ProtectionManager.java    From FlexibleLogin with MIT License 6 votes vote down vote up
public void protect(Player player) {
    SubjectData subjectData = player.getTransientSubjectData();

    Map<Set<Context>, Map<String, Boolean>> permissions = Collections.emptyMap();
    if (config.getGeneral().isProtectPermissions()) {
        permissions = subjectData.getAllPermissions();
        subjectData.clearPermissions();
    }

    protections.put(player.getUniqueId(), new ProtectionData(player.getLocation(), permissions));

    TeleportConfig teleportConfig = config.getGeneral().getTeleport();
    if (teleportConfig.isEnabled()) {
        teleportConfig.getSpawnLocation().ifPresent(worldLocation -> safeTeleport(player, worldLocation));
    } else {
        Location<World> oldLoc = player.getLocation();

        //sometimes players stuck in a wall
        safeTeleport(player, oldLoc);
    }
}
 
Example 6
Source File: PlayerEventHandler.java    From GriefPrevention with MIT License 6 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onPlayerUseItem(UseItemStackEvent.Start event, @First Player player) {
    if (!GPFlags.ITEM_USE || !GriefPreventionPlugin.instance.claimsEnabledForWorld(player.getWorld().getProperties())) {
        return;
    }
    if (GriefPreventionPlugin.isTargetIdBlacklisted(ClaimFlag.ITEM_USE.toString(), event.getItemStackInUse().getType(), player.getWorld().getProperties())) {
        return;
    }

    GPTimings.PLAYER_USE_ITEM_EVENT.startTimingIfSync();
    Location<World> location = player.getLocation();
    GPPlayerData playerData = this.dataStore.getOrCreatePlayerData(location.getExtent(), player.getUniqueId());
    GPClaim claim = this.dataStore.getClaimAtPlayer(playerData, location);

    final Tristate result = GPPermissionHandler.getClaimPermission(event, location, claim, GPPermissions.ITEM_USE, player, event.getItemStackInUse().getType(), player, TrustType.ACCESSOR, true);
    if (result == Tristate.FALSE) {
        final Text message = GriefPreventionPlugin.instance.messageData.permissionItemUse
                .apply(ImmutableMap.of(
                "item", event.getItemStackInUse().getType().getId())).build();
        GriefPreventionPlugin.sendClaimDenyMessage(claim, player,  message);
        event.setCancelled(true);
    }
    GPTimings.PLAYER_USE_ITEM_EVENT.stopTimingIfSync();
}
 
Example 7
Source File: PlayerEventHandler.java    From GriefDefender with MIT License 6 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onPlayerUseItem(UseItemStackEvent.Start event, @First Player player) {
    if (!GDFlags.ITEM_USE || !GriefDefenderPlugin.getInstance().claimsEnabledForWorld(player.getWorld().getUniqueId())) {
        return;
    }
    if (GriefDefenderPlugin.isTargetIdBlacklisted(Flags.ITEM_USE.getName(), event.getItemStackInUse().getType(), player.getWorld().getProperties())) {
        return;
    }

    GDTimings.PLAYER_USE_ITEM_EVENT.startTimingIfSync();
    Location<World> location = player.getLocation();
    GDPlayerData playerData = this.dataStore.getOrCreatePlayerData(location.getExtent(), player.getUniqueId());
    GDClaim claim = this.dataStore.getClaimAtPlayer(playerData, location);

    final Tristate result = GDPermissionManager.getInstance().getFinalPermission(event, location, claim, Flags.ITEM_USE, player, event.getItemStackInUse().getType(), player, TrustTypes.ACCESSOR, true);
    if (result == Tristate.FALSE) {
        final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.PERMISSION_ITEM_USE,
                ImmutableMap.of(
                "item", event.getItemStackInUse().getType().getId()));
        GriefDefenderPlugin.sendClaimDenyMessage(claim, player,  message);
        event.setCancelled(true);
    }
    GDTimings.PLAYER_USE_ITEM_EVENT.stopTimingIfSync();
}
 
Example 8
Source File: PlayerEventHandler.java    From GriefDefender with MIT License 6 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onPlayerInteractInventoryClose(InteractInventoryEvent.Close event, @Root Player player) {
    final ItemStackSnapshot cursor = event.getCursorTransaction().getOriginal();
    if (cursor == ItemStackSnapshot.NONE || !GDFlags.ITEM_DROP || !GriefDefenderPlugin.getInstance().claimsEnabledForWorld(player.getWorld().getUniqueId())) {
        return;
    }
    if (GriefDefenderPlugin.isTargetIdBlacklisted(Flags.ITEM_DROP.getName(), cursor, player.getWorld().getProperties())) {
        return;
    }

    GDTimings.PLAYER_INTERACT_INVENTORY_CLOSE_EVENT.startTimingIfSync();
    final Location<World> location = player.getLocation();
    final GDClaim claim = this.dataStore.getClaimAt(location);
    if (GDPermissionManager.getInstance().getFinalPermission(event, location, claim, Flags.ITEM_DROP, player, cursor, player, TrustTypes.ACCESSOR, true) == Tristate.FALSE) {
        final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.PERMISSION_ITEM_DROP,
                ImmutableMap.of(
                "player", claim.getOwnerName(),
                "item", cursor.getType().getId()));
        GriefDefenderPlugin.sendClaimDenyMessage(claim, player, message);
        event.setCancelled(true);
    }

    GDTimings.PLAYER_INTERACT_INVENTORY_CLOSE_EVENT.stopTimingIfSync();
}
 
Example 9
Source File: CachedPlayer.java    From Web-API with MIT License 5 votes vote down vote up
public CachedPlayer(Player player) {
    super(player);

    this.uuid = UUID.fromString(player.getUniqueId().toString());
    this.name = player.getName();
    this.isOnline = true;

    this.location = new CachedLocation(player.getLocation());
    this.rotation = player.getRotation().clone();
    this.velocity = player.getVelocity().clone();
    this.scale = player.getScale().clone();

    this.address = player.getConnection().getAddress().toString();
    this.latency = player.getConnection().getLatency();

    // Collect unlocked advancements
    for (AdvancementTree tree : player.getUnlockedAdvancementTrees()) {
        addUnlockedAdvancements(player, tree.getRootAdvancement());
    }

    // This will be moved to the other constructor once Sponge implements the offline inventory API
    this.helmet = player.getHelmet().map(ItemStack::copy).orElse(null);
    this.chestplate = player.getChestplate().map(ItemStack::copy).orElse(null);
    this.leggings = player.getLeggings().map(ItemStack::copy).orElse(null);
    this.boots = player.getBoots().map(ItemStack::copy).orElse(null);
    this.inventory = new CachedInventory(player.getInventory());
}
 
Example 10
Source File: ParticlesUtil.java    From EagleFactions with MIT License 5 votes vote down vote up
public HomeParticles(final Player player)
{
	this.player = player;
	this.world = player.getWorld();
	this.location = player.getLocation();
	this.lastBlockPosition = player.getLocation().getBlockPosition();
}
 
Example 11
Source File: MobSpawnExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
public Location<World> getSpawnLocFromPlayerLoc(Player player)
{
	BlockRay<World> playerBlockRay = BlockRay.from(player).blockLimit(350).build();
	BlockRayHit<World> finalHitRay = null;

	while (playerBlockRay.hasNext())
	{
		BlockRayHit<World> currentHitRay = playerBlockRay.next();

		if (!player.getWorld().getBlockType(currentHitRay.getBlockPosition()).equals(BlockTypes.AIR))
		{
			finalHitRay = currentHitRay;
			break;
		}
	}

	Location<World> spawnLocation = null;

	if (finalHitRay == null)
	{
		spawnLocation = player.getLocation();
	}
	else
	{
		spawnLocation = finalHitRay.getLocation();
	}

	return spawnLocation;
}
 
Example 12
Source File: NationClaimOutpostExecutor.java    From Nations with MIT License 4 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		Player player = (Player) src;
		if (!ConfigHandler.getNode("worlds").getNode(player.getWorld().getName()).getNode("enabled").getBoolean())
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_PLUGINDISABLEDINWORLD));
			return CommandResult.success();
		}
		Nation nation = DataHandler.getNationOfPlayer(player.getUniqueId());
		if (nation == null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NONATION));
			return CommandResult.success();
		}
		if (!nation.isStaff(player.getUniqueId()))
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_PERM_NATIONSTAFF));
			return CommandResult.success();
		}
		Location<World> loc = player.getLocation();
		if (!DataHandler.canClaim(loc, false, nation.getUUID()))
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_TOOCLOSE));
			return CommandResult.success();
		}
		
		if (NationsPlugin.getEcoService() == null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOECO));
			return CommandResult.success();
		}
		Optional<Account> optAccount = NationsPlugin.getEcoService().getOrCreateAccount("nation-" + nation.getUUID());
		if (!optAccount.isPresent())
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ECONONATION));
			return CommandResult.success();
		}
		BigDecimal price = BigDecimal.valueOf(ConfigHandler.getNode("prices", "outpostCreationPrice").getDouble());
		TransactionResult result = optAccount.get().withdraw(NationsPlugin.getEcoService().getDefaultCurrency(), price, NationsPlugin.getCause());
		if (result.getResult() == ResultType.ACCOUNT_NO_FUNDS)
		{
			src.sendMessage(Text.builder()
					.append(Text.of(TextColors.RED, LanguageHandler.ERROR_NEEDMONEYNATION.split("\\{AMOUNT\\}")[0]))
					.append(Utils.formatPrice(TextColors.RED, price))
					.append(Text.of(TextColors.RED, LanguageHandler.ERROR_NEEDMONEYNATION.split("\\{AMOUNT\\}")[1])).build());
			return CommandResult.success();
		}
		else if (result.getResult() != ResultType.SUCCESS)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ECOTRANSACTION));
			return CommandResult.success();
		}
		
		nation.getRegion().addRect(new Rect(loc.getExtent().getUniqueId(), loc.getBlockX(), loc.getBlockX(), loc.getBlockZ(), loc.getBlockZ()));
		DataHandler.addToWorldChunks(nation);
		DataHandler.saveNation(nation.getUUID());
		src.sendMessage(Text.of(TextColors.GREEN, LanguageHandler.SUCCESS_OUTPOST));
	}
	else
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOPLAYER));
	}
	return CommandResult.success();
}
 
Example 13
Source File: NationSetspawnExecutor.java    From Nations with MIT License 4 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		if (!ctx.<String>getOne("name").isPresent())
		{
			src.sendMessage(Text.of(TextColors.YELLOW, "/n setspawn <name>"));
			return CommandResult.success();
		}
		String spawnName = ctx.<String>getOne("name").get();
		Player player = (Player) src;
		Nation nation = DataHandler.getNationOfPlayer(player.getUniqueId());
		if (nation == null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NONATION));
			return CommandResult.success();
		}
		if (!nation.isStaff(player.getUniqueId()))
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_PERM_NATIONSTAFF));
			return CommandResult.success();
		}
		Location<World> newSpawn = player.getLocation();
		if (!nation.getRegion().isInside(newSpawn))
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_BADSPAWNLOCATION));
			return CommandResult.success();
		}
		if (nation.getNumSpawns() + 1 > nation.getMaxSpawns() && !nation.getSpawns().containsKey(spawnName))
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_MAXSPAWNREACH
					.replaceAll("\\{MAX\\}", String.valueOf(nation.getMaxSpawns()))));
			return CommandResult.success();
		}
		if (!spawnName.matches("[\\p{Alnum}\\p{IsIdeographic}\\p{IsLetter}]{1,30}"))
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ALPHASPAWN
					.replaceAll("\\{MIN\\}", ConfigHandler.getNode("others", "minZoneNameLength").getString())
					.replaceAll("\\{MAX\\}", ConfigHandler.getNode("others", "maxZoneNameLength").getString())));
			return CommandResult.success();
		}
		nation.addSpawn(spawnName, newSpawn);
		DataHandler.saveNation(nation.getUUID());
		src.sendMessage(Text.of(TextColors.AQUA, LanguageHandler.SUCCESS_CHANGESPAWN));
	}
	else
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOPLAYER));
	}
	return CommandResult.success();
}
 
Example 14
Source File: NationadminSetspawnExecutor.java    From Nations with MIT License 4 votes vote down vote up
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
	if (src instanceof Player)
	{
		Player player = (Player) src;
		if (!ctx.<String>getOne("nation").isPresent() || !ctx.<String>getOne("name").isPresent())
		{
			src.sendMessage(Text.of(TextColors.YELLOW, "/na setspawn <nation> <name>"));
			return CommandResult.success();
		}
		String nationName = ctx.<String>getOne("nation").get();
		Nation nation = DataHandler.getNation(nationName);
		if (nation == null)
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_BADNATIONNAME));
			return CommandResult.success();
		}
		String spawnName = ctx.<String>getOne("name").get();
		
		Location<World> newSpawn = player.getLocation();
		if (!nation.getRegion().isInside(newSpawn))
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_BADSPAWNLOCATION));
			return CommandResult.success();
		}
		if (nation.getNumSpawns() + 1 > nation.getMaxSpawns() && !nation.getSpawns().containsKey(spawnName))
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_MAXSPAWNREACH
					.replaceAll("\\{MAX\\}", String.valueOf(nation.getMaxSpawns()))));
			return CommandResult.success();
		}
		if (!spawnName.matches("[\\p{Alnum}\\p{IsIdeographic}\\p{IsLetter}]{1,30}"))
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ALPHASPAWN
					.replaceAll("\\{MIN\\}", ConfigHandler.getNode("others", "minZoneNameLength").getString())
					.replaceAll("\\{MAX\\}", ConfigHandler.getNode("others", "maxZoneNameLength").getString())));
			return CommandResult.success();
		}
		nation.addSpawn(spawnName, newSpawn);
		DataHandler.saveNation(nation.getUUID());
		src.sendMessage(Text.of(TextColors.AQUA, LanguageHandler.SUCCESS_CHANGESPAWN));
	}
	else
	{
		src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOPLAYER));
	}
	return CommandResult.success();
}
 
Example 15
Source File: PlayerListener.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
@Listener(order = Order.FIRST)
public void onInteractRight(InteractBlockEvent.Secondary event, @First Player p) {
    BlockSnapshot b = event.getTargetBlock();
    Location<World> l;

    RedProtect.get().logger.debug(LogLevel.PLAYER, "PlayerListener - Is InteractBlockEvent.Secondary event");

    if (!b.getState().getType().equals(BlockTypes.AIR)) {
        l = b.getLocation().get();
        RedProtect.get().logger.debug(LogLevel.PLAYER, "PlayerListener - Is InteractBlockEvent.Secondary event. The block is " + b.getState().getType().getName());
    } else {
        l = p.getLocation();
    }

    Region r = RedProtect.get().rm.getTopRegion(l, this.getClass().getName());
    ItemType itemInHand = RedProtect.get().getVersionHelper().getItemInHand(p);

    String claimmode = RedProtect.get().config.getWorldClaimType(p.getWorld().getName());
    if (event instanceof InteractBlockEvent.Secondary.MainHand && itemInHand.getId().equalsIgnoreCase(RedProtect.get().config.configRoot().wands.adminWandID) && ((claimmode.equalsIgnoreCase("WAND") || claimmode.equalsIgnoreCase("BOTH")) || RedProtect.get().ph.hasPerm(p, "redprotect.admin.claim"))) {
        if (!RedProtect.get().getUtil().canBuildNear(p, l)) {
            event.setCancelled(true);
            return;
        }
        RedProtect.get().secondLocationSelections.put(p, l);
        p.sendMessage(RedProtect.get().getUtil().toText(RedProtect.get().lang.get("playerlistener.wand2") + RedProtect.get().lang.get("general.color") + " (&e" + l.getBlockX() + RedProtect.get().lang.get("general.color") + ", &e" + l.getBlockY() + RedProtect.get().lang.get("general.color") + ", &e" + l.getBlockZ() + RedProtect.get().lang.get("general.color") + ")."));
        event.setCancelled(true);

        //show preview border
        previewSelection(p);
        return;
    }

    //other blocks and interactions
    if (r != null) {
        if ((itemInHand.equals(ItemTypes.ENDER_PEARL) || itemInHand.getName().equals("minecraft:chorus_fruit")) && !r.canTeleport(p)) {
            RedProtect.get().lang.sendMessage(p, "playerlistener.region.cantuse");
            event.setUseItemResult(Tristate.FALSE);
            event.setCancelled(true);
        } else if ((itemInHand.equals(ItemTypes.BOW) || itemInHand.equals(ItemTypes.SNOWBALL) || itemInHand.equals(ItemTypes.EGG)) && !r.canProtectiles(p)) {
            RedProtect.get().lang.sendMessage(p, "playerlistener.region.cantuse");
            event.setUseItemResult(Tristate.FALSE);
            event.setCancelled(true);
        } else if (itemInHand.equals(ItemTypes.POTION) && !r.usePotions(p)) {
            RedProtect.get().lang.sendMessage(p, "playerlistener.region.cantuse");
            event.setUseItemResult(Tristate.FALSE);
            event.setCancelled(true);
        } else if (itemInHand.equals(ItemTypes.MONSTER_EGG) && !r.canInteractPassives(p)) {
            RedProtect.get().lang.sendMessage(p, "playerlistener.region.cantuse");
            event.setUseItemResult(Tristate.FALSE);
            event.setCancelled(true);
        } else if ((itemInHand.equals(ItemTypes.BOAT) || itemInHand.getType().getName().contains("_minecart")) && !r.canMinecart(p)) {
            RedProtect.get().lang.sendMessage(p, "playerlistener.region.cantuse");
            event.setUseItemResult(Tristate.FALSE);
            event.setCancelled(true);
        }
    }
}
 
Example 16
Source File: PlayerEventHandler.java    From GriefPrevention with MIT License 4 votes vote down vote up
@Listener(order = Order.LAST, beforeModifications = true)
public void onPlayerPickupItem(ChangeInventoryEvent.Pickup.Pre event, @Root Player player) {
    if (!GPFlags.ITEM_PICKUP || !GriefPreventionPlugin.instance.claimsEnabledForWorld(player.getWorld().getProperties())) {
        return;
    }
    if (GriefPreventionPlugin.isTargetIdBlacklisted(ClaimFlag.ITEM_PICKUP.toString(), event.getTargetEntity(), player.getWorld().getProperties())) {
        return;
    }

    GPTimings.PLAYER_PICKUP_ITEM_EVENT.startTimingIfSync();
    final World world = player.getWorld();
    GPPlayerData playerData = this.dataStore.getOrCreatePlayerData(world, player.getUniqueId());
    Location<World> location = player.getLocation();
    GPClaim claim = this.dataStore.getClaimAtPlayer(playerData, location);
    if (GPPermissionHandler.getClaimPermission(event, location, claim, GPPermissions.ITEM_PICKUP, player, event.getTargetEntity(), player, TrustType.ACCESSOR, true) == Tristate.FALSE) {
        event.setCancelled(true);
        GPTimings.PLAYER_PICKUP_ITEM_EVENT.stopTimingIfSync();
        return;
    }

    // the rest of this code is specific to pvp worlds
    if (claim.pvpRulesApply()) {
        // if we're preventing spawn camping and the player was previously empty handed...
        if (GriefPreventionPlugin.getActiveConfig(world.getProperties()).getConfig().pvp.protectFreshSpawns && PlayerUtils.hasItemInOneHand(player, ItemTypes.NONE)) {
            // if that player is currently immune to pvp
            if (playerData.pvpImmune) {
                // if it's been less than 10 seconds since the last time he spawned, don't pick up the item
                long now = Calendar.getInstance().getTimeInMillis();
                long elapsedSinceLastSpawn = now - playerData.lastSpawn;
                if (elapsedSinceLastSpawn < 10000) {
                    event.setCancelled(true);
                    GPTimings.PLAYER_PICKUP_ITEM_EVENT.stopTimingIfSync();
                    return;
                }

                // otherwise take away his immunity. he may be armed now. at least, he's worth killing for some loot
                playerData.pvpImmune = false;
                GriefPreventionPlugin.sendMessage(player, GriefPreventionPlugin.instance.messageData.pvpImmunityEnd.toText());
            }
        }
    }
    GPTimings.PLAYER_PICKUP_ITEM_EVENT.stopTimingIfSync();
}
 
Example 17
Source File: PlayerEventHandler.java    From GriefPrevention with MIT License 4 votes vote down vote up
public InteractEvent handleItemInteract(InteractEvent event, Player player, World world, ItemStack itemInHand) {
    if (lastInteractItemSecondaryTick == Sponge.getServer().getRunningTimeTicks() || lastInteractItemPrimaryTick == Sponge.getServer().getRunningTimeTicks()) {
        // ignore
        return event;
    }

    if (event instanceof InteractItemEvent.Primary) {
        lastInteractItemPrimaryTick = Sponge.getServer().getRunningTimeTicks();
    } else {
        lastInteractItemSecondaryTick = Sponge.getServer().getRunningTimeTicks();
    }

    final ItemType itemType = itemInHand.getType();
    if (itemInHand.isEmpty() || itemType instanceof ItemFood) {
        return event;
    }

    final boolean primaryEvent = event instanceof InteractItemEvent.Primary || event instanceof InteractBlockEvent.Primary;
    if (!GPFlags.INTERACT_ITEM_PRIMARY && primaryEvent || !GPFlags.INTERACT_ITEM_SECONDARY && !primaryEvent || !GriefPreventionPlugin.instance.claimsEnabledForWorld(world.getProperties())) {
        return event;
    }

    if (primaryEvent && GriefPreventionPlugin.isTargetIdBlacklisted(ClaimFlag.INTERACT_ITEM_PRIMARY.toString(), itemInHand.getType(), world.getProperties())) {
        return event;
    }
    if (!primaryEvent && GriefPreventionPlugin.isTargetIdBlacklisted(ClaimFlag.INTERACT_ITEM_SECONDARY.toString(), itemInHand.getType(), world.getProperties())) {
        return event;
    }

    final Cause cause = event.getCause();
    final EventContext context = cause.getContext();
    final BlockSnapshot blockSnapshot = context.get(EventContextKeys.BLOCK_HIT).orElse(BlockSnapshot.NONE);
    final Vector3d interactPoint = event.getInteractionPoint().orElse(null);
    final Entity entity = context.get(EventContextKeys.ENTITY_HIT).orElse(null);
    final Location<World> location = entity != null ? entity.getLocation() 
            : blockSnapshot != BlockSnapshot.NONE ? blockSnapshot.getLocation().get() 
                    : interactPoint != null ? new Location<World>(world, interactPoint) 
                            : player.getLocation();

    final String ITEM_PERMISSION = primaryEvent ? GPPermissions.INTERACT_ITEM_PRIMARY : GPPermissions.INTERACT_ITEM_SECONDARY;
    final GPPlayerData playerData = this.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    if (!itemInHand.isEmpty() && (itemInHand.getType().equals(GriefPreventionPlugin.instance.modificationTool) ||
            itemInHand.getType().equals(GriefPreventionPlugin.instance.investigationTool))) {
        GPPermissionHandler.addEventLogEntry(event, location, itemInHand, blockSnapshot == null ? entity : blockSnapshot, player, ITEM_PERMISSION, null, Tristate.TRUE);
        if (investigateClaim(event, player, blockSnapshot, itemInHand)) {
            return event;
        }

        onPlayerHandleShovelAction(event, blockSnapshot, player,  ((HandInteractEvent) event).getHandType(), playerData);
        return event;
    }

    final GPClaim claim = this.dataStore.getClaimAtPlayer(location, playerData, true);
    if (GPPermissionHandler.getClaimPermission(event, location, claim, ITEM_PERMISSION, player, itemType, player, TrustType.ACCESSOR, true) == Tristate.FALSE) {
        Text message = GriefPreventionPlugin.instance.messageData.permissionInteractItem
                .apply(ImmutableMap.of(
                "owner", claim.getOwnerName(),
                "item", itemInHand.getType().getId())).build();
        GriefPreventionPlugin.sendClaimDenyMessage(claim, player, message);
        if (event instanceof InteractItemEvent) {
            if (!SpongeImplHooks.isFakePlayer(((EntityPlayerMP) player)) && itemType == ItemTypes.WRITABLE_BOOK) {
                ((EntityPlayerMP) player).closeScreen();
            }
        }
        event.setCancelled(true);
    }
    return event;
}
 
Example 18
Source File: CommandHelper.java    From GriefDefender with MIT License 4 votes vote down vote up
public static Consumer<CommandSource> createTeleportConsumer(CommandSource src, Location<World> location, Claim claim, boolean isClaimSpawn) {
    return teleport -> {
        if (!(src instanceof Player)) {
            // ignore
            return;
        }

        final Player player = (Player) src;
        final GDPlayerData playerData = GriefDefenderPlugin.getInstance().dataStore.getPlayerData(player.getWorld(), player.getUniqueId());
        final int teleportDelay = GDPermissionManager.getInstance().getInternalOptionValue(TypeToken.of(Integer.class), player, Options.PLAYER_TELEPORT_DELAY, claim);
        if (isClaimSpawn) {
            if (teleportDelay > 0) {
                playerData.teleportDelay = teleportDelay + 1;
                playerData.teleportSourceLocation = player.getLocation();
                playerData.teleportLocation = location;
                return;
            }

            player.setLocation(location);
            return;
        }

        Location<World> safeLocation = Sponge.getGame().getTeleportHelper().getSafeLocation(location, 64, 16).orElse(null);
        if (safeLocation == null) {
            if (teleportDelay > 0) {
                playerData.teleportDelay = teleportDelay + 1;
                playerData.teleportLocation = location;
                return;
            }
            TextAdapter.sendComponent(player, TextComponent.builder("")
                    .append("Location is not safe. ", TextColor.RED)
                    .append(TextComponent.builder("")
                            .append("Are you sure you want to teleport here?", TextColor.GREEN)
                            .clickEvent(ClickEvent.runCommand(GDCallbackHolder.getInstance().createCallbackRunCommand(createForceTeleportConsumer(player, location)))).decoration(TextDecoration.UNDERLINED, true).build()).build());
        } else {
            if (teleportDelay > 0) {
                playerData.teleportDelay = teleportDelay + 1;
                playerData.teleportLocation = safeLocation;
                return;
            }
            player.setLocation(safeLocation);
        }
    };
}
 
Example 19
Source File: BlockEventHandler.java    From GriefDefender with MIT License 4 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onBlockNotify(NotifyNeighborBlockEvent event) {
    LocatableBlock locatableBlock = event.getCause().first(LocatableBlock.class).orElse(null);
    TileEntity tileEntity = event.getCause().first(TileEntity.class).orElse(null);
    Location<World> sourceLocation = locatableBlock != null ? locatableBlock.getLocation() : tileEntity != null ? tileEntity.getLocation() : null;
    GDClaim sourceClaim = null;
    GDPlayerData playerData = null;
    if (sourceLocation != null) {
        if (GriefDefenderPlugin.isSourceIdBlacklisted("block-notify", event.getSource(), sourceLocation.getExtent().getProperties())) {
            return;
        }
    }

    final User user = CauseContextHelper.getEventUser(event);
    if (user == null) {
        return;
    }
    if (sourceLocation == null) {
        Player player = event.getCause().first(Player.class).orElse(null);
        if (player == null) {
            return;
        }

        sourceLocation = player.getLocation();
        playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
        sourceClaim = this.dataStore.getClaimAtPlayer(playerData, player.getLocation());
    } else {
        playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(sourceLocation.getExtent(), user.getUniqueId());
        sourceClaim = this.dataStore.getClaimAt(sourceLocation);
    }

    if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(sourceLocation.getExtent().getUniqueId())) {
        return;
    }

    GDTimings.BLOCK_NOTIFY_EVENT.startTimingIfSync();
    Iterator<Direction> iterator = event.getNeighbors().keySet().iterator();
    GDClaim targetClaim = null;
    while (iterator.hasNext()) {
        Direction direction = iterator.next();
        Location<World> location = sourceLocation.getBlockRelative(direction);
        Vector3i pos = location.getBlockPosition();
        targetClaim = this.dataStore.getClaimAt(location, targetClaim);
        if (sourceClaim.isWilderness() && targetClaim.isWilderness()) {
            if (playerData != null) {
                playerData.eventResultCache = new EventResultCache(targetClaim, "block-notify", Tristate.TRUE);
            }
            continue;
        } else if (!sourceClaim.isWilderness() && targetClaim.isWilderness()) {
            if (playerData != null) {
                playerData.eventResultCache = new EventResultCache(targetClaim, "block-notify", Tristate.TRUE);
            }
            continue;
        } else if (sourceClaim.getUniqueId().equals(targetClaim.getUniqueId())) {
            if (playerData != null) {
                playerData.eventResultCache = new EventResultCache(targetClaim, "block-notify", Tristate.TRUE);
            }
            continue;
        } else {
            if (playerData.eventResultCache != null && playerData.eventResultCache.checkEventResultCache(targetClaim, "block-notify") == Tristate.TRUE) {
                continue;
            }
            // Needed to handle levers notifying doors to open etc.
            if (targetClaim.isUserTrusted(user, TrustTypes.ACCESSOR)) {
                if (playerData != null) {
                    playerData.eventResultCache = new EventResultCache(targetClaim, "block-notify", Tristate.TRUE, TrustTypes.ACCESSOR.getName().toLowerCase());
                }
                continue;
            }
        }

        // no claim crossing unless trusted
        iterator.remove();
    }
    GDTimings.BLOCK_NOTIFY_EVENT.stopTimingIfSync();
}
 
Example 20
Source File: WEHook.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
public static Region pasteWithWE(Player p, File file) {
    Location<World> loc = p.getLocation();
    Region r = null;

    if (p.getLocation().getBlockRelative(Direction.DOWN).getBlock().getType().equals(BlockTypes.WATER) ||
            p.getLocation().getBlockRelative(Direction.DOWN).getBlock().getType().equals(BlockTypes.FLOWING_WATER)) {
        RedProtect.get().lang.sendMessage(p, "playerlistener.region.needground");
        return null;
    }

    SpongePlayer sp = SpongeWorldEdit.inst().wrapPlayer(p);
    SpongeWorld ws = SpongeWorldEdit.inst().getWorld(p.getWorld());

    LocalSession session = SpongeWorldEdit.inst().getSession(p);

    Closer closer = Closer.create();
    try {
        ClipboardFormat format = ClipboardFormat.findByAlias("schematic");
        FileInputStream fis = closer.register(new FileInputStream(file));
        BufferedInputStream bis = closer.register(new BufferedInputStream(fis));
        ClipboardReader reader = format.getReader(bis);

        WorldData worldData = ws.getWorldData();
        Clipboard clipboard = reader.read(ws.getWorldData());
        session.setClipboard(new ClipboardHolder(clipboard, worldData));

        Vector bmin = clipboard.getMinimumPoint();
        Vector bmax = clipboard.getMaximumPoint();

        Location<World> min = loc.add(bmin.getX(), bmin.getY(), bmin.getZ());
        Location<World> max = loc.add(bmax.getX(), bmax.getY(), bmax.getZ());

        PlayerRegion leader = new PlayerRegion(p.getUniqueId().toString(), p.getName());
        RegionBuilder rb2 = new DefineRegionBuilder(p, min, max, "", leader, new HashSet<>(), false);
        if (rb2.ready()) {
            r = rb2.build();
        }

        ClipboardHolder holder = session.getClipboard();

        Operation op = holder.createPaste(session.createEditSession(sp), ws.getWorldData()).to(session.getPlacementPosition(sp)).build();
        Operations.completeLegacy(op);
    } catch (IOException | EmptyClipboardException | IncompleteRegionException | MaxChangedBlocksException e) {
        CoreUtil.printJarVersion();
        e.printStackTrace();
    }

    return r;
}