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;
}
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<>());
}
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;
}
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());
}
}
}
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();
});
}
Aggregations