com.flowpowered.math.vector.Vector3d Java Examples

The following examples show how to use com.flowpowered.math.vector.Vector3d. 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: 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 #2
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 #3
Source File: MarkerImpl.java    From BlueMap with MIT License 6 votes vote down vote up
public MarkerImpl(String id, BlueMapMap map, Vector3d position) {
	Preconditions.checkNotNull(id);
	Preconditions.checkNotNull(map);
	Preconditions.checkNotNull(position);
	
	this.id = id;
	this.map = map;
	this.postition = position;
	this.minDistance = 0;
	this.maxDistance = 100000;
	this.label = id;
	this.link = null;
	this.newTab = true;
	
	this.hasUnsavedChanges = true;
}
 
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: Vector3dParamConverter.java    From Web-API with MIT License 6 votes vote down vote up
@Override
public Vector3d fromString(String value) {
    // If we didn't specify a vector3d don't try to parse one
    if (value == null)
        return null;

    String[] splits = value.split("\\|");
    if (splits.length < 3) {
        throw new BadRequestException("Invalid Vector3d");
    }

    try {
        double x = Double.parseDouble(splits[0]);
        double y = Double.parseDouble(splits[1]);
        double z = Double.parseDouble(splits[2]);
        return new Vector3d(x, y, z);
    } catch (NumberFormatException e) {
        throw new BadRequestException(e.getMessage());
    }
}
 
Example #6
Source File: TransformSerializer.java    From UltimateCore with MIT License 6 votes vote down vote up
@Override
public Transform<World> deserialize(TypeToken<?> type, ConfigurationNode node) throws ObjectMappingException {
    World world = Sponge.getServer().getWorld(node.getNode("world").getValue(TypeToken.of(UUID.class))).orElse(null);
    if (world == null) throw new ObjectMappingException("World could not be found.");
    double locx = node.getNode("locx").getDouble();
    double locy = node.getNode("locy").getDouble();
    double locz = node.getNode("locz").getDouble();
    Location<World> loc = world.getLocation(locx, locy, locz);
    double rotx = node.getNode("rotx").getDouble();
    double roty = node.getNode("roty").getDouble();
    double rotz = node.getNode("rotz").getDouble();
    Vector3d rot = new Vector3d(rotx, roty, rotz);
    double scax = node.getNode("scax").getDouble();
    double scay = node.getNode("scay").getDouble();
    double scaz = node.getNode("scaz").getDouble();
    Vector3d sca = new Vector3d(scax, scay, scaz);
    return new Transform<>(loc, rot, sca);
}
 
Example #7
Source File: Utils.java    From EssentialCmds with MIT License 5 votes vote down vote up
public static Transform<World> getFirstSpawn()
{
	String worldName = Configs.getConfig(spawnConfig).getNode("first-spawn", "world").getString();
	World world = Sponge.getServer().getWorld(worldName).orElse(null);
	double x = Configs.getConfig(spawnConfig).getNode("first-spawn", "X").getDouble();
	double y = Configs.getConfig(spawnConfig).getNode("first-spawn", "Y").getDouble();
	double z = Configs.getConfig(spawnConfig).getNode("first-spawn", "Z").getDouble();

	if (Configs.getConfig(spawnConfig).getNode("spawn", "transform", "pitch").getValue() == null)
	{
		if (world != null)
			return new Transform<>(new Location<>(world, x, y, z));
		else
			return null;
	}
	else
	{
		double pitch = Configs.getConfig(spawnConfig).getNode("spawn", "transform", "pitch").getDouble();
		double yaw = Configs.getConfig(spawnConfig).getNode("spawn", "transform", "yaw").getDouble();
		double roll = Configs.getConfig(spawnConfig).getNode("spawn", "transform", "roll").getDouble();

		if (world != null)
			return new Transform<>(world, new Vector3d(x, y, z), new Vector3d(pitch, yaw, roll));
		else
			return null;
	}
}
 
Example #8
Source File: MarkerSetImpl.java    From BlueMap with MIT License 5 votes vote down vote up
@Override
public synchronized POIMarkerImpl createPOIMarker(String id, BlueMapMap map, Vector3d position) {
	removeMarker(id);
	
	POIMarkerImpl marker = new POIMarkerImpl(id, map, position);
	markers.put(id, marker);
	
	return marker;
}
 
Example #9
Source File: MathUtils.java    From BlueMap with MIT License 5 votes vote down vote up
/**
 * Calculates the surface-normal of a plane spanned between three vectors.
 * @param p1 The first vector
 * @param p2 The second vector
 * @param p3 The third vector
 * @return The calculated normal
 */
public static Vector3d getSurfaceNormal(Vector3d p1, Vector3d p2, Vector3d p3){
	Vector3d u = p2.sub(p1);
	Vector3d v = p3.sub(p1);
	
	double nX = u.getY() * v.getZ() - u.getZ() * v.getY();
	double nY = u.getZ() * v.getX() - u.getX() * v.getZ();
	double nZ = u.getX() * v.getY() - u.getY() * v.getX();
	
	return new Vector3d(nX, nY, nZ);
}
 
Example #10
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 #11
Source File: Vector3dSerializer.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public Vector3d deserialize(TypeToken<?> type, ConfigurationNode node) throws ObjectMappingException {
    double x = node.getNode("x").getDouble();
    double y = node.getNode("y").getDouble();
    double z = node.getNode("z").getDouble();
    return new Vector3d(x, y, z);
}
 
Example #12
Source File: MarkerSetImpl.java    From BlueMap with MIT License 5 votes vote down vote up
@Override
public synchronized ShapeMarkerImpl createShapeMarker(String id, BlueMapMap map, Vector3d position, Shape shape, float height) {
	removeMarker(id);
	
	ShapeMarkerImpl marker = new ShapeMarkerImpl(id, map, position, shape, height);
	markers.put(id, marker);
	
	return marker;
}
 
Example #13
Source File: POIMarkerImpl.java    From BlueMap with MIT License 5 votes vote down vote up
public POIMarkerImpl(String id, BlueMapMap map, Vector3d position) {
	super(id, map, position);
	
	this.iconAddress = "assets/poi.svg";
	this.anchor = new Vector2i(25, 45);
	
	this.hasUnsavedChanges = true;
}
 
Example #14
Source File: BlockRay.java    From GriefDefender with MIT License 5 votes vote down vote up
/**
 * Resets the iterator; it will iterate from the starting location again.
 */
public final void reset() {
    // Start at the position
    this.xCurrent = this.position.getX();
    this.yCurrent = this.position.getY();
    this.zCurrent = this.position.getZ();

    // First planes are for the block that contains the coordinates
    this.xPlaneNext = GenericMath.floor(this.xCurrent);
    // noinspection SuspiciousNameCombination
    this.yPlaneNext = GenericMath.floor(this.yCurrent);
    this.zPlaneNext = GenericMath.floor(this.zCurrent);

    // Correct the next planes for the direction when inside the block
    if (this.xCurrent - this.xPlaneNext != 0 && this.direction.getX() >= 0) {
        this.xPlaneNext++;
    }
    if (this.yCurrent - this.yPlaneNext != 0 && this.direction.getY() >= 0) {
        this.yPlaneNext++;
    }
    if (this.zCurrent - this.zPlaneNext != 0 && this.direction.getZ() >= 0) {
        this.zPlaneNext++;
    }

    // Compute the first intersection solutions for each plane
    this.xPlaneT = (this.xPlaneNext - this.position.getX()) / this.direction.getX();
    this.yPlaneT = (this.yPlaneNext - this.position.getY()) / this.direction.getY();
    this.zPlaneT = (this.zPlaneNext - this.position.getZ()) / this.direction.getZ();

    // We start in the block, no plane has been entered yet
    this.normalCurrent = Vector3d.ZERO;

    // Reset the block
    this.ahead = false;
    this.hit = null;
}
 
Example #15
Source File: SpongePlayer.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Location getLocation() {
    org.spongepowered.api.world.Location<World> entityLoc = this.player.getLocation();
    Vector3d entityRot = this.player.getRotation();

    return SpongeWorldEdit.inst().getAdapter().adapt(entityLoc, entityRot);
}
 
Example #16
Source File: BlockRay.java    From GriefDefender with MIT License 5 votes vote down vote up
/**
 * Sets the direction and ending location. This or setting the direction
 * is required and can only be done once.
 *
 * @param end The ending location
 * @return This for chained calls
 */
public BlockRayBuilder to(Vector3d end) {
    checkState(this.direction == null, "Direction has already been set");
    checkNotNull(end, "end");
    checkArgument(!this.position.equals(end), "Start and end cannot be equal");
    this.direction = end.sub(this.position).normalize();
    return stopFilter(new TargetBlockFilter(end));
}
 
Example #17
Source File: SpongeCommandSource.java    From BlueMap with MIT License 5 votes vote down vote up
@Override
public Optional<Vector3d> getPosition() {
	if (delegate instanceof Locatable) {
		return Optional.of(((Locatable) delegate).getLocation().getPosition());
	}
	
	return Optional.empty();
}
 
Example #18
Source File: Utils.java    From EssentialCmds with MIT License 5 votes vote down vote up
public static Transform<World> getSpawn()
{
	String worldName = Configs.getConfig(spawnConfig).getNode("spawn", "world").getString();
	World world = Sponge.getServer().getWorld(worldName).orElse(null);
	double x = Configs.getConfig(spawnConfig).getNode("spawn", "X").getDouble();
	double y = Configs.getConfig(spawnConfig).getNode("spawn", "Y").getDouble();
	double z = Configs.getConfig(spawnConfig).getNode("spawn", "Z").getDouble();

	if (Configs.getConfig(spawnConfig).getNode("spawn", "transform", "pitch").getValue() == null)
	{
		if (world != null)
			return new Transform<>(new Location<>(world, x, y, z));
		else
			return null;
	}
	else
	{
		double pitch = Configs.getConfig(spawnConfig).getNode("spawn", "transform", "pitch").getDouble();
		double yaw = Configs.getConfig(spawnConfig).getNode("spawn", "transform", "yaw").getDouble();
		double roll = Configs.getConfig(spawnConfig).getNode("spawn", "transform", "roll").getDouble();

		if (world != null)
			return new Transform<>(world, new Vector3d(x, y, z), new Vector3d(pitch, yaw, roll));
		else
			return null;
	}
}
 
Example #19
Source File: BloodEffect.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public BloodEffect deserialize(TypeToken<?> type, ConfigurationNode node) throws ObjectMappingException {
    Vector3d coffset = node.getNode("center-offset").getValue(TypeToken.of(Vector3d.class));
    Vector3d poffset = node.getNode("particle-offset").getValue(TypeToken.of(Vector3d.class));
    BlockState state = Serializers.BLOCKSTATE.deserialize(TypeToken.of(BlockState.class), node.getNode("blockstate"));
    int count = node.getNode("count").getInt();
    boolean enabled = node.getNode("enabled").getBoolean();
    return new BloodEffect(enabled, state, coffset, poffset, count);
}
 
Example #20
Source File: VectorSerializers.java    From helper with MIT License 5 votes vote down vote up
public static Vector3d deserialize3d(JsonElement element) {
    return new Vector3d(
            element.getAsJsonObject().get("x").getAsDouble(),
            element.getAsJsonObject().get("y").getAsDouble(),
            element.getAsJsonObject().get("z").getAsDouble()
    );
}
 
Example #21
Source File: ParticlesUtil.java    From EagleFactions with MIT License 5 votes vote down vote up
public static void spawnAddAccessParticles(final Claim claim)
{
	final Optional<World> optionalWorld = Sponge.getServer().getWorld(claim.getWorldUUID());
	if(!optionalWorld.isPresent())
		return;

	final World world = optionalWorld.get();
	final Vector3d position = getChunkCenter(world, claim.getChunkPosition());
	world.spawnParticles(ParticleEffect.builder().type(ParticleTypes.FIREWORKS_SPARK).option(ParticleOptions.VELOCITY, new Vector3d(0, 0.15, 0)).quantity(400).offset(new Vector3d(8, 2, 8)).build(), position);
	world.playSound(SoundTypes.ENTITY_EXPERIENCE_ORB_PICKUP, position, 5, 10);
}
 
Example #22
Source File: Utils.java    From EssentialCmds with MIT License 5 votes vote down vote up
public static Transform<World> getHome(UUID uuid, String homeName)
{
	CommentedConfigurationNode homeNode = Configs.getConfig(homesConfig).getNode("home", "users", uuid.toString(), getConfigHomeName(uuid, homeName));
	String worldName = homeNode.getNode("world").getString();
	World world = Sponge.getServer().getWorld(worldName).orElse(null);
	double x = homeNode.getNode("X").getDouble();
	double y = homeNode.getNode("Y").getDouble();
	double z = homeNode.getNode("Z").getDouble();

	if (homeNode.getNode("transform", "pitch").getValue() == null)
	{
		if (world != null)
			return new Transform<>(new Location<>(world, x, y, z));
		else
			return null;
	}
	else
	{
		double pitch = homeNode.getNode("transform", "pitch").getDouble();
		double yaw = homeNode.getNode("transform", "yaw").getDouble();
		double roll = homeNode.getNode("transform", "roll").getDouble();

		if (world != null)
			return new Transform<>(world, new Vector3d(x, y, z), new Vector3d(pitch, yaw, roll));
		else
			return null;
	}
}
 
Example #23
Source File: ParticlesUtil.java    From EagleFactions with MIT License 5 votes vote down vote up
public static void spawnUnclaimParticles(final Claim claim)
{
	final Optional<World> optionalWorld = Sponge.getServer().getWorld(claim.getWorldUUID());
	if(!optionalWorld.isPresent())
		return;

	final World world = optionalWorld.get();
	final Vector3d position = getChunkCenter(world, claim.getChunkPosition());
	world.spawnParticles(ParticleEffect.builder().type(ParticleTypes.CLOUD).option(ParticleOptions.VELOCITY, new Vector3d(0, 0.15, 0)).quantity(800).offset(new Vector3d(8, 1, 8)).build(), position);
	world.playSound(SoundTypes.ENTITY_SHULKER_SHOOT, position, 5, -20);
}
 
Example #24
Source File: ParticlesUtil.java    From EagleFactions with MIT License 5 votes vote down vote up
public static void spawnDestroyClaimParticles(final Claim claim)
{
	final Optional<World> optionalWorld = Sponge.getServer().getWorld(claim.getWorldUUID());
	if(!optionalWorld.isPresent())
		return;

	final World world = optionalWorld.get();
	final Vector3d position = getChunkCenter(world, claim.getChunkPosition());
	world.spawnParticles(ParticleEffect.builder().type(ParticleTypes.FLAME).option(ParticleOptions.VELOCITY, new Vector3d(0, 0.15, 0)).quantity(800).offset(new Vector3d(8, 1, 8)).build(), position);
	world.playSound(SoundTypes.ENTITY_BLAZE_SHOOT, position, 5, -20);
}
 
Example #25
Source File: ParticlesUtil.java    From EagleFactions with MIT License 5 votes vote down vote up
public static Vector3d getChunkCenter(final World world, final Vector3i chunkPosition)
{
	final double x = (chunkPosition.getX() << 4) + 8;
	final double z = (chunkPosition.getZ() << 4) + 8;
	final double y = world.getHighestYAt((int)x, (int)z);
	return new Vector3d(x, y, z);
}
 
Example #26
Source File: SpongePlayer.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setPosition(Vector pos, float pitch, float yaw) {
    org.spongepowered.api.world.Location<World> loc = new org.spongepowered.api.world.Location<>(
            this.player.getWorld(), pos.getX(), pos.getY(), pos.getZ()
    );

    this.player.setLocationAndRotation(loc, new Vector3d(pitch, yaw, 0));
}
 
Example #27
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();
}
 
Example #28
Source File: RandomTeleportCommand.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    checkIfPlayer(src);
    Player p = (Player) src;
    Vector3d pos = p.getLocation().getPosition();

    TeleportHelper tph = Sponge.getGame().getTeleportHelper();
    int tries = 0;
    while (tries < this.maxTries) {
        tries++;

        //Try to find suitable location
        Integer x = pos.getFloorX() + RandomUtil.nextInt(-this.maxDistance, this.maxDistance);
        Integer z = pos.getFloorZ() + RandomUtil.nextInt(-this.maxDistance, this.maxDistance);
        Integer y = LocationUtil.getHighestY(p.getWorld(), x, z).orElse(null);
        if (y == null) continue;
        Location<World> loc = tph.getSafeLocation(new Location<>(p.getWorld(), x, y, z)).orElse(null);
        if (loc == null) continue;
        if (this.bannedBlocks.contains(loc.getBlockType()) || this.bannedBlocks.contains(loc.add(0, -1, 0).getBlockType())) continue;

        //Found suitable location
        Teleportation request = UltimateCore.get().getTeleportService().createTeleportation(p, Arrays.asList(p), new Transform<>(loc, p.getRotation(), p.getScale()), teleportRequest -> {
            //Complete
            Messages.send(p, "teleport.command.randomteleport.success");
        }, (teleportRequest, reason) -> {
        }, true, false);
        request.start();
        return CommandResult.success();
    }
    throw Messages.error(src, "teleport.command.randomteleport.fail");
}
 
Example #29
Source File: ParamConverterProvider.java    From Web-API with MIT License 5 votes vote down vote up
@Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
    if (CachedWorld.class.isAssignableFrom(rawType)) {
        return (ParamConverter<T>) new WorldParamConverter();
    } else if (CachedPlayer.class.isAssignableFrom(rawType)) {
        return (ParamConverter<T>) new PlayerParamConverter();
    } else if (Vector3d.class.isAssignableFrom(rawType)) {
        return (ParamConverter<T>) new Vector3dParamConverter();
    } else if (Vector3i.class.isAssignableFrom(rawType)) {
        return (ParamConverter<T>) new Vector3iParamConverter();
    }
    return null;
}
 
Example #30
Source File: SpongePlayer.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Location getLocation() {
    org.spongepowered.api.world.Location<World> entityLoc = this.player.getLocation();
    Vector3d entityRot = this.player.getRotation();

    return SpongeWorldEdit.inst().getAdapter().adapt(entityLoc, entityRot);
}