Search in sources :

Example 21 with Key

use of org.spongepowered.api.data.key.Key in project LanternServer by LanternPowered.

the class SlabItemInteractionBehavior method tryInteract.

@Override
public BehaviorResult tryInteract(BehaviorPipeline<Behavior> pipeline, BehaviorContext context) {
    final Optional<Location<World>> optLocation = context.getContext(ContextKeys.INTERACTION_LOCATION);
    if (!optLocation.isPresent()) {
        return BehaviorResult.CONTINUE;
    }
    final BlockType halfSlabType = this.halfSlabType.get();
    final BlockType doubleSlabType = this.doubleSlabType.get();
    Location<World> location = optLocation.get();
    final Direction blockFace = context.getContext(ContextKeys.INTERACTION_FACE).get().getOpposite();
    final LanternBlockType blockType = (LanternBlockType) context.getContext(ContextKeys.ITEM_TYPE).get().getBlock().get();
    if (blockType != halfSlabType) {
        return BehaviorResult.PASS;
    }
    BlockState state = location.getBlock();
    final BlockState.Builder stateBuilder = BlockState.builder();
    stateBuilder.blockType(blockType);
    context.getContext(ContextKeys.USED_ITEM_STACK).ifPresent(itemStack -> itemStack.getValues().forEach(value -> stateBuilder.add((Key) value.getKey(), value.get())));
    BlockState blockState = stateBuilder.build();
    BlockSnapshotBuilder snapshotBuilder = null;
    boolean success = false;
    if (state.getType() == blockType) {
        if (state.getTraitValue(this.variantTrait).get().equals(blockState.getTraitValue(this.variantTrait).get())) {
            final PortionType portionType = state.getTraitValue(LanternEnumTraits.PORTION_TYPE).get();
            if ((blockFace == Direction.DOWN && portionType == PortionTypes.BOTTOM) || (blockFace == Direction.UP && portionType == PortionTypes.TOP)) {
                snapshotBuilder = BlockSnapshotBuilder.create().blockState(doubleSlabType.getDefaultState());
                success = true;
            }
        }
    } else if (location.getProperty(ReplaceableProperty.class).get().getValue()) {
        success = true;
    }
    if (!success) {
        location = location.add(blockFace.getOpposite().asBlockOffset());
        state = location.getBlock();
        if (state.getType() == blockType) {
            if (state.getTraitValue(this.variantTrait).get().equals(blockState.getTraitValue(this.variantTrait).get())) {
                final PortionType portionType = state.getTraitValue(LanternEnumTraits.PORTION_TYPE).get();
                if ((blockFace == Direction.DOWN && portionType == PortionTypes.TOP) || (blockFace == Direction.UP && portionType == PortionTypes.BOTTOM)) {
                    snapshotBuilder = BlockSnapshotBuilder.create().blockState(doubleSlabType.getDefaultState());
                    success = true;
                }
            }
        } else if (location.getProperty(ReplaceableProperty.class).get().getValue()) {
            success = true;
        }
    }
    if (success) {
        if (snapshotBuilder == null) {
            PortionType portionType;
            if (blockFace == Direction.UP) {
                portionType = PortionTypes.TOP;
            } else if (blockFace == Direction.DOWN) {
                portionType = PortionTypes.BOTTOM;
            } else {
                final double y = location.getY() - location.getBlockY();
                if (y >= 0.5) {
                    portionType = PortionTypes.TOP;
                } else {
                    portionType = PortionTypes.BOTTOM;
                }
            }
            snapshotBuilder = BlockSnapshotBuilder.create().blockState(halfSlabType.getDefaultState()).add(Keys.PORTION_TYPE, portionType);
        }
        final BlockSnapshotBuilder snapshotBuilder1 = snapshotBuilder;
        snapshotBuilder1.location(location);
        context.getContext(ContextKeys.USED_ITEM_STACK).ifPresent(itemStack -> itemStack.getValues().forEach(value -> snapshotBuilder1.add((Key) value.getKey(), value.get())));
        context.addBlockChange(snapshotBuilder1.build());
        context.getContext(ContextKeys.PLAYER).ifPresent(player -> {
            if (!player.get(Keys.GAME_MODE).orElse(GameModes.NOT_SET).equals(GameModes.CREATIVE)) {
                context.requireContext(ContextKeys.USED_SLOT).poll(1);
            }
        });
        return BehaviorResult.SUCCESS;
    }
    return BehaviorResult.FAIL;
}
Also used : ContextKeys(org.lanternpowered.server.behavior.ContextKeys) PortionTypes(org.spongepowered.api.data.type.PortionTypes) Location(org.spongepowered.api.world.Location) Keys(org.spongepowered.api.data.key.Keys) PortionType(org.spongepowered.api.data.type.PortionType) LanternBlockType(org.lanternpowered.server.block.LanternBlockType) BehaviorPipeline(org.lanternpowered.server.behavior.pipeline.BehaviorPipeline) EnumTrait(org.spongepowered.api.block.trait.EnumTrait) Behavior(org.lanternpowered.server.behavior.Behavior) GameModes(org.spongepowered.api.entity.living.player.gamemode.GameModes) Supplier(java.util.function.Supplier) Key(org.spongepowered.api.data.key.Key) BlockState(org.spongepowered.api.block.BlockState) Direction(org.spongepowered.api.util.Direction) BehaviorContext(org.lanternpowered.server.behavior.BehaviorContext) BlockSnapshotBuilder(org.lanternpowered.server.block.BlockSnapshotBuilder) InteractWithItemBehavior(org.lanternpowered.server.item.behavior.types.InteractWithItemBehavior) World(org.spongepowered.api.world.World) BehaviorResult(org.lanternpowered.server.behavior.BehaviorResult) BlockType(org.spongepowered.api.block.BlockType) Optional(java.util.Optional) LanternEnumTraits(org.lanternpowered.server.block.trait.LanternEnumTraits) ReplaceableProperty(org.spongepowered.api.data.property.block.ReplaceableProperty) PortionType(org.spongepowered.api.data.type.PortionType) World(org.spongepowered.api.world.World) Direction(org.spongepowered.api.util.Direction) LanternBlockType(org.lanternpowered.server.block.LanternBlockType) BlockState(org.spongepowered.api.block.BlockState) LanternBlockType(org.lanternpowered.server.block.LanternBlockType) BlockType(org.spongepowered.api.block.BlockType) ReplaceableProperty(org.spongepowered.api.data.property.block.ReplaceableProperty) Location(org.spongepowered.api.world.Location) BlockSnapshotBuilder(org.lanternpowered.server.block.BlockSnapshotBuilder)

Example 22 with Key

use of org.spongepowered.api.data.key.Key in project LanternServer by LanternPowered.

the class LanternLiving method registerKeys.

@Override
public void registerKeys() {
    super.registerKeys();
    final ValueCollection c = getValueCollection();
    c.register(Keys.MAX_AIR, 300, 0, Integer.MAX_VALUE);
    c.register(Keys.REMAINING_AIR, 300, 0, Keys.MAX_AIR);
    c.register(Keys.MAX_HEALTH, 20.0, 0.0, 1024.0);
    c.register(Keys.HEALTH, 20.0, 0.0, Keys.MAX_HEALTH).addListener((oldElement, newElement) -> {
        if (newElement <= 0) {
            handleDeath();
        }
    });
    // noinspection unchecked
    c.register((Key<MutableBoundedValue<Double>>) (Key) Keys.ABSORPTION, 0.0, 0.0, 1024.0);
    c.register(Keys.POTION_EFFECTS, new ArrayList<>());
}
Also used : ValueCollection(org.lanternpowered.server.data.ValueCollection) MutableBoundedValue(org.spongepowered.api.data.value.mutable.MutableBoundedValue) Key(org.spongepowered.api.data.key.Key)

Example 23 with Key

use of org.spongepowered.api.data.key.Key in project LanternServer by LanternPowered.

the class DataManipulatorGenerator method findKeyMatches.

@SuppressWarnings("unchecked")
private static Key[] findKeyMatches(List<Method> methods, Set<Key<?>> requiredKeys) {
    Key[] keys = new Key[methods.size()];
    for (int i = 0; i < methods.size(); i++) {
        final Method method = methods.get(i);
        final String methodName = DataHelper.camelToSnake(method.getName());
        int closestDistance = Integer.MAX_VALUE;
        Key closestKey = null;
        for (Key key : requiredKeys) {
            String keyId = key.getId();
            final int index = keyId.indexOf(':');
            if (index != -1) {
                keyId = keyId.substring(index + 1);
            }
            final int distance = StringUtils.getLevenshteinDistance(methodName, keyId);
            if (distance < closestDistance) {
                closestDistance = distance;
                closestKey = key;
            }
        }
        if (closestKey == null) {
            throw new IllegalStateException("No key match could be found for the method: " + method);
        }
        keys[i] = closestKey;
    }
    return keys;
}
Also used : Method(java.lang.reflect.Method) Key(org.spongepowered.api.data.key.Key)

Example 24 with Key

use of org.spongepowered.api.data.key.Key in project LanternServer by LanternPowered.

the class ProcessorPlayOutParticleEffect method getBlockState.

private static int getBlockState(LanternParticleEffect effect, Optional<BlockState> defaultBlockState) {
    final Optional<BlockState> blockState = effect.getOption(ParticleOptions.BLOCK_STATE);
    if (blockState.isPresent()) {
        return BlockRegistryModule.get().getStateInternalIdAndData(blockState.get());
    } else {
        final Optional<ItemStackSnapshot> optSnapshot = effect.getOption(ParticleOptions.ITEM_STACK_SNAPSHOT);
        if (optSnapshot.isPresent()) {
            final ItemStackSnapshot snapshot = optSnapshot.get();
            final Optional<BlockType> blockType = snapshot.getType().getBlock();
            if (blockType.isPresent()) {
                final BlockState state;
                if (blockType.get().getDefaultState().getTraits().isEmpty()) {
                    state = blockType.get().getDefaultState();
                } else {
                    final BlockState.Builder builder = BlockState.builder().blockType(blockType.get());
                    // noinspection unchecked
                    snapshot.getValues().forEach(value -> builder.add((Key) value.getKey(), value.get()));
                    state = builder.build();
                }
                return BlockRegistryModule.get().getStateInternalIdAndData(state);
            } else {
                return 0;
            }
        } else {
            return BlockRegistryModule.get().getStateInternalIdAndData(defaultBlockState.get());
        }
    }
}
Also used : BlockState(org.spongepowered.api.block.BlockState) BlockType(org.spongepowered.api.block.BlockType) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) Key(org.spongepowered.api.data.key.Key)

Example 25 with Key

use of org.spongepowered.api.data.key.Key in project LanternServer by LanternPowered.

the class CommandSetData method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    final ThreadLocal<Key<?>> currentKey = new ThreadLocal<>();
    specBuilder.arguments(GenericArguments.playerOrSource(Text.of("player")), new PatternMatchingCommandElement(Text.of("key")) {

        @Override
        protected Iterable<String> getChoices(CommandSource source) {
            return Sponge.getGame().getRegistry().getAllOf(Key.class).stream().map(Key::getId).collect(Collectors.toList());
        }

        @Override
        protected Object getValue(String choice) throws IllegalArgumentException {
            final Optional<Key> ret = Sponge.getGame().getRegistry().getType(Key.class, choice);
            if (!ret.isPresent()) {
                throw new IllegalArgumentException("Invalid input " + choice + " was found");
            }
            currentKey.set(ret.get());
            return ret.get();
        }
    }, new CommandElement(Text.of("data")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            args.next();
            final String content = args.getRaw().substring(args.getRawPosition()).trim();
            while (args.hasNext()) {
                args.next();
            }
            final Object data;
            try {
                // Don't be too strict
                data = JsonDataFormat.read(content, true).orElse(null);
            } catch (IOException e) {
                throw args.createError(t("Invalid json data: %s\nError: %s", content, e.getMessage()));
            }
            final Key key = currentKey.get();
            final TypeToken<?> typeToken = key.getElementToken();
            if (content.isEmpty()) {
                return null;
            }
            final DataTypeSerializer dataTypeSerializer = Lantern.getGame().getDataManager().getTypeSerializer(typeToken).orElse(null);
            if (dataTypeSerializer == null) {
                throw args.createError(Text.of("Unable to deserialize the data key value: {}, " + "no supported deserializer exists.", key.getId()));
            } else {
                final DataTypeSerializerContext context = Lantern.getGame().getDataManager().getTypeSerializerContext();
                try {
                    // Put it in a holder object, the command element separates iterable objects
                    return new ValueHolder(dataTypeSerializer.deserialize(typeToken, context, data));
                } catch (InvalidDataException e) {
                    throw args.createError(t("Invalid data: %s", e.getMessage()));
                }
            }
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            return new ArrayList<>();
        }
    }).executor((src, args) -> {
        final Player target = args.<Player>getOne("player").get();
        final Key key = args.<Key>getOne("key").get();
        final Object data = args.<ValueHolder>getOne("data").get().data;
        target.offer(key, data);
        src.sendMessage(t("Successfully offered the data for the key %s to the player %s", key.getId(), target.getName()));
        return CommandResult.success();
    });
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) Player(org.spongepowered.api.entity.living.player.Player) CommandContext(org.spongepowered.api.command.args.CommandContext) DataTypeSerializerContext(org.lanternpowered.server.data.persistence.DataTypeSerializerContext) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CommandSource(org.spongepowered.api.command.CommandSource) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) InvalidDataException(org.spongepowered.api.data.persistence.InvalidDataException) CommandElement(org.spongepowered.api.command.args.CommandElement) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) Key(org.spongepowered.api.data.key.Key)

Aggregations

Key (org.spongepowered.api.data.key.Key)28 HashMap (java.util.HashMap)8 Map (java.util.Map)8 ArrayList (java.util.ArrayList)7 BlockState (org.spongepowered.api.block.BlockState)7 BaseValue (org.spongepowered.api.data.value.BaseValue)7 List (java.util.List)6 Optional (java.util.Optional)6 Sponge (org.spongepowered.api.Sponge)5 Text (org.spongepowered.api.text.Text)5 ImmutableSet (com.google.common.collect.ImmutableSet)4 Collection (java.util.Collection)4 BlockType (org.spongepowered.api.block.BlockType)4 ImmutableValue (org.spongepowered.api.data.value.immutable.ImmutableValue)4 World (org.spongepowered.api.world.World)4 Set (java.util.Set)3 DataTypeSerializer (org.lanternpowered.server.data.persistence.DataTypeSerializer)3 CommandContext (org.spongepowered.api.command.args.CommandContext)3 CommandElement (org.spongepowered.api.command.args.CommandElement)3 DataView (org.spongepowered.api.data.DataView)3