Search in sources :

Example 1 with ArchetypeVolume

use of org.spongepowered.api.world.volume.archetype.ArchetypeVolume in project SpongeCommon by SpongePowered.

the class VolumeStreamTest method onGamePreInitialization.

@Listener
public void onGamePreInitialization(final RegisterCommandEvent<Command.Parameterized> event) throws IOException, CommandException {
    this.schematicsDir = this.config.resolve("schematics");
    Files.createDirectories(this.config);
    final Parameter.Value<Biome> biomeKey = Parameter.registryElement(TypeToken.get(Biome.class), ImmutableList.of(VariableValueParameters.RegistryEntryBuilder.WORLD_FROM_LOCATABLE_HOLDER_PROVIDER, VariableValueParameters.RegistryEntryBuilder.WORLD_FROM_CAUSE_HOLDER_PROVIDER), RegistryTypes.BIOME, "minecraft").key("format").build();
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Sets the biome in a selected region")).permission(this.plugin.metadata().id() + ".command.setbiome").addParameter(biomeKey).executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final PlayerData data = VolumeStreamTest.get(player);
        if (data.getPos1() == null || data.getPos2() == null) {
            player.sendMessage(Identity.nil(), Component.text("You must set both positions before copying", NamedTextColor.RED));
            return CommandResult.success();
        }
        final Vector3i min = data.getPos1().min(data.getPos2());
        final Vector3i max = data.getPos1().max(data.getPos2());
        final Biome target = src.requireOne(biomeKey);
        player.world().biomeStream(min, max, StreamOptions.forceLoadedAndCopied()).map((world, biome, x, y, z) -> target).apply(VolumeCollectors.of(player.world(), VolumePositionTranslators.identity(), VolumeApplicators.applyBiomes()));
        return CommandResult.success();
    }).build(), "setBiome");
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Copies a region of the world to your clipboard")).permission(this.plugin.metadata().id() + ".command.copy").executor(src -> {
        if (!(src.cause().root() instanceof Player)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final Player player = (Player) src.cause().root();
        final PlayerData data = VolumeStreamTest.get(player);
        if (data.getPos1() == null || data.getPos2() == null) {
            player.sendMessage(Identity.nil(), Component.text("You must set both positions before copying", NamedTextColor.RED));
            return CommandResult.success();
        }
        final Vector3i min = data.getPos1().min(data.getPos2());
        final Vector3i max = data.getPos1().max(data.getPos2());
        data.setOrigin(player.blockPosition());
        final ArchetypeVolume archetypeVolume = player.world().createArchetypeVolume(min, max, player.blockPosition());
        data.setClipboard(archetypeVolume);
        player.sendMessage(Identity.nil(), Component.text("Saved to clipboard.", VolumeStreamTest.GREEN));
        return CommandResult.success();
    }).build(), "copy");
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Pastes your clipboard to where you are standing")).permission(this.plugin.metadata().id() + ".command.paste").executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final PlayerData data = VolumeStreamTest.get(player);
        final ArchetypeVolume volume = data.getClipboard();
        if (volume == null) {
            player.sendMessage(Identity.nil(), Component.text("You must copy something before pasting", NamedTextColor.RED));
            return CommandResult.success();
        }
        try (final CauseStackManager.StackFrame frame = Sponge.server().causeStackManager().pushCauseFrame()) {
            frame.pushCause(this.plugin);
            volume.applyToWorld(player.world(), player.blockPosition(), SpawnTypes.PLACEMENT::get);
        }
        src.sendMessage(Identity.nil(), Component.text("Pasted clipboard into world.", VolumeStreamTest.GREEN));
        return CommandResult.success();
    }).build(), "paste");
    final Parameter.Value<String> fileName = Parameter.string().key("fileName").build();
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Pastes your clipboard to where you are standing")).permission(this.plugin.metadata().id() + ".command.paste").addParameter(fileName).executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final String file = src.requireOne(fileName);
        final Path desiredFilePath = this.schematicsDir.resolve(file + VolumeStreamTest.FILE_ENDING);
        if (Files.exists(desiredFilePath)) {
            throw new CommandException(Component.text(file + " already exists, please delete the file first", NamedTextColor.RED));
        }
        if (Files.isDirectory(desiredFilePath)) {
            throw new CommandException(Component.text(file + "is a directory, please use a file name", NamedTextColor.RED));
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final PlayerData data = VolumeStreamTest.get(player);
        final ArchetypeVolume volume = data.getClipboard();
        if (volume == null) {
            player.sendMessage(Identity.nil(), Component.text("You must copy something before pasting", NamedTextColor.RED));
            return CommandResult.success();
        }
        final Schematic schematic = Schematic.builder().volume(data.getClipboard()).metaValue(Schematic.METADATA_AUTHOR, player.name()).metaValue(Schematic.METADATA_NAME, file).build();
        final DataContainer schematicData = Sponge.dataManager().translator(Schematic.class).orElseThrow(() -> new IllegalStateException("Sponge doesn't have a DataTranslator for Schematics!")).translate(schematic);
        try {
            final Path output = Files.createFile(desiredFilePath);
            DataFormats.NBT.get().writeTo(new GZIPOutputStream(Files.newOutputStream(output)), schematicData);
            player.sendMessage(Identity.nil(), Component.text("Saved schematic to " + output.toAbsolutePath(), VolumeStreamTest.SAVE));
        } catch (final Exception e) {
            e.printStackTrace();
            final StringWriter writer = new StringWriter();
            e.printStackTrace(new PrintWriter(writer));
            final Component errorText = Component.text(writer.toString().replace("\t", "    ").replace("\r\n", "\n").replace("\r", "\n"));
            final TextComponent text = Component.text("Error saving schematic: " + e.getMessage(), NamedTextColor.RED).hoverEvent(HoverEvent.showText(errorText));
            return CommandResult.builder().error(text).build();
        }
        return CommandResult.success();
    }).build(), "save");
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Load a schematic from file")).permission(this.plugin.metadata().id() + ".command.load").addParameter(fileName).executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final String file = src.requireOne(fileName);
        final Path desiredFilePath = this.schematicsDir.resolve(file + VolumeStreamTest.FILE_ENDING);
        if (!Files.isRegularFile(desiredFilePath)) {
            throw new CommandException(Component.text("File " + file + " was not a normal schemaic file"));
        }
        final Schematic schematic;
        final DataContainer schematicContainer;
        try (final GZIPInputStream stream = new GZIPInputStream(Files.newInputStream(desiredFilePath))) {
            schematicContainer = DataFormats.NBT.get().readFrom(stream);
        } catch (IOException e) {
            e.printStackTrace();
            final StringWriter writer = new StringWriter();
            e.printStackTrace(new PrintWriter(writer));
            final Component errorText = Component.text(writer.toString().replace("\t", "    ").replace("\r\n", "\n").replace("\r", "\n"));
            final TextComponent text = Component.text("Error loading schematic: " + e.getMessage(), NamedTextColor.RED).hoverEvent(HoverEvent.showText(errorText));
            return CommandResult.builder().error(text).build();
        }
        schematic = Sponge.dataManager().translator(Schematic.class).orElseThrow(() -> new IllegalStateException("Expected a DataTranslator for a Schematic")).translate(schematicContainer);
        src.sendMessage(Identity.nil(), Component.text("Loaded schematic from " + file, TextColor.color(0x003434)));
        final PlayerData data = VolumeStreamTest.get(player);
        data.setClipboard(schematic);
        data.setOrigin(player.blockPosition());
        return CommandResult.success();
    }).build(), "load");
    final Parameter.Value<Rotation> rotation = Parameter.registryElement(TypeToken.get(Rotation.class), RegistryTypes.ROTATION).key("rotation").build();
    event.register(this.plugin, Command.builder().shortDescription(Component.text("Rotate clipboard")).permission(this.plugin.metadata().id() + ".command.rotate").addParameter(rotation).executor(src -> {
        if (!(src.cause().root() instanceof ServerPlayer)) {
            src.sendMessage(Identity.nil(), Component.text("Player only.", NamedTextColor.RED));
            return CommandResult.success();
        }
        final ServerPlayer player = (ServerPlayer) src.cause().root();
        final Rotation desiredRotation = src.requireOne(rotation);
        final Schematic schematic;
        final PlayerData data = VolumeStreamTest.get(player);
        if (data.clipboard == null) {
            throw new CommandException(Component.text("Load a clipboard first before trying to rotate it"));
        }
        final ArchetypeVolume newClipboard = data.clipboard.transform(Transformation.builder().origin(data.clipboard.min().toDouble().add(data.clipboard.size().toDouble().div(2))).rotate(desiredRotation).build());
        src.sendMessage(Identity.nil(), Component.text("Rotated clipboard " + desiredRotation.angle().degrees() + " degrees"));
        data.setClipboard(newClipboard);
        return CommandResult.success();
    }).build(), "rotate");
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) Command(org.spongepowered.api.command.Command) Inject(com.google.inject.Inject) Level(org.apache.logging.log4j.Level) VolumeApplicators(org.spongepowered.api.world.volume.stream.VolumeApplicators) Biome(org.spongepowered.api.world.biome.Biome) Map(java.util.Map) ArchetypeVolume(org.spongepowered.api.world.volume.archetype.ArchetypeVolume) Path(java.nio.file.Path) PrintWriter(java.io.PrintWriter) TextComponent(net.kyori.adventure.text.TextComponent) Plugin(org.spongepowered.plugin.builtin.jvm.Plugin) TextColor(net.kyori.adventure.text.format.TextColor) Sponge(org.spongepowered.api.Sponge) StreamOptions(org.spongepowered.api.world.volume.stream.StreamOptions) StoppingEngineEvent(org.spongepowered.api.event.lifecycle.StoppingEngineEvent) UUID(java.util.UUID) TypeToken(io.leangen.geantyref.TypeToken) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) Root(org.spongepowered.api.event.filter.cause.Root) Transformation(org.spongepowered.api.util.transformation.Transformation) Logger(org.apache.logging.log4j.Logger) Cancellable(org.spongepowered.api.event.Cancellable) GZIPOutputStream(java.util.zip.GZIPOutputStream) Player(org.spongepowered.api.entity.living.player.Player) VolumeCollectors(org.spongepowered.api.world.volume.stream.VolumeCollectors) HoverEvent(net.kyori.adventure.text.event.HoverEvent) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) NonNull(org.checkerframework.checker.nullness.qual.NonNull) DataContainer(org.spongepowered.api.data.persistence.DataContainer) EventContextKeys(org.spongepowered.api.event.EventContextKeys) Schematic(org.spongepowered.api.world.schematic.Schematic) ItemTypes(org.spongepowered.api.item.ItemTypes) HashMap(java.util.HashMap) Rotation(org.spongepowered.api.util.rotation.Rotation) ImmutableList(com.google.common.collect.ImmutableList) Parameter(org.spongepowered.api.command.parameter.Parameter) DataFormats(org.spongepowered.api.data.persistence.DataFormats) Component(net.kyori.adventure.text.Component) Server(org.spongepowered.api.Server) InteractBlockEvent(org.spongepowered.api.event.block.InteractBlockEvent) CauseStackManager(org.spongepowered.api.event.CauseStackManager) RegisterCommandEvent(org.spongepowered.api.event.lifecycle.RegisterCommandEvent) CommandResult(org.spongepowered.api.command.CommandResult) LoadableModule(org.spongepowered.test.LoadableModule) VolumePositionTranslators(org.spongepowered.api.world.volume.stream.VolumePositionTranslators) Files(java.nio.file.Files) Identity(net.kyori.adventure.identity.Identity) StringWriter(java.io.StringWriter) ConfigDir(org.spongepowered.api.config.ConfigDir) IOException(java.io.IOException) RegistryTypes(org.spongepowered.api.registry.RegistryTypes) VariableValueParameters(org.spongepowered.api.command.parameter.managed.standard.VariableValueParameters) PluginContainer(org.spongepowered.plugin.PluginContainer) CommandContext(org.spongepowered.api.command.parameter.CommandContext) Listener(org.spongepowered.api.event.Listener) SpawnTypes(org.spongepowered.api.event.cause.entity.SpawnTypes) CommandException(org.spongepowered.api.command.exception.CommandException) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Vector3i(org.spongepowered.math.vector.Vector3i) GZIPInputStream(java.util.zip.GZIPInputStream) DataContainer(org.spongepowered.api.data.persistence.DataContainer) Biome(org.spongepowered.api.world.biome.Biome) StringWriter(java.io.StringWriter) GZIPOutputStream(java.util.zip.GZIPOutputStream) CauseStackManager(org.spongepowered.api.event.CauseStackManager) TextComponent(net.kyori.adventure.text.TextComponent) Component(net.kyori.adventure.text.Component) PrintWriter(java.io.PrintWriter) Path(java.nio.file.Path) TextComponent(net.kyori.adventure.text.TextComponent) Player(org.spongepowered.api.entity.living.player.Player) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) CommandException(org.spongepowered.api.command.exception.CommandException) IOException(java.io.IOException) Rotation(org.spongepowered.api.util.rotation.Rotation) IOException(java.io.IOException) CommandException(org.spongepowered.api.command.exception.CommandException) ArchetypeVolume(org.spongepowered.api.world.volume.archetype.ArchetypeVolume) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) Vector3i(org.spongepowered.math.vector.Vector3i) Parameter(org.spongepowered.api.command.parameter.Parameter) Schematic(org.spongepowered.api.world.schematic.Schematic) Listener(org.spongepowered.api.event.Listener)

Example 2 with ArchetypeVolume

use of org.spongepowered.api.world.volume.archetype.ArchetypeVolume in project SpongeCommon by SpongePowered.

the class AbstractReferentArchetypeVolume method applyTransformationsToStream.

private <T> VolumeStream<ArchetypeVolume, T> applyTransformationsToStream(final Vector3i min, final Vector3i max, final StreamOptions options, final StreamCreator<A, T> streamCreator, final VolumeStreamUtils.TriFunction<VolumeElement<ArchetypeVolume, T>, Supplier<Rotation>, Supplier<Mirror>, T> elementTransform) {
    final Vector3i transformedMin = this.min();
    final Vector3i transformedMax = this.max();
    VolumeStreamUtils.validateStreamArgs(min, max, transformedMin, transformedMax, options);
    final Vector3i minDiff = min.sub(transformedMin);
    final Vector3i maxDiff = transformedMax.sub(max);
    final boolean xMirror = this.transformation.mirror(Axis.X);
    final boolean zMirror = this.transformation.mirror(Axis.Z);
    final Supplier<Mirror> mirror = xMirror ? Mirrors.FRONT_BACK : zMirror ? Mirrors.LEFT_RIGHT : Mirrors.NONE;
    return this.applyReference(a -> streamCreator.createStream(a, a.min().add(minDiff), a.max().sub(maxDiff), options)).transform(e -> VolumeElement.of(this, elementTransform.apply(e, this.transformation::rotation, mirror), this.transformStreamBlockPosition(e.position().add(VolumePositionTranslators.BLOCK_OFFSET)).sub(VolumePositionTranslators.BLOCK_OFFSET)));
}
Also used : FluidState(org.spongepowered.api.fluid.FluidState) BiFunction(java.util.function.BiFunction) VolumeElement(org.spongepowered.api.world.volume.stream.VolumeElement) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Biome(org.spongepowered.api.world.biome.Biome) Rotation(org.spongepowered.api.util.rotation.Rotation) Mirror(org.spongepowered.api.util.mirror.Mirror) Map(java.util.Map) EntityArchetypeVolume(org.spongepowered.api.world.volume.archetype.entity.EntityArchetypeVolume) ArchetypeVolume(org.spongepowered.api.world.volume.archetype.ArchetypeVolume) Nullable(org.checkerframework.checker.nullness.qual.Nullable) BlockEntityArchetype(org.spongepowered.api.block.entity.BlockEntityArchetype) BiomeVolume(org.spongepowered.api.world.volume.biome.BiomeVolume) VolumeStream(org.spongepowered.api.world.volume.stream.VolumeStream) BlockEntityArchetypeVolume(org.spongepowered.api.world.volume.archetype.block.entity.BlockEntityArchetypeVolume) VolumePositionTranslators(org.spongepowered.api.world.volume.stream.VolumePositionTranslators) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Axis(org.spongepowered.api.util.Axis) StreamOptions(org.spongepowered.api.world.volume.stream.StreamOptions) Collectors(java.util.stream.Collectors) BlockState(org.spongepowered.api.block.BlockState) Mirrors(org.spongepowered.api.util.mirror.Mirrors) Transformation(org.spongepowered.api.util.transformation.Transformation) Objects(java.util.Objects) Consumer(java.util.function.Consumer) Stream(java.util.stream.Stream) Vector3d(org.spongepowered.math.vector.Vector3d) Volume(org.spongepowered.api.world.volume.Volume) VolumeStreamUtils(org.spongepowered.common.world.volume.VolumeStreamUtils) EntityArchetypeEntry(org.spongepowered.api.world.volume.archetype.entity.EntityArchetypeEntry) MemoizedSupplier(org.spongepowered.common.util.MemoizedSupplier) Optional(java.util.Optional) BlockVolume(org.spongepowered.api.world.volume.block.BlockVolume) EntityArchetype(org.spongepowered.api.entity.EntityArchetype) Vector3i(org.spongepowered.math.vector.Vector3i) Vector3i(org.spongepowered.math.vector.Vector3i) Mirror(org.spongepowered.api.util.mirror.Mirror)

Example 3 with ArchetypeVolume

use of org.spongepowered.api.world.volume.archetype.ArchetypeVolume in project SpongeCommon by SpongePowered.

the class VolumeTransformationTest method testTransformationsOfPositions.

@MethodSource("testTransformationsOfPositions")
@ParameterizedTest
void testTransformationsOfPositions(final Vector3i min, final Vector3i max, final Vector3i origin, final Vector3i testForRoundTrip, final int rotationCount, final StubRotations wanted) {
    final SpongeArchetypeVolume volume = VolumeTransformationTest.fillVolume(min, max, origin);
    final Vector3i size = volume.size();
    final Vector3i relativeMin = volume.min();
    final Vector3d center = volume.logicalCenter();
    ArchetypeVolume intermediary = volume;
    for (int i = 0; i < rotationCount; i++) {
        intermediary = intermediary.transform(Transformation.builder().origin(center).rotate(wanted).build());
    }
    Rotation expected = Rotations.NONE.get();
    for (int i = 0; i < rotationCount; i++) {
        expected = expected.and(wanted);
    }
    final Transformation expectedTransform = Transformation.builder().origin(center).rotate(expected).build();
    final Transformation inverse = expectedTransform.inverse();
    final ArchetypeVolume rotated = intermediary;
    if (rotationCount > 0) {
        final Vector3d preliminaryTransformed = expectedTransform.transformPosition(testForRoundTrip.toDouble());
        Vector3i unTransformed = preliminaryTransformed.round().toInt();
        for (int i = 0; i < rotationCount; i++) {
            unTransformed = ((AbstractReferentArchetypeVolume) rotated).inverseTransform(unTransformed.x(), unTransformed.y(), unTransformed.z());
        }
        Assertions.assertEquals(testForRoundTrip, unTransformed);
    }
    for (int x = 0; x < size.x(); x++) {
        for (int y = 0; y < size.y(); y++) {
            for (int z = 0; z < size.z(); z++) {
                final int relativeX = x + relativeMin.x();
                final int relativeY = y + relativeMin.y();
                final int relativeZ = z + relativeMin.z();
                final Vector3d rawRelativePosition = new Vector3d(relativeX, relativeY, relativeZ);
                final BlockState untransformedState = volume.block(relativeX, relativeY, relativeZ);
                final Vector3i transformedPosition = expectedTransform.transformPosition(rawRelativePosition).toInt();
                final BlockState transformedState = rotated.block(transformedPosition.x(), transformedPosition.y(), transformedPosition.z());
                Assertions.assertEquals(untransformedState, transformedState, () -> String.format("Block Check Failed!\nOriginal(%d, %d, %d): %s\nTransformed(%d, %d, %d): %s\n", relativeX, relativeY, relativeZ, untransformedState, transformedPosition.x(), transformedPosition.y(), transformedPosition.z(), transformedState));
            }
        }
    }
    if (rotationCount < 0) {
        return;
    }
    // At this point, we should have an abstract referent volume at least
    rotated.blockStateStream(rotated.min(), rotated.max(), StreamOptions.lazily()).forEach((rotatedRef, type, x, y, z) -> {
        final Vector3d transformedPos = new Vector3d(x, y, z);
        // We have this offset in the stream, so we have to undo it here.
        final Vector3d invertedTransformedPos = inverse.transformPosition(transformedPos.add(VolumePositionTranslators.BLOCK_OFFSET)).sub(VolumePositionTranslators.BLOCK_OFFSET);
        final Vector3i invertedBlockPos = invertedTransformedPos.toInt();
        final Vector3i expectedPos;
        Assertions.assertTrue(type instanceof StubState, () -> String.format("expected state to be a stub state for pos: [%f, %f, %f] but got %s", x, y, z, type));
        Assertions.assertNotEquals(((StubState) type).deducedPos, VolumeTransformationTest.INVALID_STUB_POSITION, () -> String.format("expected to have a positioned stub state: [%f, %f, %f] but got %s", x, y, z, type));
        expectedPos = ((StubState) type).deducedPos;
        Assertions.assertEquals(expectedPos, invertedBlockPos, () -> String.format("expected untransformed position %s for state %s does not match reverse transformed position: %s", expectedPos, type, invertedBlockPos));
        final BlockState block = volume.block(expectedPos.x(), expectedPos.y(), expectedPos.z());
        Assertions.assertEquals(type, block, () -> String.format("Expected deduced state to be equal from the original target volume but had a mismatch: Original target %s does not match %s", block, type));
    });
}
Also used : AbstractReferentArchetypeVolume(org.spongepowered.common.world.volume.buffer.archetype.AbstractReferentArchetypeVolume) ArchetypeVolume(org.spongepowered.api.world.volume.archetype.ArchetypeVolume) SpongeArchetypeVolume(org.spongepowered.common.world.volume.buffer.archetype.SpongeArchetypeVolume) Transformation(org.spongepowered.api.util.transformation.Transformation) BlockState(org.spongepowered.api.block.BlockState) SpongeArchetypeVolume(org.spongepowered.common.world.volume.buffer.archetype.SpongeArchetypeVolume) Vector3d(org.spongepowered.math.vector.Vector3d) StubState(org.spongepowered.common.test.stub.block.StubState) Vector3i(org.spongepowered.math.vector.Vector3i) Rotation(org.spongepowered.api.util.rotation.Rotation) MethodSource(org.junit.jupiter.params.provider.MethodSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 4 with ArchetypeVolume

use of org.spongepowered.api.world.volume.archetype.ArchetypeVolume in project SpongeCommon by SpongePowered.

the class LevelMixin_API method createArchetypeVolume.

@Override
public ArchetypeVolume createArchetypeVolume(final Vector3i min, final Vector3i max, final Vector3i origin) {
    final Vector3i rawVolMin = Objects.requireNonNull(min, "min").min(Objects.requireNonNull(max, "max"));
    final Vector3i volMax = max.max(min);
    final Vector3i size = volMax.sub(rawVolMin).add(1, 1, 1);
    final Vector3i relativeMin = rawVolMin.sub(Objects.requireNonNull(origin, "origin"));
    final SpongeArchetypeVolume volume = new SpongeArchetypeVolume(relativeMin, size, this);
    this.blockStateStream(min, max, StreamOptions.lazily()).apply(VolumeCollectors.of(volume, VolumePositionTranslators.offset(origin), VolumeApplicators.applyBlocks()));
    this.blockEntityStream(min, max, StreamOptions.lazily()).map((world, blockEntity, x, y, z) -> blockEntity.get().createArchetype()).apply(VolumeCollectors.of(volume, VolumePositionTranslators.offset(origin), VolumeApplicators.applyBlockEntityArchetypes()));
    this.biomeStream(min, max, StreamOptions.lazily()).apply(VolumeCollectors.of(volume, VolumePositionTranslators.offset(origin), VolumeApplicators.applyBiomes()));
    this.entityStream(min, max, StreamOptions.lazily()).filter((world, entity, x, y, z) -> ((EntityAccessor) entity.get()).invoker$getEncodeId() != null || entity.get().type() == HumanEntity.TYPE).map((world, entity, x, y, z) -> entity.get().createArchetype()).apply(VolumeCollectors.of(volume, VolumePositionTranslators.offset(origin), VolumeApplicators.applyEntityArchetypes()));
    return volume;
}
Also used : ResourceLocation(net.minecraft.resources.ResourceLocation) MusicDisc(org.spongepowered.api.effect.sound.music.MusicDisc) WorldChunk(org.spongepowered.api.world.chunk.WorldChunk) Random(java.util.Random) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) ClientboundCustomSoundPacket(net.minecraft.network.protocol.game.ClientboundCustomSoundPacket) VolumeApplicators(org.spongepowered.api.world.volume.stream.VolumeApplicators) Registry(net.minecraft.core.Registry) ChunkSource(net.minecraft.world.level.chunk.ChunkSource) MonotonicNonNull(org.checkerframework.checker.nullness.qual.MonotonicNonNull) Biome(org.spongepowered.api.world.biome.Biome) MinecraftServer(net.minecraft.server.MinecraftServer) ParticleEffect(org.spongepowered.api.effect.particle.ParticleEffect) Mixin(org.spongepowered.asm.mixin.Mixin) ImposterProtoChunk(net.minecraft.world.level.chunk.ImposterProtoChunk) ArchetypeVolume(org.spongepowered.api.world.volume.archetype.ArchetypeVolume) RegistryHolderLogic(org.spongepowered.common.registry.RegistryHolderLogic) BiomeVolume(org.spongepowered.api.world.volume.biome.BiomeVolume) Location(org.spongepowered.api.world.Location) Predicate(java.util.function.Predicate) Collection(java.util.Collection) SpongeRegistryHolder(org.spongepowered.common.registry.SpongeRegistryHolder) StreamOptions(org.spongepowered.api.world.volume.stream.StreamOptions) ChunkMapAccessor(org.spongepowered.common.accessor.server.level.ChunkMapAccessor) UUID(java.util.UUID) LevelReader(net.minecraft.world.level.LevelReader) Final(org.spongepowered.asm.mixin.Final) ObjectArrayMutableEntityBuffer(org.spongepowered.common.world.volume.buffer.entity.ObjectArrayMutableEntityBuffer) ChunkAccess(net.minecraft.world.level.chunk.ChunkAccess) Objects(java.util.Objects) List(java.util.List) Sound(net.kyori.adventure.sound.Sound) Stream(java.util.stream.Stream) SpongeArchetypeVolume(org.spongepowered.common.world.volume.buffer.archetype.SpongeArchetypeVolume) BlockPos(net.minecraft.core.BlockPos) SoundEvent(net.minecraft.sounds.SoundEvent) VolumeStreamUtils(org.spongepowered.common.world.volume.VolumeStreamUtils) World(org.spongepowered.api.world.World) LevelAccessor(net.minecraft.world.level.LevelAccessor) HeightTypes(org.spongepowered.api.world.HeightTypes) Shadow(org.spongepowered.asm.mixin.Shadow) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) VolumeCollectors(org.spongepowered.api.world.volume.stream.VolumeCollectors) Level(net.minecraft.world.level.Level) HumanEntity(org.spongepowered.common.entity.living.human.HumanEntity) SoundSource(net.minecraft.sounds.SoundSource) BlockEntity(org.spongepowered.api.block.entity.BlockEntity) LevelChunk(net.minecraft.world.level.chunk.LevelChunk) DataContainer(org.spongepowered.api.data.persistence.DataContainer) ServerChunkCache(net.minecraft.server.level.ServerChunkCache) Constants(org.spongepowered.common.util.Constants) BlockState(net.minecraft.world.level.block.state.BlockState) AABB(org.spongepowered.api.util.AABB) LevelData(net.minecraft.world.level.storage.LevelData) ArrayList(java.util.ArrayList) ClientboundBlockUpdatePacket(net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket) ServerPlayer(net.minecraft.server.level.ServerPlayer) EntityAccessor(org.spongepowered.common.accessor.world.entity.EntityAccessor) Nullable(org.checkerframework.checker.nullness.qual.Nullable) VolumeStream(org.spongepowered.api.world.volume.stream.VolumeStream) LevelBridge(org.spongepowered.common.bridge.world.level.LevelBridge) Context(org.spongepowered.api.service.context.Context) VolumePositionTranslators(org.spongepowered.api.world.volume.stream.VolumePositionTranslators) Tuple(net.minecraft.util.Tuple) ResourceKey(net.minecraft.resources.ResourceKey) Entity(org.spongepowered.api.entity.Entity) WorldLike(org.spongepowered.api.world.WorldLike) SpongeChunkLayout(org.spongepowered.common.world.storage.SpongeChunkLayout) Vector3d(org.spongepowered.math.vector.Vector3d) VecHelper(org.spongepowered.common.util.VecHelper) EntityType(org.spongepowered.api.entity.EntityType) ChunkStatus(net.minecraft.world.level.chunk.ChunkStatus) SpongeParticleHelper(org.spongepowered.common.effect.particle.SpongeParticleHelper) Collections(java.util.Collections) SpongeMusicDisc(org.spongepowered.common.effect.record.SpongeMusicDisc) Vector3i(org.spongepowered.math.vector.Vector3i) SpongeArchetypeVolume(org.spongepowered.common.world.volume.buffer.archetype.SpongeArchetypeVolume) Vector3i(org.spongepowered.math.vector.Vector3i)

Example 5 with ArchetypeVolume

use of org.spongepowered.api.world.volume.archetype.ArchetypeVolume in project SpongeCommon by SpongePowered.

the class SpongeArchetypeVolume method blockStateStream.

@Override
public VolumeStream<ArchetypeVolume, BlockState> blockStateStream(final Vector3i min, final Vector3i max, final StreamOptions options) {
    final Vector3i blockMin = this.min();
    final Vector3i blockMax = this.max();
    VolumeStreamUtils.validateStreamArgs(min, max, blockMin, blockMax, options);
    final ArrayMutableBlockBuffer buffer;
    if (options.carbonCopy()) {
        buffer = this.blocks.copy();
    } else {
        buffer = this.blocks;
    }
    final Stream<VolumeElement<ArchetypeVolume, BlockState>> stateStream = IntStream.range(min.x(), max.x() + 1).mapToObj(x -> IntStream.range(min.z(), max.z() + 1).mapToObj(z -> IntStream.range(min.y(), max.y() + 1).mapToObj(y -> VolumeElement.of((ArchetypeVolume) this, () -> buffer.block(x, y, z), new Vector3d(x, y, z)))).flatMap(Function.identity())).flatMap(Function.identity());
    return new SpongeVolumeStream<>(stateStream, () -> this);
}
Also used : IntStream(java.util.stream.IntStream) NonNull(org.checkerframework.checker.nullness.qual.NonNull) ServerWorld(org.spongepowered.api.world.server.ServerWorld) RegistryHolder(org.spongepowered.api.registry.RegistryHolder) FluidState(org.spongepowered.api.fluid.FluidState) ArrayMutableBlockBuffer(org.spongepowered.common.world.volume.buffer.block.ArrayMutableBlockBuffer) VolumeElement(org.spongepowered.api.world.volume.stream.VolumeElement) SpawnType(org.spongepowered.api.event.cause.entity.SpawnType) Function(java.util.function.Function) Supplier(java.util.function.Supplier) VolumeApplicators(org.spongepowered.api.world.volume.stream.VolumeApplicators) Biome(org.spongepowered.api.world.biome.Biome) PaletteTypes(org.spongepowered.api.world.schematic.PaletteTypes) AbstractVolumeBuffer(org.spongepowered.common.world.volume.buffer.AbstractVolumeBuffer) Map(java.util.Map) SpongeVolumeStream(org.spongepowered.common.world.volume.SpongeVolumeStream) PluginPhase(org.spongepowered.common.event.tracking.phase.plugin.PluginPhase) ArchetypeVolume(org.spongepowered.api.world.volume.archetype.ArchetypeVolume) BlockEntityArchetype(org.spongepowered.api.block.entity.BlockEntityArchetype) VolumeStream(org.spongepowered.api.world.volume.stream.VolumeStream) BlockEntityArchetypeVolume(org.spongepowered.api.world.volume.archetype.block.entity.BlockEntityArchetypeVolume) VolumePositionTranslators(org.spongepowered.api.world.volume.stream.VolumePositionTranslators) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Sponge(org.spongepowered.api.Sponge) StreamOptions(org.spongepowered.api.world.volume.stream.StreamOptions) Palette(org.spongepowered.api.world.schematic.Palette) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) ObjectArrayMutableEntityArchetypeBuffer(org.spongepowered.common.world.volume.buffer.archetype.entity.ObjectArrayMutableEntityArchetypeBuffer) RegistryTypes(org.spongepowered.api.registry.RegistryTypes) BlockState(org.spongepowered.api.block.BlockState) Transformation(org.spongepowered.api.util.transformation.Transformation) MutableMapBlockEntityArchetypeBuffer(org.spongepowered.common.world.volume.buffer.archetype.blockentity.MutableMapBlockEntityArchetypeBuffer) Objects(java.util.Objects) Stream(java.util.stream.Stream) Vector3d(org.spongepowered.math.vector.Vector3d) PhaseContext(org.spongepowered.common.event.tracking.PhaseContext) VolumeStreamUtils(org.spongepowered.common.world.volume.VolumeStreamUtils) BlockChangeFlags(org.spongepowered.api.world.BlockChangeFlags) BlockType(org.spongepowered.api.block.BlockType) EntityArchetypeEntry(org.spongepowered.api.world.volume.archetype.entity.EntityArchetypeEntry) Optional(java.util.Optional) VolumeCollectors(org.spongepowered.api.world.volume.stream.VolumeCollectors) ByteArrayMutableBiomeBuffer(org.spongepowered.common.world.volume.buffer.biome.ByteArrayMutableBiomeBuffer) EntityArchetype(org.spongepowered.api.entity.EntityArchetype) Vector3i(org.spongepowered.math.vector.Vector3i) ArchetypeVolume(org.spongepowered.api.world.volume.archetype.ArchetypeVolume) BlockEntityArchetypeVolume(org.spongepowered.api.world.volume.archetype.block.entity.BlockEntityArchetypeVolume) Vector3d(org.spongepowered.math.vector.Vector3d) Vector3i(org.spongepowered.math.vector.Vector3i) ArrayMutableBlockBuffer(org.spongepowered.common.world.volume.buffer.block.ArrayMutableBlockBuffer) VolumeElement(org.spongepowered.api.world.volume.stream.VolumeElement) SpongeVolumeStream(org.spongepowered.common.world.volume.SpongeVolumeStream)

Aggregations

ArchetypeVolume (org.spongepowered.api.world.volume.archetype.ArchetypeVolume)5 Vector3i (org.spongepowered.math.vector.Vector3i)5 Biome (org.spongepowered.api.world.biome.Biome)4 StreamOptions (org.spongepowered.api.world.volume.stream.StreamOptions)4 VolumePositionTranslators (org.spongepowered.api.world.volume.stream.VolumePositionTranslators)4 Vector3d (org.spongepowered.math.vector.Vector3d)4 Collection (java.util.Collection)3 Map (java.util.Map)3 Objects (java.util.Objects)3 Optional (java.util.Optional)3 Predicate (java.util.function.Predicate)3 Stream (java.util.stream.Stream)3 Rotation (org.spongepowered.api.util.rotation.Rotation)3 Transformation (org.spongepowered.api.util.transformation.Transformation)3 UUID (java.util.UUID)2 Function (java.util.function.Function)2 Supplier (java.util.function.Supplier)2 BlockState (org.spongepowered.api.block.BlockState)2 VolumeApplicators (org.spongepowered.api.world.volume.stream.VolumeApplicators)2 VolumeCollectors (org.spongepowered.api.world.volume.stream.VolumeCollectors)2