More sorting work.

This commit is contained in:
drcrazy 2018-04-27 18:15:56 +03:00
parent de61d24082
commit 649a6bf67f
10 changed files with 10 additions and 10 deletions

View file

@ -0,0 +1,476 @@
/*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2018 TechReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package techreborn.tiles.tier1;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundCategory;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import org.apache.commons.lang3.tuple.Pair;
import reborncore.api.IToolDrop;
import reborncore.api.tile.IInventoryProvider;
import reborncore.common.powerSystem.TilePowerAcceptor;
import reborncore.common.registration.RebornRegistry;
import reborncore.common.registration.impl.ConfigRegistry;
import reborncore.common.util.Inventory;
import reborncore.common.util.ItemUtils;
import techreborn.client.container.IContainerProvider;
import techreborn.client.container.builder.BuiltContainer;
import techreborn.client.container.builder.ContainerBuilder;
import techreborn.init.ModBlocks;
import techreborn.init.ModSounds;
import techreborn.lib.ModInfo;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by modmuss50 on 20/06/2017.
*/
@RebornRegistry(modID = ModInfo.MOD_ID)
public class TileAutoCraftingTable extends TilePowerAcceptor
implements IToolDrop, IInventoryProvider, IContainerProvider {
@ConfigRegistry(config = "machines", category = "autocrafter", key = "AutoCrafterInput", comment = "AutoCrafting Table Max Input (Value in EU)")
public static int maxInput = 32;
@ConfigRegistry(config = "machines", category = "autocrafter", key = "AutoCrafterMaxEnergy", comment = "AutoCrafting Table Max Energy (Value in EU)")
public static int maxEnergy = 10_000;
ResourceLocation currentRecipe;
public Inventory inventory = new Inventory(11, "TileAutoCraftingTable", 64, this);
public int progress;
public int maxProgress = 120;
public int euTick = 10;
public Pair<ResourceLocation, IRecipe> cachedRecipe;
public boolean customRecipe = false;
InventoryCrafting inventoryCrafting = null;
IRecipe lastCustomRecipe = null;
public TileAutoCraftingTable() {
super();
}
public void setCurrentRecipe(IRecipe recipe, boolean customRecipe) {
if (recipe != null) {
currentRecipe = recipe.getRegistryName();
} else {
currentRecipe = null;
}
// Disabled due to performance issues
//this.customRecipe = customRecipe;
this.customRecipe = false;
cachedRecipe = null;
}
public void setCurrentRecipe(ResourceLocation recipe, boolean customRecipe) {
currentRecipe = recipe;
// Disabled due to performance issues
//this.customRecipe = customRecipe;
this.customRecipe = false;
cachedRecipe = null;
}
@Nullable
public IRecipe getIRecipe() {
if (customRecipe) {
InventoryCrafting crafting = getCraftingInventory();
if(!crafting.isEmpty()){
for (IRecipe testRecipe : CraftingManager.REGISTRY) {
if (testRecipe.matches(crafting, world)) {
return testRecipe;
}
}
}
}
if (currentRecipe == null) {
return null;
}
if (cachedRecipe == null || !cachedRecipe.getLeft().equals(currentRecipe)) {
IRecipe recipe = ForgeRegistries.RECIPES.getValue(currentRecipe);
if (recipe != null) {
cachedRecipe = Pair.of(currentRecipe, recipe);
return recipe;
}
cachedRecipe = null;
return null;
}
return cachedRecipe.getRight();
}
public InventoryCrafting getCraftingInventory() {
if (inventoryCrafting == null) {
inventoryCrafting = new InventoryCrafting(new Container() {
@Override
public boolean canInteractWith(EntityPlayer playerIn) {
return false;
}
}, 3, 3);
}
for (int i = 0; i < 9; i++) {
inventoryCrafting.setInventorySlotContents(i, inventory.getStackInSlot(i));
}
return inventoryCrafting;
}
public boolean canMake(IRecipe recipe) {
if (customRecipe) {
recipe = getIRecipe();
}
if (recipe != null && recipe.canFit(3, 3)) {
boolean missingOutput = false;
int[] stacksInSlots = new int[9];
for (int i = 0; i < 9; i++) {
stacksInSlots[i] = inventory.getStackInSlot(i).getCount();
}
for (Ingredient ingredient : recipe.getIngredients()) {
if (ingredient != Ingredient.EMPTY) {
boolean foundIngredient = false;
for (int i = 0; i < 9; i++) {
ItemStack stack = inventory.getStackInSlot(i);
int requiredSize = customRecipe ? 1 : 0;
if(stack.getMaxStackSize() == 1){
requiredSize = 0;
}
if (stacksInSlots[i] > requiredSize) {
if (ingredient.apply(stack)) {
if(stack.getItem().getContainerItem() != null){
if(!hasRoomForExtraItem(stack.getItem().getContainerItem(stack))){
continue;
}
}
foundIngredient = true;
stacksInSlots[i]--;
break;
}
}
}
if (!foundIngredient) {
missingOutput = true;
}
}
}
if (!missingOutput) {
if (hasOutputSpace(recipe.getRecipeOutput(), 9)) {
return true;
}
}
return false;
}
return false;
}
boolean hasRoomForExtraItem(ItemStack stack){
ItemStack extraOutputSlot = getStackInSlot(10);
if(extraOutputSlot.isEmpty()){
return true;
}
return hasOutputSpace(stack, 10);
}
public boolean hasOutputSpace(ItemStack output, int slot) {
ItemStack stack = inventory.getStackInSlot(slot);
if (stack.isEmpty()) {
return true;
}
if (ItemUtils.isItemEqual(stack, output, true, true)) {
if (stack.getMaxStackSize() > stack.getCount() + output.getCount()) {
return true;
}
}
return false;
}
public boolean make(IRecipe recipe) {
IRecipe recipe2 = recipe;
if (canMake(recipe2)) {
if (recipe2 == null && customRecipe) {
if (lastCustomRecipe == null) {
return false;
}//Should be uptodate as we just set it in canMake
recipe = lastCustomRecipe;
}
else if (recipe2 != null) {
for (int i = 0; i < recipe2.getIngredients().size(); i++) {
Ingredient ingredient = recipe2.getIngredients().get(i);
//Looks for the best slot to take it from
ItemStack bestSlot = inventory.getStackInSlot(i);
if (ingredient.apply(bestSlot)) {
handleContainerItem(bestSlot);
bestSlot.shrink(1);
} else {
for (int j = 0; j < 9; j++) {
ItemStack stack = inventory.getStackInSlot(j);
if (ingredient.apply(stack)) {
handleContainerItem(stack);
stack.shrink(1); //TODO is this right? or do I need to use it as an actull crafting grid
break;
}
}
}
}
ItemStack output = inventory.getStackInSlot(9);
//TODO fire forge recipe event
ItemStack ouputStack = recipe2.getCraftingResult(getCraftingInventory());
if (output.isEmpty()) {
inventory.setInventorySlotContents(9, ouputStack.copy());
} else {
//TODO use ouputStack in someway?
output.grow(recipe2.getRecipeOutput().getCount());
}
return true;
}
}
return false;
}
private void handleContainerItem(ItemStack stack){
if(stack.getItem().hasContainerItem(stack)){
ItemStack containerItem = stack.getItem().getContainerItem(stack);
ItemStack extraOutputSlot = getStackInSlot(10);
if(hasOutputSpace(containerItem, 10)){
if(extraOutputSlot.isEmpty()){
setInventorySlotContents(10, containerItem.copy());
} else if(ItemUtils.isItemEqual(extraOutputSlot, containerItem, true, true) && extraOutputSlot.getMaxStackSize() < extraOutputSlot.getCount() + containerItem.getCount()) {
extraOutputSlot.grow(1);
}
}
}
}
public boolean hasIngredient(Ingredient ingredient) {
for (int i = 0; i < 9; i++) {
ItemStack stack = inventory.getStackInSlot(i);
if (ingredient.apply(stack)) {
return true;
}
}
return false;
}
public boolean isItemValidForRecipeSlot(IRecipe recipe, ItemStack stack, int slotID) {
if (recipe == null) {
return true;
}
int bestSlot = findBestSlotForStack(recipe, stack);
if (bestSlot != -1) {
return bestSlot == slotID;
}
return true;
}
public int findBestSlotForStack(IRecipe recipe, ItemStack stack) {
if (recipe == null) {
return -1;
}
List<Integer> possibleSlots = new ArrayList<>();
for (int i = 0; i < recipe.getIngredients().size(); i++) {
ItemStack stackInSlot = inventory.getStackInSlot(i);
Ingredient ingredient = recipe.getIngredients().get(i);
if (ingredient != Ingredient.EMPTY && ingredient.apply(stack)) {
if (stackInSlot.isEmpty()) {
possibleSlots.add(i);
} else if (stackInSlot.getItem() == stack.getItem() && stackInSlot.getItemDamage() == stack.getItemDamage()) {
if (stackInSlot.getMaxStackSize() >= stackInSlot.getCount() + stack.getCount()) {
possibleSlots.add(i);
}
}
}
}
//Slot, count
Pair<Integer, Integer> smallestCount = null;
for (Integer slot : possibleSlots) {
ItemStack slotStack = inventory.getStackInSlot(slot);
if (slotStack.isEmpty()) {
return slot;
}
if (smallestCount == null) {
smallestCount = Pair.of(slot, slotStack.getCount());
} else if (smallestCount.getRight() >= slotStack.getCount()) {
smallestCount = Pair.of(slot, slotStack.getCount());
}
}
if (smallestCount != null) {
return smallestCount.getLeft();
}
return -1;
}
public int getProgress() {
return progress;
}
public void setProgress(int progress) {
this.progress = progress;
}
public int getMaxProgress() {
if (maxProgress == 0) {
maxProgress = 1;
}
return maxProgress;
}
public void setMaxProgress(int maxProgress) {
this.maxProgress = maxProgress;
}
// TilePowerAcceptor
@Override
public void update() {
super.update();
if (world.isRemote) {
return;
}
IRecipe recipe = getIRecipe();
if (recipe != null || customRecipe) {
if (progress >= maxProgress) {
if (make(recipe)) {
progress = 0;
}
} else {
if (canMake(recipe)) {
if (canUseEnergy(euTick)) {
progress++;
if(progress == 1){
world.playSound(null, pos.getX(), pos.getY(),
pos.getZ(), ModSounds.AUTO_CRAFTING,
SoundCategory.BLOCKS, 0.3F, 0.8F);
}
useEnergy(euTick);
}
}
}
}
if (recipe == null) {
progress = 0;
}
}
@Override
public double getBaseMaxPower() {
return maxEnergy;
}
@Override
public double getBaseMaxOutput() {
return 0;
}
@Override
public double getBaseMaxInput() {
return maxInput;
}
@Override
public boolean canAcceptEnergy(EnumFacing enumFacing) {
return true;
}
@Override
public boolean canProvideEnergy(EnumFacing enumFacing) {
return false;
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tag) {
if (currentRecipe != null) {
tag.setString("currentRecipe", currentRecipe.toString());
}
// Disable due to performance issues
// tag.setBoolean("customRecipe", customRecipe);
tag.setBoolean("customRecipe", false);
return super.writeToNBT(tag);
}
@Override
public void readFromNBT(NBTTagCompound tag) {
if (tag.hasKey("currentRecipe")) {
currentRecipe = new ResourceLocation(tag.getString("currentRecipe"));
}
// Disabled due to performance issues
//customRecipe = tag.getBoolean("customRecipe");
customRecipe = false;
super.readFromNBT(tag);
}
// TileLegacyMachineBase
@Override
public boolean canBeUpgraded() {
return false;
}
@Override
public boolean isItemValidForSlot(int index, ItemStack stack) {
int bestSlot = findBestSlotForStack(getIRecipe(), stack);
if (bestSlot != -1) {
return index == bestSlot;
}
return super.isItemValidForSlot(index, stack);
}
//This machine doesnt have a facing
@Override
public EnumFacing getFacingEnum() {
return EnumFacing.NORTH;
}
// IToolDrop
@Override
public ItemStack getToolDrop(EntityPlayer playerIn) {
return new ItemStack(ModBlocks.AUTO_CRAFTING_TABLE, 1);
}
// IInventoryProvider
@Override
public IInventory getInventory() {
return inventory;
}
// IContainerProvider
@Override
public BuiltContainer createContainer(EntityPlayer player) {
return new ContainerBuilder("autocraftingTable").player(player.inventory).inventory().hotbar()
.addInventory().tile(this)
.slot(0, 28, 25).slot(1, 46, 25).slot(2, 64, 25)
.slot(3, 28, 43).slot(4, 46, 43).slot(5, 64, 43)
.slot(6, 28, 61).slot(7, 46, 61).slot(8, 64, 61)
.outputSlot(9, 145, 42).outputSlot(10, 145, 70).syncEnergyValue()
.syncIntegerValue(this::getProgress, this::setProgress)
.syncIntegerValue(this::getMaxProgress, this::setMaxProgress)
.addInventory().create(this);
}
}

View file

@ -0,0 +1,143 @@
/*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2018 TechReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package techreborn.tiles.tier1;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import reborncore.api.IToolDrop;
import reborncore.common.blocks.BlockMachineBase;
import reborncore.common.powerSystem.TilePowerAcceptor;
import reborncore.common.registration.RebornRegistry;
import reborncore.common.registration.impl.ConfigRegistry;
import reborncore.common.util.WorldUtils;
import techreborn.init.ModBlocks;
import techreborn.lib.ModInfo;
import java.util.Iterator;
@RebornRegistry(modID = ModInfo.MOD_ID)
public class TilePlayerDectector extends TilePowerAcceptor implements IToolDrop {
@ConfigRegistry(config = "machines", category = "player_detector", key = "PlayerDetectorMaxInput", comment = "Player Detector Max Input (Value in EU)")
public static int maxInput = 32;
@ConfigRegistry(config = "machines", category = "player_detector", key = "PlayerDetectorMaxEnergy", comment = "Player Detector Max Energy (Value in EU)")
public static int maxEnergy = 10000;
@ConfigRegistry(config = "machines", category = "player_detector", key = "PlayerDetectorEUPerSecond", comment = "Player Detector Energy Consumption per second (Value in EU)")
public static int euPerTick = 10;
public String owenerUdid = "";
boolean redstone = false;
public TilePlayerDectector() {
super();
}
public boolean isProvidingPower() {
return redstone;
}
// TilePowerAcceptor
@Override
public void update() {
super.update();
if (!world.isRemote && world.getWorldTime() % 20 == 0) {
boolean lastRedstone = redstone;
redstone = false;
if (canUseEnergy(euPerTick)) {
Iterator<EntityPlayer> tIterator = super.world.playerEntities.iterator();
while (tIterator.hasNext()) {
EntityPlayer player = (EntityPlayer) tIterator.next();
if (player.getDistanceSq((double) super.getPos().getX() + 0.5D,
(double) super.getPos().getY() + 0.5D, (double) super.getPos().getZ() + 0.5D) <= 256.0D) {
BlockMachineBase blockMachineBase = (BlockMachineBase) world.getBlockState(pos).getBlock();
int meta = blockMachineBase.getMetaFromState(world.getBlockState(pos));
if (meta == 0) {// ALL
redstone = true;
} else if (meta == 1) {// Others
if (!owenerUdid.isEmpty() && !owenerUdid.equals(player.getUniqueID().toString())) {
redstone = true;
}
} else {// You
if (!owenerUdid.isEmpty() && owenerUdid.equals(player.getUniqueID().toString())) {
redstone = true;
}
}
}
}
useEnergy(euPerTick);
}
if (lastRedstone != redstone) {
WorldUtils.updateBlock(world, getPos());
world.notifyNeighborsOfStateChange(getPos(), world.getBlockState(getPos()).getBlock(), true);
}
}
}
@Override
public double getBaseMaxPower() {
return maxEnergy;
}
@Override
public boolean canAcceptEnergy(EnumFacing direction) {
return true;
}
@Override
public boolean canProvideEnergy(EnumFacing direction) {
return false;
}
@Override
public double getBaseMaxOutput() {
return 0;
}
@Override
public double getBaseMaxInput() {
return maxInput;
}
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
owenerUdid = tag.getString("ownerID");
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tag) {
super.writeToNBT(tag);
tag.setString("ownerID", owenerUdid);
return tag;
}
// IToolDrop
@Override
public ItemStack getToolDrop(EntityPlayer p0) {
return new ItemStack(ModBlocks.PLAYER_DETECTOR, 1, 0);
}
}

View file

@ -0,0 +1,365 @@
/*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2018 TechReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package techreborn.tiles.tier1;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import org.apache.commons.lang3.tuple.Pair;
import reborncore.api.IToolDrop;
import reborncore.api.tile.IInventoryProvider;
import reborncore.common.powerSystem.TilePowerAcceptor;
import reborncore.common.registration.RebornRegistry;
import reborncore.common.registration.impl.ConfigRegistry;
import reborncore.common.util.Inventory;
import reborncore.common.util.ItemUtils;
import techreborn.api.RollingMachineRecipe;
import techreborn.client.container.IContainerProvider;
import techreborn.client.container.builder.BuiltContainer;
import techreborn.client.container.builder.ContainerBuilder;
import techreborn.init.ModBlocks;
import techreborn.lib.ModInfo;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
//TODO add tick and power bars.
@RebornRegistry(modID = ModInfo.MOD_ID)
public class TileRollingMachine extends TilePowerAcceptor
implements IToolDrop, IInventoryProvider, IContainerProvider {
@ConfigRegistry(config = "machines", category = "rolling_machine", key = "RollingMachineMaxInput", comment = "Rolling Machine Max Input (Value in EU)")
public static int maxInput = 32;
@ConfigRegistry(config = "machines", category = "rolling_machine", key = "RollingMachineEnergyPerTick", comment = "Rolling Machine Energy Per Tick (Value in EU)")
public static int energyPerTick = 5;
@ConfigRegistry(config = "machines", category = "rolling_machine", key = "RollingMachineEnergyRunTime", comment = "Rolling Machine Run Time")
public static int runTime = 250;
@ConfigRegistry(config = "machines", category = "rolling_machine", key = "RollingMachineMaxEnergy", comment = "Rolling Machine Max Energy (Value in EU)")
public static int maxEnergy = 10000;
public int[] craftingSlots = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
private InventoryCrafting craftCache;
public Inventory inventory = new Inventory(12, "TileRollingMachine", 64, this);
public boolean isRunning;
public int tickTime;
@Nonnull
public ItemStack currentRecipeOutput;
public IRecipe currentRecipe;
private int outputSlot;
public boolean locked = false;
public int balanceSlot = 0;
public TileRollingMachine() {
super();
outputSlot = 9;
}
@Override
public double getBaseMaxPower() {
return maxEnergy;
}
@Override
public boolean canAcceptEnergy(final EnumFacing direction) {
return true;
}
@Override
public boolean canProvideEnergy(final EnumFacing direction) {
return false;
}
@Override
public double getBaseMaxOutput() {
return 0;
}
@Override
public double getBaseMaxInput() {
return maxInput;
}
@Override
public void update() {
super.update();
this.charge(2);
if (!this.world.isRemote) {
InventoryCrafting craftMatrix = getCraftingMatrix();
this.currentRecipe = RollingMachineRecipe.instance.findMatchingRecipe(craftMatrix, this.world);
if (this.currentRecipe != null) {
if (world.getTotalWorldTime() % 2 == 0) {
Optional<InventoryCrafting> balanceResult = balanceRecipe(craftMatrix);
if (balanceResult.isPresent()) {
craftMatrix = balanceResult.get();
}
}
this.currentRecipeOutput = currentRecipe.getCraftingResult(craftMatrix);
} else {
this.currentRecipeOutput = ItemStack.EMPTY;
}
if (!this.currentRecipeOutput.isEmpty() && this.canMake(craftMatrix)) {
if (this.tickTime >= Math.max((int) (runTime* (1.0 - getSpeedMultiplier())), 1)) {
this.currentRecipeOutput = RollingMachineRecipe.instance.findMatchingRecipeOutput(craftMatrix, this.world);
if (!this.currentRecipeOutput.isEmpty()) {
boolean hasCrafted = false;
if (this.inventory.getStackInSlot(outputSlot) == ItemStack.EMPTY) {
this.inventory.setInventorySlotContents(outputSlot, this.currentRecipeOutput);
this.tickTime = 0;
hasCrafted = true;
} else {
if (this.inventory.getStackInSlot(outputSlot).getCount() + this.currentRecipeOutput.getCount() <= this.currentRecipeOutput
.getMaxStackSize()) {
final ItemStack stack = this.inventory.getStackInSlot(outputSlot);
stack.setCount(stack.getCount() + this.currentRecipeOutput.getCount());
this.inventory.setInventorySlotContents(outputSlot, stack);
this.tickTime = 0;
hasCrafted = true;
}
}
if (hasCrafted) {
for (int i = 0; i < craftMatrix.getSizeInventory(); i++) {
inventory.decrStackSize(i, 1);
}
this.currentRecipeOutput = ItemStack.EMPTY;
this.currentRecipe = null;
}
}
}
} else {
this.tickTime = 0;
}
if (!this.currentRecipeOutput.isEmpty()) {
if (this.canUseEnergy(getEuPerTick(energyPerTick)) && this.tickTime < Math.max((int) (runTime* (1.0 - getSpeedMultiplier())), 1) && canMake(craftMatrix)) {
this.useEnergy(getEuPerTick(energyPerTick));
this.tickTime++;
}
}
if (this.currentRecipeOutput.isEmpty()) {
this.tickTime = 0;
this.currentRecipe = null;
}
}
}
public Optional<InventoryCrafting> balanceRecipe(InventoryCrafting craftCache) {
if (currentRecipe == null) {
return Optional.empty();
}
if (world.isRemote) {
return Optional.empty();
}
if (!locked) {
return Optional.empty();
}
if (craftCache.isEmpty()) {
return Optional.empty();
}
balanceSlot++;
if (balanceSlot > craftCache.getSizeInventory()) {
balanceSlot = 0;
}
//Find the best slot for each item in a recipe, and move it if needed
ItemStack sourceStack = inventory.getStackInSlot(balanceSlot);
if (sourceStack.isEmpty()) {
return Optional.empty();
}
List<Integer> possibleSlots = new ArrayList<>();
for (int s = 0; s < currentRecipe.getIngredients().size(); s++) {
ItemStack stackInSlot = inventory.getStackInSlot(s);
Ingredient ingredient = currentRecipe.getIngredients().get(s);
if (ingredient != Ingredient.EMPTY && ingredient.apply(sourceStack)) {
if (stackInSlot.isEmpty()) {
possibleSlots.add(s);
} else if (stackInSlot.getItem() == sourceStack.getItem() && stackInSlot.getItemDamage() == sourceStack.getItemDamage()) {
possibleSlots.add(s);
}
}
}
//Slot, count
Pair<Integer, Integer> bestSlot = null;
for (Integer slot : possibleSlots) {
ItemStack slotStack = inventory.getStackInSlot(slot);
if (slotStack.isEmpty()) {
bestSlot = Pair.of(slot, 0);
}
if (bestSlot == null) {
bestSlot = Pair.of(slot, slotStack.getCount());
} else if (bestSlot.getRight() >= slotStack.getCount()) {
bestSlot = Pair.of(slot, slotStack.getCount());
}
}
if (bestSlot == null
|| bestSlot.getLeft() == balanceSlot
|| bestSlot.getRight() == sourceStack.getCount()
|| inventory.getStackInSlot(bestSlot.getLeft()).isEmpty()
|| !ItemUtils.isItemEqual(sourceStack, inventory.getStackInSlot(bestSlot.getLeft()), true, true, true)) {
return Optional.empty();
}
sourceStack.shrink(1);
inventory.getStackInSlot(bestSlot.getLeft()).grow(1);
inventory.hasChanged = true;
return Optional.of(getCraftingMatrix());
}
private InventoryCrafting getCraftingMatrix() {
if (craftCache == null) {
craftCache = new InventoryCrafting(new RollingTileContainer(), 3, 3);
}
if (inventory.hasChanged) {
for (int i = 0; i < 9; i++) {
craftCache.setInventorySlotContents(i, inventory.getStackInSlot(i).copy());
}
inventory.hasChanged = false;
}
return craftCache;
}
public boolean canMake(InventoryCrafting craftMatrix) {
ItemStack stack = RollingMachineRecipe.instance.findMatchingRecipeOutput(craftMatrix, this.world);
if (locked) {
for (int i = 0; i < craftMatrix.getSizeInventory(); i++) {
ItemStack stack1 = craftMatrix.getStackInSlot(i);
if (!stack1.isEmpty() && stack1.getCount() < 2) {
return false;
}
}
}
if (stack.isEmpty()) {
return false;
}
ItemStack output = getStackInSlot(outputSlot);
if (output.isEmpty()) {
return true;
}
return ItemUtils.isItemEqual(stack, output, true, true);
}
@Override
public ItemStack getToolDrop(final EntityPlayer entityPlayer) {
return new ItemStack(ModBlocks.ROLLING_MACHINE, 1);
}
@Override
public void readFromNBT(final NBTTagCompound tagCompound) {
super.readFromNBT(tagCompound);
this.isRunning = tagCompound.getBoolean("isRunning");
this.tickTime = tagCompound.getInteger("tickTime");
this.locked = tagCompound.getBoolean("locked");
}
@Override
public NBTTagCompound writeToNBT(final NBTTagCompound tagCompound) {
super.writeToNBT(tagCompound);
tagCompound.setBoolean("isRunning", this.isRunning);
tagCompound.setInteger("tickTime", this.tickTime);
tagCompound.setBoolean("locked", locked);
return tagCompound;
}
@Override
public void invalidate() {
super.invalidate();
}
@Override
public void onChunkUnload() {
super.onChunkUnload();
}
@Override
public Inventory getInventory() {
return this.inventory;
}
public int getBurnTime() {
return this.tickTime;
}
public void setBurnTime(final int burnTime) {
this.tickTime = burnTime;
}
public int getBurnTimeRemainingScaled(final int scale) {
if (this.tickTime == 0 || Math.max((int) (runTime* (1.0 - getSpeedMultiplier())), 1) == 0) {
return 0;
}
return this.tickTime * scale / Math.max((int) (runTime* (1.0 - getSpeedMultiplier())), 1);
}
@Override
public BuiltContainer createContainer(final EntityPlayer player) {
return new ContainerBuilder("rollingmachine").player(player.inventory)
.inventory().hotbar()
.addInventory().tile(this)
.slot(0, 30, 22).slot(1, 48, 22).slot(2, 66, 22)
.slot(3, 30, 40).slot(4, 48, 40).slot(5, 66, 40)
.slot(6, 30, 58).slot(7, 48, 58).slot(8, 66, 58)
.onCraft(inv -> this.inventory.setInventorySlotContents(1, RollingMachineRecipe.instance.findMatchingRecipeOutput(getCraftingMatrix(), this.world)))
.outputSlot(9, 124, 40)
.energySlot(10, 8, 70)
.syncEnergyValue().syncIntegerValue(this::getBurnTime, this::setBurnTime).syncIntegerValue(this::getLockedInt, this::setLockedInt).addInventory().create(this);
}
//Easyest way to sync back to the client
public int getLockedInt() {
return locked ? 1 : 0;
}
public void setLockedInt(int lockedInt) {
locked = lockedInt == 1;
}
public int getProgressScaled(final int scale) {
if (tickTime != 0 && Math.max((int) (runTime* (1.0 - getSpeedMultiplier())), 1) != 0) {
return tickTime * scale / Math.max((int) (runTime* (1.0 - getSpeedMultiplier())), 1);
}
return 0;
}
private static class RollingTileContainer extends Container {
@Override
public boolean canInteractWith(final EntityPlayer entityplayer) {
return true;
}
}
@Override
public boolean canBeUpgraded() {
return true;
}
}