org.spongepowered.api.world.Location Java Examples

The following examples show how to use org.spongepowered.api.world.Location. 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: GPClaim.java    From GriefPrevention with MIT License 6 votes vote down vote up
@Override
public boolean isInside(Claim claim) {
    final GPClaim otherClaim = (GPClaim) claim;
    if(!otherClaim.contains(this.lesserBoundaryCorner)) {
        return false;
    }
    if(!otherClaim.contains(this.greaterBoundaryCorner)) {
        return false;
    }

    if(!otherClaim.contains(new Location<World>(this.world, this.lesserBoundaryCorner.getBlockX(), this.lesserBoundaryCorner.getBlockY(), this.greaterBoundaryCorner.getBlockZ()))) {
        return false;
    }
    if(!otherClaim.contains(new Location<World>(this.world, this.greaterBoundaryCorner.getBlockX(), this.greaterBoundaryCorner.getBlockY(), this.lesserBoundaryCorner.getBlockZ()))) {
        return false;
    }

    return true;
}
 
Example #2
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 #3
Source File: LowCommandCallable.java    From UltimateCore with MIT License 6 votes vote down vote up
/**
 * Get a list of suggestions based on input.
 * <p>
 * If a suggestion is chosen by the user, it will replace the last
 * word.</p>
 *
 * @param source    The command source
 * @param arguments The arguments entered up to this point
 * @param loc       The position the source is looking at when performing tab completion
 * @return A list of suggestions
 * @throws CommandException Thrown if there was a parsing error
 */
@Override
public List<String> getSuggestions(CommandSource source, String arguments, Location<World> loc) throws CommandException {
    if (!source.hasPermission(command.getPermission().get())) {
        return new ArrayList<>();
    }
    String[] args = arguments.split(" ");
    //TODO how does this work?
    List<String> rtrn = command.onTabComplete(source, args, args[args.length - 1], args.length - 1);
    if (rtrn == null) {
        rtrn = new ArrayList<>();
        for (Player p : Sponge.getServer().getOnlinePlayers()) {
            rtrn.add(p.getName());
        }
    }
    String start = args[args.length - 1];
    rtrn = rtrn.stream().filter(name -> name.toLowerCase().startsWith(start.toLowerCase())).collect(Collectors.toList());
    return rtrn;
}
 
Example #4
Source File: PlayerInteractListener.java    From EagleFactions with MIT License 6 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onEntityInteract(final InteractEntityEvent event, @Root final Player player)
{
    final Entity targetEntity = event.getTargetEntity();
    final Optional<Vector3d> optionalInteractionPoint = event.getInteractionPoint();

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

    final Vector3d blockPosition = optionalInteractionPoint.orElseGet(() -> targetEntity.getLocation().getPosition());
    final Location<World> location = new Location<>(targetEntity.getWorld(), blockPosition);
    boolean canInteractWithEntity = super.getPlugin().getProtectionManager().canInteractWithBlock(location, player, true).hasAccess();
    if(!canInteractWithEntity)
    {
        event.setCancelled(true);
        return;
    }
}
 
Example #5
Source File: CommandHandlers.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
private static void tpWait(final Player p, final Location<World> loc, final String rname) {
    if (p.hasPermission("redprotect.command.admin.teleport")) {
        p.setLocation(loc);
        return;
    }
    if (!RedProtect.get().tpWait.contains(p.getName())) {
        RedProtect.get().tpWait.add(p.getName());
        RedProtect.get().lang.sendMessage(p, "cmdmanager.region.tpdontmove");
        Sponge.getScheduler().createSyncExecutor(RedProtect.get().container).schedule(() -> {
            if (RedProtect.get().tpWait.contains(p.getName())) {
                RedProtect.get().tpWait.remove(p.getName());
                p.setLocation(loc);
                RedProtect.get().lang.sendMessage(p, RedProtect.get().lang.get("cmdmanager.region.teleport") + " " + rname);
            }
        }, RedProtect.get().config.configRoot().region_settings.teleport_time, TimeUnit.SECONDS);
    } else {
        RedProtect.get().lang.sendMessage(p, "cmdmanager.region.tpneedwait");
    }
}
 
Example #6
Source File: SkinApplier.java    From ChangeSkin with MIT License 6 votes vote down vote up
private void sendUpdateSelf() {
    receiver.getTabList().removeEntry(receiver.getUniqueId());
    receiver.getTabList().addEntry(TabListEntry.builder()
            .displayName(receiver.getDisplayNameData().displayName().get())
            .latency(receiver.getConnection().getLatency())
            .list(receiver.getTabList())
            .gameMode(receiver.getGameModeData().type().get())
            .profile(receiver.getProfile())
            .build());

    Location<World> oldLocation = receiver.getLocation();
    Vector3d rotation = receiver.getRotation();
    World receiverWorld = receiver.getWorld();
    Sponge.getServer().getWorlds()
            .stream()
            .filter(world -> !world.equals(receiverWorld))
            .findFirst()
            .ifPresent(world -> {
                receiver.setLocation(world.getSpawnLocation());
                receiver.setLocationAndRotation(oldLocation, rotation);
            });
}
 
Example #7
Source File: Utils.java    From EssentialCmds with MIT License 6 votes vote down vote up
public static void teleportPlayerToJail(Player player, int number)
{
	UUID worldUuid = UUID.fromString(Configs.getConfig(jailsConfig).getNode("jails", String.valueOf(number), "world").getString());
	double x = Configs.getConfig(jailsConfig).getNode("jails", String.valueOf(number), "X").getDouble();
	double y = Configs.getConfig(jailsConfig).getNode("jails", String.valueOf(number), "Y").getDouble();
	double z = Configs.getConfig(jailsConfig).getNode("jails", String.valueOf(number), "Z").getDouble();
	World world = Sponge.getServer().getWorld(worldUuid).orElse(null);

	if (world != null)
	{
		Location<World> location = new Location<World>(world, x, y, z);

		if (player.getWorld().getUniqueId().equals(worldUuid))
		{
			player.setLocation(location);
		}
		else
		{
			player.transferToWorld(world.getUniqueId(), location.getPosition());
		}
	}
}
 
Example #8
Source File: GDClaimManager.java    From GriefDefender with MIT License 6 votes vote down vote up
private GDClaim findClaim(GDClaim claim, Location<World> location, GDPlayerData playerData, boolean useBorderBlockRadius) {
    if (claim.contains(location, playerData, useBorderBlockRadius)) {
        // when we find a top level claim, if the location is in one of its children,
        // return the child claim, not the top level claim
        for (Claim childClaim : claim.children) {
            GDClaim child = (GDClaim) childClaim;
            if (!child.children.isEmpty()) {
                GDClaim innerChild = findClaim(child, location, playerData, useBorderBlockRadius);
                if (innerChild != null) {
                    return innerChild;
                }
            }
            // check if child has children (Town -> Basic -> Subdivision)
            if (child.contains(location, playerData, useBorderBlockRadius)) {
                return child;
            }
        }
        return claim;
    }
    return null;
}
 
Example #9
Source File: ConditionGroup.java    From Prism with MIT License 6 votes vote down vote up
/**
 * Convenience method to build conditions for a region of radius around a central location.
 *
 * @param location Location<?>
 * @param radius Integer
 * @return ConditionGroup
 */
public static ConditionGroup from(Location<?> location, int radius) {
    ConditionGroup conditions = new ConditionGroup(Operator.AND);

    // World
    conditions.add(FieldCondition.of(DataQueries.Location.then(DataQueries.WorldUuid), MatchRule.EQUALS, location.getExtent().getUniqueId().toString()));

    // X
    Range<Integer> xRange = Range.open(location.getBlockX() - radius, location.getBlockX() + radius);
    conditions.add(FieldCondition.of(DataQueries.Location.then(DataQueries.X), xRange));

    // Y
    Range<Integer> yRange = Range.open(location.getBlockY() - radius, location.getBlockY() + radius);
    conditions.add(FieldCondition.of(DataQueries.Location.then(DataQueries.Y), yRange));

    // Z
    Range<Integer> zRange = Range.open(location.getBlockZ() - radius, location.getBlockZ() + radius);
    conditions.add(FieldCondition.of(DataQueries.Location.then(DataQueries.Z), zRange));

    return conditions;
}
 
Example #10
Source File: Visualization.java    From GriefPrevention with MIT License 6 votes vote down vote up
public void addRightLine(World world, int y, BlockType cornerMaterial, BlockType accentMaterial) {
    BlockSnapshot rightVisualBlock1 =
            snapshotBuilder.from(new Location<World>(world, this.bigx, y, this.smallz)).blockState(cornerMaterial.getDefaultState()).build();
    newElements.add(new Transaction<BlockSnapshot>(rightVisualBlock1.getLocation().get().createSnapshot(), rightVisualBlock1));
    this.corners.add(rightVisualBlock1.getPosition());
    BlockSnapshot rightVisualBlock2 =
            snapshotBuilder.from(new Location<World>(world, this.bigx, y, this.smallz + 1)).blockState(accentMaterial.getDefaultState()).build();
    newElements.add(new Transaction<BlockSnapshot>(rightVisualBlock2.getLocation().get().createSnapshot(), rightVisualBlock2));
    if (STEP != 0) {
        for (int z = this.smallz + STEP; z < this.bigz - STEP / 2; z += STEP) {
            if ((y != 0 && z >= this.smallz && z <= this.bigz) || (z > this.minz && z < this.maxz)) {
                BlockSnapshot visualBlock =
                        snapshotBuilder.from(new Location<World>(world, this.bigx, y, z)).blockState(accentMaterial.getDefaultState()).build();
                newElements.add(new Transaction<BlockSnapshot>(visualBlock.getLocation().get().createSnapshot(), visualBlock));
            }
        }
    }
    BlockSnapshot rightVisualBlock3 =
            snapshotBuilder.from(new Location<World>(world, this.bigx, y, this.bigz - 1)).blockState(accentMaterial.getDefaultState()).build();
    newElements.add(new Transaction<BlockSnapshot>(rightVisualBlock3.getLocation().get().createSnapshot(), rightVisualBlock3));
    BlockSnapshot rightVisualBlock4 =
            snapshotBuilder.from(new Location<World>(world, this.bigx, y, this.bigz)).blockState(cornerMaterial.getDefaultState()).build();
    newElements.add(new Transaction<BlockSnapshot>(rightVisualBlock4.getLocation().get().createSnapshot(), rightVisualBlock4));
    this.corners.add(rightVisualBlock4.getPosition());
}
 
Example #11
Source File: RedProtectUtil.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
public int simuleTotalRegionSize(String player, Region r2) {
    int total = 0;
    int regs = 0;
    for (Location<World> loc : r2.get4Points(r2.getCenterY())) {
        Map<Integer, Region> pregs = RedProtect.get().rm.getGroupRegion(loc.getExtent().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
        pregs.remove(r2.getPrior());
        Region other;
        if (pregs.size() > 0) {
            other = pregs.get(Collections.max(pregs.keySet()));
        } else {
            continue;
        }
        if (!r2.getID().equals(other.getID()) && r2.getPrior() > other.getPrior() && other.isLeader(player)) {
            regs++;
        }
    }
    if (regs != 4) {
        total += r2.getArea();
    }
    return total;
}
 
Example #12
Source File: GriefPreventionPlugin.java    From GriefPrevention with MIT License 5 votes vote down vote up
public void restoreChunk(Chunk chunk, int miny, boolean aggressiveMode, long delayInTicks, Player player) {
    // build a snapshot of this chunk, including 1 block boundary outside of
    // the chunk all the way around
    int maxHeight = chunk.getWorld().getDimension().getBuildHeight() - 1;
    BlockSnapshot[][][] snapshots = new BlockSnapshot[18][maxHeight][18];
    BlockSnapshot startBlock = chunk.createSnapshot(0, 0, 0);
    Location<World> startLocation =
            new Location<World>(chunk.getWorld(), startBlock.getPosition().getX() - 1, 0, startBlock.getPosition().getZ() - 1);
    for (int x = 0; x < snapshots.length; x++) {
        for (int z = 0; z < snapshots[0][0].length; z++) {
            for (int y = 0; y < snapshots[0].length; y++) {
                snapshots[x][y][z] = chunk.getWorld()
                        .createSnapshot(startLocation.getBlockX() + x, startLocation.getBlockY() + y, startLocation.getBlockZ() + z);
            }
        }
    }

    // create task to process those data in another thread
    Location<World> lesserBoundaryCorner = chunk.createSnapshot(0, 0, 0).getLocation().get();
    Location<World> greaterBoundaryCorner = chunk.createSnapshot(15, 0, 15).getLocation().get();
    // create task when done processing, this task will create a main thread task to actually update the world with processing results
    /*RestoreNatureProcessingTask task = new RestoreNatureProcessingTask(snapshots, miny, chunk.getWorld().getDimension().getType(),
            lesserBoundaryCorner.getBiome(), lesserBoundaryCorner, greaterBoundaryCorner, this.getSeaLevel(chunk.getWorld()),
            aggressiveMode, claimModeIsActive(lesserBoundaryCorner.getExtent().getProperties(), ClaimsMode.Creative),
            playerReceivingVisualization);*/
    // show visualization to player who started the restoration
    if (player != null) {
        GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
        GPClaim claim = new GPClaim(lesserBoundaryCorner, greaterBoundaryCorner , ClaimType.BASIC, false);
        // TODO
        claim.getVisualizer().resetVisuals();
        claim.getVisualizer().createClaimBlockVisuals(player.getLocation().getBlockY(), player.getLocation(), playerData);
        claim.getVisualizer().apply(player);
    }

    BlockUtils.regenerateChunk((net.minecraft.world.chunk.Chunk) chunk);
}
 
Example #13
Source File: BlockUtils.java    From GriefPrevention with MIT License 5 votes vote down vote up
public static boolean isLocationNearClaim(GPClaim claim, Location<World> location, int howNear) {
    Location<World> lesserBoundaryCorner = new Location<World>(claim.lesserBoundaryCorner.getExtent(), claim.lesserBoundaryCorner.getBlockX() - howNear,
            claim.lesserBoundaryCorner.getBlockY(), claim.lesserBoundaryCorner.getBlockZ() - howNear);
    Location<World> greaterBoundaryCorner = new Location<World>(claim.greaterBoundaryCorner.getExtent(), claim.greaterBoundaryCorner.getBlockX() + howNear,
            claim.greaterBoundaryCorner.getBlockY(), claim.greaterBoundaryCorner.getBlockZ() + howNear);
    // not in the same world implies false
    if (!location.getExtent().equals(lesserBoundaryCorner.getExtent())) {
        return false;
    }

    double x = location.getX();
    double y = location.getY();
    double z = location.getZ();

    // main check
    boolean inClaim = false;
    if (claim.isCuboid()) {
        inClaim = (
                x >= lesserBoundaryCorner.getX() &&
                x <= greaterBoundaryCorner.getX() &&
                y >= lesserBoundaryCorner.getY()) &&
                y <= greaterBoundaryCorner.getY() &&
                z >= lesserBoundaryCorner.getZ() &&
                z <= greaterBoundaryCorner.getZ();
    } else {
        inClaim = (y >= lesserBoundaryCorner.getY()) &&
            x >= lesserBoundaryCorner.getX() &&
            x < greaterBoundaryCorner.getX() + 1 &&
            z >= lesserBoundaryCorner.getZ() &&
            z < greaterBoundaryCorner.getZ() + 1;
    }

    if (!inClaim) {
        return false;
    }

    return true;
}
 
Example #14
Source File: BlockEventHandler.java    From GriefDefender with MIT License 5 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onSignChanged(ChangeSignEvent event) {
    final User user = CauseContextHelper.getEventUser(event);
    if (user == null) {
        return;
    }

    if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(event.getTargetTile().getLocation().getExtent().getUniqueId())) {
        return;
    }

    GDTimings.SIGN_CHANGE_EVENT.startTimingIfSync();
    Location<World> location = event.getTargetTile().getLocation();
    // Prevent users exploiting signs
    GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAt(location);
    if (GDPermissionManager.getInstance().getFinalPermission(event, location, claim, Flags.INTERACT_BLOCK_SECONDARY, user, location.getBlock(), user, TrustTypes.ACCESSOR, true) == Tristate.FALSE) {
        if (user instanceof Player) {
            event.setCancelled(true);
            final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.PERMISSION_ACCESS,
                    ImmutableMap.of("player", claim.getOwnerName()));
            GriefDefenderPlugin.sendClaimDenyMessage(claim, (Player) user, message);
            return;
        }
    }

    GDTimings.SIGN_CHANGE_EVENT.stopTimingIfSync();
}
 
Example #15
Source File: ContainerManager.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public boolean canOpen(BlockSnapshot b, Player p) {
    if (!RedProtect.get().config.configRoot().private_cat.use || p.hasPermission("redprotect.bypass")) {
        return true;
    }

    List<Direction> dirs = Arrays.asList(Direction.EAST, Direction.NORTH, Direction.SOUTH, Direction.WEST);
    String blocktype = b.getState().getType().getName();
    Location<World> loc = b.getLocation().get();
    List<String> blocks = RedProtect.get().config.configRoot().private_cat.allowed_blocks;
    boolean deny = true;
    if (blocks.stream().anyMatch(blocktype::matches)) {
        for (Direction dir : dirs) {
            Location<World> loc1 = loc.getBlockRelative(dir);
            if (isSign(loc1.createSnapshot())) {
                deny = false;
                if (validateOpenBlock(loc1.createSnapshot(), p)) {
                    return true;
                }
            }

            if (blocks.stream().anyMatch(loc1.getBlockType().getName()::matches) && loc1.getBlockType().equals(b.getState().getType())) {
                for (Direction dir2 : dirs) {
                    Location<World> loc3 = loc1.getBlockRelative(dir2);
                    if (isSign(loc3.createSnapshot())) {
                        deny = false;
                        if (validateOpenBlock(loc3.createSnapshot(), p)) {
                            return true;
                        }
                    }
                }
            }
        }
    }
    return deny;
}
 
Example #16
Source File: KittyCannonExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
public void spawnEntity(Location<World> location, Vector3d velocity, CommandSource src)
{
	velocity = velocity.mul(5);
	Extent extent = location.getExtent();
	Entity kitten = extent.createEntity(EntityTypes.OCELOT, location.getPosition());
	kitten.offer(Keys.VELOCITY, velocity);
	extent.spawnEntity(kitten, Cause.of(NamedCause.source(SpawnCause.builder().type(SpawnTypes.CUSTOM).build())));
}
 
Example #17
Source File: ProtectionManagerImpl.java    From EagleFactions with MIT License 5 votes vote down vote up
@Override
public ProtectionResult canExplode(final Location<World> location)
{
    //Not claimable worlds should be always ignored by protection system.
    if(this.protectionConfig.getNotClaimableWorldNames().contains(location.getExtent().getName()))
        return ProtectionResult.ok();

    boolean shouldProtectWarZoneFromMobGrief = this.protectionConfig.shouldProtectWarZoneFromMobGrief();
    boolean shouldProtectClaimsFromMobGrief = this.protectionConfig.shouldProtectClaimFromMobGrief();

    //Check world
    if (this.protectionConfig.getSafeZoneWorldNames().contains(location.getExtent().getName()))
        return ProtectionResult.forbiddenSafeZone();

    if (this.protectionConfig.getWarZoneWorldNames().contains(location.getExtent().getName()))
    {
        if (!shouldProtectWarZoneFromMobGrief)
            return ProtectionResult.okWarZone();
        else return ProtectionResult.forbiddenWarZone();
    }

    Optional<Faction> optionalChunkFaction = this.factionLogic.getFactionByChunk(location.getExtent().getUniqueId(), location.getChunkPosition());
    if (!optionalChunkFaction.isPresent())
        return ProtectionResult.ok();

    Faction chunkFaction = optionalChunkFaction.get();
    if (chunkFaction.isSafeZone())
        return ProtectionResult.forbiddenSafeZone();
    else if (chunkFaction.isWarZone() && shouldProtectWarZoneFromMobGrief)
        return ProtectionResult.forbiddenWarZone();
    else
    {
        if (!shouldProtectClaimsFromMobGrief)
            return ProtectionResult.ok();
        else return ProtectionResult.forbidden();
    }
}
 
Example #18
Source File: BlockEventHandler.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Listener(order = Order.FIRST, beforeModifications = true)
public void onProjectileImpactBlock(CollideBlockEvent.Impact event) {
    if (!GPFlags.PROJECTILE_IMPACT_BLOCK || !(event.getSource() instanceof Entity)) {
        return;
    }

    final Entity source = (Entity) event.getSource();
    if (GriefPreventionPlugin.isSourceIdBlacklisted(ClaimFlag.PROJECTILE_IMPACT_BLOCK.toString(), source.getType().getId(), source.getWorld().getProperties())) {
        return;
    }

    final User user = CauseContextHelper.getEventUser(event);
    if (user == null) {
        return;
    }

    if (!GriefPreventionPlugin.instance.claimsEnabledForWorld(event.getImpactPoint().getExtent().getProperties())) {
        return;
    }

    GPTimings.PROJECTILE_IMPACT_BLOCK_EVENT.startTimingIfSync();
    Location<World> impactPoint = event.getImpactPoint();
    GPClaim targetClaim = null;
    GPPlayerData playerData = null;
    if (user instanceof Player) {
        playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(event.getTargetLocation().getExtent(), user.getUniqueId());
        targetClaim = this.dataStore.getClaimAtPlayer(playerData, impactPoint);
    } else {
        targetClaim = this.dataStore.getClaimAt(impactPoint);
    }

    Tristate result = GPPermissionHandler.getClaimPermission(event, impactPoint, targetClaim, GPPermissions.PROJECTILE_IMPACT_BLOCK, source, event.getTargetBlock(), user, TrustType.ACCESSOR, true);
    if (result == Tristate.FALSE) {
        event.setCancelled(true);
        GPTimings.PROJECTILE_IMPACT_BLOCK_EVENT.stopTimingIfSync();
        return;
    }

    GPTimings.PROJECTILE_IMPACT_BLOCK_EVENT.stopTimingIfSync();
}
 
Example #19
Source File: EntityDamageListener.java    From EagleFactions with MIT License 5 votes vote down vote up
private boolean isSafeZone(final Location<World> location)
{
    final Set<String> safeZoneWorlds = this.protectionConfig.getSafeZoneWorldNames();
    if (safeZoneWorlds.contains(location.getExtent().getName()))
        return true;

    final Optional<Faction> faction = super.getPlugin().getFactionLogic().getFactionByChunk(location.getExtent().getUniqueId(), location.getChunkPosition());
    return faction.map(Faction::isSafeZone).orElse(false);
}
 
Example #20
Source File: PlayerListener.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
@Listener(order = Order.FIRST)
public void onInteractLeft(InteractBlockEvent.Primary event, @First Player p) {
    BlockSnapshot b = event.getTargetBlock();
    Location<World> l;

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

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

    ItemType itemInHand = RedProtect.get().getVersionHelper().getItemInHand(p);

    String claimmode = RedProtect.get().config.getWorldClaimType(p.getWorld().getName());
    if (event instanceof InteractBlockEvent.Primary.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().firstLocationSelections.put(p, l);
        p.sendMessage(RedProtect.get().getUtil().toText(RedProtect.get().lang.get("playerlistener.wand1") + 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);
    }
}
 
Example #21
Source File: MobSpawnExecutor.java    From EssentialCmds with MIT License 5 votes vote down vote up
public void spawnEntity(Location<World> location, Player player, EntityType type, int amount)
{
	for (int i = 1; i <= amount; i++)
	{
		Entity entity = location.getExtent().createEntity(type, location.getPosition());
		location.getExtent().spawnEntity(entity, Cause.of(NamedCause.source(SpawnCause.builder().type(SpawnTypes.CUSTOM).build())));
	}
}
 
Example #22
Source File: GPClaim.java    From GriefPrevention with MIT License 5 votes vote down vote up
public boolean contains(Location<World> location, boolean excludeChildren, GPPlayerData playerData, boolean useBorderBlockRadius) {
    int x = location.getBlockX();
    int y = location.getBlockY();
    int z = location.getBlockZ();

    int borderBlockRadius = 0;
    if (useBorderBlockRadius && (playerData != null && !playerData.ignoreBorderCheck)) {
        final int borderRadiusConfig = GriefPreventionPlugin.getActiveConfig(location.getExtent().getUniqueId()).getConfig().claim.borderBlockRadius;
        if (borderRadiusConfig > 0 && !this.isUserTrusted((User) playerData.getPlayerSubject(), TrustType.BUILDER)) {
            borderBlockRadius = borderRadiusConfig;
        }
    }
    // main check
    boolean inClaim = (
            y >= (this.lesserBoundaryCorner.getBlockY() - borderBlockRadius)) &&
            y < (this.greaterBoundaryCorner.getBlockY() + 1 + borderBlockRadius) &&
            x >= (this.lesserBoundaryCorner.getBlockX() - borderBlockRadius) &&
            x < (this.greaterBoundaryCorner.getBlockX() + 1 + borderBlockRadius) &&
            z >= (this.lesserBoundaryCorner.getBlockZ() - borderBlockRadius) &&
            z < (this.greaterBoundaryCorner.getBlockZ() + 1 + borderBlockRadius);

    if (!inClaim) {
        return false;
    }

    // additional check for children claims, you're only in a child claim when you're also in its parent claim
    // NOTE: if a player creates children then resizes the parent claim,
    // it's possible that a child can reach outside of its parent's boundaries. so this check is important!
    if (!excludeChildren && this.parent != null && (this.getData() == null || (this.getData() != null && this.getData().doesInheritParent()))) {
        return this.parent.contains(location, false);
    }

    return true;
}
 
Example #23
Source File: Visualization.java    From GriefPrevention with MIT License 5 votes vote down vote up
public void addCorners(World world, int y, BlockType accentMaterial) {
    BlockSnapshot corner1 =
            snapshotBuilder.from(new Location<World>(world, this.smallx, y, this.bigz)).blockState(accentMaterial.getDefaultState()).build();
    newElements.add(new Transaction<BlockSnapshot>(corner1.getLocation().get().createSnapshot(), corner1));
    BlockSnapshot corner2 =
            snapshotBuilder.from(new Location<World>(world, this.bigx, y, this.bigz)).blockState(accentMaterial.getDefaultState()).build();
    newElements.add(new Transaction<BlockSnapshot>(corner2.getLocation().get().createSnapshot(), corner2));
    BlockSnapshot corner3 =
            snapshotBuilder.from(new Location<World>(world, this.bigx, y, this.smallz)).blockState(accentMaterial.getDefaultState()).build();
    newElements.add(new Transaction<BlockSnapshot>(corner3.getLocation().get().createSnapshot(), corner3));
    BlockSnapshot corner4 =
            snapshotBuilder.from(new Location<World>(world, this.smallx, y, this.smallz)).blockState(accentMaterial.getDefaultState()).build();
    newElements.add(new Transaction<BlockSnapshot>(corner4.getLocation().get().createSnapshot(), corner4));
}
 
Example #24
Source File: Pos1Command.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public CommandSpec register() {
    return CommandSpec.builder()
            .description(Text.of("Command to set selected points."))
            .permission("redprotect.command.pos1")
            .executor((src, args) -> {
                if (!(src instanceof Player)) {
                    HandleHelpPage(src, 1);
                } else {
                    Player player = (Player) src;

                    String claimmode = RedProtect.get().config.getWorldClaimType(player.getWorld().getName());
                    if (!claimmode.equalsIgnoreCase("WAND") && !claimmode.equalsIgnoreCase("BOTH") && !RedProtect.get().ph.hasCommandPerm(player, "redefine")) {
                        return CommandResult.success();
                    }

                    Location<World> pl = player.getLocation();
                    RedProtect.get().firstLocationSelections.put(player, pl);
                    player.sendMessage(RedProtect.get().getUtil().toText(RedProtect.get().lang.get("playerlistener.wand1") + RedProtect.get().lang.get("general.color") + " (&6" + pl.getBlockX() + RedProtect.get().lang.get("general.color") + ", &6" + pl.getBlockY() + RedProtect.get().lang.get("general.color") + ", &6" + pl.getBlockZ() + RedProtect.get().lang.get("general.color") + ")."));

                    //show preview border
                    if (RedProtect.get().firstLocationSelections.containsKey(player) && RedProtect.get().secondLocationSelections.containsKey(player)) {
                        Location<World> loc1 = RedProtect.get().firstLocationSelections.get(player);
                        Location<World> loc2 = RedProtect.get().secondLocationSelections.get(player);
                        if (RedProtect.get().hooks.WE && RedProtect.get().config.configRoot().hooks.useWECUI) {
                            WEHook.setSelectionRP(player, loc1, loc2);
                        }

                        if (loc1.getPosition().distanceSquared(loc2.getPosition()) > RedProtect.get().config.configRoot().region_settings.max_scan && !player.hasPermission("redprotect.bypass.define-max-distance")) {
                            double dist = loc1.getPosition().distanceSquared(loc2.getPosition());
                            RedProtect.get().lang.sendMessage(player, String.format(RedProtect.get().lang.get("regionbuilder.selection.maxdefine"), RedProtect.get().config.configRoot().region_settings.max_scan, (int) dist));
                        } else {
                            RedProtect.get().getUtil().addBorder(player, loc1, loc2);
                        }
                    }
                }
                return CommandResult.success();
            }).build();
}
 
Example #25
Source File: InventoryListener.java    From Prism with MIT License 5 votes vote down vote up
/**
 * Saves event records when a player closes or opens an Inventory.
 *
 * @param event  InteractInventoryEvent
 * @param player Player
 */
@Listener(order = Order.POST)
public void onInteractInventory(InteractInventoryEvent event, @Root Player player) {
    if (!(event.getTargetInventory() instanceof CarriedInventory)
            || (!Prism.getInstance().getConfig().getEventCategory().isInventoryClose() && !Prism.getInstance().getConfig().getEventCategory().isInventoryOpen())) {
        return;
    }

    CarriedInventory<? extends Carrier> carriedInventory = (CarriedInventory<? extends Carrier>) event.getTargetInventory();
    if (carriedInventory.getCarrier().filter(Player.class::isInstance).isPresent()) {
        return;
    }

    // Get the location of the inventory otherwise fallback on the players location
    Location<World> location = carriedInventory.getCarrier()
            .filter(Locatable.class::isInstance)
            .map(Locatable.class::cast)
            .map(Locatable::getLocation)
            .orElse(player.getLocation());

    // Get the title of the inventory otherwise fallback on the class name
    String title = carriedInventory.getProperty(InventoryTitle.class, InventoryTitle.PROPERTY_NAME)
            .map(InventoryTitle::getValue)
            .map(Text::toPlain)
            .orElse(carriedInventory.getClass().getSimpleName());

    PrismRecord.EventBuilder eventBuilder = PrismRecord.create()
            .source(event.getCause())
            .container(title)
            .location(location);

    if (event instanceof InteractInventoryEvent.Close && Prism.getInstance().getConfig().getEventCategory().isInventoryClose()) {
        eventBuilder.event(PrismEvents.INVENTORY_CLOSE).buildAndSave();
    } else if (event instanceof InteractInventoryEvent.Open && Prism.getInstance().getConfig().getEventCategory().isInventoryOpen()) {
        eventBuilder.event(PrismEvents.INVENTORY_OPEN).buildAndSave();
    }
}
 
Example #26
Source File: SignUtil.java    From GriefDefender with MIT License 5 votes vote down vote up
public static Sign getSign(World world, Vector3i pos) {
    if (pos == null) {
        return null;
    }

    // Don't load chunks to update signs
    if (BlockUtil.getInstance().getLoadedChunkWithoutMarkingActive(world, pos.getX() >> 4, pos.getZ() >> 4) == null) {
        return null;
    }

    return getSign(new Location<>(world, pos));
}
 
Example #27
Source File: HomeCommand.java    From EagleFactions with MIT License 5 votes vote down vote up
private void teleport(final Player player, final FactionHome factionHome)
{
    final Optional<World> optionalWorld = Sponge.getServer().getWorld(factionHome.getWorldUUID());
    if (!optionalWorld.isPresent())
    {
        player.sendMessage(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, Messages.MISSING_OR_CORRUPTED_HOME));
        return;
    }
    player.setLocationSafely(new Location<>(optionalWorld.get(), factionHome.getBlockPosition()));
    player.sendMessage(ChatTypes.ACTION_BAR, Text.of(TextColors.GREEN, Messages.YOU_WERE_TELEPORTED_TO_FACTIONS_HOME));
    startHomeCooldown(player.getUniqueId());
}
 
Example #28
Source File: PlayerEventHandler.java    From GriefPrevention with MIT License 5 votes vote down vote up
private GPClaim findNearbyClaim(Player player) {
    int maxDistance = GriefPreventionPlugin.instance.maxInspectionDistance;
    BlockRay<World> blockRay = BlockRay.from(player).distanceLimit(maxDistance).build();
    GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    GPClaim claim = null;
    int count = 0;
    while (blockRay.hasNext()) {
        BlockRayHit<World> blockRayHit = blockRay.next();
        Location<World> location = blockRayHit.getLocation();
        claim = this.dataStore.getClaimAt(location);
        if (claim != null && !claim.isWilderness() && (playerData.visualBlocks == null || (claim.id != playerData.visualClaimId))) {
            playerData.lastValidInspectLocation = location;
            return claim;
        }

        BlockType blockType = location.getBlockType();
        if (blockType != BlockTypes.AIR && blockType != BlockTypes.TALLGRASS) {
            break;
        }
        count++;
    }

    if (count == maxDistance) {
        GriefPreventionPlugin.sendMessage(player, GriefPreventionPlugin.instance.messageData.claimTooFar.toText());
    } else if (claim != null && claim.isWilderness()){
        GriefPreventionPlugin.sendMessage(player, GriefPreventionPlugin.instance.messageData.blockNotClaimed.toText());
    }

    return claim;
}
 
Example #29
Source File: GPClaimManager.java    From GriefPrevention with MIT License 5 votes vote down vote up
public void createWildernessClaim(WorldProperties worldProperties) {
    World world = Sponge.getServer().getWorld(worldProperties.getUniqueId()).get();
    Location<World> lesserCorner = new Location<World>(world, -30000000, 0, -30000000);
    Location<World> greaterCorner = new Location<World>(world, 29999999, 255, 29999999);
    // Use world UUID as wilderness claim ID
    GPClaim wilderness = new GPClaim(lesserCorner, greaterCorner, worldProperties.getUniqueId(), ClaimType.WILDERNESS, null, false);
    wilderness.setOwnerUniqueId(GriefPreventionPlugin.WORLD_USER_UUID);
    wilderness.initializeClaimData(null);
    DATASTORE.writeClaimToStorage(wilderness);
    this.theWildernessClaim = wilderness;
    this.claimUniqueIdMap.put(wilderness.getUniqueId(), wilderness);
}
 
Example #30
Source File: NucleusServlet.java    From Web-API with MIT License 5 votes vote down vote up
@POST
@Path("/jail")
@Permission({ "jail", "create" })
@ApiOperation(value = "Create a jail", response = CachedNamedLocation.class, notes = "Creates a new jail.")
public Response createJail(CachedNamedLocation req)
        throws BadRequestException, URISyntaxException {

    if (req == null) {
        throw new BadRequestException("Request body is required");
    }

    Optional<NucleusJailService> optSrv = NucleusAPI.getJailService();
    if (!optSrv.isPresent()) {
        throw new InternalServerErrorException("Nuclues jail service not available");
    }

    NucleusJailService srv = optSrv.get();

    if (req.getLocation() == null) {
        throw new BadRequestException("A location is required");
    }

    CachedNamedLocation jail = WebAPI.runOnMain(() -> {
        Optional<Location> optLive = req.getLocation().getLive();
        if (!optLive.isPresent()) {
            throw new InternalServerErrorException("Could not get live location");
        }
        Vector3d rot = req.getRotation() == null ? Vector3d.FORWARD : req.getRotation();
        srv.setJail(req.getName(), optLive.get(), rot);
        Optional<NamedLocation> optJail = srv.getJail(req.getName());
        if (!optJail.isPresent()) {
            throw new InternalServerErrorException("Could not get jail after creating it");
        }
        return new CachedNamedLocation(optJail.get());
    });

    return Response.created(new URI(null, null, jail.getLink(), null)).entity(jail).build();
}