Search in sources :

Example 6 with Biome

use of org.spongepowered.api.world.biome.Biome in project SpongeCommon by SpongePowered.

the class VolumeTransformationTest method setup.

@BeforeAll
static void setup() {
    VolumeTransformationTest.guice.injectMembers(new DummyInjectable());
    final StubGame game = (StubGame) Sponge.game();
    final SpongeFactoryProvider factoryProvider = game.factoryProvider();
    final SpongeBuilderProvider builderProvider = game.builderProvider();
    // Set up Rotations
    final StubbedRegistry<Rotation> rotation = new StubbedRegistry<>(() -> RegistryTypes.ROTATION, (k) -> Rotations.NONE.get());
    // Set up Blocks and BlockState
    final StubbedRegistry<BlockType> blocktypes = new StubbedRegistry<>(() -> RegistryTypes.BLOCK_TYPE, StubBlock::new);
    // Set up biomes
    final StubbedRegistry<Biome> biomes = new StubbedRegistry<>(() -> RegistryTypes.BIOME, (key) -> Mockito.mock(Biome.class));
    // Set up palettes
    final StubbedRegistry<PaletteType<?, ?>> paletteTypeRegistry = new StubbedRegistry<>(() -> RegistryTypes.PALETTE_TYPE, (key) -> new StubPaletteType<>());
    factoryProvider.registerFactory(RegistryType.Factory.class, new SpongeRegistryType.FactoryImpl());
    factoryProvider.registerFactory(RegistryKey.Factory.class, new SpongeRegistryKey.FactoryImpl());
    factoryProvider.registerFactory(PaletteReference.Factory.class, new SpongePaletteReferenceFactory());
    // and finally, set up the resourcekey stuff
    factoryProvider.registerFactory(ResourceKey.Factory.class, new StubRegistryFactory());
    game.register(rotation);
    game.register(blocktypes);
    game.register(biomes);
    game.register(paletteTypeRegistry);
    final StubbedRegistry<Mirror> mirror = new StubbedRegistry<>(() -> RegistryTypes.MIRROR, (k) -> Mockito.mock(Mirror.class));
    StubMirror.registerDefaults(mirror);
    game.register(mirror);
    builderProvider.register(Transformation.Builder.class, SpongeTransformationBuilder::new);
    builderProvider.register(StreamOptions.Builder.class, SpongeStreamOptionsBuilder::new);
    StubRotations.registerDefaults(rotation);
    paletteTypeRegistry.register(new StubKey("sponge", "block_state_palette"), new StubBlockStatePaletteType());
}
Also used : SpongeFactoryProvider(org.spongepowered.common.registry.SpongeFactoryProvider) Transformation(org.spongepowered.api.util.transformation.Transformation) StubKey(org.spongepowered.common.test.stub.StubKey) StreamOptions(org.spongepowered.api.world.volume.stream.StreamOptions) PaletteType(org.spongepowered.api.world.schematic.PaletteType) StubBlockStatePaletteType(org.spongepowered.common.test.stub.world.schematic.StubBlockStatePaletteType) StubPaletteType(org.spongepowered.common.test.stub.world.schematic.StubPaletteType) PaletteReference(org.spongepowered.api.world.schematic.PaletteReference) Biome(org.spongepowered.api.world.biome.Biome) SpongeRegistryType(org.spongepowered.common.registry.SpongeRegistryType) SpongeRegistryKey(org.spongepowered.common.registry.SpongeRegistryKey) StubBlock(org.spongepowered.common.test.stub.block.StubBlock) SpongeStreamOptionsBuilder(org.spongepowered.common.world.volume.stream.SpongeStreamOptionsBuilder) StubGame(org.spongepowered.common.test.stub.StubGame) StubRegistryFactory(org.spongepowered.common.test.stub.registry.StubRegistryFactory) SpongeRegistryType(org.spongepowered.common.registry.SpongeRegistryType) RegistryType(org.spongepowered.api.registry.RegistryType) SpongeBuilderProvider(org.spongepowered.common.registry.SpongeBuilderProvider) Rotation(org.spongepowered.api.util.rotation.Rotation) StubbedRegistry(org.spongepowered.common.test.stub.registry.StubbedRegistry) StubBlockStatePaletteType(org.spongepowered.common.test.stub.world.schematic.StubBlockStatePaletteType) ResourceKey(org.spongepowered.api.ResourceKey) BlockType(org.spongepowered.api.block.BlockType) Mirror(org.spongepowered.api.util.mirror.Mirror) StubMirror(org.spongepowered.common.test.stub.util.StubMirror) RegistryKey(org.spongepowered.api.registry.RegistryKey) SpongeRegistryKey(org.spongepowered.common.registry.SpongeRegistryKey) SpongePaletteReferenceFactory(org.spongepowered.common.world.schematic.SpongePaletteReferenceFactory) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 7 with Biome

use of org.spongepowered.api.world.biome.Biome in project SpongeCommon by SpongePowered.

the class SchematicUpdater2_to_3 method update.

@Override
public DataView update(final DataView content) {
    // Move BlockData, BlockPalette, BlockEntities -> Blocks.Data, Blocks.Palette, and Blocks.BlockEntities
    content.getView(Constants.Sponge.Schematic.Versions.V2_BLOCK_PALETTE).ifPresent(dataView -> {
        content.remove(Constants.Sponge.Schematic.Versions.V2_BLOCK_PALETTE);
        final byte[] blockData = (byte[]) content.get(Constants.Sponge.Schematic.BLOCK_DATA).orElseThrow(() -> new InvalidDataException("Missing BlockData for Schematic"));
        content.remove(Constants.Sponge.Schematic.Versions.V2_BLOCK_DATA);
        final List<DataView> blockEntities = content.getViewList(Constants.Sponge.Schematic.BLOCKENTITY_CONTAINER).orElse(Collections.emptyList());
        content.remove(Constants.Sponge.Schematic.BLOCKENTITY_CONTAINER);
        final DataView blockContainer = content.createView(Constants.Sponge.Schematic.BLOCK_CONTAINER);
        blockContainer.set(Constants.Sponge.Schematic.BLOCK_DATA, blockData);
        blockContainer.set(Constants.Sponge.Schematic.BLOCK_PALETTE, dataView);
        blockContainer.set(Constants.Sponge.Schematic.BLOCKENTITY_CONTAINER, blockEntities);
    });
    // Move BiomeData, BiomePalette -> Biomes.Data and Biomes.Palette
    content.get(Constants.Sponge.Schematic.Versions.V2_BIOME_DATA).ifPresent(biomeData -> {
        content.remove(Constants.Sponge.Schematic.Versions.V2_BIOME_DATA);
        // But first, convert from a 2D array to a 3D array, which basically means almost fully deserializing
        // the entirety of the biome into a new buffer.
        final int[] offset = (int[]) content.get(Constants.Sponge.Schematic.OFFSET).orElse(new int[3]);
        if (offset.length != 3) {
            throw new InvalidDataException("Schematic offset was not of length 3");
        }
        final int xOffset = offset[0];
        final int yOffset = offset[1];
        final int zOffset = offset[2];
        final DataView palette = content.getView(Constants.Sponge.Schematic.Versions.V2_BIOME_PALETTE).orElseThrow(() -> new InvalidDataException("Missing Biome Palette for schematic"));
        final int width = content.getShort(Constants.Sponge.Schematic.WIDTH).orElseThrow(() -> new InvalidDataException("Missing value for: " + Constants.Sponge.Schematic.WIDTH));
        final int height = content.getShort(Constants.Sponge.Schematic.HEIGHT).orElseThrow(() -> new InvalidDataException("Missing value for: " + Constants.Sponge.Schematic.HEIGHT));
        final int length = content.getShort(Constants.Sponge.Schematic.LENGTH).orElseThrow(() -> new InvalidDataException("Missing value for: " + Constants.Sponge.Schematic.LENGTH));
        final Set<DataQuery> biomeKeys = palette.keys(false);
        final Registry<Biome> biomeRegistry = VolumeStreamUtils.nativeToSpongeRegistry(BuiltinRegistries.BIOME);
        final MutableBimapPalette<Biome, Biome> biomePalette = new MutableBimapPalette<>(PaletteTypes.BIOME_PALETTE.get(), biomeRegistry, RegistryTypes.BIOME, biomeKeys.size());
        final ByteArrayMutableBiomeBuffer biomeBuffer = new ByteArrayMutableBiomeBuffer(biomePalette, new Vector3i(-xOffset, -yOffset, -zOffset), new Vector3i(width, height, length));
        final DataView biomeView = content.createView(Constants.Sponge.Schematic.BIOME_CONTAINER);
        biomeView.set(Constants.Sponge.Schematic.BLOCK_PALETTE, palette);
        final byte[] biomes = (byte[]) biomeData;
        int biomeIndex = 0;
        int biomeJ = 0;
        int bVal = 0;
        int varIntLength = 0;
        final int yMin = biomeBuffer.min().y();
        final int yMax = biomeBuffer.max().y();
        while (biomeJ < biomes.length) {
            bVal = 0;
            varIntLength = 0;
            while (true) {
                bVal |= (biomes[biomeJ] & 127) << (varIntLength++ * 7);
                if (varIntLength > 5) {
                    throw new RuntimeException("VarInt too big (probably corrupted data)");
                }
                if (((biomes[biomeJ] & 128) != 128)) {
                    biomeJ++;
                    break;
                }
                biomeJ++;
            }
            final int z = (biomeIndex % (width * length)) / width;
            final int x = (biomeIndex % (width * length)) % width;
            final Biome type = biomePalette.get(bVal, Sponge.server()).get();
            for (int y = yMin; y <= yMax; y++) {
                biomeBuffer.setBiome(x - xOffset, y, z - zOffset, type);
            }
            biomeIndex++;
        }
        try (final ByteArrayOutputStream buffer = new ByteArrayOutputStream(width * height * length)) {
            final int xMin = biomeBuffer.min().x();
            final int zMin = biomeBuffer.min().z();
            for (int y = 0; y < height; y++) {
                final int y0 = yMin + y;
                for (int z = 0; z < length; z++) {
                    final int z0 = zMin + z;
                    for (int x = 0; x < width; x++) {
                        final int x0 = xMin + x;
                        final Biome biome = biomeBuffer.biome(x0, y0, z0);
                        SchematicTranslator.writeIdToBuffer(buffer, biomePalette.orAssign(biome));
                    }
                }
            }
            content.set(Constants.Sponge.Schematic.BIOME_DATA, buffer.toByteArray());
        } catch (final IOException e) {
        // Should never reach here.
        }
        content.remove(Constants.Sponge.Schematic.Versions.V2_BIOME_PALETTE);
    });
    content.set(Constants.Sponge.Schematic.VERSION, 3);
    return content;
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DataView(org.spongepowered.api.data.persistence.DataView) Biome(org.spongepowered.api.world.biome.Biome) InvalidDataException(org.spongepowered.api.data.persistence.InvalidDataException) Vector3i(org.spongepowered.math.vector.Vector3i) MutableBimapPalette(org.spongepowered.common.world.schematic.MutableBimapPalette) DataQuery(org.spongepowered.api.data.persistence.DataQuery) ByteArrayMutableBiomeBuffer(org.spongepowered.common.world.volume.buffer.biome.ByteArrayMutableBiomeBuffer)

Example 8 with Biome

use of org.spongepowered.api.world.biome.Biome 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 9 with Biome

use of org.spongepowered.api.world.biome.Biome 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 10 with Biome

use of org.spongepowered.api.world.biome.Biome in project SpongeCommon by SpongePowered.

the class SchematicTranslator method deserializeBiomeContainer.

private static void deserializeBiomeContainer(final DataView view, final SpongeArchetypeVolume archetypeVolume, final int width, final int length, final Vector3i offset) {
    final MutableBimapPalette<Biome, Biome> biomePalette;
    final DataView biomeMap = view.getView(Constants.Sponge.Schematic.BIOME_PALETTE).orElseThrow(() -> new InvalidDataException("Missing BiomePalette as required by the schematic spec"));
    final Set<DataQuery> biomeKeys = biomeMap.keys(false);
    final Registry<Biome> biomeRegistry = VolumeStreamUtils.nativeToSpongeRegistry(BuiltinRegistries.BIOME);
    biomePalette = new MutableBimapPalette<>(PaletteTypes.BIOME_PALETTE.get(), biomeRegistry, RegistryTypes.BIOME, biomeKeys.size());
    for (final DataQuery biomeKey : biomeKeys) {
        final ResourceKey key = ResourceKey.resolve(biomeKey.parts().get(0));
        final Biome biome = biomeRegistry.findValue(key).get();
        biomePalette.assign(biome, biomeMap.getInt(biomeKey).get());
    }
    final byte[] biomeData = (byte[]) view.get(Constants.Sponge.Schematic.BIOME_DATA).orElseThrow(() -> new InvalidDataException("Missing BlockData for Schematic"));
    SchematicTranslator.readByteArrayData(width, (width * length), offset, biomePalette, biomeData, archetypeVolume, BiomeVolume.Modifiable::setBiome);
}
Also used : DataView(org.spongepowered.api.data.persistence.DataView) Biome(org.spongepowered.api.world.biome.Biome) InvalidDataException(org.spongepowered.api.data.persistence.InvalidDataException) DataQuery(org.spongepowered.api.data.persistence.DataQuery) ResourceKey(org.spongepowered.api.ResourceKey)

Aggregations

Biome (org.spongepowered.api.world.biome.Biome)11 Sponge (org.spongepowered.api.Sponge)5 RegistryTypes (org.spongepowered.api.registry.RegistryTypes)5 Collectors (java.util.stream.Collectors)4 ResourceKey (org.spongepowered.api.ResourceKey)4 StreamOptions (org.spongepowered.api.world.volume.stream.StreamOptions)4 Vector3d (org.spongepowered.math.vector.Vector3d)4 Vector3i (org.spongepowered.math.vector.Vector3i)4 Inject (com.google.inject.Inject)3 TypeToken (io.leangen.geantyref.TypeToken)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 Arrays (java.util.Arrays)3 List (java.util.List)3 Map (java.util.Map)3 Optional (java.util.Optional)3 Stream (java.util.stream.Stream)3 ImmutableList (com.google.common.collect.ImmutableList)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 Objects (java.util.Objects)2