Search in sources :

Example 21 with ServerPlayer

use of org.spongepowered.api.entity.living.player.server.ServerPlayer in project SpongeCommon by SpongePowered.

the class PlayerListMixin method impl$onInitPlayer_getWorld.

@Redirect(method = "placeNewPlayer", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;getLevel(Lnet/minecraft/resources/ResourceKey;)Lnet/minecraft/server/level/ServerLevel;"))
private net.minecraft.server.level.ServerLevel impl$onInitPlayer_getWorld(final MinecraftServer minecraftServer, final ResourceKey<Level> dimension, final Connection networkManager, final net.minecraft.server.level.ServerPlayer mcPlayer) {
    @Nullable final net.minecraft.network.chat.Component kickReason = ((ConnectionBridge) networkManager).bridge$getKickReason();
    final Component disconnectMessage;
    if (kickReason != null) {
        disconnectMessage = SpongeAdventure.asAdventure(kickReason);
    } else {
        disconnectMessage = Component.text("You are not allowed to log in to this server.");
    }
    net.minecraft.server.level.ServerLevel mcWorld = minecraftServer.getLevel(dimension);
    if (mcWorld == null) {
        SpongeCommon.logger().warn("The player '{}' was located in a world that isn't loaded or doesn't exist. This is not safe so " + "the player will be moved to the spawn of the default world.", mcPlayer.getGameProfile().getName());
        mcWorld = minecraftServer.overworld();
        final BlockPos spawnPoint = mcWorld.getSharedSpawnPos();
        mcPlayer.setPos(spawnPoint.getX() + 0.5, spawnPoint.getY() + 0.5, spawnPoint.getZ() + 0.5);
    }
    mcPlayer.setLevel(mcWorld);
    final ServerPlayer player = (ServerPlayer) mcPlayer;
    final ServerLocation location = player.serverLocation();
    final Vector3d rotation = player.rotation();
    // player.connection() cannot be used here, because it's still be null at this point
    final ServerSideConnection connection = (ServerSideConnection) networkManager.getPacketListener();
    // The user is not yet in the player list, so we need to make special provision.
    final User user = SpongeUserView.createLoginEventUser(player);
    final Cause cause = Cause.of(EventContext.empty(), connection, user);
    final ServerSideConnectionEvent.Login event = SpongeEventFactory.createServerSideConnectionEventLogin(cause, disconnectMessage, disconnectMessage, location, location, rotation, rotation, connection, user);
    if (kickReason != null) {
        event.setCancelled(true);
    }
    if (SpongeCommon.post(event)) {
        this.impl$disconnectClient(networkManager, event.message(), player.profile());
        return null;
    }
    final ServerLocation toLocation = event.toLocation();
    final Vector3d toRotation = event.toRotation();
    mcPlayer.absMoveTo(toLocation.x(), toLocation.y(), toLocation.z(), (float) toRotation.y(), (float) toRotation.x());
    return (net.minecraft.server.level.ServerLevel) toLocation.world();
}
Also used : ServerLevel(net.minecraft.server.level.ServerLevel) User(org.spongepowered.api.entity.living.player.User) ServerLocation(org.spongepowered.api.world.server.ServerLocation) ServerSideConnection(org.spongepowered.api.network.ServerSideConnection) ServerSideConnectionEvent(org.spongepowered.api.event.network.ServerSideConnectionEvent) ServerLevel(net.minecraft.server.level.ServerLevel) Vector3d(org.spongepowered.math.vector.Vector3d) ConnectionBridge(org.spongepowered.common.bridge.network.ConnectionBridge) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Cause(org.spongepowered.api.event.Cause) BlockPos(net.minecraft.core.BlockPos) TranslatableComponent(net.minecraft.network.chat.TranslatableComponent) TextComponent(net.minecraft.network.chat.TextComponent) MutableComponent(net.minecraft.network.chat.MutableComponent) Component(net.kyori.adventure.text.Component) Nullable(javax.annotation.Nullable) Redirect(org.spongepowered.asm.mixin.injection.Redirect)

Example 22 with ServerPlayer

use of org.spongepowered.api.entity.living.player.server.ServerPlayer in project SpongeCommon by SpongePowered.

the class RecipeTest method onRecipeRegistry.

@Listener
@SuppressWarnings("unchecked")
public void onRecipeRegistry(final RegisterDataPackValueEvent<RecipeRegistration> event) {
    if (!this.enabled) {
        return;
    }
    // Standard recipes and ItemStack(with nbt) ingredient and results
    final Ingredient whiteRock = Ingredient.of(ItemTypes.POLISHED_DIORITE.get());
    final Ingredient whiteBed = Ingredient.of(ItemTypes.WHITE_BED.get());
    final ItemStack bedrock = ItemStack.of(ItemTypes.BEDROCK);
    final RecipeRegistration whiteBedrockRecipe = CraftingRecipe.shapedBuilder().rows().row(whiteRock, whiteRock, whiteRock).row(whiteRock, whiteBed, whiteRock).row(whiteRock, whiteRock, whiteRock).result(bedrock.copy()).key(ResourceKey.of(this.plugin, "white_bedrock")).build();
    event.register(whiteBedrockRecipe);
    final Ingredient redRock = Ingredient.of(ItemTypes.POLISHED_GRANITE);
    final Ingredient redBed = Ingredient.of(ItemTypes.RED_BED);
    final ItemStack redBedRock = bedrock.copy();
    redBedRock.offer(Keys.CUSTOM_NAME, Component.text("Bedrock", NamedTextColor.RED));
    final RecipeRegistration redBedrockRecipe = CraftingRecipe.shapedBuilder().rows().aisle("ggg", "gbg", "ggg").where('g', redRock).where('b', redBed).result(redBedRock).key(ResourceKey.of(this.plugin, "red_bedrock")).build();
    event.register(redBedrockRecipe);
    final ItemStack moreBedrock = bedrock.copy();
    moreBedrock.setQuantity(9);
    final RecipeRegistration moreBedrockRecipe = CraftingRecipe.shapedBuilder().rows().aisle("ggg", "gbg", "ggg").where('g', redRock).where('b', Ingredient.of(bedrock.copy())).result(moreBedrock).key(ResourceKey.of(this.plugin, "more_red_bedrock")).build();
    event.register(moreBedrockRecipe);
    final RecipeRegistration cheapGoldenAppleRecipe = CraftingRecipe.shapelessBuilder().addIngredients(ItemTypes.YELLOW_WOOL, ItemTypes.APPLE).result(ItemStack.of(ItemTypes.GOLDEN_APPLE)).key(ResourceKey.of(this.plugin, "cheap_golden_apple")).build();
    event.register(cheapGoldenAppleRecipe);
    final RecipeRegistration expensiveGoldenAppleRecipe = CraftingRecipe.shapelessBuilder().addIngredients(ItemTypes.YELLOW_WOOL, ItemTypes.ENCHANTED_GOLDEN_APPLE).result(ItemStack.of(ItemTypes.GOLDEN_APPLE)).key(ResourceKey.of(this.plugin, "expensive_golden_apple")).build();
    event.register(expensiveGoldenAppleRecipe);
    final Ingredient bedrocks = Ingredient.of(bedrock, redBedRock);
    final RecipeRegistration bedrocksToGranite = CraftingRecipe.shapelessBuilder().addIngredients(bedrocks, bedrocks).result(ItemStack.of(ItemTypes.GRANITE, 13)).key(ResourceKey.of(this.plugin, "bedrocks_to_granite")).build();
    event.register(bedrocksToGranite);
    final RecipeRegistration diamondToCoalRecipe = CookingRecipe.builder().type(RecipeTypes.SMELTING).ingredient(Ingredient.of(ItemTypes.DIAMOND)).result(ItemTypes.COAL).experience(0).key(ResourceKey.of(this.plugin, "diamond_to_coal")).build();
    event.register(diamondToCoalRecipe);
    final RecipeRegistration burnPaperAndSticksRecipe = CookingRecipe.builder().type(RecipeTypes.SMELTING).ingredient(Ingredient.of(ItemTypes.PAPER, ItemTypes.STICK)).result(ItemTypes.GUNPOWDER).experience(1).cookingTime(Ticks.of(1)).key(ResourceKey.of(this.plugin, "burn_paper_and_sticks")).build();
    event.register(burnPaperAndSticksRecipe);
    final RecipeRegistration charcoalToCoalRecipe = CookingRecipe.builder().type(RecipeTypes.BLASTING).ingredient(Ingredient.of(ItemTypes.CHARCOAL)).result(ItemTypes.COAL).key(ResourceKey.of(this.plugin, "charcoal_to_coal")).build();
    event.register(charcoalToCoalRecipe);
    final ItemStack redderBedrock = bedrock.copy();
    redderBedrock.offer(Keys.CUSTOM_NAME, Component.text("Bedrock", NamedTextColor.DARK_RED));
    final RecipeRegistration removeRedOnBedrock = CookingRecipe.builder().type(RecipeTypes.BLASTING).ingredient(Ingredient.of(redBedRock)).result(redderBedrock).cookingTime(Ticks.of(20)).experience(100).key(ResourceKey.of(this.plugin, "redder_bedrock")).build();
    event.register(removeRedOnBedrock);
    final RecipeRegistration overcookedPorkchopRecipe = CookingRecipe.builder().type(RecipeTypes.SMOKING).ingredient(Ingredient.of(ItemTypes.COOKED_PORKCHOP)).result(ItemTypes.COAL).key(ResourceKey.of(this.plugin, "overcooked_porkchop")).build();
    event.register(overcookedPorkchopRecipe);
    final RecipeRegistration sticksToTorches = CookingRecipe.builder().type(RecipeTypes.CAMPFIRE_COOKING).ingredient(Ingredient.of(ItemTypes.STICK)).result(ItemTypes.TORCH).cookingTime(Ticks.of(20)).key(ResourceKey.of(this.plugin, "stick_to_torch")).build();
    event.register(sticksToTorches);
    final RecipeRegistration stonecutter1 = StoneCutterRecipe.builder().ingredient(ItemTypes.BEDROCK).result(ItemStack.of(ItemTypes.BLACK_CONCRETE, 64)).key(ResourceKey.of(this.plugin, "cut_bedrock_to_concrete")).build();
    final RecipeRegistration stonecutter2 = StoneCutterRecipe.builder().ingredient(ItemTypes.BEDROCK).result(ItemStack.of(ItemTypes.BLACK_GLAZED_TERRACOTTA, 64)).key(ResourceKey.of(this.plugin, "cut_bedrock_to_terracotta")).build();
    final RecipeRegistration stonecutter3 = StoneCutterRecipe.builder().ingredient(ItemTypes.BEDROCK).result(ItemStack.of(ItemTypes.BLACK_WOOL, 64)).key(ResourceKey.of(this.plugin, "cut_bedrock_wool")).build();
    event.register(stonecutter1);
    event.register(stonecutter2);
    event.register(stonecutter3);
    // Predicate Ingredients
    // e.g. obsidian
    final Predicate<ItemStack> hardnessPredicate = stack -> stack.type().block().map(b -> b.defaultState().get(Keys.DESTROY_SPEED).orElse(0d) > 20).orElse(false);
    final Ingredient hardBlock = Ingredient.of(ResourceKey.of(this.plugin, "hardblock"), hardnessPredicate, ItemStack.of(ItemTypes.BEDROCK));
    final RecipeRegistration hardblockToWool = ShapelessCraftingRecipe.builder().addIngredients(hardBlock).result(ItemStack.of(ItemTypes.WHITE_WOOL)).key(ResourceKey.of(this.plugin, "hardblock_to_wool")).build();
    event.register(hardblockToWool);
    // Function Results
    final ItemStack villagerEgg = ItemStack.of(ItemTypes.VILLAGER_SPAWN_EGG);
    final RecipeRegistration villagerSpawnEggRecipe = ShapedCraftingRecipe.builder().aisle(" e ", "eve", " e ").where('v', Ingredient.of(ItemTypes.BOOK)).where('e', Ingredient.of(ItemTypes.EMERALD_BLOCK)).result(grid -> {
        final Optional<ServerPlayer> player = Sponge.server().causeStackManager().currentCause().first(ServerPlayer.class);
        final String name = player.map(ServerPlayer::name).orElse("Steve");
        villagerEgg.offer(Keys.CUSTOM_NAME, Component.text(name));
        return villagerEgg.copy();
    }, villagerEgg.copy()).key(ResourceKey.of(this.plugin, "villager_spawn_egg")).build();
    event.register(villagerSpawnEggRecipe);
    final ItemStack writtenBook = ItemStack.of(ItemTypes.WRITTEN_BOOK);
    writtenBook.offer(Keys.CUSTOM_NAME, Component.text("Biome Data"));
    writtenBook.offer(Keys.AUTHOR, Component.text("Herobrine"));
    final RecipeRegistration biomeDetectorRecipe = ShapedCraftingRecipe.builder().aisle("d", "b").where('d', Ingredient.of(ItemTypes.DAYLIGHT_DETECTOR)).where('b', Ingredient.of(ItemTypes.BOOK)).result(grid -> {
        final Optional<ServerPlayer> player = Sponge.server().causeStackManager().currentCause().first(ServerPlayer.class);
        final Optional<Biome> biome = player.map(p -> p.world().biome(p.blockPosition()));
        final String name = biome.map(present -> RegistryTypes.BIOME.keyFor(player.get().world(), present)).map(ResourceKey::toString).orElse("Unknown");
        final Integer biomeTemperature = biome.map(Biome::temperature).map(d -> (int) (d * 10)).orElse(0);
        final Integer biomeHumidity = biome.map(Biome::humidity).map(d -> (int) (d * 10)).orElse(0);
        final TextComponent temperature = Component.text("Temperature: ").append(Component.text(biomeTemperature));
        final TextComponent humidity = Component.text("Humidity: ").append(Component.text(biomeHumidity));
        writtenBook.offer(Keys.CUSTOM_NAME, Component.text("Biome Data: " + name));
        writtenBook.offer(Keys.PAGES, Arrays.asList(temperature, humidity));
        writtenBook.offer(Keys.AUTHOR, Component.text(player.map(ServerPlayer::name).orElse("Herobrine")));
        return writtenBook.copy();
    }, writtenBook.copy()).key(ResourceKey.of(this.plugin, "biome_detector")).build();
    event.register(biomeDetectorRecipe);
    final Ingredient blackOrWhite = Ingredient.of(ItemTypes.BLACK_WOOL, ItemTypes.WHITE_WOOL);
    final RecipeRegistration blackOrWhiteRecipe = ShapelessCraftingRecipe.builder().addIngredients(blackOrWhite, blackOrWhite, blackOrWhite).result(grid -> {
        final int blacks = grid.query(QueryTypes.ITEM_TYPE, ItemTypes.BLACK_WOOL).capacity();
        final int whites = grid.query(QueryTypes.ITEM_TYPE, ItemTypes.WHITE_WOOL).capacity();
        return blacks > whites ? ItemStack.of(ItemTypes.BLACK_WOOL, 3) : ItemStack.of(ItemTypes.WHITE_WOOL, 3);
    }, ItemStack.empty()).key(ResourceKey.of(this.plugin, "black_or_white")).build();
    event.register(blackOrWhiteRecipe);
    // Custom results dont work well in cooking recipes
    // final ItemStack anvil = ItemStack.of(ItemTypes.DAMAGED_ANVIL);
    // final RecipeRegistration<SmeltingRecipe> cookedAnvilRecipe = SmeltingRecipe.builder().type(RecipeTypes.BLASTING)
    // .ingredient(ItemTypes.IRON_BLOCK)
    // .result(inv -> {
    // return anvil.copy();
    // }, anvil.copy())
    // .key(ResourceKey.of(this.plugin, "cooked_anvil"))
    // .build();
    // event.register(cookedAnvilRecipe);
    final RecipeRegistration cutPlanksRecipe = StoneCutterRecipe.builder().ingredient(ItemTypes.OAK_PLANKS).result(input -> {
        if (new Random().nextBoolean()) {
            return ItemStack.of(ItemTypes.OAK_SLAB, 4);
        }
        return ItemStack.of(ItemTypes.OAK_SLAB, 3);
    }, ItemStack.of(ItemTypes.OAK_SLAB, 2)).key(ResourceKey.of(this.plugin, "cut_planks")).build();
    event.register(cutPlanksRecipe);
    final RecipeRegistration stripedBannerRecipe = SpecialCraftingRecipe.builder().matching((inv, world) -> {
        if (inv.capacity() != 9) {
            return false;
        }
        final ItemType stick = inv.asGrid().peek(2, 1).get().type();
        if (!stick.isAnyOf(ItemTypes.STICK)) {
            return false;
        }
        final ItemStack middleItem = inv.peekAt(1).get();
        final ItemType type00 = inv.asGrid().peek(0, 0).get().type();
        final ItemType type10 = inv.asGrid().peek(0, 1).get().type();
        final ItemType type20 = inv.asGrid().peek(0, 2).get().type();
        final ItemType type01 = inv.asGrid().peek(1, 0).get().type();
        final ItemType type11 = inv.asGrid().peek(1, 1).get().type();
        final ItemType type21 = inv.asGrid().peek(1, 2).get().type();
        if (type00 == type01 && type01 == type20 && type20 == type21 && type10 == type11) {
            if (type00.isAnyOf(ItemTypes.WHITE_WOOL)) {
                if (middleItem.get(Keys.DYE_COLOR).isPresent()) {
                    return true;
                }
            }
        }
        return false;
    }).result((inv -> {
        final DyeColor dyeColor = inv.peekAt(1).get().get(Keys.DYE_COLOR).get();
        final ItemStack banner = ItemStack.of(ItemTypes.WHITE_BANNER);
        final BannerPatternLayer pattern = BannerPatternLayer.of(BannerPatternShapes.STRIPE_CENTER, dyeColor);
        banner.offer(Keys.BANNER_PATTERN_LAYERS, Arrays.asList(pattern));
        return banner;
    })).key(ResourceKey.of(this.plugin, "special")).build();
    event.register(stripedBannerRecipe);
    final RecipeRegistration squeezeSpongeRecipe = ShapelessCraftingRecipe.builder().addIngredients(ItemTypes.WET_SPONGE, ItemTypes.BUCKET).remainingItems(inv -> inv.slots().stream().map(Slot::peek).map(item -> (item.type().isAnyOf(ItemTypes.WET_SPONGE) ? ItemTypes.SPONGE : ItemTypes.AIR).get()).map(ItemStack::of).collect(Collectors.toList())).result(ItemStack.of(ItemTypes.WATER_BUCKET)).key(ResourceKey.of(this.plugin, "squeeze_sponge_recipe")).build();
    event.register(squeezeSpongeRecipe);
    // Smithing recipes
    final RecipeRegistration ironToGoldIngot = SmithingRecipe.builder().base(ItemTypes.IRON_INGOT).addition(ItemTypes.NETHERITE_INGOT).result(ItemStack.of(ItemTypes.GOLD_INGOT)).key(ResourceKey.of(this.plugin, "iron_to_gold_ingot")).build();
    event.register(ironToGoldIngot);
    final ItemStack chainMail = ItemStack.of(ItemTypes.CHAINMAIL_CHESTPLATE);
    chainMail.offer(Keys.CUSTOM_NAME, Component.text("Heavy Chainmail", NamedTextColor.DARK_GRAY));
    chainMail.offer(Keys.LORE, Arrays.asList(Component.text("Smithing occured", NamedTextColor.DARK_GRAY)));
    final RecipeRegistration smithChainmail = SmithingRecipe.builder().base(ItemTypes.IRON_CHESTPLATE).addition(ItemTypes.FIRE_CHARGE).result(chainMail).key(ResourceKey.of(this.plugin, "smith_chainmail")).build();
    event.register(smithChainmail);
}
Also used : ShapelessCraftingRecipe(org.spongepowered.api.item.recipe.crafting.ShapelessCraftingRecipe) Arrays(java.util.Arrays) Inject(com.google.inject.Inject) ItemTypes(org.spongepowered.api.item.ItemTypes) Random(java.util.Random) Biome(org.spongepowered.api.world.biome.Biome) ShapedCraftingRecipe(org.spongepowered.api.item.recipe.crafting.ShapedCraftingRecipe) ItemStack(org.spongepowered.api.item.inventory.ItemStack) RegisterDataPackValueEvent(org.spongepowered.api.event.lifecycle.RegisterDataPackValueEvent) Ingredient(org.spongepowered.api.item.recipe.crafting.Ingredient) Component(net.kyori.adventure.text.Component) CookingRecipe(org.spongepowered.api.item.recipe.cooking.CookingRecipe) ResourceKey(org.spongepowered.api.ResourceKey) SmithingRecipe(org.spongepowered.api.item.recipe.smithing.SmithingRecipe) RecipeTypes(org.spongepowered.api.item.recipe.RecipeTypes) SpecialCraftingRecipe(org.spongepowered.api.item.recipe.crafting.SpecialCraftingRecipe) TextComponent(net.kyori.adventure.text.TextComponent) Plugin(org.spongepowered.plugin.builtin.jvm.Plugin) Ticks(org.spongepowered.api.util.Ticks) LoadableModule(org.spongepowered.test.LoadableModule) DyeColor(org.spongepowered.api.data.type.DyeColor) Predicate(java.util.function.Predicate) Sponge(org.spongepowered.api.Sponge) RecipeRegistration(org.spongepowered.api.item.recipe.RecipeRegistration) StoneCutterRecipe(org.spongepowered.api.item.recipe.single.StoneCutterRecipe) Slot(org.spongepowered.api.item.inventory.Slot) QueryTypes(org.spongepowered.api.item.inventory.query.QueryTypes) RegistryTypes(org.spongepowered.api.registry.RegistryTypes) Collectors(java.util.stream.Collectors) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) Keys(org.spongepowered.api.data.Keys) BannerPatternLayer(org.spongepowered.api.data.meta.BannerPatternLayer) PluginContainer(org.spongepowered.plugin.PluginContainer) CraftingRecipe(org.spongepowered.api.item.recipe.crafting.CraftingRecipe) CommandContext(org.spongepowered.api.command.parameter.CommandContext) Optional(java.util.Optional) BannerPatternShapes(org.spongepowered.api.data.type.BannerPatternShapes) Listener(org.spongepowered.api.event.Listener) ItemType(org.spongepowered.api.item.ItemType) CommandException(org.spongepowered.api.command.exception.CommandException) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) TextComponent(net.kyori.adventure.text.TextComponent) BannerPatternLayer(org.spongepowered.api.data.meta.BannerPatternLayer) ItemType(org.spongepowered.api.item.ItemType) RecipeRegistration(org.spongepowered.api.item.recipe.RecipeRegistration) DyeColor(org.spongepowered.api.data.type.DyeColor) Biome(org.spongepowered.api.world.biome.Biome) Random(java.util.Random) Ingredient(org.spongepowered.api.item.recipe.crafting.Ingredient) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) ItemStack(org.spongepowered.api.item.inventory.ItemStack) Listener(org.spongepowered.api.event.Listener)

Example 23 with ServerPlayer

use of org.spongepowered.api.entity.living.player.server.ServerPlayer in project SpongeCommon by SpongePowered.

the class TagTest method requireItemInHand.

private static ItemType requireItemInHand(final CommandContext ctx) throws CommandException {
    final ServerPlayer serverPlayer = ctx.cause().first(ServerPlayer.class).orElseThrow(() -> new CommandException(Component.text("You must be a player to use this command! (Held item)")));
    final ItemStack heldItem = serverPlayer.itemInHand(HandTypes.MAIN_HAND);
    if (heldItem.isEmpty()) {
        throw new CommandException(Component.text("You must hold an item in your main hand!"));
    }
    return heldItem.type();
}
Also used : ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) CommandException(org.spongepowered.api.command.exception.CommandException) ItemStack(org.spongepowered.api.item.inventory.ItemStack)

Example 24 with ServerPlayer

use of org.spongepowered.api.entity.living.player.server.ServerPlayer in project SpongeCommon by SpongePowered.

the class WorldTest method createRandomCheckerboardWorld.

private CommandResult createRandomCheckerboardWorld(final CommandContext context) {
    final WorldManager wm = Sponge.server().worldManager();
    final ServerPlayer player = (ServerPlayer) context.cause().root();
    final String owner = player.name();
    final Random random = player.world().random();
    final List<RegistryReference<Biome>> allBiomes = Sponge.server().registry(RegistryTypes.BIOME).streamEntries().map(RegistryEntry::asReference).collect(Collectors.toList());
    final List<RegistryReference<Biome>> biomes = IntStream.range(0, random.nextInt(allBiomes.size())).mapToObj(i -> allBiomes.get(random.nextInt(allBiomes.size()))).collect(Collectors.toList());
    final List<Structure> allStructures = RegistryTypes.STRUCTURE.get().stream().collect(Collectors.toList());
    final Map<Structure, SeparatedStructureConfig> abundantStructures = IntStream.range(0, random.nextInt(allStructures.size())).mapToObj(i -> allStructures.get(random.nextInt(allStructures.size()))).distinct().collect(Collectors.toMap(s -> s, s -> SeparatedStructureConfig.of(random.nextInt(3) + 2, 1, random.nextInt(10))));
    final Map<Structure, SeparatedStructureConfig> rareStructures = IntStream.range(0, random.nextInt(8) + 2).mapToObj(i -> allStructures.get(random.nextInt(allStructures.size()))).distinct().collect(Collectors.toMap(s -> s, s -> SeparatedStructureConfig.of(random.nextInt(10) + 6, 5, random.nextInt(10))));
    final StructureGenerationConfig structureConfig = StructureGenerationConfig.builder().addStructures(abundantStructures).addStructures(rareStructures).build();
    final NoiseConfig noiseConfig = NoiseConfig.builder().height(256).build();
    final NoiseGeneratorConfig noiseGenConfig = NoiseGeneratorConfig.builder().structureConfig(structureConfig).noiseConfig(noiseConfig).seaLevel(// 2 rolls
    random.nextInt(61 - 1) + 1 + random.nextInt(30)).build();
    final ResourceKey worldKey = ResourceKey.of(this.plugin, owner.toLowerCase());
    final WorldTemplate customTemplate = WorldTemplate.builder().from(WorldTemplate.overworld()).key(worldKey).worldType(WorldTypes.OVERWORLD).serializationBehavior(SerializationBehavior.NONE).loadOnStartup(false).performsSpawnLogic(true).displayName(Component.text("Custom world by " + owner)).generator(ChunkGenerator.noise(BiomeProvider.checkerboard(CheckerboardBiomeConfig.builder().addBiomes(biomes).scale(random.nextInt(16 - 2) + 2).build()), noiseGenConfig)).build();
    if (player.world().key().equals(worldKey)) {
        player.setLocation(ServerLocation.of(wm.defaultWorld(), wm.defaultWorld().properties().spawnPosition()));
    }
    context.sendMessage(Identity.nil(), Component.text("Generating your world..."));
    wm.deleteWorld(worldKey).thenCompose(b -> wm.loadWorld(customTemplate)).thenAccept(w -> this.transportToWorld(player, w)).exceptionally(e -> {
        context.sendMessage(Identity.nil(), Component.text("Failed to teleport!", NamedTextColor.DARK_RED));
        e.printStackTrace();
        return null;
    });
    return CommandResult.success();
}
Also used : IntStream(java.util.stream.IntStream) RegistryEntry(org.spongepowered.api.registry.RegistryEntry) PortalType(org.spongepowered.api.world.portal.PortalType) Command(org.spongepowered.api.command.Command) ServerWorld(org.spongepowered.api.world.server.ServerWorld) Game(org.spongepowered.api.Game) SerializationBehavior(org.spongepowered.api.world.SerializationBehavior) WorldType(org.spongepowered.api.world.WorldType) Inject(com.google.inject.Inject) Random(java.util.Random) Biome(org.spongepowered.api.world.biome.Biome) Title(net.kyori.adventure.title.Title) WorldTemplate(org.spongepowered.api.world.server.WorldTemplate) BiomeProvider(org.spongepowered.api.world.biome.provider.BiomeProvider) Parameter(org.spongepowered.api.command.parameter.Parameter) Component(net.kyori.adventure.text.Component) Map(java.util.Map) NoiseGeneratorConfig(org.spongepowered.api.world.generation.config.NoiseGeneratorConfig) ResourceKey(org.spongepowered.api.ResourceKey) ChunkGenerator(org.spongepowered.api.world.generation.ChunkGenerator) NoSuchElementException(java.util.NoSuchElementException) CommonParameters(org.spongepowered.api.command.parameter.CommonParameters) RegisterCommandEvent(org.spongepowered.api.event.lifecycle.RegisterCommandEvent) CommandResult(org.spongepowered.api.command.CommandResult) RegistryKey(org.spongepowered.api.registry.RegistryKey) Plugin(org.spongepowered.plugin.builtin.jvm.Plugin) WorldTypes(org.spongepowered.api.world.WorldTypes) WorldManager(org.spongepowered.api.world.server.WorldManager) Structure(org.spongepowered.api.world.generation.structure.Structure) Identity(net.kyori.adventure.identity.Identity) CheckerboardBiomeConfig(org.spongepowered.api.world.biome.provider.CheckerboardBiomeConfig) Sponge(org.spongepowered.api.Sponge) Axis(org.spongepowered.api.util.Axis) TypeToken(io.leangen.geantyref.TypeToken) RegistryTypes(org.spongepowered.api.registry.RegistryTypes) Collectors(java.util.stream.Collectors) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) SeparatedStructureConfig(org.spongepowered.api.world.generation.config.structure.SeparatedStructureConfig) List(java.util.List) RegistryReference(org.spongepowered.api.registry.RegistryReference) Vector3d(org.spongepowered.math.vector.Vector3d) PluginContainer(org.spongepowered.plugin.PluginContainer) StructureGenerationConfig(org.spongepowered.api.world.generation.config.structure.StructureGenerationConfig) CommandContext(org.spongepowered.api.command.parameter.CommandContext) Listener(org.spongepowered.api.event.Listener) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) NoiseConfig(org.spongepowered.api.world.generation.config.noise.NoiseConfig) ServerLocation(org.spongepowered.api.world.server.ServerLocation) NoiseGeneratorConfig(org.spongepowered.api.world.generation.config.NoiseGeneratorConfig) RegistryReference(org.spongepowered.api.registry.RegistryReference) NoiseConfig(org.spongepowered.api.world.generation.config.noise.NoiseConfig) WorldManager(org.spongepowered.api.world.server.WorldManager) ResourceKey(org.spongepowered.api.ResourceKey) StructureGenerationConfig(org.spongepowered.api.world.generation.config.structure.StructureGenerationConfig) Random(java.util.Random) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) SeparatedStructureConfig(org.spongepowered.api.world.generation.config.structure.SeparatedStructureConfig) Structure(org.spongepowered.api.world.generation.structure.Structure) WorldTemplate(org.spongepowered.api.world.server.WorldTemplate)

Example 25 with ServerPlayer

use of org.spongepowered.api.entity.living.player.server.ServerPlayer in project SpongeCommon by SpongePowered.

the class WorldTest method onRegisterCommand.

@Listener
public void onRegisterCommand(final RegisterCommandEvent<Command.Parameterized> event) {
    final Parameter.Value<ServerPlayer> optPlayerParameter = Parameter.player().optional().key("player").build();
    final Parameter.Value<ResourceKey> worldKeyParameter = Parameter.resourceKey().key("world").build();
    final Parameter.Value<ServerWorld> optWorldParameter = Parameter.world().optional().key("world").build();
    final Parameter.Value<Vector3d> optPositionParameter = Parameter.vector3d().optional().key("position").build();
    final Parameter.Value<PortalType> portalTypeParameter = Parameter.registryElement(TypeToken.get(PortalType.class), RegistryTypes.PORTAL_TYPE, "minecraft", "sponge").key("portal_type").build();
    final Parameter.Value<WorldType> worldTypeParameter = Parameter.registryElement(TypeToken.get(WorldType.class), RegistryTypes.WORLD_TYPE, "minecraft", "sponge").key("world_type").build();
    final Parameter.Value<ResourceKey> copyWorldKeyParameter = Parameter.resourceKey().key("copy_world").build();
    final Parameter.Value<ResourceKey> moveWorldKeyParameter = Parameter.resourceKey().key("move_world").build();
    event.register(this.plugin, Command.builder().addParameters(CommonParameters.LOCATION_ONLINE_ONLY, portalTypeParameter).permission(this.plugin.metadata().id() + ".command.portal.create").executor(context -> {
        final ServerLocation location = context.requireOne(CommonParameters.LOCATION_ONLINE_ONLY);
        final PortalType portalType = context.requireOne(portalTypeParameter);
        portalType.generatePortal(location, Axis.X);
        return CommandResult.success();
    }).build(), "cp", "createportal").register(this.plugin, Command.builder().addParameters(optPlayerParameter, CommonParameters.LOCATION_ONLINE_ONLY, portalTypeParameter).permission(this.plugin.metadata().id() + ".command.portal.use").executor(context -> {
        final ServerPlayer player = context.one(optPlayerParameter).orElse(this.getSourcePlayer(context));
        final ServerLocation location = context.requireOne(CommonParameters.LOCATION_ONLINE_ONLY);
        final PortalType portalType = context.requireOne(portalTypeParameter);
        return portalType.teleport(player, location, true) ? CommandResult.success() : CommandResult.error(Component.text("Could not teleport!"));
    }).build(), "up", "useportal").register(this.plugin, Command.builder().addParameters(optPlayerParameter, worldTypeParameter).permission(this.plugin.metadata().id() + ".command.environment.change").executor(context -> {
        final ServerPlayer player = context.one(optPlayerParameter).orElse(this.getSourcePlayer(context));
        final WorldType worldType = context.requireOne(worldTypeParameter);
        player.sendWorldType(worldType);
        return CommandResult.success();
    }).build(), "ce", "changeenvironment").register(this.plugin, Command.builder().addParameters(CommonParameters.WORLD, worldTypeParameter).permission(this.plugin.metadata().id() + ".command.worldtype.change").executor(context -> {
        final ServerWorld world = context.requireOne(CommonParameters.WORLD);
        final WorldType worldType = context.requireOne(worldTypeParameter);
        world.properties().setWorldType(worldType);
        return CommandResult.success();
    }).build(), "cwt", "changeworldtype").register(this.plugin, Command.builder().addParameters(optPlayerParameter, optWorldParameter, optPositionParameter).permission(this.plugin.metadata().id() + ".command.location.change").executor(context -> {
        final ServerPlayer player = context.one(optPlayerParameter).orElse(this.getSourcePlayer(context));
        final ServerWorld world = context.one(optWorldParameter).orElse(player.world());
        final Vector3d position = context.one(optPositionParameter).orElse(world.properties().spawnPosition().toDouble());
        return player.setLocation(ServerLocation.of(world, position)) ? CommandResult.success() : CommandResult.error(Component.text("Could not teleport!"));
    }).build(), "cl", "changelocation").register(this.plugin, Command.builder().addParameter(worldKeyParameter).permission(this.plugin.metadata().id() + ".command.world.load").executor(context -> {
        final ResourceKey key = context.requireOne(worldKeyParameter);
        this.game.server().worldManager().loadWorld(key).whenComplete((r, t) -> {
            if (t != null) {
                context.cause().audience().sendMessage(Identity.nil(), Component.text(t.getMessage()));
            } else {
                if (r != null) {
                    context.cause().audience().sendMessage(Identity.nil(), Component.text("World loaded successfully!"));
                } else {
                    context.cause().audience().sendMessage(Identity.nil(), Component.text("World failed to load!"));
                }
            }
        });
        return CommandResult.success();
    }).build(), "lw", "loadworld").register(this.plugin, Command.builder().addParameters(worldKeyParameter, worldTypeParameter).permission(this.plugin.metadata().id() + ".command.world.create").executor(context -> {
        final ResourceKey key = context.requireOne(worldKeyParameter);
        final ResourceKey worldType = RegistryTypes.WORLD_TYPE.get().valueKey(context.requireOne(worldTypeParameter));
        final WorldTemplate template = WorldTemplate.builder().from(WorldTemplate.overworld()).key(key).worldType(RegistryKey.of(RegistryTypes.WORLD_TYPE, worldType).asReference()).performsSpawnLogic(true).build();
        this.game.server().worldManager().loadWorld(template).whenComplete((r, t) -> {
            if (t != null) {
                context.cause().audience().sendMessage(Identity.nil(), Component.text(t.getMessage()));
            } else {
                if (r != null) {
                    context.cause().audience().sendMessage(Identity.nil(), Component.text("World created successfully!"));
                } else {
                    context.cause().audience().sendMessage(Identity.nil(), Component.text("World failed to create!"));
                }
            }
        });
        return CommandResult.success();
    }).build(), "cw", "createworld").register(this.plugin, Command.builder().addParameter(CommonParameters.WORLD).executor(context -> {
        final ServerWorld world = context.requireOne(CommonParameters.WORLD);
        this.game.server().worldManager().unloadWorld(world).whenComplete((r, t) -> {
            if (t != null) {
                context.cause().audience().sendMessage(Identity.nil(), Component.text(t.getMessage()));
            } else {
                if (r) {
                    context.cause().audience().sendMessage(Identity.nil(), Component.text("World unloaded successfully!"));
                } else {
                    context.cause().audience().sendMessage(Identity.nil(), Component.text("World failed to unload!"));
                }
            }
        });
        return CommandResult.success();
    }).build(), "uw", "unloadworld").register(this.plugin, Command.builder().addParameters(worldKeyParameter, copyWorldKeyParameter).executor(context -> {
        final ResourceKey key = context.requireOne(worldKeyParameter);
        final ResourceKey copyWorldKey = context.requireOne(copyWorldKeyParameter);
        this.game.server().worldManager().copyWorld(key, copyWorldKey).whenComplete((r, t) -> {
            if (t != null) {
                context.cause().audience().sendMessage(Identity.nil(), Component.text(t.getMessage()));
            } else {
                if (r) {
                    context.cause().audience().sendMessage(Identity.nil(), Component.text("World copied successfully!"));
                } else {
                    context.cause().audience().sendMessage(Identity.nil(), Component.text("World failed to copy!"));
                }
            }
        });
        return CommandResult.success();
    }).build(), "cpw", "copyworld").register(this.plugin, Command.builder().addParameters(worldKeyParameter, moveWorldKeyParameter).executor(context -> {
        final ResourceKey key = context.requireOne(worldKeyParameter);
        final ResourceKey moveWorldKey = context.requireOne(moveWorldKeyParameter);
        this.game.server().worldManager().moveWorld(key, moveWorldKey).whenComplete((r, t) -> {
            if (t != null) {
                context.cause().audience().sendMessage(Identity.nil(), Component.text(t.getMessage()));
            } else {
                if (r) {
                    context.cause().audience().sendMessage(Identity.nil(), Component.text("World moved successfully!"));
                } else {
                    context.cause().audience().sendMessage(Identity.nil(), Component.text("World failed to move!"));
                }
            }
        });
        return CommandResult.success();
    }).build(), "mw", "moveworld").register(this.plugin, Command.builder().addParameters(worldKeyParameter).executor(context -> {
        final ResourceKey key = context.requireOne(worldKeyParameter);
        this.game.server().worldManager().deleteWorld(key).whenComplete((r, t) -> {
            if (t != null) {
                context.cause().audience().sendMessage(Identity.nil(), Component.text(t.getMessage()));
            } else {
                if (r) {
                    context.cause().audience().sendMessage(Identity.nil(), Component.text("World deleted successfully!"));
                } else {
                    context.cause().audience().sendMessage(Identity.nil(), Component.text("World failed to delete!"));
                }
            }
        });
        return CommandResult.success();
    }).build(), "dw", "deleteworld").register(this.plugin, Command.builder().addParameter(optPlayerParameter).executor(context -> {
        final ServerPlayer player = context.one(optPlayerParameter).orElse(this.getSourcePlayer(context));
        player.sendMessage(Identity.nil(), Component.text("You are in World ").append(player.world().properties().displayName().orElseGet(() -> Component.text(player.world().key().toString(), NamedTextColor.AQUA))).append(Component.text(" at (" + player.position().floorX() + ", " + player.position().floorY() + ", " + player.position().floorZ() + ")")));
        return CommandResult.success();
    }).build(), "wai", "whereami").register(this.plugin, Command.builder().executor(this::createRandomCheckerboardWorld).build(), "createrandomworld", "crw");
}
Also used : IntStream(java.util.stream.IntStream) RegistryEntry(org.spongepowered.api.registry.RegistryEntry) PortalType(org.spongepowered.api.world.portal.PortalType) Command(org.spongepowered.api.command.Command) ServerWorld(org.spongepowered.api.world.server.ServerWorld) Game(org.spongepowered.api.Game) SerializationBehavior(org.spongepowered.api.world.SerializationBehavior) WorldType(org.spongepowered.api.world.WorldType) Inject(com.google.inject.Inject) Random(java.util.Random) Biome(org.spongepowered.api.world.biome.Biome) Title(net.kyori.adventure.title.Title) WorldTemplate(org.spongepowered.api.world.server.WorldTemplate) BiomeProvider(org.spongepowered.api.world.biome.provider.BiomeProvider) Parameter(org.spongepowered.api.command.parameter.Parameter) Component(net.kyori.adventure.text.Component) Map(java.util.Map) NoiseGeneratorConfig(org.spongepowered.api.world.generation.config.NoiseGeneratorConfig) ResourceKey(org.spongepowered.api.ResourceKey) ChunkGenerator(org.spongepowered.api.world.generation.ChunkGenerator) NoSuchElementException(java.util.NoSuchElementException) CommonParameters(org.spongepowered.api.command.parameter.CommonParameters) RegisterCommandEvent(org.spongepowered.api.event.lifecycle.RegisterCommandEvent) CommandResult(org.spongepowered.api.command.CommandResult) RegistryKey(org.spongepowered.api.registry.RegistryKey) Plugin(org.spongepowered.plugin.builtin.jvm.Plugin) WorldTypes(org.spongepowered.api.world.WorldTypes) WorldManager(org.spongepowered.api.world.server.WorldManager) Structure(org.spongepowered.api.world.generation.structure.Structure) Identity(net.kyori.adventure.identity.Identity) CheckerboardBiomeConfig(org.spongepowered.api.world.biome.provider.CheckerboardBiomeConfig) Sponge(org.spongepowered.api.Sponge) Axis(org.spongepowered.api.util.Axis) TypeToken(io.leangen.geantyref.TypeToken) RegistryTypes(org.spongepowered.api.registry.RegistryTypes) Collectors(java.util.stream.Collectors) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) SeparatedStructureConfig(org.spongepowered.api.world.generation.config.structure.SeparatedStructureConfig) List(java.util.List) RegistryReference(org.spongepowered.api.registry.RegistryReference) Vector3d(org.spongepowered.math.vector.Vector3d) PluginContainer(org.spongepowered.plugin.PluginContainer) StructureGenerationConfig(org.spongepowered.api.world.generation.config.structure.StructureGenerationConfig) CommandContext(org.spongepowered.api.command.parameter.CommandContext) Listener(org.spongepowered.api.event.Listener) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) NoiseConfig(org.spongepowered.api.world.generation.config.noise.NoiseConfig) ServerLocation(org.spongepowered.api.world.server.ServerLocation) ServerLocation(org.spongepowered.api.world.server.ServerLocation) ResourceKey(org.spongepowered.api.ResourceKey) ServerWorld(org.spongepowered.api.world.server.ServerWorld) WorldType(org.spongepowered.api.world.WorldType) Vector3d(org.spongepowered.math.vector.Vector3d) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Parameter(org.spongepowered.api.command.parameter.Parameter) WorldTemplate(org.spongepowered.api.world.server.WorldTemplate) PortalType(org.spongepowered.api.world.portal.PortalType) Listener(org.spongepowered.api.event.Listener)

Aggregations

ServerPlayer (org.spongepowered.api.entity.living.player.server.ServerPlayer)32 Component (net.kyori.adventure.text.Component)13 Cause (org.spongepowered.api.event.Cause)9 Listener (org.spongepowered.api.event.Listener)8 Sponge (org.spongepowered.api.Sponge)7 Inject (org.spongepowered.asm.mixin.injection.Inject)7 TypeToken (io.leangen.geantyref.TypeToken)6 RegistryTypes (org.spongepowered.api.registry.RegistryTypes)6 Inject (com.google.inject.Inject)5 UUID (java.util.UUID)5 Identity (net.kyori.adventure.identity.Identity)5 NamedTextColor (net.kyori.adventure.text.format.NamedTextColor)5 BlockPos (net.minecraft.core.BlockPos)5 AdvancementCriterion (org.spongepowered.api.advancement.criteria.AdvancementCriterion)5 CommandResult (org.spongepowered.api.command.CommandResult)5 CommandException (org.spongepowered.api.command.exception.CommandException)5 CommandContext (org.spongepowered.api.command.parameter.CommandContext)5 Map (java.util.Map)4 Command (org.spongepowered.api.command.Command)4 Parameter (org.spongepowered.api.command.parameter.Parameter)4