Jump to content

Recommended Posts

Posted

I'm rather new to modding and I want to create a tech mod. I was using for all my machines FE but it seems like I've been doing something wrong because it doesn't work with other mods that use FE. My implementation works like this:

I have a machine tile entity that has an energy storage as the capability. When it's an energy generator it has a max receive of 0 and a max extract of a non 0 number. If it is a energy consumer it has a max receive of a non 0 number and a max extract of 0. My cable check if there's a tile entitiy with energy capability and remove/give it energy based on the max receive and max extract.

I tried to use one of my generators with my cable and connected it with a Mekanism machine. But it seems like the Mekansim machine has a max receive of 0 so my cable doesn't give any energy to it.

What have I understood wong?

Posted

In the TileEntity:

public abstract class CoalGeneratorTileEntity extends TileEntity implements INamedContainerProvider {

    protected ITextComponent customName;
    protected I inventory;
	protected BaseEnergyStorage energy = new BaseEnergyStorage(getCapacity(), getMaxReceive(), getMaxExtract(), getStartEnergy());
 	public int currentProcessingTime;
	protected boolean isProcessing = false;

    public static final String CURRENT_PROCESSING_TIME = "CurrentProcessingTime";
    public static final String CUSTOM_NAME = "CustomName";

    public CoalGeneratorTileEntity(TileEntityType<?> tileEntityTypeIn) {
        super(tileEntityTypeIn);
		inventory = new BaseItemHandler(1);
    }

	@Override
    public Container createMenu(int windowId, PlayerInventory playerInventory, PlayerEntity player) {
        return new CoalGeneratorContainer(windowId, playerInventory, this, ModContainerTypes.COAL_GENERATOR);
    }

    @Override
    public ITextComponent getDisplayName() {
        return getName();
    }

    public void setCustomName(ITextComponent name) {
        customName = name;
    }

    public ITextComponent getName() {
        return customName != null ? customName : getDefaultName();
    }

    private ITextComponent getDefaultName() {
        return new TranslationTextComponent("container." + TodayAndTomorrow.MOD_ID + "." + "coal_generator");
    }

    @Override
    public void read(CompoundNBT compound) {
        super.read(compound);
        if (compound.contains(CUSTOM_NAME, Constants.NBT.TAG_STRING)) {
            customName = ITextComponent.Serializer.fromJson(compound.getString(CUSTOM_NAME));
        }
        NonNullList<ItemStack> inv = NonNullList.withSize(inventory.getSlots(), ItemStack.EMPTY);
        ItemStackHelper.loadAllItems(compound, inv);
        inventory.setNonNullList(inv);
		energy.readFromNBT(compound);
		currentProcessingTime = compound.getInt(CURRENT_PROCESSING_TIME);
    }

    @Override
    public CompoundNBT write(CompoundNBT compound) {
        super.write(compound);
        if (customName != null) {
            compound.putString("CustomName", ITextComponent.Serializer.toJson(this.customName));
        }

        ItemStackHelper.saveAllItems(compound, inventory.toNonNullList());
		energy.writeToNBT(compound);
		compound.putInt(CURRENT_PROCESSING_TIME, currentProcessingTime);
        return compound;
    }

    public I getInventory() {
        return inventory;
    }

    @Override
    public SUpdateTileEntityPacket getUpdatePacket() {
        CompoundNBT nbt = new CompoundNBT();
        this.write(nbt);
        return new SUpdateTileEntityPacket(this.pos, 0, nbt);
    }

    @Override
    public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt) {
        this.read(pkt.getNbtCompound());
    }

    @Override
    public CompoundNBT getUpdateTag() {
        CompoundNBT nbt = new CompoundNBT();
        this.write(nbt);
        return nbt;
    }

    @Override
    public void handleUpdateTag(CompoundNBT nbt) {
        this.read(nbt);
    }

    @Override
    public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
        LazyOptional<T> inventory = CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.orEmpty(cap, LazyOptional.of(() -> inventory));
		if (inventory.isPresent()) {
            return inventory;
        }
        return CapabilityEnergy.ENERGY.orEmpty(cap, LazyOptional.of(() -> energy));
    }

    @Override
    public Container createMenu(int windowId, PlayerInventory playerInventory, PlayerEntity player) {
        return createMenu(windowId, playerInventory, player);
    }

	@Override
    public void tick() {
        boolean dirty = false;

        if (world != null && !world.isRemote()) {
            if ((energy.getMaxEnergyStored() > energy.getEnergyStored() && inventory.getStackInSlot(0).getCount() > 0)
				|| isProcessing) {
                if (currentProcessingTime < getProcessingTime()) {
                    if (currentProcessingTime == 0) {
                        inventory.decrStackSize(0, 1);
        				isProcessing = true;
                    }
                    energy.receiveEnergyRaw(ENERGY_PER_TICK, false);
                    setLit(true);
                    currentProcessingTime++;
                    dirty = true;
                } else {
                    currentProcessingTime = 0;
                    isProcessing = false;
                }
            } else {
                currentProcessingTime = 0;
                setLit(false);
            }
        }

        if (dirty) {
            markDirty();
            world.notifyBlockUpdate(getPos(), getBlockState(), getBlockState(), Constants.BlockFlags.BLOCK_UPDATE);
        }
    }

    protected void setLit(boolean lit) {
        if (getBlockState().getBlock() instanceof LitGuiBlock) {
            world.setBlockState(getPos(), getBlockState().with("lit", lit));
        }
    }
}

BaseEnergyStorage is a class that extends EnergyStorage.

 

In the wire I've gone through all connected wires and checked if a tile entity with energy capacity is there.

public class CopperWireTileEntity extends TileEntity implements ITickableTileEntity {

    boolean[] machineAt = new boolean[6];

    public CopperWireTileEntity(TileEntityType<?> tileEntityTypeIn) {
        super(tileEntityTypeIn);

        Arrays.fill(machineAt, false);
    }

    public CopperWireTileEntity() {
        this(ModTileEntityTypes.COPPER_WIRE.get());
    }

    @Override
    public void tick() {
        updateSide(0, getPos().north(), Direction.NORTH);
        updateSide(1, getPos().east(), Direction.EAST);
        updateSide(2, getPos().south(), Direction.SOUTH);
        updateSide(3, getPos().west(), Direction.WEST);
        updateSide(4, getPos().up(), Direction.UP);
        updateSide(5, getPos().down(), Direction.DOWN);

        int energyAvailable = getEnergyAvailable();
        if (energyAvailable != 0) {
            int takeAway = scatterEnergy(energyAvailable);
            takeAwayEnergy(takeAway, energyAvailable);
        }
    }

    protected void updateSide(int index, BlockPos pos, Direction direction) {
        if (!machineAt[index]) {
            TileEntity tileEntity = world.getTileEntity(pos);
            if (tileEntity != null && tileEntity.getCapability(CapabilityEnergy.ENERGY).isPresent()) {
                machineAt[index] = true;
            }
        } else if (world.getBlockState(pos).getBlock() == Blocks.AIR) {
            machineAt[index] = false;
        }
    }

    protected int getEnergyAvailable() {
        AtomicInteger energyAvailable = new AtomicInteger();
        for (int i = 0; i < machineAt.length; i++) {
            if (machineAt[i]) {
                world.getTileEntity(getBlockPosByIndex(pos, i)).getCapability(CapabilityEnergy.ENERGY).ifPresent((e) -> energyAvailable.addAndGet(e.extractEnergy(Integer.MAX_VALUE, true)));
            }
        }
        return energyAvailable.get();
    }

    protected int scatterEnergy(int energyAvailable) {
        ArrayList<BlockPos> visited = new ArrayList<>();
        ArrayList<IEnergyStorage> outputMachinePositions = new ArrayList<>();
        getOutputMachinesEnergy(getPos(), visited, outputMachinePositions);

        int maxReceives = 0;
        for (IEnergyStorage energy : outputMachinePositions) {
            maxReceives += energy.receiveEnergy(Integer.MAX_VALUE, true);
        }

        if (maxReceives <= energyAvailable) {
            for (IEnergyStorage energy : outputMachinePositions) {
                int sent = energy.receiveEnergy(Integer.MAX_VALUE, false);
            }
            return maxReceives;
        }

        int energyGiven = 0;
        for (IEnergyStorage energy : outputMachinePositions) {
            int energyNeeded = energy.receiveEnergy(Integer.MAX_VALUE, true);
            int energyToGive = (int)((float)energyNeeded / (float)maxReceives * (float)energyAvailable);
            energyGiven += energyToGive;
            int a = energy.receiveEnergy(energyToGive, false);
        }

        return energyGiven;
    }

    protected void takeAwayEnergy(int takeAway, int energyAvailable) {
        for (int i = 0; i < machineAt.length; i++) {
            if (machineAt[i]) {
                world.getTileEntity(getBlockPosByIndex(pos, i)).getCapability(CapabilityEnergy.ENERGY).ifPresent((e) -> {
                    int energyProviding = e.extractEnergy(Integer.MAX_VALUE, true);
                    int energyToTakeAway = (int)((float)energyProviding / (float)energyAvailable * (float)takeAway);
                    e.extractEnergy(energyToTakeAway, false);
                });
            }
        }
    }

    protected void getOutputMachinesEnergy(BlockPos pos, ArrayList<BlockPos> visited, ArrayList<IEnergyStorage> outEnergies) {
        if (!visited.contains(pos)) {
            if (world.getBlockState(pos).getBlock() == BlockInit.COPPER_WIRE.get()) {
                visited.add(pos);
                getOutputMachinesEnergy(pos.north(), visited, outEnergies);
                getOutputMachinesEnergy(pos.east(), visited, outEnergies);
                getOutputMachinesEnergy(pos.south(), visited, outEnergies);
                getOutputMachinesEnergy(pos.west(), visited, outEnergies);
                getOutputMachinesEnergy(pos.up(), visited, outEnergies);
                getOutputMachinesEnergy(pos.down(), visited, outEnergies);
            } else if (world.getTileEntity(pos) != null && world.getTileEntity(pos).getCapability(CapabilityEnergy.ENERGY).isPresent()) {
                AtomicReference<IEnergyStorage> energy = new AtomicReference<>();
                world.getTileEntity(pos).getCapability(CapabilityEnergy.ENERGY).ifPresent(energy::set);
                outEnergies.add(energy.get());
            }
        }
    }

    protected BlockPos getBlockPosByIndex(BlockPos pos, int index) {
        switch (index) {
            case 0:
                return pos.north();
            case 1:
                return pos.east();
            case 2:
                return pos.south();
            case 3:
                return pos.west();
            case 4:
                return pos.up();
            case 5:
                return pos.down();
        }
        throw new IllegalArgumentException("Invalid index: " + index);
    }
}

I thought that the energy consuming machines from other Mods would have EnergyStorge with maxReceive from more that 0 so that I could give them energy. But when i tested it with Mekansim:

int energyNeeded = energy.receiveEnergy(Integer.MAX_VALUE, true);

and energyNeeded was 0 so the wire didn't extract any energy.

Posted
  On 10/31/2020 at 3:46 PM, loordgek said:
Expand  

Thank you! Using this method fixed many bugs. I also figured out that the generator should give the cable the energy instead of the cable taking away energy from the generator. After I fixed that everthing worked.

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



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Hi everyone, I'm currently developing a Forge 1.21 mod for Minecraft and I want to display a custom HUD overlay for a minigame. My goal: When the game starts, all players should see an item/block icon (from the base game, not a custom texture) plus its name/text in the HUD – similar to how the bossbar overlay works. The HUD should appear centered above the hotbar (or at a similar prominent spot), and update dynamically (icon and name change as the target item changes). What I've tried: I looked at many online tutorials and several GitHub repos (e.g. SeasonHUD, MiniHUD), but most of them use NeoForge or Forge versions <1.20 that provide the IGuiOverlay API (e.g. implements IGuiOverlay, RegisterGuiOverlaysEvent). In Forge 1.21, it seems that neither IGuiOverlay nor RegisterGuiOverlaysEvent exist anymore – at least, I can't import them and they are missing from the docs and code completion. I tried using RenderLevelStageEvent as a workaround but it is probably not intended for custom HUDs. I am not using NeoForge, and switching the project to NeoForge is currently not an option for me. I tried to look at the original minecraft source code to see how elements like hearts, hotbar etc are drawn on the screen but I am too new to Minecraft modding to understand. What I'm looking for: What is the correct way to add a custom HUD element (icon + text) in Forge 1.21, given that the previous overlay API is missing? Is there a new recommended event, callback, or method in Forge 1.21 for custom HUD overlays, or is everyone just using a workaround? Is there a minimal open-source example repo for Forge 1.21 that demonstrates a working HUD overlay without relying on NeoForge or deprecated Forge APIs? My ideal solution: Centered HUD element with an in-game item/block icon (from the base game's assets, e.g. a diamond or any ItemStack / Item) and its name as text, with a transparent background rectangle. It should be visible to the players when the mini game is running. Easy to update the item (e.g. static variable or other method), so it can change dynamically during the game. Any help, code snippets, or up-to-date references would be really appreciated! If this is simply not possible right now in Forge 1.21, it would also help to know that for sure. Thank you very much in advance!
    • The simple answer is there is not an easy way. You would need to know how to program in Java, as well as at least some familiarity with how Forge works so you could port the differences. You would also need the sourcecode for the original mod, and permission from the author to modify it, if they did not use some sort of open source license. So it's not impossible, but it would take some effort, but doing so would open up a whole new world of possibilities for you!
    • Does it still crash if you remove holdmyitems? Looks like that mod doesn't work on a server as far as I can tell from the error.  
    • Crashes the server when trying to start. Error code -1. Log  
  • Topics

×
×
  • Create New...

Important Information

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