Search in sources :

Example 1 with WeightedTable

use of org.spongepowered.api.util.weighted.WeightedTable in project modules-extra by CubeEngine.

the class Spawner method onInteract.

@Listener(order = POST)
public void onInteract(InteractBlockEvent.Secondary event, @First Player player) {
    if (!event.getTargetBlock().getLocation().isPresent()) {
        return;
    }
    Location<World> block = event.getTargetBlock().getLocation().get();
    if (block.getBlockType().equals(MOB_SPAWNER) && player.getItemInHand(MAIN_HAND).map(i -> i.getType().equals(ItemTypes.SPAWN_EGG)).orElse(false)) {
        event.setCancelled(true);
        if (block.get(SPAWNER_ENTITIES).map(RandomObjectTable::isEmpty).orElse(false)) {
            ItemStack itemInHand = player.getItemInHand(MAIN_HAND).get();
            EntityType type = itemInHand.get(Keys.SPAWNABLE_ENTITY_TYPE).get();
            Permission perm = this.perms.get(type);
            if (perm == null) {
                this.initPerm(type);
                perm = this.perms.get(type);
            }
            if (perm == null && !player.hasPermission(eggPerms.getId())) {
                i18n.send(ACTION_BAR, player, NEGATIVE, "Invalid SpawnEgg!");
                return;
            }
            if (perm != null && !player.hasPermission(perm.getId())) {
                i18n.send(ACTION_BAR, player, NEGATIVE, "You are not allowed to change Monster Spawner to this EntityType!");
                return;
            }
            WeightedTable<EntityArchetype> spawns = new WeightedTable<>();
            EntityArchetype nextSpawn = EntityArchetype.builder().type(type).build();
            spawns.add(nextSpawn, 1);
            block.offer(SPAWNER_ENTITIES, spawns);
            block.offer(SPAWNER_NEXT_ENTITY_TO_SPAWN, new WeightedSerializableObject<>(nextSpawn, 1));
            if (!player.gameMode().get().equals(CREATIVE)) {
                itemInHand.setQuantity(itemInHand.getQuantity() - 1);
                player.setItemInHand(MAIN_HAND, itemInHand);
            }
            i18n.send(ACTION_BAR, player, POSITIVE, "Monster Spawner activated!");
            return;
        }
        i18n.send(ACTION_BAR, player, NEGATIVE, "You can only change inactive Monster Spawner!");
    }
}
Also used : EntityType(org.spongepowered.api.entity.EntityType) WeightedTable(org.spongepowered.api.util.weighted.WeightedTable) EntityArchetype(org.spongepowered.api.entity.EntityArchetype) Permission(org.cubeengine.libcube.service.permission.Permission) World(org.spongepowered.api.world.World) ItemStack(org.spongepowered.api.item.inventory.ItemStack) Listener(org.spongepowered.api.event.Listener)

Example 2 with WeightedTable

use of org.spongepowered.api.util.weighted.WeightedTable in project SpongeAPI by SpongePowered.

the class ItemStackBuilderPopulators method values.

/**
 * Creates a new {@link BiConsumer} that applies a random selection of the
 * provided {@link BaseValue}s.
 *
 * <p>Note that custom data is not supported through this method, use
 * {@link #data(Collection)} or any variant thereof for applying custom data.</p>
 *
 * @param values The iterable collection of values to choose from
 * @param <E> The type of element
 * @param <V> The type of value
 * @return The new biconsumer to apply to an itemstack builder
 */
public static <E, V extends BaseValue<E>> BiConsumer<ItemStack.Builder, Random> values(Iterable<V> values) {
    WeightedTable<V> tableEntries = new WeightedTable<>(1);
    for (V value : values) {
        tableEntries.add(checkNotNull(value, "Value cannot be null!"), 1);
    }
    return ((builder, random) -> {
        final V value = tableEntries.get(random).get(0);
        final ItemStack itemStack = builder.build();
        final DataTransactionResult result = itemStack.offer(value);
        if (result.isSuccessful()) {
            builder.from(itemStack);
        }
    });
}
Also used : WeightedTable(org.spongepowered.api.util.weighted.WeightedTable) DataTransactionResult(org.spongepowered.api.data.DataTransactionResult)

Example 3 with WeightedTable

use of org.spongepowered.api.util.weighted.WeightedTable in project SpongeCommon by SpongePowered.

the class ItemStackData method register.

// @formatter:off
public static void register(final DataProviderRegistrator registrator) {
    registrator.asMutable(ItemStack.class).create(Keys.APPLICABLE_POTION_EFFECTS).get(h -> {
        if (h.isEdible()) {
            final List<Pair<MobEffectInstance, Float>> itemEffects = h.getItem().getFoodProperties().getEffects();
            final WeightedTable<PotionEffect> effects = new WeightedTable<>();
            final ChanceTable<PotionEffect> chance = new ChanceTable<>();
            for (final Pair<MobEffectInstance, Float> effect : itemEffects) {
                chance.add((PotionEffect) effect.getFirst(), effect.getSecond());
            }
            effects.add(new NestedTableEntry<>(1, chance));
            return effects;
        }
        return null;
    }).create(Keys.BURN_TIME).get(h -> {
        final Integer burnTime = AbstractFurnaceBlockEntity.getFuel().get(h.getItem());
        if (burnTime != null && burnTime > 0) {
            return burnTime;
        }
        return null;
    }).create(Keys.CAN_HARVEST).get(h -> {
        final Item item = h.getItem();
        if (item instanceof DiggerItemAccessor && !(item instanceof PickaxeItem)) {
            final Set<Block> blocks = ((DiggerItemAccessor) item).accessor$blocks();
            return ImmutableSet.copyOf((Set<BlockType>) (Object) blocks);
        }
        final Set<BlockType> blockTypes = Registry.BLOCK.stream().filter(b -> item.isCorrectToolForDrops(b.defaultBlockState())).map(BlockType.class::cast).collect(ImmutableSet.toImmutableSet());
        return blockTypes.isEmpty() ? null : blockTypes;
    }).create(Keys.CONTAINER_ITEM).get(h -> (ItemType) h.getItem().getCraftingRemainingItem()).create(Keys.DISPLAY_NAME).get(h -> SpongeAdventure.asAdventure(h.getDisplayName())).create(Keys.CUSTOM_MODEL_DATA).get(h -> {
        final CompoundTag tag = h.getTag();
        if (tag == null || !tag.contains(Constants.Item.CUSTOM_MODEL_DATA, Constants.NBT.TAG_INT)) {
            return null;
        }
        return tag.getInt(Constants.Item.CUSTOM_MODEL_DATA);
    }).set((h, v) -> {
        final CompoundTag tag = h.getOrCreateTag();
        tag.putInt(Constants.Item.CUSTOM_MODEL_DATA, v);
    }).delete(h -> {
        final CompoundTag tag = h.getTag();
        if (tag != null) {
            tag.remove(Constants.Item.CUSTOM_MODEL_DATA);
        }
    }).create(Keys.CUSTOM_NAME).get(h -> {
        if (h.hasCustomHoverName()) {
            return SpongeAdventure.asAdventure(h.getHoverName());
        }
        if (h.getItem() == Items.WRITTEN_BOOK) {
            // When no custom name is set on a written book fallback to its title
            // The custom name has a higher priority than the title so no setter is needed.
            final CompoundTag tag = h.getTag();
            if (tag != null) {
                final String title = tag.getString(Constants.Item.Book.ITEM_BOOK_TITLE);
                return LegacyComponentSerializer.legacySection().deserialize(title);
            }
        }
        return null;
    }).set((h, v) -> h.setHoverName(SpongeAdventure.asVanilla(v))).delete(ItemStack::resetHoverName).create(Keys.IS_UNBREAKABLE).get(h -> {
        final CompoundTag tag = h.getTag();
        if (tag == null || !tag.contains(Constants.Item.ITEM_UNBREAKABLE, Constants.NBT.TAG_BYTE)) {
            return false;
        }
        return tag.getBoolean(Constants.Item.ITEM_UNBREAKABLE);
    }).set(ItemStackData::setIsUnbrekable).delete(h -> ItemStackData.setIsUnbrekable(h, false)).create(Keys.LORE).get(h -> {
        final CompoundTag tag = h.getTag();
        if (tag == null || !tag.contains(Constants.Item.ITEM_DISPLAY)) {
            return null;
        }
        final CompoundTag displayCompound = tag.getCompound(Constants.Item.ITEM_DISPLAY);
        final ListTag list = displayCompound.getList(Constants.Item.ITEM_LORE, Constants.NBT.TAG_STRING);
        return list.isEmpty() ? null : SpongeAdventure.json(list.stream().collect(NBTCollectors.toStringList()));
    }).set((h, v) -> {
        if (v.isEmpty()) {
            ItemStackData.deleteLore(h);
            return;
        }
        final ListTag list = SpongeAdventure.listTagJson(v);
        h.getOrCreateTagElement(Constants.Item.ITEM_DISPLAY).put(Constants.Item.ITEM_LORE, list);
    }).delete(ItemStackData::deleteLore).create(Keys.MAX_DURABILITY).get(h -> h.getItem().canBeDepleted() ? h.getItem().getMaxDamage() : null).supports(h -> h.getItem().canBeDepleted()).create(Keys.ITEM_DURABILITY).get(stack -> stack.getMaxDamage() - stack.getDamageValue()).set((stack, durability) -> stack.setDamageValue(stack.getMaxDamage() - durability)).supports(h -> h.getItem().canBeDepleted()).create(Keys.ITEM_RARITY).get(stack -> (ItemRarity) (Object) stack.getRarity()).create(Keys.REPLENISHED_FOOD).get(h -> {
        if (h.getItem().isEdible()) {
            final FoodProperties food = h.getItem().getFoodProperties();
            return food == null ? null : food.getNutrition();
        }
        return null;
    }).supports(h -> h.getItem().isEdible()).create(Keys.REPLENISHED_SATURATION).get(h -> {
        if (h.getItem().isEdible()) {
            final FoodProperties food = h.getItem().getFoodProperties();
            if (food != null) {
                // Translate's Minecraft's weird internal value to the actual saturation value
                return food.getSaturationModifier() * food.getNutrition() * 2.0;
            }
        }
        return null;
    }).supports(h -> h.getItem().isEdible());
}
Also used : Items(net.minecraft.world.item.Items) DiggerItemAccessor(org.spongepowered.common.accessor.world.item.DiggerItemAccessor) Constants(org.spongepowered.common.util.Constants) StringTag(net.minecraft.nbt.StringTag) Item(net.minecraft.world.item.Item) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) PickaxeItem(net.minecraft.world.item.PickaxeItem) NestedTableEntry(org.spongepowered.api.util.weighted.NestedTableEntry) Registry(net.minecraft.core.Registry) PotionEffect(org.spongepowered.api.effect.potion.PotionEffect) LegacyComponentSerializer(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) FoodProperties(net.minecraft.world.food.FoodProperties) ImmutableSet(com.google.common.collect.ImmutableSet) ChanceTable(org.spongepowered.api.util.weighted.ChanceTable) Set(java.util.Set) MobEffectInstance(net.minecraft.world.effect.MobEffectInstance) SpongeCommon(org.spongepowered.common.SpongeCommon) Pair(com.mojang.datafixers.util.Pair) AbstractFurnaceBlockEntity(net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity) Keys(org.spongepowered.api.data.Keys) List(java.util.List) CompoundTag(net.minecraft.nbt.CompoundTag) ItemRarity(org.spongepowered.api.item.ItemRarity) NBTCollectors(org.spongepowered.common.util.NBTCollectors) DataProviderRegistrator(org.spongepowered.common.data.provider.DataProviderRegistrator) BlockType(org.spongepowered.api.block.BlockType) WeightedTable(org.spongepowered.api.util.weighted.WeightedTable) Block(net.minecraft.world.level.block.Block) ItemStack(net.minecraft.world.item.ItemStack) ItemType(org.spongepowered.api.item.ItemType) ListTag(net.minecraft.nbt.ListTag) PickaxeItem(net.minecraft.world.item.PickaxeItem) DiggerItemAccessor(org.spongepowered.common.accessor.world.item.DiggerItemAccessor) WeightedTable(org.spongepowered.api.util.weighted.WeightedTable) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) PotionEffect(org.spongepowered.api.effect.potion.PotionEffect) ItemType(org.spongepowered.api.item.ItemType) Item(net.minecraft.world.item.Item) PickaxeItem(net.minecraft.world.item.PickaxeItem) ChanceTable(org.spongepowered.api.util.weighted.ChanceTable) List(java.util.List) CompoundTag(net.minecraft.nbt.CompoundTag) Pair(com.mojang.datafixers.util.Pair) NestedTableEntry(org.spongepowered.api.util.weighted.NestedTableEntry) FoodProperties(net.minecraft.world.food.FoodProperties) MobEffectInstance(net.minecraft.world.effect.MobEffectInstance) ListTag(net.minecraft.nbt.ListTag) BlockType(org.spongepowered.api.block.BlockType) ItemStack(net.minecraft.world.item.ItemStack)

Example 4 with WeightedTable

use of org.spongepowered.api.util.weighted.WeightedTable in project SpongeCommon by SpongePowered.

the class SpawnerUtils method getEntities.

public static WeightedTable<EntityArchetype> getEntities(MobSpawnerBaseLogic logic) {
    WeightedTable<EntityArchetype> possibleEntities = new WeightedTable<>();
    for (WeightedSpawnerEntity weightedEntity : logic.potentialSpawns) {
        NBTTagCompound nbt = weightedEntity.getNbt();
        EntityType type = EntityUtil.fromNameToType(nbt.getString(NbtDataUtil.ENTITY_TYPE_ID)).orElse(EntityTypes.PIG);
        EntityArchetype archetype = EntityArchetype.builder().type(type).entityData(NbtTranslator.getInstance().translateFrom(nbt)).build();
        possibleEntities.add(new WeightedSerializableObject<>(archetype, weightedEntity.itemWeight));
    }
    return possibleEntities;
}
Also used : EntityType(org.spongepowered.api.entity.EntityType) WeightedTable(org.spongepowered.api.util.weighted.WeightedTable) EntityArchetype(org.spongepowered.api.entity.EntityArchetype) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) WeightedSpawnerEntity(net.minecraft.util.WeightedSpawnerEntity)

Example 5 with WeightedTable

use of org.spongepowered.api.util.weighted.WeightedTable in project LanternServer by LanternPowered.

the class LanternWeatherUniverse method nextWeather.

/**
 * Gets the next possible {@link LanternWeather}, ignoring
 * the last weather type.
 *
 * @return The next weather type
 */
@SuppressWarnings("unchecked")
private LanternWeather nextWeather() {
    final List<LanternWeather> weathers = new ArrayList(this.world.game.getRegistry().getAllOf(Weather.class));
    final LanternWeather current = this.weatherData.getWeather();
    weathers.remove(current);
    if (weathers.isEmpty()) {
        return current;
    }
    final WeightedTable<LanternWeather> table = new WeightedTable<>();
    weathers.forEach(weather -> table.add(weather, weather.getWeight()));
    return table.get(this.random).get(0);
}
Also used : Weather(org.spongepowered.api.world.weather.Weather) LanternWeather(org.lanternpowered.server.world.weather.LanternWeather) LanternWeather(org.lanternpowered.server.world.weather.LanternWeather) WeightedTable(org.spongepowered.api.util.weighted.WeightedTable) ArrayList(java.util.ArrayList)

Aggregations

WeightedTable (org.spongepowered.api.util.weighted.WeightedTable)7 EntityArchetype (org.spongepowered.api.entity.EntityArchetype)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Set (java.util.Set)2 CompoundTag (net.minecraft.nbt.CompoundTag)2 EntityType (org.spongepowered.api.entity.EntityType)2 Preconditions (com.google.common.base.Preconditions)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 Pair (com.mojang.datafixers.util.Pair)1 GenericTypeReflector (io.leangen.geantyref.GenericTypeReflector)1 TypeFactory (io.leangen.geantyref.TypeFactory)1 TypeToken (io.leangen.geantyref.TypeToken)1 ParameterizedType (java.lang.reflect.ParameterizedType)1 Type (java.lang.reflect.Type)1 Comparator (java.util.Comparator)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 Objects (java.util.Objects)1