Jump to content

Trying to register a Custom RecipeType and recipes [Forge 1.20.1]


ezShokkoh

Recommended Posts

Hi, what I'm trying to do is a Custom BlockEntity with 11 Input Slots + 1 Output Slot.
Here are my classes and json file, plus a screenshot of what the ingame menu looks like.

Ingame Menu Screenshot

Spoiler

image.png?ex=66e9e139&is=66e88fb9&hm=756

Block class

Spoiler
package com.yuseix.dragonminez.init.blocks.custom;

import com.yuseix.dragonminez.init.MainBlockEntities;
import com.yuseix.dragonminez.init.blocks.entity.KikonoArmorStationBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.DirectionProperty;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.network.NetworkHooks;
import org.jetbrains.annotations.Nullable;

public class KikonoArmorStationBlock extends BaseEntityBlock {
    public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING;
    protected static final VoxelShape WEST_AABB = Block.box(0.0D, 0.0D, -16.0D, 16.0D, 12.0D, 16.0D);
    protected static final VoxelShape EAST_AABB = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 12.0D, 32.0D);
    protected static final VoxelShape NORTH_AABB = Block.box(0.0D, 0.0D, 0.0D, 32.0D, 12.0D, 16.0D);
    protected static final VoxelShape SOUTH_AABB = Block.box(-16.0D, 0.0D, 0.0D, 16.0D, 12.0D, 16.0D);


    public KikonoArmorStationBlock(Properties pProperties) {
        super(pProperties);
    }

    @Override
    public VoxelShape getShape(BlockState pState, BlockGetter pLevel, BlockPos pPos, CollisionContext pContext) {
        switch ((Direction)pState.getValue(FACING)) {
            case NORTH:
                return SOUTH_AABB;
            case SOUTH:
                return NORTH_AABB;
            case WEST:                              
                return EAST_AABB;                   
            case EAST:                              
            default:                                
                return WEST_AABB;                   
        }
    }

    @Override
    public RenderShape getRenderShape(BlockState pState) {
        return RenderShape.MODEL;
    }

    @Override
    public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pMovedByPiston) {
        if (pState.getBlock() != pNewState.getBlock()) {
            BlockEntity blockEntity = pLevel.getBlockEntity(pPos);
            if (blockEntity instanceof KikonoArmorStationBlockEntity) {
                ((KikonoArmorStationBlockEntity) blockEntity).drops();
            }
        }
    }

    @Override
    public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand, BlockHitResult pHit) {
        if (!pLevel.isClientSide()) {
            BlockEntity entity = pLevel.getBlockEntity(pPos);
            if(entity instanceof KikonoArmorStationBlockEntity) {
                NetworkHooks.openScreen(((ServerPlayer) pPlayer), (KikonoArmorStationBlockEntity) entity, pPos);
            } else {
                throw new IllegalStateException("Named container provider missing!");
            }
        }
        return InteractionResult.sidedSuccess(pLevel.isClientSide());
    }

    @Override
    public @Nullable BlockEntity newBlockEntity(BlockPos pPos, BlockState pState) {
        return new KikonoArmorStationBlockEntity(pPos, pState);
    }

    @Override
    public @Nullable <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level pLevel, BlockState pState, BlockEntityType<T> pBlockEntityType) {
        if(pLevel.isClientSide()) {
            return null;
        }

        return createTickerHelper(pBlockEntityType, MainBlockEntities.KIKONO_ARMOR_STATION_BE.get(),
                ((pLevel1, pPos, pState1, pBlockEntity) -> pBlockEntity.tick(pLevel1, pPos, pState1)));
    }

    @Nullable
    @Override
    public BlockState getStateForPlacement(BlockPlaceContext pContext) {
        return this.defaultBlockState().setValue(FACING, pContext.getHorizontalDirection().getOpposite());
    }

    @Override
    public BlockState rotate(BlockState pState, Rotation pRotation) {
        return pState.setValue(FACING, pRotation.rotate(pState.getValue(FACING)));
    }

    @Override
    public BlockState mirror(BlockState pState, Mirror pMirror) {
        return pState.rotate(pMirror.getRotation(pState.getValue(FACING)));
    }

    @Override
    protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> pBuilder) {
        pBuilder.add(FACING);
    }
}

 


BlockEntity class

Spoiler
package com.yuseix.dragonminez.init.blocks.entity;

import com.yuseix.dragonminez.client.gui.KikonoArmorStationMenu;
import com.yuseix.dragonminez.init.MainBlockEntities;
import com.yuseix.dragonminez.recipes.ArmorStationRecipes;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.world.Containers;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.ContainerData;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Optional;

public class KikonoArmorStationBlockEntity extends BlockEntity implements MenuProvider {
    private final ItemStackHandler itemHandler = new ItemStackHandler(12);

    protected void onContentsChanged(int slot) {
        setChanged();
        if(!level.isClientSide()) {
            level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), 3);
        }
    }

    private static final int SLOT_1 = 0;
    private static final int SLOT_2 = 1;
    private static final int SLOT_3 = 2;
    private static final int SLOT_4 = 3;
    private static final int SLOT_5 = 4;
    private static final int SLOT_6 = 5;
    private static final int SLOT_7 = 6;
    private static final int SLOT_8 = 7;
    private static final int SLOT_9 = 8;
    private static final int PRESET = 9;
    private static final int ARMOR = 10;
    private static final int OUTPUT = 11;

    private LazyOptional<IItemHandler> lazyItemHandler = LazyOptional.empty();

    protected final ContainerData data;
    private int progress;
    private int maxProgress;

    public KikonoArmorStationBlockEntity(BlockPos pPos, BlockState pBlockState) {
        super(MainBlockEntities.KIKONO_ARMOR_STATION_BE.get(), pPos, pBlockState);
        this.data = new ContainerData() {
            @Override
            public int get(int pIndex) {
                return switch (pIndex) {
                    case 0 -> KikonoArmorStationBlockEntity.this.progress;
                    case 1 -> KikonoArmorStationBlockEntity.this.maxProgress;
                    default -> 0;
                };
            }

            @Override
            public void set(int pIndex, int pValue) {
                switch (pIndex) {
                    case 0 -> KikonoArmorStationBlockEntity.this.progress = pValue;
                    case 1 -> KikonoArmorStationBlockEntity.this.maxProgress = pValue;
                }
            }

            @Override
            public int getCount() {
                return 2;
            }
        };
    }

    @Override
    public @NotNull <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) {
        if(cap == ForgeCapabilities.ITEM_HANDLER) {
            return lazyItemHandler.cast();
        }
        return super.getCapability(cap, side);
    }

    @Override
    public void onLoad() {
        super.onLoad();
        lazyItemHandler = LazyOptional.of(() -> itemHandler);
    }

    @Override
    public void invalidateCaps() {
        super.invalidateCaps();
        lazyItemHandler.invalidate();
    }

    public void drops() {
        SimpleContainer inventory = new SimpleContainer(itemHandler.getSlots());
        for(int i = 0; i < itemHandler.getSlots(); i++) {
            inventory.setItem(i, itemHandler.getStackInSlot(i));
        }

        Containers.dropContents(this.level, this.worldPosition, inventory);
    }

    @Override
    public Component getDisplayName() {
        return Component.translatable("block.dragonminez.kikono_armor_station");
    }

    @Override
    public @Nullable AbstractContainerMenu createMenu(int pContainerId, Inventory pPlayerInventory, Player pPlayer) {
        return new KikonoArmorStationMenu(pContainerId, pPlayerInventory, this, this.data);
    }

    @Override
    protected void saveAdditional(CompoundTag pTag) {
        pTag.put("inventory", itemHandler.serializeNBT());
        pTag.putInt("kikono_armor_station.progress", progress);
        super.saveAdditional(pTag);
    }

    @Override
    public void load(CompoundTag pTag) {
        super.load(pTag);
        itemHandler.deserializeNBT(pTag.getCompound("inventory"));
        progress = pTag.getInt("kikono_armor_station.progress");
    }

    public void tick(Level pLevel, BlockPos pPos, BlockState pState) {
        if(hasRecipe()) {
            increaseCraftingProgress();
            setChanged(pLevel, pPos, pState);
            System.out.println("Progress: " + progress); // Metí souts para ver si esto funcionaba con las actualizaciones de los Ticks :p

            if(hasProgressFinished()) {
                craftItem();
                resetProgress();
                System.out.println("Crafted item");     // Nota: Esto debería funcionar, pero no toma la receta :v
            } else {
                resetProgress();
                System.out.println("Reset progress");
            }
        }
    }

    private void resetProgress() {
        progress = 0;
    }

    private void craftItem() {
        Optional<ArmorStationRecipes> recipe = getCurrentRecipe();
        ItemStack result = recipe.get().getResultItem(null);

        this.itemHandler.extractItem(SLOT_1, 1, false);
        this.itemHandler.extractItem(SLOT_2, 1, false);
        this.itemHandler.extractItem(SLOT_3, 1, false);
        this.itemHandler.extractItem(SLOT_4, 1, false);
        this.itemHandler.extractItem(SLOT_5, 1, false);
        this.itemHandler.extractItem(SLOT_6, 1, false);
        this.itemHandler.extractItem(SLOT_7, 1, false);
        this.itemHandler.extractItem(SLOT_8, 1, false);
        this.itemHandler.extractItem(SLOT_9, 1, false);
        this.itemHandler.extractItem(PRESET, 1, false);
        this.itemHandler.extractItem(ARMOR, 1, false);

        this.itemHandler.setStackInSlot(OUTPUT, new ItemStack(result.getItem(),
                this.itemHandler.getStackInSlot(OUTPUT).getCount() + result.getCount()));
    }

    private boolean hasProgressFinished() {
        return progress >= maxProgress;
    }

    private void increaseCraftingProgress() {
        progress++;
    }

    private boolean hasRecipe() {
        Optional<ArmorStationRecipes> recipe = getCurrentRecipe();

        if(recipe.isEmpty()) {
            return false;
        }
        ItemStack result = recipe.get().getResultItem(getLevel().registryAccess());

        return recipe.isPresent() && canInsertAmountIntoOutputSlot(result.getCount()) && canInsertItemIntoOutputSlot(result.getItem());
    }

    private boolean canInsertItemIntoOutputSlot(Item item) {
        return this.itemHandler.getStackInSlot(OUTPUT).isEmpty() || this.itemHandler.getStackInSlot(OUTPUT).is(item);
    }

    private boolean canInsertAmountIntoOutputSlot(int count) {
        return this.itemHandler.getStackInSlot(OUTPUT).getCount() + count <= this.itemHandler.getStackInSlot(OUTPUT).getMaxStackSize();
    }

    private Optional<ArmorStationRecipes> getCurrentRecipe() {
        SimpleContainer inventory = new SimpleContainer(this.itemHandler.getSlots());
        for(int i = 0; i <  itemHandler.getSlots(); i++) {
            inventory.setItem(i, itemHandler.getStackInSlot(i));
        }

        return this.level.getRecipeManager().getRecipeFor(ArmorStationRecipes.Type.INSTANCE, inventory, level);
    }

    @Nullable
    @Override
    public Packet<ClientGamePacketListener> getUpdatePacket() {
        return ClientboundBlockEntityDataPacket.create(this);
    }

    @Override
    public CompoundTag getUpdateTag() {
        return saveWithoutMetadata();
    }
}

 

RecipeType class

Spoiler
package com.yuseix.dragonminez.recipes;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.yuseix.dragonminez.DragonMineZ;
import net.minecraft.core.NonNullList;
import net.minecraft.core.RegistryAccess;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.*;
import net.minecraft.world.level.Level;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.jetbrains.annotations.Nullable;

public class ArmorStationRecipes implements Recipe<SimpleContainer> {
   private final NonNullList<Ingredient> inputItems;
   private final ItemStack outputItem;
   private final ResourceLocation id;

    public ArmorStationRecipes(NonNullList<Ingredient> inputItems, ItemStack outputItem, ResourceLocation id) {
        this.inputItems = inputItems;
        this.outputItem = outputItem;
        this.id = id;
    }

    @Override
    public boolean matches(SimpleContainer pContainer, Level pLevel) {
        if(pLevel.isClientSide()) {
            return false;
        }
        for (int i = 0; i < 9; i++) {
            if (!inputItems.get(i).test(pContainer.getItem(i))) {
                return false;  // Si algún item no coincide, no se cumple la receta
            }
        }
        // Slots separados pa ordenar nama :p
        if(!inputItems.get(9).test(pContainer.getItem(9))) {
            return false;  // PRESET_SLOT
        }
        if(!inputItems.get(10).test(pContainer.getItem(10))) {
            return false;  // ARMOR_SLOT
        }
        return true;
    }

    @Override
    public ItemStack assemble(SimpleContainer pContainer, RegistryAccess pRegistryAccess) {
        return outputItem.copy();
    }

    @Override
    public boolean canCraftInDimensions(int pWidth, int pHeight) {
        return true;
    }

    @Override
    public ItemStack getResultItem(RegistryAccess pRegistryAccess) {
        return outputItem.copy();
    }

    @Override
    public ResourceLocation getId() {
        return id;
    }

    @Override
    public RecipeSerializer<?> getSerializer() {
        return Serializer.INSTANCE;
    }

    @Override
    public RecipeType<?> getType() {
        return Type.INSTANCE;
    }

    public static class Type implements RecipeType<ArmorStationRecipes> {
        public static final Type INSTANCE = new Type();
        public static final String ID = "armor_station";
    }

    public static class Serializer implements RecipeSerializer<ArmorStationRecipes> {
        public static final Serializer INSTANCE = new Serializer();
        public static final ResourceLocation ID = new ResourceLocation(DragonMineZ.MOD_ID, "armor_station");

        @Override
        public ArmorStationRecipes fromJson(ResourceLocation pRecipeId, JsonObject pSerializedRecipe) {
            JsonArray slot1 = GsonHelper.getAsJsonArray(pSerializedRecipe, "slot_1");
            JsonArray slot2 = GsonHelper.getAsJsonArray(pSerializedRecipe, "slot_2");
            JsonArray slot3 = GsonHelper.getAsJsonArray(pSerializedRecipe, "slot_3");
            JsonArray slot4 = GsonHelper.getAsJsonArray(pSerializedRecipe, "slot_4");
            JsonArray slot5 = GsonHelper.getAsJsonArray(pSerializedRecipe, "slot_5");
            JsonArray slot6 = GsonHelper.getAsJsonArray(pSerializedRecipe, "slot_6");
            JsonArray slot7 = GsonHelper.getAsJsonArray(pSerializedRecipe, "slot_7");
            JsonArray slot8 = GsonHelper.getAsJsonArray(pSerializedRecipe, "slot_8");
            JsonArray slot9 = GsonHelper.getAsJsonArray(pSerializedRecipe, "slot_9");
            JsonArray presetItem = GsonHelper.getAsJsonArray(pSerializedRecipe, "preset");
            JsonArray armorItem = GsonHelper.getAsJsonArray(pSerializedRecipe, "armor");
            ItemStack outputItem = ShapedRecipe.itemStackFromJson(GsonHelper.getAsJsonObject(pSerializedRecipe, "output"));
            NonNullList<Ingredient> inputs = NonNullList.withSize(11, Ingredient.EMPTY);

            inputs.set(0, Ingredient.fromJson(slot1));
            inputs.set(1, Ingredient.fromJson(slot2));
            inputs.set(2, Ingredient.fromJson(slot3));
            inputs.set(3, Ingredient.fromJson(slot4));
            inputs.set(4, Ingredient.fromJson(slot5));
            inputs.set(5, Ingredient.fromJson(slot6));
            inputs.set(6, Ingredient.fromJson(slot7));
            inputs.set(7, Ingredient.fromJson(slot8));
            inputs.set(8, Ingredient.fromJson(slot9));
            inputs.set(9, Ingredient.fromJson(presetItem));
            inputs.set(10, Ingredient.fromJson(armorItem));

            return new ArmorStationRecipes(inputs, outputItem, pRecipeId);
        }

        @Override
        public @Nullable ArmorStationRecipes fromNetwork(ResourceLocation pRecipeId, FriendlyByteBuf pBuffer) {
            NonNullList<Ingredient> inputs = NonNullList.withSize(pBuffer.readInt(), Ingredient.EMPTY);

            for(int i = 0; i < inputs.size(); i++) {
                inputs.set(i, Ingredient.fromNetwork(pBuffer));
            }

            ItemStack outputItem = pBuffer.readItem();
            return new ArmorStationRecipes(inputs, outputItem, pRecipeId);
        }

        @Override
        public void toNetwork(FriendlyByteBuf pBuffer, ArmorStationRecipes pRecipe) {
            pBuffer.writeInt(pRecipe.inputItems.size());

            for (Ingredient ingredient : pRecipe.getIngredients()) {
                ingredient.toNetwork(pBuffer);
            }

            pBuffer.writeItemStack(pRecipe.getResultItem(null), false);
        }
    }

}

 

Recipe json file
 

Spoiler
{
  "type": "dragonminez:armor_station",
  "slot_1": {
    "item": "minecraft:blue_dye"
  },
  "slot_2": {
    "item": "minecraft:paper"
  },
  "slot_3": {
    "item": "minecraft:blue_dye"
  },
  "slot_4": {
    "item": "minecraft:orange_dye"
  },
  "slot_5": {
    "item": "minecraft:blue_dye"
  },
  "slot_6": {
    "item": "minecraft:orange_dye"
  },
  "slot_7": {
    "item": "minecraft:orange_dye"
  },
  "slot_8": {
    "item": "minecraft:orange_dye"
  },
  "slot_9": {
    "item": "minecraft:orange_dye"
  },
  "preset": {
    "item": "minecraft:paper"
  },
  "armor": {
    "item": "minecraft:iron_chestplate"
  },
  "output": {
    "Count": 1,
    "item": "dragonminez:goku_armor_chestplate"
  }
}

 


Don't know if also the Menu and Screen classes are needed, if so, let me know and I'll post it.
Thanks in advance.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.