From 731d15fbd58d31516d5dadd71ac84ea894bf77a4 Mon Sep 17 00:00:00 2001 From: mezz Date: Tue, 10 Nov 2015 02:44:18 -0800 Subject: [PATCH] Add API for multiblock components --- api/forestry | 2 +- .../apiculture/AlvearyBeeModifier.java | 21 + .../apiculture/blocks/BlockAlveary.java | 5 +- .../forestry/apiculture/gui/GuiAlveary.java | 6 +- .../multiblock/AlvearyController.java | 139 ++-- .../AlvearyMultiblockSizeLimits.java | 57 ++ .../multiblock/FakeAlvearyController.java | 15 +- ...r.java => IAlvearyControllerInternal.java} | 8 +- .../multiblock/MultiblockLogicAlveary.java | 35 + .../apiculture/multiblock/TileAlveary.java | 93 +-- .../multiblock/TileAlvearyClimatiser.java | 2 +- .../multiblock/TileAlvearyHygroregulator.java | 2 +- .../multiblock/TileAlvearyPlain.java | 27 +- .../multiblock/TileAlvearySieve.java | 2 +- .../multiblock/TileAlvearyStabiliser.java | 2 +- .../multiblock/TileAlvearySwarmer.java | 4 +- .../multiblock/TileAlvearyWithGui.java | 6 - .../forestry/core/blocks/BlockStructure.java | 36 +- .../core/entities/EntityMinecartForestry.java | 2 +- .../core/multiblock/BlockMultiblockBase.java | 15 - .../core/multiblock/CoordTriplet.java | 121 --- .../multiblock/FakeMultiblockController.java | 147 ++++ .../IMultiblockControllerInternal.java | 139 ++++ .../core/multiblock/IMultiblockPart.java | 193 ----- .../multiblock/IMultiblockSizeLimits.java | 60 ++ .../multiblock/MultiblockControllerBase.java | 698 ++++++------------ .../MultiblockControllerForestry.java | 192 +++++ .../core/multiblock/MultiblockLogic.java | 204 +++++ .../multiblock/MultiblockLogicFactory.java | 30 + .../core/multiblock/MultiblockRegistry.java | 11 +- .../multiblock/MultiblockTileEntityBase.java | 532 ------------- .../MultiblockTileEntityForestry.java | 202 +++++ .../core/multiblock/MultiblockUtil.java | 61 ++ .../multiblock/MultiblockWorldRegistry.java | 141 ++-- .../RectangularMultiblockControllerBase.java | 75 +- .../multiblock/rectangular/PartPosition.java | 28 - .../RectangularMultiblockTileEntityBase.java | 105 --- .../java/forestry/farming/FarmHelper.java | 2 +- .../forestry/farming/gui/ContainerFarm.java | 2 +- .../java/forestry/farming/gui/GuiFarm.java | 10 +- .../multiblock/FakeFarmController.java | 8 +- .../farming/multiblock/FarmController.java | 103 +-- .../multiblock/FarmMultiblockSizeLimits.java | 56 ++ ...ller.java => IFarmControllerInternal.java} | 6 +- .../multiblock/MultiblockLogicFarm.java | 35 + .../forestry/farming/tiles/TileControl.java | 2 +- .../java/forestry/farming/tiles/TileFarm.java | 97 +-- .../forestry/farming/tiles/TileFarmPlain.java | 12 +- .../forestry/farming/tiles/TileGearbox.java | 6 +- .../forestry/farming/tiles/TileHatch.java | 6 +- .../forestry/farming/tiles/TileValve.java | 2 +- .../triggers/TriggerLowFertilizer.java | 2 +- .../farming/triggers/TriggerLowGermlings.java | 2 +- .../farming/triggers/TriggerLowLiquid.java | 2 +- .../farming/triggers/TriggerLowSoil.java | 4 +- .../java/forestry/plugins/PluginCore.java | 4 + 56 files changed, 1828 insertions(+), 1951 deletions(-) create mode 100644 src/main/java/forestry/apiculture/AlvearyBeeModifier.java create mode 100644 src/main/java/forestry/apiculture/multiblock/AlvearyMultiblockSizeLimits.java rename src/main/java/forestry/apiculture/multiblock/{IAlvearyController.java => IAlvearyControllerInternal.java} (75%) create mode 100644 src/main/java/forestry/apiculture/multiblock/MultiblockLogicAlveary.java delete mode 100644 src/main/java/forestry/core/multiblock/BlockMultiblockBase.java delete mode 100644 src/main/java/forestry/core/multiblock/CoordTriplet.java create mode 100644 src/main/java/forestry/core/multiblock/FakeMultiblockController.java create mode 100644 src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java delete mode 100644 src/main/java/forestry/core/multiblock/IMultiblockPart.java create mode 100644 src/main/java/forestry/core/multiblock/IMultiblockSizeLimits.java create mode 100644 src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java create mode 100644 src/main/java/forestry/core/multiblock/MultiblockLogic.java create mode 100644 src/main/java/forestry/core/multiblock/MultiblockLogicFactory.java delete mode 100644 src/main/java/forestry/core/multiblock/MultiblockTileEntityBase.java create mode 100644 src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java create mode 100644 src/main/java/forestry/core/multiblock/MultiblockUtil.java rename src/main/java/forestry/core/multiblock/{rectangular => }/RectangularMultiblockControllerBase.java (58%) delete mode 100644 src/main/java/forestry/core/multiblock/rectangular/PartPosition.java delete mode 100644 src/main/java/forestry/core/multiblock/rectangular/RectangularMultiblockTileEntityBase.java create mode 100644 src/main/java/forestry/farming/multiblock/FarmMultiblockSizeLimits.java rename src/main/java/forestry/farming/multiblock/{IFarmController.java => IFarmControllerInternal.java} (77%) create mode 100644 src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java diff --git a/api/forestry b/api/forestry index e66447e58..0920e3c45 160000 --- a/api/forestry +++ b/api/forestry @@ -1 +1 @@ -Subproject commit e66447e58d631dbb73b2e6f0d3bc35b90c45c7ba +Subproject commit 0920e3c45f58c40bb1f57fe5945181a9f549aebf diff --git a/src/main/java/forestry/apiculture/AlvearyBeeModifier.java b/src/main/java/forestry/apiculture/AlvearyBeeModifier.java new file mode 100644 index 000000000..c3f8f3a9b --- /dev/null +++ b/src/main/java/forestry/apiculture/AlvearyBeeModifier.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture; + +import forestry.api.apiculture.DefaultBeeModifier; +import forestry.api.apiculture.IBeeGenome; + +public class AlvearyBeeModifier extends DefaultBeeModifier { + @Override + public float getTerritoryModifier(IBeeGenome genome, float currentModifier) { + return 2.0f; + } +} diff --git a/src/main/java/forestry/apiculture/blocks/BlockAlveary.java b/src/main/java/forestry/apiculture/blocks/BlockAlveary.java index 85e63d580..4d4632024 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockAlveary.java +++ b/src/main/java/forestry/apiculture/blocks/BlockAlveary.java @@ -37,7 +37,6 @@ import forestry.apiculture.multiblock.TileAlvearySieve; import forestry.apiculture.multiblock.TileAlvearyStabiliser; import forestry.apiculture.multiblock.TileAlvearySwarmer; import forestry.core.blocks.BlockStructure; -import forestry.core.multiblock.MultiblockRegistry; import forestry.core.render.TextureManager; public class BlockAlveary extends BlockStructure { @@ -228,7 +227,7 @@ public class BlockAlveary extends BlockStructure { @SideOnly(Side.CLIENT) private IIcon getBlockTextureFromSideAndTile(IBlockAccess world, int x, int y, int z, int side) { TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null || !(tile instanceof TileAlveary)) { + if (!(tile instanceof TileAlveary)) { return getIcon(side, 0); } @@ -261,7 +260,7 @@ public class BlockAlveary extends BlockStructure { TileAlveary tileAlveary = (TileAlveary) tileEntity; // We must check that the slabs on top were not removed - MultiblockRegistry.addDirtyController(world, tileAlveary.getMultiblockController()); + tileAlveary.getMultiblockLogic().getController().reassemble(); } } } diff --git a/src/main/java/forestry/apiculture/gui/GuiAlveary.java b/src/main/java/forestry/apiculture/gui/GuiAlveary.java index 81d888822..438fd6fc3 100755 --- a/src/main/java/forestry/apiculture/gui/GuiAlveary.java +++ b/src/main/java/forestry/apiculture/gui/GuiAlveary.java @@ -12,7 +12,7 @@ package forestry.apiculture.gui; import net.minecraft.entity.player.InventoryPlayer; -import forestry.apiculture.multiblock.IAlvearyController; +import forestry.apiculture.multiblock.IAlvearyControllerInternal; import forestry.apiculture.multiblock.TileAlvearyPlain; import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; @@ -31,7 +31,7 @@ public class GuiAlveary extends GuiForestryTitled beeListeners = new HashSet<>(); private final Set climatisers = new HashSet<>(); private final Set activeComponents = new HashSet<>(); - private final Set allComponents = new HashSet<>(); // CLIENT private int breedingProgressPercent = 0; public AlvearyController(World world) { - super(world); + super(world, AlvearyMultiblockSizeLimits.instance); this.inventory = new InventoryBeeHousing(9, "Items", getAccessHandler()); this.beekeepingLogic = BeeManager.beeRoot.createBeekeepingLogic(this); @@ -107,20 +104,13 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple } @Override - public Iterable getComponents() { - return allComponents; - } - - @Override - public void onAttachedPartWithMultiblockData(IMultiblockPart part, NBTTagCompound data) { + public void onAttachedPartWithMultiblockData(IMultiblockComponent part, NBTTagCompound data) { this.readFromNBT(data); } @Override - protected void onBlockAdded(IMultiblockPart newPart) { + protected void onBlockAdded(IMultiblockComponent newPart) { if (newPart instanceof IAlvearyComponent) { - allComponents.add((IAlvearyComponent) newPart); - if (newPart instanceof IAlvearyComponent.BeeModifier) { IAlvearyComponent.BeeModifier alvearyBeeModifier = (IAlvearyComponent.BeeModifier) newPart; IBeeModifier beeModifier = alvearyBeeModifier.getBeeModifier(); @@ -144,10 +134,8 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple } @Override - protected void onBlockRemoved(IMultiblockPart oldPart) { + protected void onBlockRemoved(IMultiblockComponent oldPart) { if (oldPart instanceof IAlvearyComponent) { - allComponents.remove(oldPart); - if (oldPart instanceof IAlvearyComponent.BeeModifier) { IAlvearyComponent.BeeModifier alvearyBeeModifier = (IAlvearyComponent.BeeModifier) oldPart; IBeeModifier beeModifier = alvearyBeeModifier.getBeeModifier(); @@ -174,14 +162,14 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple protected void isMachineWhole() throws MultiblockValidationException { super.isMachineWhole(); - final CoordTriplet maximumCoord = getMaximumCoord(); - final CoordTriplet minimumCoord = getMinimumCoord(); + final ChunkCoordinates maximumCoord = getMaximumCoord(); + final ChunkCoordinates minimumCoord = getMinimumCoord(); // check that the top is covered in wood slabs - final int slabY = maximumCoord.y + 1; - for (int slabX = minimumCoord.x; slabX <= maximumCoord.x; slabX++) { - for (int slabZ = minimumCoord.z; slabZ <= maximumCoord.z; slabZ++) { + final int slabY = maximumCoord.posY + 1; + for (int slabX = minimumCoord.posX; slabX <= maximumCoord.posX; slabX++) { + for (int slabZ = minimumCoord.posZ; slabZ <= maximumCoord.posZ; slabZ++) { Block block = worldObj.getBlock(slabX, slabY, slabZ); if (!BlockUtil.isWoodSlabBlock(block)) { throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.alveary.error.needSlabs")); @@ -196,9 +184,9 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple // check that there is space all around the alveary entrances - int airY = maximumCoord.y; - for (int airX = minimumCoord.x - 1; airX <= maximumCoord.x + 1; airX++) { - for (int airZ = minimumCoord.z - 1; airZ <= maximumCoord.z + 1; airZ++) { + int airY = maximumCoord.posY; + for (int airX = minimumCoord.posX - 1; airX <= maximumCoord.posX + 1; airX++) { + for (int airZ = minimumCoord.posZ - 1; airZ <= maximumCoord.posZ + 1; airZ++) { if (isCoordInMultiblock(airX, airY, airZ)) { continue; } @@ -211,47 +199,26 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple } @Override - protected int getMinimumNumberOfBlocksForAssembledMachine() { - return 27; + protected void isGoodForExteriorLevel(IMultiblockComponent part, int level) throws MultiblockValidationException { + if (level == 2 && !(part instanceof TileAlvearyPlain)) { + throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.alveary.error.needPlainOnTop")); + } } @Override - protected int getMaximumXSize() { - return 3; + protected void isGoodForInterior(IMultiblockComponent part) throws MultiblockValidationException { + if (!(part instanceof TileAlvearyPlain)) { + throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.alveary.error.needPlainInterior")); + } } @Override - protected int getMaximumZSize() { - return 3; - } - - @Override - protected int getMaximumYSize() { - return 3; - } - - @Override - protected int getMinimumXSize() { - return 3; - } - - @Override - protected int getMinimumYSize() { - return 3; - } - - @Override - protected int getMinimumZSize() { - return 3; - } - - @Override - protected void onAssimilate(MultiblockControllerBase assimilated) { + protected void onAssimilate(IMultiblockControllerInternal assimilated) { } @Override - protected void onAssimilated(MultiblockControllerBase assimilator) { + public void onAssimilated(IMultiblockControllerInternal assimilator) { } @@ -298,10 +265,10 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple beekeepingLogic.doBeeFX(); if (updateOnInterval(50)) { - CoordTriplet center = getCenterCoord(); - float fxX = center.x + 0.5F; - float fxY = center.y + 1.0F; - float fxZ = center.z + 0.5F; + ChunkCoordinates center = getCenterCoord(); + float fxX = center.posX + 0.5F; + float fxY = center.posY + 1.0F; + float fxZ = center.posZ + 0.5F; float distanceFromCenter = 1.6F; float leftRightSpreadFromCenter = distanceFromCenter * (worldObj.rand.nextFloat() - 0.5F); @@ -354,24 +321,24 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple @Override public ChunkCoordinates getCoordinates() { - CoordTriplet coord = getCenterCoord(); - return new ChunkCoordinates(coord.x, coord.y + 1, coord.z); + ChunkCoordinates coord = getCenterCoord(); + return new ChunkCoordinates(coord.posX, coord.posY + 1, coord.posZ); } @Override public Vec3 getBeeFXCoordinates() { - CoordTriplet coord = getCenterCoord(); - return Vec3.createVectorHelper(coord.x + 0.5, coord.y + 1.5, coord.z + 0.5); + ChunkCoordinates coord = getCenterCoord(); + return Vec3.createVectorHelper(coord.posX + 0.5, coord.posY + 1.5, coord.posZ + 0.5); } @Override public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { if (oldAccess == EnumAccess.SHARED || newAccess == EnumAccess.SHARED) { // pipes connected to this need to update - for (IMultiblockPart part : connectedParts) { - if (part instanceof MultiblockTileEntityBase) { - MultiblockTileEntityBase tile = (MultiblockTileEntityBase) part; - tile.notifyNeighborsOfBlockChange(); + for (IMultiblockComponent part : connectedParts) { + if (part instanceof TileEntity) { + TileEntity tile = (TileEntity) part; + worldObj.notifyBlocksOfNeighborChange(tile.xCoord, tile.yCoord, tile.zCoord, tile.getBlockType()); } } markDirty(); @@ -380,8 +347,8 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple @Override public float getExactTemperature() { - CoordTriplet coords = getReferenceCoord(); - return getBiome().getFloatTemperature(coords.x, coords.y, coords.z) + tempChange; + ChunkCoordinates coords = getReferenceCoord(); + return getBiome().getFloatTemperature(coords.posX, coords.posY, coords.posZ) + tempChange; } @Override @@ -417,22 +384,22 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple @Override public BiomeGenBase getBiome() { if (cachedBiome == null) { - CoordTriplet coords = getReferenceCoord(); - cachedBiome = worldObj.getBiomeGenForCoords(coords.x, coords.z); + ChunkCoordinates coords = getReferenceCoord(); + cachedBiome = worldObj.getBiomeGenForCoords(coords.posX, coords.posZ); } return cachedBiome; } @Override public int getBlockLightValue() { - CoordTriplet topCenter = getTopCenterCoord(); - return worldObj.getBlockLightValue(topCenter.x, topCenter.y + 1, topCenter.z); + ChunkCoordinates topCenter = getTopCenterCoord(); + return worldObj.getBlockLightValue(topCenter.posX, topCenter.posY + 1, topCenter.posZ); } @Override public boolean canBlockSeeTheSky() { - CoordTriplet topCenter = getTopCenterCoord(); - return worldObj.canBlockSeeTheSky(topCenter.x, topCenter.y + 2, topCenter.z); + ChunkCoordinates topCenter = getTopCenterCoord(); + return worldObj.canBlockSeeTheSky(topCenter.posX, topCenter.posY + 2, topCenter.posZ); } @Override @@ -474,12 +441,4 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple tempChange = data.readVarInt() / 100.0F; humidChange = data.readVarInt() / 100.0F; } - - private static class AlvearyBeeModifier extends DefaultBeeModifier { - @Override - public float getTerritoryModifier(IBeeGenome genome, float currentModifier) { - return 2.0f; - } - } - } diff --git a/src/main/java/forestry/apiculture/multiblock/AlvearyMultiblockSizeLimits.java b/src/main/java/forestry/apiculture/multiblock/AlvearyMultiblockSizeLimits.java new file mode 100644 index 000000000..81763e209 --- /dev/null +++ b/src/main/java/forestry/apiculture/multiblock/AlvearyMultiblockSizeLimits.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.multiblock; + +import forestry.core.multiblock.IMultiblockSizeLimits; + +class AlvearyMultiblockSizeLimits implements IMultiblockSizeLimits { + + public static final AlvearyMultiblockSizeLimits instance = new AlvearyMultiblockSizeLimits(); + + private AlvearyMultiblockSizeLimits() { + + } + + @Override + public int getMinimumNumberOfBlocksForAssembledMachine() { + return 27; + } + + @Override + public int getMaximumXSize() { + return 3; + } + + @Override + public int getMaximumZSize() { + return 3; + } + + @Override + public int getMaximumYSize() { + return 3; + } + + @Override + public int getMinimumXSize() { + return 3; + } + + @Override + public int getMinimumYSize() { + return 3; + } + + @Override + public int getMinimumZSize() { + return 3; + } +} diff --git a/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java b/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java index 4fbf8236b..9b371573c 100644 --- a/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java +++ b/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java @@ -16,12 +16,10 @@ import java.util.Collections; import net.minecraft.item.ItemStack; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.Vec3; -import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import com.mojang.authlib.GameProfile; -import forestry.api.apiculture.IAlvearyComponent; import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; import forestry.api.apiculture.IBeeModifier; @@ -36,10 +34,11 @@ import forestry.core.access.IAccessHandler; import forestry.core.errors.FakeErrorLogic; import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; +import forestry.core.multiblock.FakeMultiblockController; import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; -public class FakeAlvearyController implements IAlvearyController { +public class FakeAlvearyController extends FakeMultiblockController implements IAlvearyControllerInternal { public static final FakeAlvearyController instance = new FakeAlvearyController(); private FakeAlvearyController() { @@ -56,11 +55,6 @@ public class FakeAlvearyController implements IAlvearyController { return Collections.emptyList(); } - @Override - public Iterable getComponents() { - return Collections.emptyList(); - } - @Override public IBeeHousingInventory getBeeInventory() { return FakeBeeHousingInventory.instance; @@ -111,11 +105,6 @@ public class FakeAlvearyController implements IAlvearyController { return FakeErrorLogic.instance; } - @Override - public World getWorld() { - return null; - } - @Override public ChunkCoordinates getCoordinates() { return null; diff --git a/src/main/java/forestry/apiculture/multiblock/IAlvearyController.java b/src/main/java/forestry/apiculture/multiblock/IAlvearyControllerInternal.java similarity index 75% rename from src/main/java/forestry/apiculture/multiblock/IAlvearyController.java rename to src/main/java/forestry/apiculture/multiblock/IAlvearyControllerInternal.java index 93ba94a1c..f944bfcb3 100644 --- a/src/main/java/forestry/apiculture/multiblock/IAlvearyController.java +++ b/src/main/java/forestry/apiculture/multiblock/IAlvearyControllerInternal.java @@ -10,17 +10,15 @@ ******************************************************************************/ package forestry.apiculture.multiblock; -import forestry.api.apiculture.IAlvearyComponent; -import forestry.api.apiculture.IBeeHousing; +import forestry.api.multiblock.IAlvearyController; import forestry.core.access.IRestrictedAccess; import forestry.core.inventory.IInventoryAdapter; +import forestry.core.multiblock.IMultiblockControllerInternal; import forestry.core.network.IStreamableGui; import forestry.core.tiles.IClimatised; -public interface IAlvearyController extends IBeeHousing, IClimatised, IRestrictedAccess, IStreamableGui { +public interface IAlvearyControllerInternal extends IAlvearyController, IMultiblockControllerInternal, IClimatised, IRestrictedAccess, IStreamableGui { IInventoryAdapter getInternalInventory(); - Iterable getComponents(); - int getHealthScaled(int i); } diff --git a/src/main/java/forestry/apiculture/multiblock/MultiblockLogicAlveary.java b/src/main/java/forestry/apiculture/multiblock/MultiblockLogicAlveary.java new file mode 100644 index 000000000..92a209664 --- /dev/null +++ b/src/main/java/forestry/apiculture/multiblock/MultiblockLogicAlveary.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.multiblock; + +import net.minecraft.world.World; + +import forestry.api.multiblock.IMultiblockLogicAlveary; +import forestry.core.multiblock.MultiblockLogic; + +public class MultiblockLogicAlveary extends MultiblockLogic implements IMultiblockLogicAlveary { + public MultiblockLogicAlveary() { + super(IAlvearyControllerInternal.class); + } + + @Override + public IAlvearyControllerInternal getController() { + if (super.isConnected()) { + return controller; + } else { + return FakeAlvearyController.instance; + } + } + + public IAlvearyControllerInternal createNewController(World world) { + return new AlvearyController(world); + } +} diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlveary.java b/src/main/java/forestry/apiculture/multiblock/TileAlveary.java index a50b4d506..f9777911b 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlveary.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlveary.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.apiculture.multiblock; -import net.minecraft.util.StatCollector; +import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.Vec3; import net.minecraft.world.biome.BiomeGenBase; @@ -22,16 +22,15 @@ import forestry.api.apiculture.IBeekeepingLogic; import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; import forestry.api.core.IErrorLogic; +import forestry.api.multiblock.IAlvearyComponent; +import forestry.api.multiblock.IMultiblockController; import forestry.apiculture.blocks.BlockAlveary; import forestry.core.access.EnumAccess; import forestry.core.access.IAccessHandler; import forestry.core.access.IRestrictedAccess; -import forestry.core.multiblock.MultiblockControllerBase; -import forestry.core.multiblock.MultiblockValidationException; -import forestry.core.multiblock.rectangular.RectangularMultiblockTileEntityBase; - -public abstract class TileAlveary extends RectangularMultiblockTileEntityBase implements IBeeHousing, IRestrictedAccess { +import forestry.core.multiblock.MultiblockTileEntityForestry; +public abstract class TileAlveary extends MultiblockTileEntityForestry implements IBeeHousing, IRestrictedAccess, IAlvearyComponent { public static final int PLAIN_META = 0; public static final int ENTRANCE_META = 1; public static final int SWARMER_META = 2; @@ -41,142 +40,100 @@ public abstract class TileAlveary extends RectangularMultiblockTileEntityBase im public static final int STABILIZER_META = 6; public static final int SIEVE_META = 7; + protected TileAlveary() { + super(new MultiblockLogicAlveary()); + } + /* TEXTURES */ public int getIcon(int side) { return BlockAlveary.PLAIN; } @Override - public void isGoodForExteriorLevel(int level) throws MultiblockValidationException { - if (level == 2 && !(this instanceof TileAlvearyPlain)) { - throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.alveary.error.needPlainOnTop")); - } - } - - @Override - public void isGoodForInterior() throws MultiblockValidationException { - if (!(this instanceof TileAlvearyPlain)) { - throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.alveary.error.needPlainInterior")); - } - } - - @Override - public void onMachineActivated() { - - } - - @Override - public void onMachineDeactivated() { - - } - - @Override - public MultiblockControllerBase createNewMultiblock() { - return new AlvearyController(worldObj); - } - - @Override - public Class getMultiblockControllerType() { - return AlvearyController.class; - } - - public IAlvearyController getAlvearyController() { - if (isConnected()) { - return (IAlvearyController) getMultiblockController(); - } else { - return FakeAlvearyController.instance; - } - } - - @Override - public void onMachineAssembled(MultiblockControllerBase controller) { - super.onMachineAssembled(controller); - + public void onMachineAssembled(IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord) { // Re-render this block on the client if (worldObj.isRemote) { this.worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); } - notifyNeighborsOfBlockChange(); + worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); markDirty(); } @Override public void onMachineBroken() { - super.onMachineBroken(); - // Re-render this block on the client if (worldObj.isRemote) { this.worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); } - notifyNeighborsOfBlockChange(); + worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); markDirty(); } /* IHousing */ @Override public BiomeGenBase getBiome() { - return getAlvearyController().getBiome(); + return getMultiblockLogic().getController().getBiome(); } /* IBeeHousing */ @Override public Iterable getBeeModifiers() { - return getAlvearyController().getBeeModifiers(); + return getMultiblockLogic().getController().getBeeModifiers(); } @Override public Iterable getBeeListeners() { - return getAlvearyController().getBeeListeners(); + return getMultiblockLogic().getController().getBeeListeners(); } @Override public IBeeHousingInventory getBeeInventory() { - return getAlvearyController().getBeeInventory(); + return getMultiblockLogic().getController().getBeeInventory(); } @Override public IBeekeepingLogic getBeekeepingLogic() { - return getAlvearyController().getBeekeepingLogic(); + return getMultiblockLogic().getController().getBeekeepingLogic(); } @Override public Vec3 getBeeFXCoordinates() { - return getAlvearyController().getBeeFXCoordinates(); + return getMultiblockLogic().getController().getBeeFXCoordinates(); } /* IClimatised */ @Override public EnumTemperature getTemperature() { - return getAlvearyController().getTemperature(); + return getMultiblockLogic().getController().getTemperature(); } @Override public EnumHumidity getHumidity() { - return getAlvearyController().getHumidity(); + return getMultiblockLogic().getController().getHumidity(); } @Override public int getBlockLightValue() { - return getAlvearyController().getBlockLightValue(); + return getMultiblockLogic().getController().getBlockLightValue(); } @Override public boolean canBlockSeeTheSky() { - return getAlvearyController().canBlockSeeTheSky(); + return getMultiblockLogic().getController().canBlockSeeTheSky(); } @Override public IErrorLogic getErrorLogic() { - return getAlvearyController().getErrorLogic(); + return getMultiblockLogic().getController().getErrorLogic(); } @Override public IAccessHandler getAccessHandler() { - return getAlvearyController().getAccessHandler(); + return getMultiblockLogic().getController().getAccessHandler(); } @Override public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { - getAlvearyController().onSwitchAccess(oldAccess, newAccess); + getMultiblockLogic().getController().onSwitchAccess(oldAccess, newAccess); } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyClimatiser.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyClimatiser.java index dbc51d72d..21c67122b 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyClimatiser.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyClimatiser.java @@ -14,8 +14,8 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import forestry.api.apiculture.IAlvearyComponent; import forestry.api.core.IClimateControlled; +import forestry.api.multiblock.IAlvearyComponent; import forestry.apiculture.network.PacketActiveUpdate; import forestry.core.proxy.Proxies; import forestry.core.tiles.IActivatable; diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java index e421046b8..6abdc6f01 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java @@ -19,8 +19,8 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; -import forestry.api.apiculture.IAlvearyComponent; import forestry.api.core.IClimateControlled; +import forestry.api.multiblock.IAlvearyComponent; import forestry.apiculture.blocks.BlockAlveary; import forestry.apiculture.inventory.InventoryHygroregulator; import forestry.core.config.Constants; diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyPlain.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyPlain.java index 0ed1fb244..33e0c6ae9 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyPlain.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyPlain.java @@ -17,25 +17,24 @@ import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChunkCoordinates; import net.minecraftforge.common.util.ForgeDirection; import cpw.mods.fml.common.Optional; import forestry.api.core.ForestryAPI; +import forestry.api.multiblock.IMultiblockController; import forestry.apiculture.trigger.ApicultureTriggers; import forestry.core.config.Config; import forestry.core.gui.IHintSource; import forestry.core.inventory.IInventoryAdapter; -import forestry.core.multiblock.MultiblockControllerBase; -import forestry.core.multiblock.rectangular.PartPosition; import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.GuiId; import forestry.core.network.IStreamableGui; import forestry.core.tiles.IClimatised; import forestry.core.tiles.ITitled; -import forestry.core.utils.BlockUtil; import buildcraft.api.statements.IStatementContainer; import buildcraft.api.statements.ITriggerExternal; @@ -46,13 +45,13 @@ import buildcraft.api.statements.ITriggerProvider; public class TileAlvearyPlain extends TileAlveary implements IClimatised, IHintSource, ITitled, ITriggerProvider, IStreamableGui { @Override - public void onMachineAssembled(MultiblockControllerBase controller) { - super.onMachineAssembled(controller); + public void onMachineAssembled(IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord) { + super.onMachineAssembled(multiblockController, minCoord, maxCoord); if (!worldObj.isRemote) { // set alveary entrance block meta - if (getPartPosition() == PartPosition.Frame) { - if (BlockUtil.isWoodSlabBlock(worldObj.getBlock(xCoord, yCoord + 1, zCoord))) { + if (yCoord == maxCoord.posY) { + if ((xCoord > minCoord.posX && xCoord < maxCoord.posX) || (zCoord > minCoord.posZ && zCoord < maxCoord.posZ)) { this.worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, TileAlveary.ENTRANCE_META, 2); } } @@ -71,7 +70,7 @@ public class TileAlvearyPlain extends TileAlveary implements IClimatised, IHintS @Override public IInventoryAdapter getInternalInventory() { - return getAlvearyController().getInternalInventory(); + return getMultiblockLogic().getController().getInternalInventory(); } @Override @@ -82,20 +81,18 @@ public class TileAlvearyPlain extends TileAlveary implements IClimatised, IHintS /* GUI */ @Override public void openGui(EntityPlayer player) { - if (isConnected()) { - player.openGui(ForestryAPI.instance, GuiId.AlvearyGUI.ordinal(), worldObj, xCoord, yCoord, zCoord); - } + player.openGui(ForestryAPI.instance, GuiId.AlvearyGUI.ordinal(), worldObj, xCoord, yCoord, zCoord); } /* IStreamableGui */ @Override public void writeGuiData(DataOutputStreamForestry data) throws IOException { - getAlvearyController().writeGuiData(data); + getMultiblockLogic().getController().writeGuiData(data); } @Override public void readGuiData(DataInputStreamForestry data) throws IOException { - getAlvearyController().readGuiData(data); + getMultiblockLogic().getController().readGuiData(data); } @Override @@ -128,11 +125,11 @@ public class TileAlvearyPlain extends TileAlveary implements IClimatised, IHintS /* IClimatised */ @Override public float getExactTemperature() { - return getAlvearyController().getExactTemperature(); + return getMultiblockLogic().getController().getExactTemperature(); } @Override public float getExactHumidity() { - return getAlvearyController().getExactHumidity(); + return getMultiblockLogic().getController().getExactHumidity(); } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearySieve.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearySieve.java index df19e8cec..fc7546647 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearySieve.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearySieve.java @@ -13,12 +13,12 @@ package forestry.apiculture.multiblock; import net.minecraft.item.ItemStack; import forestry.api.apiculture.DefaultBeeListener; -import forestry.api.apiculture.IAlvearyComponent; import forestry.api.apiculture.IBeeListener; import forestry.api.arboriculture.EnumGermlingType; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IIndividual; import forestry.api.genetics.ISpeciesRoot; +import forestry.api.multiblock.IAlvearyComponent; import forestry.apiculture.blocks.BlockAlveary; import forestry.apiculture.inventory.InventoryAlvearySieve; import forestry.core.inventory.IInventoryAdapter; diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyStabiliser.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyStabiliser.java index 33307d675..e95c0907b 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyStabiliser.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyStabiliser.java @@ -11,9 +11,9 @@ package forestry.apiculture.multiblock; import forestry.api.apiculture.DefaultBeeModifier; -import forestry.api.apiculture.IAlvearyComponent; import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeModifier; +import forestry.api.multiblock.IAlvearyComponent; import forestry.apiculture.blocks.BlockAlveary; public class TileAlvearyStabiliser extends TileAlveary implements IAlvearyComponent.BeeModifier { diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearySwarmer.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearySwarmer.java index f6cd2a1b6..1e6b2a717 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearySwarmer.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearySwarmer.java @@ -20,8 +20,8 @@ import net.minecraft.nbt.NBTTagList; import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; -import forestry.api.apiculture.IAlvearyComponent; import forestry.api.apiculture.IBee; +import forestry.api.multiblock.IAlvearyComponent; import forestry.apiculture.blocks.BlockAlveary; import forestry.apiculture.inventory.InventorySwarmer; import forestry.apiculture.network.PacketActiveUpdate; @@ -101,7 +101,7 @@ public class TileAlvearySwarmer extends TileAlvearyWithGui implements ISidedInve } private ItemStack getPrincessStack() { - ItemStack princessStack = getAlvearyController().getBeeInventory().getQueen(); + ItemStack princessStack = getMultiblockLogic().getController().getBeeInventory().getQueen(); if (BeeManager.beeRoot.isMated(princessStack)) { return princessStack; diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyWithGui.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyWithGui.java index f894b922f..cbac9f97f 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyWithGui.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyWithGui.java @@ -12,7 +12,6 @@ package forestry.apiculture.multiblock; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ChunkCoordinates; import forestry.api.core.ForestryAPI; import forestry.core.access.AccessHandler; @@ -39,11 +38,6 @@ public abstract class TileAlvearyWithGui extends TileAlveary implements ITitled, return accessHandler; } - @Override - public final ChunkCoordinates getCoordinates() { - return new ChunkCoordinates(xCoord, yCoord, zCoord); - } - @Override public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { if (oldAccess == EnumAccess.SHARED || newAccess == EnumAccess.SHARED) { diff --git a/src/main/java/forestry/core/blocks/BlockStructure.java b/src/main/java/forestry/core/blocks/BlockStructure.java index bdfc71df0..2711e254d 100644 --- a/src/main/java/forestry/core/blocks/BlockStructure.java +++ b/src/main/java/forestry/core/blocks/BlockStructure.java @@ -13,14 +13,17 @@ package forestry.core.blocks; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ChatComponentText; import net.minecraft.util.StatCollector; import net.minecraft.world.World; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.api.multiblock.IMultiblockController; import forestry.core.circuits.ISocketable; -import forestry.core.multiblock.MultiblockControllerBase; -import forestry.core.multiblock.MultiblockTileEntityBase; +import forestry.core.multiblock.MultiblockTileEntityForestry; +import forestry.core.multiblock.MultiblockUtil; import forestry.core.utils.InventoryUtil; public abstract class BlockStructure extends BlockForestry { @@ -43,26 +46,23 @@ public abstract class BlockStructure extends BlockForestry { return false; } - MultiblockTileEntityBase part; - MultiblockControllerBase controller; - TileEntity tile = world.getTileEntity(x, y, z); - if (tile instanceof MultiblockTileEntityBase) { - part = (MultiblockTileEntityBase) tile; - controller = part.getMultiblockController(); - } else { + if (!(tile instanceof MultiblockTileEntityForestry)) { return false; } + MultiblockTileEntityForestry part = (MultiblockTileEntityForestry) tile; + IMultiblockController controller = part.getMultiblockLogic().getController(); + // If the player's hands are empty and they right-click on a multiblock, they get a // multiblock-debugging message if the machine is not assembled. if (player.getCurrentEquippedItem() == null && !controller.isAssembled()) { if (controller != null) { - Exception e = controller.getLastValidationException(); - if (e != null) { + String validationError = controller.getLastValidationError(); + if (validationError != null) { long tick = world.getTotalWorldTime(); if (tick > previousMessageTick + 20) { - player.addChatMessage(new ChatComponentText(e.getMessage())); + player.addChatMessage(new ChatComponentText(validationError)); previousMessageTick = tick; } return true; @@ -92,14 +92,16 @@ public abstract class BlockStructure extends BlockForestry { } TileEntity tile = world.getTileEntity(x, y, z); - if (tile instanceof MultiblockTileEntityBase) { - MultiblockTileEntityBase part = (MultiblockTileEntityBase) tile; + if (tile instanceof IMultiblockComponent) { + IMultiblockComponent part = (IMultiblockComponent) tile; // drop inventory if we're the last part remaining - if (part.getNeighboringParts().length == 0) { - InventoryUtil.dropInventory(part, world, x, y, z); + if (MultiblockUtil.getNeighboringParts(world, part).size() == 0) { + if (tile instanceof IInventory) { + InventoryUtil.dropInventory((IInventory) tile, world, x, y, z); + } if (tile instanceof ISocketable) { - InventoryUtil.dropSockets((ISocketable) tile, tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord); + InventoryUtil.dropSockets((ISocketable) tile, world, x, y, z); } } } diff --git a/src/main/java/forestry/core/entities/EntityMinecartForestry.java b/src/main/java/forestry/core/entities/EntityMinecartForestry.java index 918bbeff8..475d6f6fe 100644 --- a/src/main/java/forestry/core/entities/EntityMinecartForestry.java +++ b/src/main/java/forestry/core/entities/EntityMinecartForestry.java @@ -96,7 +96,7 @@ public abstract class EntityMinecartForestry extends EntityMinecart implements I @Override public abstract int getDisplayTileData(); - // cart contents itemStack + // cart itemStack @Override public abstract ItemStack getCartItem(); diff --git a/src/main/java/forestry/core/multiblock/BlockMultiblockBase.java b/src/main/java/forestry/core/multiblock/BlockMultiblockBase.java deleted file mode 100644 index 1ff8f06f8..000000000 --- a/src/main/java/forestry/core/multiblock/BlockMultiblockBase.java +++ /dev/null @@ -1,15 +0,0 @@ -package forestry.core.multiblock; - -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; - -/* - * Base class for multiblock-capable blocks. This is only a reference implementation - * and can be safely ignored. - */ -public abstract class BlockMultiblockBase extends BlockContainer { - - protected BlockMultiblockBase(Material material) { - super(material); - } -} diff --git a/src/main/java/forestry/core/multiblock/CoordTriplet.java b/src/main/java/forestry/core/multiblock/CoordTriplet.java deleted file mode 100644 index 0f91e3682..000000000 --- a/src/main/java/forestry/core/multiblock/CoordTriplet.java +++ /dev/null @@ -1,121 +0,0 @@ -package forestry.core.multiblock; - -import javax.annotation.Nonnull; - -import net.minecraft.world.ChunkCoordIntPair; - -import net.minecraftforge.common.util.ForgeDirection; - -/* - * Simple wrapper class for XYZ coordinates. - */ -public class CoordTriplet implements Comparable { - public int x, y, z; - - public CoordTriplet(int x, int y, int z) { - this.x = x; - this.y = y; - this.z = z; - } - - public int getChunkX() { - return x >> 4; - } - - public int getChunkZ() { - return z >> 4; - } - - public long getChunkXZHash() { - return ChunkCoordIntPair.chunkXZ2Int(x >> 4, z >> 4); - } - - @Override - public boolean equals(Object other) { - if (other == null) { - return false; - } else if (other instanceof CoordTriplet) { - CoordTriplet otherTriplet = (CoordTriplet) other; - return this.x == otherTriplet.x && this.y == otherTriplet.y && this.z == otherTriplet.z; - } else { - return false; - } - } - - public void translate(ForgeDirection dir) { - this.x += dir.offsetX; - this.y += dir.offsetY; - this.z += dir.offsetZ; - } - - public boolean equals(int x, int y, int z) { - return this.x == x && this.y == y && this.z == z; - } - - // Suggested implementation from NetBeans 7.1 - public int hashCode() { - int hash = 7; - hash = 71 * hash + this.x; - hash = 71 * hash + this.y; - hash = 71 * hash + this.z; - return hash; - } - - public CoordTriplet copy() { - return new CoordTriplet(x, y, z); - } - - public void copy(CoordTriplet other) { - this.x = other.x; - this.y = other.y; - this.z = other.z; - } - - ///// IComparable - - @Override - public int compareTo(@Nonnull Object o) { - if (o instanceof CoordTriplet) { - CoordTriplet other = (CoordTriplet) o; - if (this.x < other.x) { - return -1; - } else if (this.x > other.x) { - return 1; - } else if (this.y < other.y) { - return -1; - } else if (this.y > other.y) { - return 1; - } else if (this.z < other.z) { - return -1; - } else if (this.z > other.z) { - return 1; - } else { - return 0; - } - } - return 0; - } - - @Override - public String toString() { - return String.format("(%d, %d, %d)", this.x, this.y, this.z); - } - - public int compareTo(int xCoord, int yCoord, int zCoord) { - if (this.x < xCoord) { - return -1; - } else if (this.x > xCoord) { - return 1; - } else if (this.y < yCoord) { - return -1; - } else if (this.y > yCoord) { - return 1; - } else if (this.z < zCoord) { - return -1; - } else if (this.z > zCoord) { - return 1; - } else { - return 0; - } - } -} diff --git a/src/main/java/forestry/core/multiblock/FakeMultiblockController.java b/src/main/java/forestry/core/multiblock/FakeMultiblockController.java new file mode 100644 index 000000000..f35af3aca --- /dev/null +++ b/src/main/java/forestry/core/multiblock/FakeMultiblockController.java @@ -0,0 +1,147 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import javax.annotation.Nonnull; +import java.util.Collection; +import java.util.Collections; +import java.util.Set; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; + +import forestry.api.multiblock.IMultiblockComponent; + +public abstract class FakeMultiblockController implements IMultiblockControllerInternal { + @Override + public void attachBlock(IMultiblockComponent part) { + + } + + @Override + public void detachBlock(IMultiblockComponent part, boolean chunkUnloading) { + + } + + @Override + public void checkIfMachineIsWhole() { + + } + + @Override + public void assimilate(IMultiblockControllerInternal other) { + + } + + @Override + public void _onAssimilated(IMultiblockControllerInternal otherController) { + + } + + @Override + public void onAssimilated(IMultiblockControllerInternal assimilator) { + + } + + @Override + public void updateMultiblockEntity() { + + } + + @Override + public ChunkCoordinates getReferenceCoord() { + return null; + } + + @Override + public void recalculateMinMaxCoords() { + + } + + @Override + public void formatDescriptionPacket(NBTTagCompound data) { + + } + + @Override + public void decodeDescriptionPacket(NBTTagCompound data) { + + } + + @Override + public World getWorld() { + return null; + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + public boolean shouldConsume(IMultiblockControllerInternal otherController) { + return false; + } + + @Override + public String getPartsListString() { + return ""; + } + + @Override + public void auditParts() { + + } + + @Nonnull + @Override + public Set checkForDisconnections() { + return Collections.emptySet(); + } + + @Nonnull + @Override + public Set detachAllBlocks() { + return Collections.emptySet(); + } + + @Override + public boolean isAssembled() { + return false; + } + + @Override + public void reassemble() { + + } + + @Override + public String getLastValidationError() { + return null; + } + + @Override + @Nonnull + public Collection getComponents() { + return Collections.emptyList(); + } + + @Override + public void readFromNBT(NBTTagCompound nbttagcompound) { + + } + + @Override + public void writeToNBT(NBTTagCompound nbttagcompound) { + + } +} diff --git a/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java b/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java new file mode 100644 index 000000000..5d0fca327 --- /dev/null +++ b/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java @@ -0,0 +1,139 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import javax.annotation.Nonnull; +import java.util.Set; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; + +import forestry.api.core.INBTTagable; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.api.multiblock.IMultiblockController; + +// internal implementation of IMultiblockController +public interface IMultiblockControllerInternal extends IMultiblockController, INBTTagable { + /** + * Attach a new part to this machine. + * @param part The part to add. + */ + void attachBlock(IMultiblockComponent part); + + /** + * Call to detach a block from this machine. Generally, this should be called + * when the tile entity is being released, e.g. on block destruction. + * @param part The part to detach from this machine. + * @param chunkUnloading Is this entity detaching due to the chunk unloading? If true, the multiblock will be paused instead of broken. + */ + void detachBlock(IMultiblockComponent part, boolean chunkUnloading); + + /** + * Check if the machine is whole or not. + * If the machine was not whole, but now is, assemble the machine. + * If the machine was whole, but no longer is, disassemble the machine. + */ + void checkIfMachineIsWhole(); + + /** + * Assimilate another controller into this controller. + * Acquire all of the other controller's blocks and attach them + * to this one. + * + * @param other The controller to merge into this one. + */ + void assimilate(IMultiblockControllerInternal other); + + /** + * Called when this machine is consumed by another controller. + * Essentially, forcibly tear down this object. + * @param otherController The controller consuming this controller. + */ + void _onAssimilated(IMultiblockControllerInternal otherController); + + /** + * Callback. Called after this controller is assimilated into another controller. + * All blocks have been stripped out of this object and handed over to the + * other controller. + * This is intended primarily for cleanup. + * @param assimilator The controller which has assimilated this controller. + */ + void onAssimilated(IMultiblockControllerInternal assimilator); + + /** + * Driver for the update loop. If the machine is assembled, runs + * the game logic update method. + */ + void updateMultiblockEntity(); + + /** + * @return The reference coordinate, the block with the lowest x, y, z coordinates, evaluated in that order. + */ + ChunkCoordinates getReferenceCoord(); + + /** + * Force this multiblock to recalculate its minimum and maximum coordinates + * from the list of connected parts. + */ + void recalculateMinMaxCoords(); + + /** + * Called when the save delegate's tile entity is being asked for its description packet + * @param data A fresh compound tag to write your multiblock data into + */ + void formatDescriptionPacket(NBTTagCompound data); + + /** + * Called when the save delegate's tile entity receiving a description packet + * @param data A compound tag containing multiblock data to import + */ + void decodeDescriptionPacket(NBTTagCompound data); + + World getWorld(); + + /** + * @return True if this controller has no associated blocks, false otherwise + */ + boolean isEmpty(); + + /** + * Tests whether this multiblock should consume the other multiblock + * and become the new multiblock master when the two multiblocks + * are adjacent. Assumes both multiblocks are the same type. + * @param otherController The other multiblock controller. + * @return True if this multiblock should consume the other, false otherwise. + */ + boolean shouldConsume(IMultiblockControllerInternal otherController); + + String getPartsListString(); + + /** + * Checks all of the parts in the controller. If any are dead or do not exist in the world, they are removed. + */ + void auditParts(); + + /** + * Called when this machine may need to check for blocks that are no + * longer physically connected to the reference coordinate. + * @return the parts that were disconnected and removed + */ + @Nonnull + Set checkForDisconnections(); + + /** + * Detach all parts. Return a set of all parts which still + * have a valid tile entity. Chunk-safe. + * @return A set of all parts which still have a valid tile entity. + */ + @Nonnull + Set detachAllBlocks(); +} diff --git a/src/main/java/forestry/core/multiblock/IMultiblockPart.java b/src/main/java/forestry/core/multiblock/IMultiblockPart.java deleted file mode 100644 index e73c51079..000000000 --- a/src/main/java/forestry/core/multiblock/IMultiblockPart.java +++ /dev/null @@ -1,193 +0,0 @@ -package forestry.core.multiblock; - -import java.util.Set; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; - -/** - * Basic interface for a multiblock machine part. This is defined as an abstract class - * as we need the basic functionality of a TileEntity as well. - * Preferably, you should derive from MultiblockTileEntityBase, - * which does all the hard work for you. - * - * {@link forestry.core.multiblock.MultiblockTileEntityBase} - */ -public abstract class IMultiblockPart extends TileEntity { - public static final int INVALID_DISTANCE = Integer.MAX_VALUE; - - /** - * @return True if this block is connected to a multiblock controller. False otherwise. - */ - public abstract boolean isConnected(); - - /** - * @return The attached multiblock controller for this tile entity. - */ - public abstract MultiblockControllerBase getMultiblockController(); - - /** - * Returns the location of this tile entity in the world, in CoordTriplet form. - * @return A CoordTriplet with its x,y,z members set to the location of this tile entity in the world. - */ - public abstract CoordTriplet getWorldLocation(); - - // Multiblock connection-logic callbacks - - /** - * Called after this block has been attached to a new multiblock controller. - * @param newController The new multiblock controller to which this tile entity is attached. - */ - public abstract void onAttached(MultiblockControllerBase newController); - - /** - * Called after this block has been detached from a multiblock controller. - * @param multiblockController The multiblock controller that no longer controls this tile entity. - */ - public abstract void onDetached(MultiblockControllerBase multiblockController); - - /** - * Called when this block is being orphaned. Use this to copy game-data values that - * should persist despite a machine being broken. - * This should NOT mark the part as disconnected. onDetached will be called immediately afterwards. - * @see #onDetached(MultiblockControllerBase) - * @param oldController The controller which is orphaning this block. - * @param oldControllerSize The number of connected blocks in the controller prior to shedding orphans. - * @param newControllerSize The number of connected blocks in the controller after shedding orphans. - */ - public abstract void onOrphaned(MultiblockControllerBase oldController, int oldControllerSize, int newControllerSize); - - // Multiblock fuse/split helper methods. Here there be dragons. - - /** - * Factory method. Creates a new multiblock controller and returns it. - * Does not attach this tile entity to it. - * Override this in your game code! - * @return A new Multiblock Controller, derived from MultiblockControllerBase. - */ - public abstract MultiblockControllerBase createNewMultiblock(); - - /** - * Retrieve the type of multiblock controller which governs this part. - * Used to ensure that incompatible multiblocks are not merged. - * @return The class/type of the multiblock controller which governs this type of part. - */ - public abstract Class getMultiblockControllerType(); - - /** - * Called when this block is moved from its current controller into a new controller. - * A special case of attach/detach, done here for efficiency to avoid triggering - * lots of recalculation logic. - * @param newController The new controller into which this tile entity is being merged. - */ - public abstract void onAssimilated(MultiblockControllerBase newController); - - // Multiblock connection data access. - // You generally shouldn't toy with these! - // They're for use by Multiblock Controllers. - - /** - * Set that this block has been visited by your validation algorithms. - */ - public abstract void setVisited(); - - /** - * Set that this block has not been visited by your validation algorithms; - */ - public abstract void setUnvisited(); - - /** - * @return True if this block has been visited by your validation algorithms since the last reset. - */ - public abstract boolean isVisited(); - - /** - * Called when this block becomes the designated block for saving data and - * transmitting data across the wire. - */ - public abstract void becomeMultiblockSaveDelegate(); - - /** - * Called when this block is no longer the designated block for saving data - * and transmitting data across the wire. - */ - public abstract void forfeitMultiblockSaveDelegate(); - - /** - * Is this block the designated save/load & network delegate? - */ - public abstract boolean isMultiblockSaveDelegate(); - - /** - * Returns an array containing references to neighboring IMultiblockPart tile entities. - * Primarily a utility method. Only works after tileentity construction, so it cannot be used in - * MultiblockControllerBase::attachBlock. - * - * This method is chunk-safe on the server; it will not query for parts in chunks that are unloaded. - * Note that no method is chunk-safe on the client, because ChunkProviderClient is stupid. - * @return An array of references to neighboring IMultiblockPart tile entities. - */ - public abstract IMultiblockPart[] getNeighboringParts(); - - // Multiblock business-logic callbacks - implement these! - - /** - * Called when a machine is fully assembled from the disassembled state, meaning - * it was broken by a player/entity action, not by chunk unloads. - * Note that, for non-square machines, the min/max coordinates may not actually be part - * of the machine! They form an outer bounding box for the whole machine itself. - * @param multiblockControllerBase The controller to which this part is being assembled. - */ - public abstract void onMachineAssembled(MultiblockControllerBase multiblockControllerBase); - - /** - * Called when the machine is broken for game reasons, e.g. a player removed a block - * or an explosion occurred. - */ - public abstract void onMachineBroken(); - - /** - * Called when the user activates the machine. This is not called by default, but is included - * as most machines have this game-logical concept. - */ - public abstract void onMachineActivated(); - - /** - * Called when the user deactivates the machine. This is not called by default, but is included - * as most machines have this game-logical concept. - */ - public abstract void onMachineDeactivated(); - - // Block events - - /** - * Called when this part should check its neighbors. - * This method MUST NOT cause additional chunks to load. - * ALWAYS check to see if a chunk is loaded before querying for its tile entity - * This part should inform the controller that it is attaching at this time. - * @return A Set of multiblock controllers to which this object would like to attach. It should have attached to one of the controllers in this list. Return null if there are no compatible controllers nearby. - */ - public abstract Set attachToNeighbors(); - - /** - * Assert that this part is detached. If not, log a warning and set the part's controller to null. - * Do NOT fire the full disconnection logic. - */ - public abstract void assertDetached(); - - /** - * @return True if a part has multiblock game-data saved inside it. - */ - public abstract boolean hasMultiblockSaveData(); - - /** - * @return The part's saved multiblock game-data in NBT format, or null if there isn't any. - */ - public abstract NBTTagCompound getMultiblockSaveData(); - - /** - * Called after a block is added and the controller has incorporated the part's saved - * multiblock game-data into itself. Generally, you should clear the saved data here. - */ - public abstract void onMultiblockDataAssimilated(); -} diff --git a/src/main/java/forestry/core/multiblock/IMultiblockSizeLimits.java b/src/main/java/forestry/core/multiblock/IMultiblockSizeLimits.java new file mode 100644 index 000000000..8aa575f4f --- /dev/null +++ b/src/main/java/forestry/core/multiblock/IMultiblockSizeLimits.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +public interface IMultiblockSizeLimits { + /** + * Helper method so we don't check for a whole machine until we have enough blocks + * to actually assemble it. This isn't as simple as xmax*ymax*zmax for non-cubic machines + * or for machines with hollow/complex interiors. + * @return The minimum number of blocks connected to the machine for it to be assembled. + */ + int getMinimumNumberOfBlocksForAssembledMachine(); + + /** + * Returns the maximum X dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable + * dimension checking in X. (This is not recommended.) + * @return The maximum X dimension size of the machine, or -1 + */ + int getMaximumXSize(); + + /** + * Returns the maximum Z dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable + * dimension checking in X. (This is not recommended.) + * @return The maximum Z dimension size of the machine, or -1 + */ + int getMaximumZSize(); + + /** + * Returns the maximum Y dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable + * dimension checking in X. (This is not recommended.) + * @return The maximum Y dimension size of the machine, or -1 + */ + int getMaximumYSize(); + + /** + * Returns the minimum X dimension size of the machine. Must be at least 1, because nothing else makes sense. + * @return The minimum X dimension size of the machine + */ + int getMinimumXSize(); + + /** + * Returns the minimum Y dimension size of the machine. Must be at least 1, because nothing else makes sense. + * @return The minimum Y dimension size of the machine + */ + int getMinimumYSize(); + + /** + * Returns the minimum Z dimension size of the machine. Must be at least 1, because nothing else makes sense. + * @return The minimum Z dimension size of the machine + */ + int getMinimumZSize(); +} diff --git a/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java b/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java index 18231289e..44eed3471 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java +++ b/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java @@ -1,35 +1,23 @@ package forestry.core.multiblock; -import com.google.common.collect.HashMultiset; -import com.google.common.collect.Multiset; - +import javax.annotation.Nonnull; +import java.util.Collection; +import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; +import java.util.List; import java.util.Random; import java.util.Set; import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; -import com.mojang.authlib.GameProfile; - -import forestry.api.core.ForestryAPI; -import forestry.api.core.IErrorLogic; -import forestry.api.core.IErrorLogicSource; -import forestry.core.access.AccessHandler; -import forestry.core.access.IAccessHandler; -import forestry.core.access.IOwnable; -import forestry.core.access.IRestrictedAccess; -import forestry.core.inventory.FakeInventoryAdapter; -import forestry.core.inventory.IInventoryAdapter; -import forestry.core.tiles.ILocatable; +import forestry.api.multiblock.IMultiblockComponent; import forestry.core.utils.Log; import forestry.core.utils.StringUtil; @@ -37,13 +25,15 @@ import forestry.core.utils.StringUtil; * This class contains the base logic for "multiblock controllers". Conceptually, they are * meta-TileEntities. They govern the logic for an associated group of TileEntities. * - * Subordinate TileEntities implement the IMultiblockPart class and, generally, should not have an update() loop. + * Subordinate TileEntities implement the IMultiblockComponent class and, generally, should not have an update() loop. */ -public abstract class MultiblockControllerBase implements ISidedInventory, IRestrictedAccess, IErrorLogicSource, ILocatable { - public static final short DIMENSION_UNBOUNDED = -1; - +public abstract class MultiblockControllerBase implements IMultiblockControllerInternal { // Multiblock stuff - do not mess with protected World worldObj; + + // Ticks + private static final Random rand = new Random(); + private int tickCount = rand.nextInt(256); // Disassembled -> Assembled; Assembled -> Disassembled OR Paused; Paused -> Assembled protected enum AssemblyState { @@ -52,7 +42,7 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest protected AssemblyState assemblyState; - protected HashSet connectedParts; + protected HashSet connectedParts; /** This is a deterministically-picked coordinate that identifies this * multiblock uniquely in its dimension. @@ -60,19 +50,19 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest * i.e. If something has a lower X but higher Y/Z coordinates, it will still be the reference. * If something has the same X but a lower Y coordinate, it will be the reference. Etc. */ - private CoordTriplet referenceCoord; + private ChunkCoordinates referenceCoord; /** * Minimum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine * is not a cube/rectangular prism. */ - private CoordTriplet minimumCoord; + private ChunkCoordinates minimumCoord; /** * Maximum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine * is not a cube/rectangular prism. */ - private CoordTriplet maximumCoord; + private ChunkCoordinates maximumCoord; /** * Set to true whenever a part is removed from this controller. @@ -84,51 +74,24 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest */ private MultiblockValidationException lastValidationException; - // Ticks - private static final Random rand = new Random(); - private int tickCount = rand.nextInt(256); - - private final AccessHandler accessHandler; - private final IErrorLogic errorLogic; - - protected boolean debugMode; - protected MultiblockControllerBase(World world) { - // Multiblock stuff - worldObj = world; - connectedParts = new HashSet<>(); + this.worldObj = world; + this.connectedParts = new HashSet<>(); - referenceCoord = null; - assemblyState = AssemblyState.Disassembled; + this.referenceCoord = null; + this.assemblyState = AssemblyState.Disassembled; - minimumCoord = null; - maximumCoord = null; + this.minimumCoord = null; + this.maximumCoord = null; - shouldCheckForDisconnections = true; - lastValidationException = null; - - accessHandler = new AccessHandler(this); - errorLogic = ForestryAPI.errorStateRegistry.createErrorLogic(); - - debugMode = false; + this.shouldCheckForDisconnections = true; + this.lastValidationException = null; } @Override - public IAccessHandler getAccessHandler() { - return accessHandler; - } - - @Override - public IErrorLogic getErrorLogic() { - return errorLogic; - } - - public void setDebugMode(boolean active) { - debugMode = active; - } - - public boolean isDebugMode() { - return debugMode; + @Nonnull + public Collection getComponents() { + return Collections.unmodifiableCollection(connectedParts); } /** @@ -136,62 +99,67 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest * The part will be notified that the data has been used after this call completes. * @param part The NBT tag containing this controller's data. */ - public abstract void onAttachedPartWithMultiblockData(IMultiblockPart part, NBTTagCompound data); - - /** - * Attach a new part to this machine. - * @param part The part to add. - */ - public void attachBlock(IMultiblockPart part) { - CoordTriplet coord = part.getWorldLocation(); + protected abstract void onAttachedPartWithMultiblockData(IMultiblockComponent part, NBTTagCompound data); + + @Override + public void attachBlock(IMultiblockComponent part) { + ChunkCoordinates coord = part.getCoordinates(); if (!connectedParts.add(part)) { - Log.warning("[%s] Controller %s is double-adding part %d @ %s. This is unusual. If you encounter odd behavior, please tear down the machine and rebuild it.", (worldObj.isRemote ? "CLIENT" : "SERVER"), hashCode(), part.hashCode(), coord); + Log.warning("[%s] Controller %s is double-adding part %d @ %s. This is unusual. " + + "If you encounter odd behavior, please tear down the machine and rebuild it.", + (worldObj.isRemote ? "CLIENT" : "SERVER"), hashCode(), part.hashCode(), coord); } + + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); - part.onAttached(this); + logic.setController(this); this.onBlockAdded(part); - if (part.hasMultiblockSaveData()) { - NBTTagCompound savedData = part.getMultiblockSaveData(); + if (logic.hasMultiblockSaveData()) { + NBTTagCompound savedData = logic.getMultiblockSaveData(); onAttachedPartWithMultiblockData(part, savedData); - part.onMultiblockDataAssimilated(); + logic.onMultiblockDataAssimilated(); } if (this.referenceCoord == null) { referenceCoord = coord; - part.becomeMultiblockSaveDelegate(); + logic.becomeMultiblockSaveDelegate(); } else if (coord.compareTo(referenceCoord) < 0) { - TileEntity te = this.worldObj.getTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); - ((IMultiblockPart) te).forfeitMultiblockSaveDelegate(); + TileEntity te = this.worldObj.getTileEntity(referenceCoord.posX, referenceCoord.posY, referenceCoord.posZ); + if (te instanceof IMultiblockComponent) { + IMultiblockComponent tePart = (IMultiblockComponent) te; + MultiblockLogic teLogic = (MultiblockLogic) tePart.getMultiblockLogic(); + teLogic.forfeitMultiblockSaveDelegate(); + } referenceCoord = coord; - part.becomeMultiblockSaveDelegate(); + logic.becomeMultiblockSaveDelegate(); } else { - part.forfeitMultiblockSaveDelegate(); + logic.forfeitMultiblockSaveDelegate(); } - + if (minimumCoord != null) { - if (part.xCoord < minimumCoord.x) { - minimumCoord.x = part.xCoord; + if (coord.posX < minimumCoord.posX) { + minimumCoord.posX = coord.posX; } - if (part.yCoord < minimumCoord.y) { - minimumCoord.y = part.yCoord; + if (coord.posY < minimumCoord.posY) { + minimumCoord.posY = coord.posY; } - if (part.zCoord < minimumCoord.z) { - minimumCoord.z = part.zCoord; + if (coord.posZ < minimumCoord.posZ) { + minimumCoord.posZ = coord.posZ; } } if (maximumCoord != null) { - if (part.xCoord > maximumCoord.x) { - maximumCoord.x = part.xCoord; + if (coord.posX > maximumCoord.posX) { + maximumCoord.posX = coord.posX; } - if (part.yCoord > maximumCoord.y) { - maximumCoord.y = part.yCoord; + if (coord.posY > maximumCoord.posY) { + maximumCoord.posY = coord.posY; } - if (part.zCoord > maximumCoord.z) { - maximumCoord.z = part.zCoord; + if (coord.posZ > maximumCoord.posZ) { + maximumCoord.posZ = coord.posZ; } } @@ -202,52 +170,19 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest * Called when a new part is added to the machine. Good time to register things into lists. * @param newPart The part being added. */ - protected abstract void onBlockAdded(IMultiblockPart newPart); + protected abstract void onBlockAdded(IMultiblockComponent newPart); /** * Called when a part is removed from the machine. Good time to clean up lists. * @param oldPart The part being removed. */ - protected abstract void onBlockRemoved(IMultiblockPart oldPart); + protected abstract void onBlockRemoved(IMultiblockComponent oldPart); /** * Called when a machine is assembled from a disassembled state. */ protected void onMachineAssembled() { - if (worldObj.isRemote) { - return; - } - // Figure out who owns the multiblock, by majority - - Multiset owners = HashMultiset.create(); - for (IMultiblockPart part : connectedParts) { - if (part instanceof IRestrictedAccess) { - IAccessHandler accessHandler = ((IRestrictedAccess) part).getAccessHandler(); - GameProfile owner = accessHandler.getOwner(); - if (owner != null) { - owners.add(owner); - } - } else if (part instanceof IOwnable) { - IOwnable ownable = (IOwnable) part; - GameProfile owner = ownable.getOwner(); - if (owner != null) { - owners.add(owner); - } - } - } - - GameProfile owner = null; - int max = 0; - for (Multiset.Entry entry : owners.entrySet()) { - int count = entry.getCount(); - if (count > max) { - max = count; - owner = entry.getElement(); - } - } - - getAccessHandler().setOwner(owner); } /** @@ -278,28 +213,24 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest * Do housekeeping/callbacks, also nulls min/max coords. * @param part The part being removed. */ - private void onDetachBlock(IMultiblockPart part) { + private void onDetachBlock(IMultiblockComponent part) { // Strip out this part - part.onDetached(this); + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); + logic.setController(null); this.onBlockRemoved(part); - part.forfeitMultiblockSaveDelegate(); + logic.forfeitMultiblockSaveDelegate(); minimumCoord = maximumCoord = null; - if (referenceCoord != null && referenceCoord.equals(part.xCoord, part.yCoord, part.zCoord)) { + if (referenceCoord != null && referenceCoord.equals(part.getCoordinates())) { referenceCoord = null; } shouldCheckForDisconnections = true; } - - /** - * Call to detach a block from this machine. Generally, this should be called - * when the tile entity is being released, e.g. on block destruction. - * @param part The part to detach from this machine. - * @param chunkUnloading Is this entity detaching due to the chunk unloading? If true, the multiblock will be paused instead of broken. - */ - public void detachBlock(IMultiblockPart part, boolean chunkUnloading) { + + @Override + public void detachBlock(IMultiblockComponent part, boolean chunkUnloading) { if (chunkUnloading && this.assemblyState == AssemblyState.Assembled) { this.assemblyState = AssemblyState.Paused; this.onMachinePaused(); @@ -308,7 +239,10 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest // Strip out this part onDetachBlock(part); if (!connectedParts.remove(part)) { - Log.warning("[%s] Double-removing part (%d) @ %d, %d, %d, this is unexpected and may cause problems. If you encounter anomalies, please tear down the reactor and rebuild it.", worldObj.isRemote ? "CLIENT" : "SERVER", part.hashCode(), part.xCoord, part.yCoord, part.zCoord); + ChunkCoordinates partCoords = part.getCoordinates(); + Log.warning("[%s] Double-removing part (%d) @ %d, %d, %d, this is unexpected and may cause problems. " + + "If you encounter anomalies, please tear down the reactor and rebuild it.", + worldObj.isRemote ? "CLIENT" : "SERVER", part.hashCode(), partCoords.posX, partCoords.posY, partCoords.posZ); } if (connectedParts.isEmpty()) { @@ -325,79 +259,25 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest } } - /** - * Helper method so we don't check for a whole machine until we have enough blocks - * to actually assemble it. This isn't as simple as xmax*ymax*zmax for non-cubic machines - * or for machines with hollow/complex interiors. - * @return The minimum number of blocks connected to the machine for it to be assembled. - */ - protected abstract int getMinimumNumberOfBlocksForAssembledMachine(); - - /** - * Returns the maximum X dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable - * dimension checking in X. (This is not recommended.) - * @return The maximum X dimension size of the machine, or -1 - */ - protected abstract int getMaximumXSize(); - - /** - * Returns the maximum Z dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable - * dimension checking in X. (This is not recommended.) - * @return The maximum Z dimension size of the machine, or -1 - */ - protected abstract int getMaximumZSize(); - - /** - * Returns the maximum Y dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable - * dimension checking in X. (This is not recommended.) - * @return The maximum Y dimension size of the machine, or -1 - */ - protected abstract int getMaximumYSize(); - - /** - * Returns the minimum X dimension size of the machine. Must be at least 1, because nothing else makes sense. - * @return The minimum X dimension size of the machine - */ - protected int getMinimumXSize() { - return 1; + @Override + public String getLastValidationError() { + if (lastValidationException == null) { + return null; + } + return lastValidationException.getMessage(); } - /** - * Returns the minimum Y dimension size of the machine. Must be at least 1, because nothing else makes sense. - * @return The minimum Y dimension size of the machine - */ - protected int getMinimumYSize() { - return 1; + @Override + public void reassemble() { + MultiblockRegistry.addDirtyController(worldObj, this); } - /** - * Returns the minimum Z dimension size of the machine. Must be at least 1, because nothing else makes sense. - * @return The minimum Z dimension size of the machine - */ - protected int getMinimumZSize() { - return 1; - } - - - /** - * @return An exception representing the last error encountered when trying to assemble this - * multiblock, or null if there is no error. - */ - public MultiblockValidationException getLastValidationException() { - return lastValidationException; - } - /** * Checks if a machine is whole. If not, throws an exception with the reason why. */ protected abstract void isMachineWhole() throws MultiblockValidationException; - - /** - * Check if the machine is whole or not. - * If the machine was not whole, but now is, assemble the machine. - * If the machine was whole, but no longer is, disassemble the machine. - * @return - */ + + @Override public void checkIfMachineIsWhole() { AssemblyState oldState = this.assemblyState; boolean isWhole; @@ -428,8 +308,8 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest private void assembleMachine(AssemblyState oldState) { this.assemblyState = AssemblyState.Assembled; - for (IMultiblockPart part : connectedParts) { - part.onMachineAssembled(this); + for (IMultiblockComponent part : connectedParts) { + part.onMachineAssembled(this, getMinimumCoord(), getMaximumCoord()); } if (oldState == AssemblyState.Paused) { @@ -448,39 +328,34 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest private void disassembleMachine() { this.assemblyState = AssemblyState.Disassembled; - for (IMultiblockPart part : connectedParts) { + for (IMultiblockComponent part : connectedParts) { part.onMachineBroken(); } onMachineDisassembled(); } - /** - * Assimilate another controller into this controller. - * Acquire all of the other controller's blocks and attach them - * to this one. - * - * @param other The controller to merge into this one. - */ - public void assimilate(MultiblockControllerBase other) { - CoordTriplet otherReferenceCoord = other.getReferenceCoord(); + @Override + public void assimilate(IMultiblockControllerInternal other) { + ChunkCoordinates otherReferenceCoord = other.getReferenceCoord(); if (otherReferenceCoord != null && getReferenceCoord().compareTo(otherReferenceCoord) >= 0) { throw new IllegalArgumentException("The controller with the lowest minimum-coord value must consume the one with the higher coords"); } - Set partsToAcquire = new HashSet<>(other.connectedParts); + Set partsToAcquire = new HashSet<>(other.getComponents()); // releases all blocks and references gently so they can be incorporated into another multiblock other._onAssimilated(this); - for (IMultiblockPart acquiredPart : partsToAcquire) { + for (IMultiblockComponent acquiredPart : partsToAcquire) { // By definition, none of these can be the minimum block. if (acquiredPart.isInvalid()) { continue; } connectedParts.add(acquiredPart); - acquiredPart.onAssimilated(this); + MultiblockLogic logic = (MultiblockLogic) acquiredPart.getMultiblockLogic(); + logic.setController(this); this.onBlockAdded(acquiredPart); } @@ -493,12 +368,15 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest * Essentially, forcibly tear down this object. * @param otherController The controller consuming this controller. */ - private void _onAssimilated(MultiblockControllerBase otherController) { + @Override + public void _onAssimilated(IMultiblockControllerInternal otherController) { if (referenceCoord != null) { - if (worldObj.getChunkProvider().chunkExists(referenceCoord.getChunkX(), referenceCoord.getChunkZ())) { - TileEntity te = this.worldObj.getTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); - if (te instanceof IMultiblockPart) { - ((IMultiblockPart) te).forfeitMultiblockSaveDelegate(); + if (worldObj.getChunkProvider().chunkExists(referenceCoord.posX >> 4, referenceCoord.posZ >> 4)) { + TileEntity te = this.worldObj.getTileEntity(referenceCoord.posX, referenceCoord.posY, referenceCoord.posZ); + if (te instanceof IMultiblockComponent) { + IMultiblockComponent part = (IMultiblockComponent) te; + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); + logic.forfeitMultiblockSaveDelegate(); } } this.referenceCoord = null; @@ -513,7 +391,7 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest * Use this to absorb that controller's game data. * @param assimilated The controller whose uniqueness was added to our own. */ - protected abstract void onAssimilate(MultiblockControllerBase assimilated); + protected abstract void onAssimilate(IMultiblockControllerInternal assimilated); /** * Callback. Called after this controller is assimilated into another controller. @@ -522,12 +400,10 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest * This is intended primarily for cleanup. * @param assimilator The controller which has assimilated this controller. */ - protected abstract void onAssimilated(MultiblockControllerBase assimilator); + @Override + public abstract void onAssimilated(IMultiblockControllerInternal assimilator); - /** - * Driver for the update loop. If the machine is assembled, runs - * the game logic update method. - */ + @Override public final void updateMultiblockEntity() { tickCount++; @@ -548,12 +424,12 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest // If this returns true, the server has changed its internal data. // If our chunks are loaded (they should be), we must mark our chunks as dirty. if (minimumCoord != null && maximumCoord != null && - this.worldObj.checkChunksExist(minimumCoord.x, minimumCoord.y, minimumCoord.z, - maximumCoord.x, maximumCoord.y, maximumCoord.z)) { - int minChunkX = minimumCoord.x >> 4; - int minChunkZ = minimumCoord.z >> 4; - int maxChunkX = maximumCoord.x >> 4; - int maxChunkZ = maximumCoord.z >> 4; + this.worldObj.checkChunksExist(minimumCoord.posX, minimumCoord.posY, minimumCoord.posZ, + maximumCoord.posX, maximumCoord.posY, maximumCoord.posZ)) { + int minChunkX = minimumCoord.posX >> 4; + int minChunkZ = minimumCoord.posZ >> 4; + int maxChunkX = maximumCoord.posX >> 4; + int maxChunkZ = maximumCoord.posZ >> 4; for (int x = minChunkX; x <= maxChunkX; x++) { for (int z = minChunkZ; z <= maxChunkZ; z++) { @@ -614,10 +490,8 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest throw new MultiblockValidationException(StringUtil.localizeAndFormatRaw("for.multiblock.error.invalid.interior", x, y, z, block.getLocalizedName())); } - /** - * @return The reference coordinate, the block with the lowest x, y, z coordinates, evaluated in that order. - */ - public CoordTriplet getReferenceCoord() { + @Override + public ChunkCoordinates getReferenceCoord() { if (referenceCoord == null) { selectNewReferenceCoord(); } @@ -631,40 +505,30 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest return connectedParts.size(); } - public void writeToNBT(NBTTagCompound data) { - accessHandler.writeToNBT(data); - } - - public void readFromNBT(NBTTagCompound data) { - accessHandler.readFromNBT(data); - } - - /** - * Force this multiblock to recalculate its minimum and maximum coordinates - * from the list of connected parts. - */ + @Override public void recalculateMinMaxCoords() { - minimumCoord = new CoordTriplet(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); - maximumCoord = new CoordTriplet(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); + minimumCoord = new ChunkCoordinates(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); + maximumCoord = new ChunkCoordinates(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); - for (IMultiblockPart part : connectedParts) { - if (part.xCoord < minimumCoord.x) { - minimumCoord.x = part.xCoord; + for (IMultiblockComponent part : connectedParts) { + ChunkCoordinates partCoords = part.getCoordinates(); + if (partCoords.posX < minimumCoord.posX) { + minimumCoord.posX = partCoords.posX; } - if (part.xCoord > maximumCoord.x) { - maximumCoord.x = part.xCoord; + if (partCoords.posX > maximumCoord.posX) { + maximumCoord.posX = partCoords.posX; } - if (part.yCoord < minimumCoord.y) { - minimumCoord.y = part.yCoord; + if (partCoords.posY < minimumCoord.posY) { + minimumCoord.posY = partCoords.posY; } - if (part.yCoord > maximumCoord.y) { - maximumCoord.y = part.yCoord; + if (partCoords.posY > maximumCoord.posY) { + maximumCoord.posY = partCoords.posY; } - if (part.zCoord < minimumCoord.z) { - minimumCoord.z = part.zCoord; + if (partCoords.posZ < minimumCoord.posZ) { + minimumCoord.posZ = partCoords.posZ; } - if (part.zCoord > maximumCoord.z) { - maximumCoord.z = part.zCoord; + if (partCoords.posZ > maximumCoord.posZ) { + maximumCoord.posZ = partCoords.posZ; } } } @@ -672,76 +536,56 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest /** * @return The minimum bounding-box coordinate containing this machine's blocks. */ - public CoordTriplet getMinimumCoord() { + protected ChunkCoordinates getMinimumCoord() { if (minimumCoord == null) { recalculateMinMaxCoords(); } - return minimumCoord.copy(); + return new ChunkCoordinates(minimumCoord); } /** * @return The maximum bounding-box coordinate containing this machine's blocks. */ - public CoordTriplet getMaximumCoord() { + protected ChunkCoordinates getMaximumCoord() { if (maximumCoord == null) { recalculateMinMaxCoords(); } - return maximumCoord.copy(); + return new ChunkCoordinates(maximumCoord); } - public final CoordTriplet getCenterCoord() { - CoordTriplet minCoord = getMinimumCoord(); - CoordTriplet maxCoord = getMaximumCoord(); + protected final ChunkCoordinates getCenterCoord() { + ChunkCoordinates minCoord = getMinimumCoord(); + ChunkCoordinates maxCoord = getMaximumCoord(); - return new CoordTriplet( - (minCoord.x + maxCoord.x) / 2, - (minCoord.y + maxCoord.y) / 2, - (minCoord.z + maxCoord.z) / 2 + return new ChunkCoordinates( + (minCoord.posX + maxCoord.posX) / 2, + (minCoord.posY + maxCoord.posY) / 2, + (minCoord.posZ + maxCoord.posZ) / 2 ); } - public final CoordTriplet getTopCenterCoord() { - CoordTriplet minCoord = getMinimumCoord(); - CoordTriplet maxCoord = getMaximumCoord(); + protected final ChunkCoordinates getTopCenterCoord() { + ChunkCoordinates minCoord = getMinimumCoord(); + ChunkCoordinates maxCoord = getMaximumCoord(); - return new CoordTriplet( - (minCoord.x + maxCoord.x) / 2, - maxCoord.y, - (minCoord.z + maxCoord.z) / 2 + return new ChunkCoordinates( + (minCoord.posX + maxCoord.posX) / 2, + maxCoord.posY, + (minCoord.posZ + maxCoord.posZ) / 2 ); } - public final boolean isCoordInMultiblock(int x, int y, int z) { - return (x >= minimumCoord.x && x <= maximumCoord.x) && (y >= minimumCoord.y && y <= maximumCoord.y) && (z >= minimumCoord.z && z <= maximumCoord.z); + protected final boolean isCoordInMultiblock(int x, int y, int z) { + return (x >= minimumCoord.posX && x <= maximumCoord.posX) && (y >= minimumCoord.posY && y <= maximumCoord.posY) && (z >= minimumCoord.posZ && z <= maximumCoord.posZ); } - /** - * Called when the save delegate's tile entity is being asked for its description packet - * @param data A fresh compound tag to write your multiblock data into - */ - public abstract void formatDescriptionPacket(NBTTagCompound data); - - /** - * Called when the save delegate's tile entity receiving a description packet - * @param data A compound tag containing multiblock data to import - */ - public abstract void decodeDescriptionPacket(NBTTagCompound data); - - /** - * @return True if this controller has no associated blocks, false otherwise - */ + @Override public boolean isEmpty() { return connectedParts.isEmpty(); } - /** - * Tests whether this multiblock should consume the other multiblock - * and become the new multiblock master when the two multiblocks - * are adjacent. Assumes both multiblocks are the same type. - * @param otherController The other multiblock controller. - * @return True if this multiblock should consume the other, false otherwise. - */ - public boolean shouldConsume(MultiblockControllerBase otherController) { + @Override + public boolean shouldConsume(IMultiblockControllerInternal otherController) { if (!otherController.getClass().equals(getClass())) { throw new IllegalArgumentException("Attempting to merge two multiblocks with different master classes - this should never happen!"); } @@ -768,16 +612,17 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest return false; } else { Log.severe("My Controller (%d): size (%d), parts: %s", hashCode(), connectedParts.size(), getPartsListString()); - Log.severe("Other Controller (%d): size (%d), coords: %s", otherController.hashCode(), otherController.connectedParts.size(), otherController.getPartsListString()); - throw new IllegalArgumentException("[" + (worldObj.isRemote ? "CLIENT" : "SERVER") + "] Two controllers with the same reference coord that somehow both have valid parts - this should never happen!"); + Log.severe("Other Controller (%d): size (%d), coords: %s", otherController.hashCode(), otherController.getComponents().size(), otherController.getPartsListString()); + throw new IllegalArgumentException("[" + (worldObj.isRemote ? "CLIENT" : "SERVER") + "] " + + "Two controllers with the same reference coord that somehow both have valid parts - this should never happen!"); } } } - private int _shouldConsume(MultiblockControllerBase otherController) { - CoordTriplet myCoord = getReferenceCoord(); - CoordTriplet theirCoord = otherController.getReferenceCoord(); + private int _shouldConsume(IMultiblockControllerInternal otherController) { + ChunkCoordinates myCoord = getReferenceCoord(); + ChunkCoordinates theirCoord = otherController.getReferenceCoord(); // Always consume other controllers if their reference coordinate is null - this means they're empty and can be assimilated on the cheap if (theirCoord == null) { @@ -786,28 +631,29 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest return myCoord.compareTo(theirCoord); } } - - private String getPartsListString() { + + @Override + public String getPartsListString() { StringBuilder sb = new StringBuilder(); boolean first = true; - for (IMultiblockPart part : connectedParts) { + for (IMultiblockComponent part : connectedParts) { if (!first) { sb.append(", "); } - sb.append(String.format("(%d: %d, %d, %d)", part.hashCode(), part.xCoord, part.yCoord, part.zCoord)); + ChunkCoordinates partCoord = part.getCoordinates(); + sb.append(String.format("(%d: %d, %d, %d)", part.hashCode(), partCoord.posX, partCoord.posY, partCoord.posZ)); first = false; } return sb.toString(); } - /** - * Checks all of the parts in the controller. If any are dead or do not exist in the world, they are removed. - */ - private void auditParts() { - HashSet deadParts = new HashSet<>(); - for (IMultiblockPart part : connectedParts) { - if (part.isInvalid() || worldObj.getTileEntity(part.xCoord, part.yCoord, part.zCoord) != part) { + @Override + public void auditParts() { + HashSet deadParts = new HashSet<>(); + for (IMultiblockComponent part : connectedParts) { + ChunkCoordinates partCoord = part.getCoordinates(); + if (part.isInvalid() || worldObj.getTileEntity(partCoord.posX, partCoord.posY, partCoord.posZ) != part) { onDetachBlock(part); deadParts.add(part); } @@ -817,19 +663,16 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest Log.warning("[%s] Controller found %d dead parts during an audit, %d parts remain attached", worldObj.isRemote ? "CLIENT" : "SERVER", deadParts.size(), connectedParts.size()); } - /** - * Called when this machine may need to check for blocks that are no - * longer physically connected to the reference coordinate. - * @return - */ - public Set checkForDisconnections() { + @Override + @Nonnull + public Set checkForDisconnections() { if (!this.shouldCheckForDisconnections) { - return null; + return Collections.emptySet(); } if (this.isEmpty()) { MultiblockRegistry.addDeadController(worldObj, this); - return null; + return Collections.emptySet(); } IChunkProvider chunkProvider = worldObj.getChunkProvider(); @@ -838,30 +681,33 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest referenceCoord = null; // Reset visitations and find the minimum coordinate - Set deadParts = new HashSet<>(); - CoordTriplet c; - IMultiblockPart referencePart = null; + Set deadParts = new HashSet<>(); + ChunkCoordinates c; + IMultiblockComponent referencePart = null; int originalSize = connectedParts.size(); - for (IMultiblockPart part : connectedParts) { + for (IMultiblockComponent part : connectedParts) { // This happens during chunk unload. - if (!chunkProvider.chunkExists(part.xCoord >> 4, part.zCoord >> 4) || part.isInvalid()) { + ChunkCoordinates partCoord = part.getCoordinates(); + if (!chunkProvider.chunkExists(partCoord.posX >> 4, partCoord.posZ >> 4) || part.isInvalid()) { deadParts.add(part); onDetachBlock(part); continue; } - if (worldObj.getTileEntity(part.xCoord, part.yCoord, part.zCoord) != part) { + if (worldObj.getTileEntity(partCoord.posX, partCoord.posY, partCoord.posZ) != part) { deadParts.add(part); onDetachBlock(part); continue; } - part.setUnvisited(); - part.forfeitMultiblockSaveDelegate(); + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); + + logic.setUnvisited(); + logic.forfeitMultiblockSaveDelegate(); - c = part.getWorldLocation(); + c = part.getCoordinates(); if (referenceCoord == null) { referenceCoord = c; referencePart = part; @@ -878,43 +724,44 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest // There are no valid parts remaining. The entire multiblock was unloaded during a chunk unload. Halt. shouldCheckForDisconnections = false; MultiblockRegistry.addDeadController(worldObj, this); - return null; + return Collections.emptySet(); } else { - referencePart.becomeMultiblockSaveDelegate(); + MultiblockLogic logic = (MultiblockLogic) referencePart.getMultiblockLogic(); + logic.becomeMultiblockSaveDelegate(); } // Now visit all connected parts, breadth-first, starting from reference coord's part - IMultiblockPart part; - LinkedList partsToCheck = new LinkedList<>(); - int visitedParts = 0; + IMultiblockComponent part; + LinkedList partsToCheck = new LinkedList<>(); partsToCheck.add(referencePart); while (!partsToCheck.isEmpty()) { part = partsToCheck.removeFirst(); - part.setVisited(); - visitedParts++; + MultiblockLogic partLogic = (MultiblockLogic) part.getMultiblockLogic(); + partLogic.setVisited(); - IMultiblockPart[] nearbyParts = part.getNeighboringParts(); // Chunk-safe on server, but not on client - for (IMultiblockPart nearbyPart : nearbyParts) { + List nearbyParts = MultiblockUtil.getNeighboringParts(worldObj, part); // Chunk-safe on server, but not on client + for (IMultiblockComponent nearbyPart : nearbyParts) { // Ignore different machines - if (nearbyPart.getMultiblockController() != this) { + MultiblockLogic nearbyPartLogic = (MultiblockLogic) nearbyPart.getMultiblockLogic(); + if (nearbyPartLogic.getController() != this) { continue; } - if (!nearbyPart.isVisited()) { - nearbyPart.setVisited(); + if (!nearbyPartLogic.isVisited()) { + nearbyPartLogic.setVisited(); partsToCheck.add(nearbyPart); } } } // Finally, remove all parts that remain disconnected. - Set removedParts = new HashSet<>(); - for (IMultiblockPart orphanCandidate : connectedParts) { - if (!orphanCandidate.isVisited()) { + Set removedParts = new HashSet<>(); + for (IMultiblockComponent orphanCandidate : connectedParts) { + MultiblockLogic logic = (MultiblockLogic) orphanCandidate.getMultiblockLogic(); + if (!logic.isVisited()) { deadParts.add(orphanCandidate); - orphanCandidate.onOrphaned(this, originalSize, visitedParts); onDetachBlock(orphanCandidate); removedParts.add(orphanCandidate); } @@ -937,24 +784,22 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest return removedParts; } - /** - * Detach all parts. Return a set of all parts which still - * have a valid tile entity. Chunk-safe. - * @return A set of all parts which still have a valid tile entity. - */ - public Set detachAllBlocks() { + @Override + @Nonnull + public Set detachAllBlocks() { if (worldObj == null) { return new HashSet<>(); } IChunkProvider chunkProvider = worldObj.getChunkProvider(); - for (IMultiblockPart part : connectedParts) { - if (chunkProvider.chunkExists(part.xCoord >> 4, part.zCoord >> 4)) { + for (IMultiblockComponent part : connectedParts) { + ChunkCoordinates partCoord = part.getCoordinates(); + if (chunkProvider.chunkExists(partCoord.posX >> 4, partCoord.posZ >> 4)) { onDetachBlock(part); } } - Set detachedParts = connectedParts; + Set detachedParts = connectedParts; connectedParts = new HashSet<>(); return detachedParts; } @@ -968,23 +813,25 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest private void selectNewReferenceCoord() { IChunkProvider chunkProvider = worldObj.getChunkProvider(); - TileEntity theChosenOne = null; + IMultiblockComponent theChosenOne = null; referenceCoord = null; - for (IMultiblockPart part : connectedParts) { - if (part.isInvalid() || !chunkProvider.chunkExists(part.xCoord >> 4, part.zCoord >> 4)) { + for (IMultiblockComponent part : connectedParts) { + ChunkCoordinates partCoord = part.getCoordinates(); + if (part.isInvalid() || !chunkProvider.chunkExists(partCoord.posX >> 4, partCoord.posZ >> 4)) { // Chunk is unloading, skip this coord to prevent chunk thrashing continue; } - if (referenceCoord == null || referenceCoord.compareTo(part.xCoord, part.yCoord, part.zCoord) > 0) { - referenceCoord = part.getWorldLocation(); + if (referenceCoord == null || referenceCoord.compareTo(partCoord) > 0) { + referenceCoord = part.getCoordinates(); theChosenOne = part; } } if (theChosenOne != null) { - ((IMultiblockPart) theChosenOne).becomeMultiblockSaveDelegate(); + MultiblockLogic logic = (MultiblockLogic) theChosenOne.getMultiblockLogic(); + logic.becomeMultiblockSaveDelegate(); } } @@ -999,9 +846,9 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest * On the client, this will mark the block for a rendering update. */ protected void markReferenceCoordForUpdate() { - CoordTriplet rc = getReferenceCoord(); + ChunkCoordinates rc = getReferenceCoord(); if (worldObj != null && rc != null) { - worldObj.markBlockForUpdate(rc.x, rc.y, rc.z); + worldObj.markBlockForUpdate(rc.posX, rc.posY, rc.posZ); } } @@ -1020,97 +867,12 @@ public abstract class MultiblockControllerBase implements ISidedInventory, IRest return; } - CoordTriplet referenceCoord = getReferenceCoord(); + ChunkCoordinates referenceCoord = getReferenceCoord(); if (referenceCoord == null) { return; } - TileEntity saveTe = worldObj.getTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); - worldObj.markTileEntityChunkModified(referenceCoord.x, referenceCoord.y, referenceCoord.z, saveTe); - } - - /* INVENTORY */ - public IInventoryAdapter getInternalInventory() { - return FakeInventoryAdapter.instance(); - } - - @Override - public void markDirty() { - getInternalInventory().markDirty(); - } - - @Override - public final int getSizeInventory() { - return getInternalInventory().getSizeInventory(); - } - - @Override - public final ItemStack getStackInSlot(int slotIndex) { - return getInternalInventory().getStackInSlot(slotIndex); - } - - @Override - public final ItemStack decrStackSize(int slotIndex, int amount) { - return getInternalInventory().decrStackSize(slotIndex, amount); - } - - @Override - public final ItemStack getStackInSlotOnClosing(int slotIndex) { - return getInternalInventory().getStackInSlotOnClosing(slotIndex); - } - - @Override - public final void setInventorySlotContents(int slotIndex, ItemStack itemstack) { - getInternalInventory().setInventorySlotContents(slotIndex, itemstack); - } - - @Override - public final int getInventoryStackLimit() { - return getInternalInventory().getInventoryStackLimit(); - } - - @Override - public final void openInventory() { - getInternalInventory().openInventory(); - } - - @Override - public final void closeInventory() { - getInternalInventory().closeInventory(); - } - - @Override - public final String getInventoryName() { - return getInternalInventory().getInventoryName(); - } - - @Override - public final boolean isUseableByPlayer(EntityPlayer player) { - return getInternalInventory().isUseableByPlayer(player); - } - - @Override - public final boolean hasCustomInventoryName() { - return getInternalInventory().hasCustomInventoryName(); - } - - @Override - public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { - return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); - } - - @Override - public final int[] getAccessibleSlotsFromSide(int side) { - return getInternalInventory().getAccessibleSlotsFromSide(side); - } - - @Override - public final boolean canInsertItem(int slotIndex, ItemStack itemStack, int side) { - return getInternalInventory().canInsertItem(slotIndex, itemStack, side); - } - - @Override - public final boolean canExtractItem(int slotIndex, ItemStack itemStack, int side) { - return getInternalInventory().canExtractItem(slotIndex, itemStack, side); + TileEntity saveTe = worldObj.getTileEntity(referenceCoord.posX, referenceCoord.posY, referenceCoord.posZ); + worldObj.markTileEntityChunkModified(referenceCoord.posX, referenceCoord.posY, referenceCoord.posZ, saveTe); } } diff --git a/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java b/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java new file mode 100644 index 000000000..c92d1fb58 --- /dev/null +++ b/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java @@ -0,0 +1,192 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import com.google.common.collect.HashMultiset; +import com.google.common.collect.Multiset; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +import com.mojang.authlib.GameProfile; + +import forestry.api.core.ForestryAPI; +import forestry.api.core.IErrorLogic; +import forestry.api.core.IErrorLogicSource; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.core.access.AccessHandler; +import forestry.core.access.IAccessHandler; +import forestry.core.access.IOwnable; +import forestry.core.access.IRestrictedAccess; +import forestry.core.inventory.FakeInventoryAdapter; +import forestry.core.inventory.IInventoryAdapter; +import forestry.core.tiles.ILocatable; + +public abstract class MultiblockControllerForestry extends MultiblockControllerBase implements ISidedInventory, IRestrictedAccess, IErrorLogicSource, ILocatable { + private final AccessHandler accessHandler; + private final IErrorLogic errorLogic; + + protected MultiblockControllerForestry(World world) { + super(world); + + this.accessHandler = new AccessHandler(this); + this.errorLogic = ForestryAPI.errorStateRegistry.createErrorLogic(); + } + + @Override + public IAccessHandler getAccessHandler() { + return accessHandler; + } + + @Override + public IErrorLogic getErrorLogic() { + return errorLogic; + } + + @Override + protected void onMachineAssembled() { + super.onMachineAssembled(); + + if (worldObj.isRemote) { + return; + } + + // Figure out who owns the multiblock, by majority + + Multiset owners = HashMultiset.create(); + for (IMultiblockComponent part : connectedParts) { + if (part instanceof IRestrictedAccess) { + IAccessHandler accessHandler = ((IRestrictedAccess) part).getAccessHandler(); + GameProfile owner = accessHandler.getOwner(); + if (owner != null) { + owners.add(owner); + } + } else if (part instanceof IOwnable) { + IOwnable ownable = (IOwnable) part; + GameProfile owner = ownable.getOwner(); + if (owner != null) { + owners.add(owner); + } + } + } + + GameProfile owner = null; + int max = 0; + for (Multiset.Entry entry : owners.entrySet()) { + int count = entry.getCount(); + if (count > max) { + max = count; + owner = entry.getElement(); + } + } + + getAccessHandler().setOwner(owner); + } + + /* INBTTagable */ + @Override + public void writeToNBT(NBTTagCompound data) { + accessHandler.writeToNBT(data); + } + + @Override + public void readFromNBT(NBTTagCompound data) { + accessHandler.readFromNBT(data); + } + + /* INVENTORY */ + public IInventoryAdapter getInternalInventory() { + return FakeInventoryAdapter.instance(); + } + + @Override + public void markDirty() { + getInternalInventory().markDirty(); + } + + @Override + public final int getSizeInventory() { + return getInternalInventory().getSizeInventory(); + } + + @Override + public final ItemStack getStackInSlot(int slotIndex) { + return getInternalInventory().getStackInSlot(slotIndex); + } + + @Override + public final ItemStack decrStackSize(int slotIndex, int amount) { + return getInternalInventory().decrStackSize(slotIndex, amount); + } + + @Override + public final ItemStack getStackInSlotOnClosing(int slotIndex) { + return getInternalInventory().getStackInSlotOnClosing(slotIndex); + } + + @Override + public final void setInventorySlotContents(int slotIndex, ItemStack itemstack) { + getInternalInventory().setInventorySlotContents(slotIndex, itemstack); + } + + @Override + public final int getInventoryStackLimit() { + return getInternalInventory().getInventoryStackLimit(); + } + + @Override + public final void openInventory() { + getInternalInventory().openInventory(); + } + + @Override + public final void closeInventory() { + getInternalInventory().closeInventory(); + } + + @Override + public final String getInventoryName() { + return getInternalInventory().getInventoryName(); + } + + @Override + public final boolean isUseableByPlayer(EntityPlayer player) { + return getInternalInventory().isUseableByPlayer(player); + } + + @Override + public final boolean hasCustomInventoryName() { + return getInternalInventory().hasCustomInventoryName(); + } + + @Override + public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { + return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); + } + + @Override + public final int[] getAccessibleSlotsFromSide(int side) { + return getInternalInventory().getAccessibleSlotsFromSide(side); + } + + @Override + public final boolean canInsertItem(int slotIndex, ItemStack itemStack, int side) { + return getInternalInventory().canInsertItem(slotIndex, itemStack, side); + } + + @Override + public final boolean canExtractItem(int slotIndex, ItemStack itemStack, int side) { + return getInternalInventory().canExtractItem(slotIndex, itemStack, side); + } +} diff --git a/src/main/java/forestry/core/multiblock/MultiblockLogic.java b/src/main/java/forestry/core/multiblock/MultiblockLogic.java new file mode 100644 index 000000000..337b94c44 --- /dev/null +++ b/src/main/java/forestry/core/multiblock/MultiblockLogic.java @@ -0,0 +1,204 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; + +import forestry.api.multiblock.IMultiblockComponent; +import forestry.api.multiblock.IMultiblockLogic; +import forestry.core.utils.Log; + +public abstract class MultiblockLogic implements IMultiblockLogic { + private final Class controllerClass; + private boolean visited; + private boolean saveMultiblockData; + private NBTTagCompound cachedMultiblockData; + protected T controller; + + protected MultiblockLogic(Class controllerClass) { + this.controllerClass = controllerClass; + this.controller = null; + this.visited = false; + this.saveMultiblockData = false; + this.cachedMultiblockData = null; + } + + public void setController(IMultiblockControllerInternal controller) { + if (controller == null) { + this.controller = null; + } else if (controllerClass.isAssignableFrom(controller.getClass())) { + this.controller = controllerClass.cast(controller); + } + } + + public Class getControllerClass() { + return controllerClass; + } + + @Override + public abstract T getController(); + + public abstract T createNewController(World world); + + /** + * This is called when a block is being marked as valid by the chunk, but has not yet fully + * been placed into the world's TileEntity cache. this.worldObj, xCoord, yCoord and zCoord have + * been initialized, but any attempts to read data about the world can cause infinite loops - + * if you call getTileEntity on this TileEntity's coordinate from within validate(), you will + * blow your call stack. + * + * TL;DR: Here there be dragons. + * @see net.minecraft.tileentity.TileEntity#validate() + */ + @Override + public void validate(World world, IMultiblockComponent part) { + MultiblockRegistry.onPartAdded(world, part); + } + + /** + * Called when a block is removed by game actions, such as a player breaking the block + * or the block being changed into another block. + * @see net.minecraft.tileentity.TileEntity#invalidate() + */ + @Override + public final void invalidate(World world, IMultiblockComponent part) { + detachSelf(world, part, false); + } + + /** + * Called from Minecraft's tile entity loop, after all tile entities have been ticked, + * as the chunk in which this tile entity is contained is unloading. + * Happens before the Forge TickEnd event. + * @see net.minecraft.tileentity.TileEntity#onChunkUnload() + */ + @Override + public final void onChunkUnload(World world, IMultiblockComponent part) { + detachSelf(world, part, true); + } + + /* + * Detaches this block from its controller. Calls detachBlock() and clears the controller member. + */ + protected void detachSelf(World world, IMultiblockComponent part, boolean chunkUnloading) { + if (this.controller != null) { + // Clean part out of controller + this.controller.detachBlock(part, chunkUnloading); + + // The above should call onDetached, but, just in case... + this.controller = null; + } + + // Clean part out of lists in the registry + MultiblockRegistry.onPartRemovedFromWorld(world, part); + } + + @Override + public void readFromNBT(NBTTagCompound data) { + // We can't directly initialize a multiblock controller yet, so we cache the data here until + // we receive a validate() call, which creates the controller and hands off the cached data. + if (data.hasKey("multiblockData")) { + this.cachedMultiblockData = data.getCompoundTag("multiblockData"); + } + } + + @Override + public void writeToNBT(NBTTagCompound data) { + if (isMultiblockSaveDelegate() && isConnected()) { + NBTTagCompound multiblockData = new NBTTagCompound(); + this.controller.writeToNBT(multiblockData); + data.setTag("multiblockData", multiblockData); + } + } + + public final void assertDetached(IMultiblockComponent part) { + if (this.controller != null) { + ChunkCoordinates coords = part.getCoordinates(); + Log.info("[assert] Part @ (%d, %d, %d) should be detached already, but detected that it was not. This is not a fatal error, and will be repaired, but is unusual.", coords.posX, coords.posY, coords.posZ); + this.controller = null; + } + } + + @Override + public final boolean isConnected() { + return (controller != null); + } + + public final void becomeMultiblockSaveDelegate() { + this.saveMultiblockData = true; + } + + public final void forfeitMultiblockSaveDelegate() { + this.saveMultiblockData = false; + } + + public final boolean isMultiblockSaveDelegate() { + return this.saveMultiblockData; + } + + public final void setUnvisited() { + this.visited = false; + } + + public final void setVisited() { + this.visited = true; + } + + public final boolean isVisited() { + return this.visited; + } + + public final boolean hasMultiblockSaveData() { + return this.cachedMultiblockData != null; + } + + public final NBTTagCompound getMultiblockSaveData() { + return this.cachedMultiblockData; + } + + public final void onMultiblockDataAssimilated() { + this.cachedMultiblockData = null; + } + + /** + * Override this to easily modify the description packet's data without having + * to worry about sending the packet itself. + * Decode this data in decodeDescriptionPacket. + * @param packetData An NBT compound tag into which you should write your custom description data. + */ + @Override + public void encodeDescriptionPacket(NBTTagCompound packetData) { + if (this.isMultiblockSaveDelegate() && isConnected()) { + NBTTagCompound tag = new NBTTagCompound(); + controller.formatDescriptionPacket(tag); + packetData.setTag("multiblockData", tag); + } + } + + /** + * Override this to easily read in data from a TileEntity's description packet. + * Encoded in encodeDescriptionPacket. + * @param packetData The NBT data from the tile entity's description packet. + */ + @Override + public void decodeDescriptionPacket(NBTTagCompound packetData) { + if (packetData.hasKey("multiblockData")) { + NBTTagCompound tag = packetData.getCompoundTag("multiblockData"); + if (isConnected()) { + controller.decodeDescriptionPacket(tag); + } else { + // This part hasn't been added to a machine yet, so cache the data. + this.cachedMultiblockData = tag; + } + } + } +} diff --git a/src/main/java/forestry/core/multiblock/MultiblockLogicFactory.java b/src/main/java/forestry/core/multiblock/MultiblockLogicFactory.java new file mode 100644 index 000000000..d60294a3d --- /dev/null +++ b/src/main/java/forestry/core/multiblock/MultiblockLogicFactory.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import forestry.api.multiblock.IMultiblockLogicAlveary; +import forestry.api.multiblock.IMultiblockLogicFactory; +import forestry.api.multiblock.IMultiblockLogicFarm; +import forestry.apiculture.multiblock.MultiblockLogicAlveary; +import forestry.farming.multiblock.MultiblockLogicFarm; + +public class MultiblockLogicFactory implements IMultiblockLogicFactory { + + @Override + public IMultiblockLogicAlveary createAlvearyLogic() { + return new MultiblockLogicAlveary(); + } + + @Override + public IMultiblockLogicFarm createFarmLogic() { + return new MultiblockLogicFarm(); + } +} diff --git a/src/main/java/forestry/core/multiblock/MultiblockRegistry.java b/src/main/java/forestry/core/multiblock/MultiblockRegistry.java index 65c063634..73d87c5b5 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockRegistry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockRegistry.java @@ -6,6 +6,7 @@ import java.util.Set; import net.minecraft.world.World; +import forestry.api.multiblock.IMultiblockComponent; import forestry.core.utils.Log; /** @@ -46,7 +47,7 @@ public class MultiblockRegistry { * @param world The world into which this part is loading. * @param part The part being loaded. */ - public static void onPartAdded(World world, IMultiblockPart part) { + public static void onPartAdded(World world, IMultiblockComponent part) { MultiblockWorldRegistry registry = getOrCreateRegistry(world); registry.onPartAdded(part); } @@ -56,7 +57,7 @@ public class MultiblockRegistry { * @param world The world from which a multiblock part is being removed. * @param part The part being removed. */ - public static void onPartRemovedFromWorld(World world, IMultiblockPart part) { + public static void onPartRemovedFromWorld(World world, IMultiblockComponent part) { if (registries.containsKey(world)) { registries.get(world).onPartRemovedFromWorld(part); } @@ -81,7 +82,7 @@ public class MultiblockRegistry { * @param world The world containing the multiblock * @param controller The dirty controller */ - public static void addDirtyController(World world, MultiblockControllerBase controller) { + public static void addDirtyController(World world, IMultiblockControllerInternal controller) { if (registries.containsKey(world)) { registries.get(world).addDirtyController(controller); } else { @@ -95,7 +96,7 @@ public class MultiblockRegistry { * @param world The world formerly containing the multiblock * @param controller The dead controller */ - public static void addDeadController(World world, MultiblockControllerBase controller) { + public static void addDeadController(World world, IMultiblockControllerInternal controller) { if (registries.containsKey(world)) { registries.get(world).addDeadController(controller); } else { @@ -107,7 +108,7 @@ public class MultiblockRegistry { * @param world The world whose controllers you wish to retrieve. * @return An unmodifiable set of controllers active in the given world, or null if there are none. */ - public static Set getControllersFromWorld(World world) { + public static Set getControllersFromWorld(World world) { if (registries.containsKey(world)) { return registries.get(world).getControllers(); } diff --git a/src/main/java/forestry/core/multiblock/MultiblockTileEntityBase.java b/src/main/java/forestry/core/multiblock/MultiblockTileEntityBase.java deleted file mode 100644 index b5beb56ff..000000000 --- a/src/main/java/forestry/core/multiblock/MultiblockTileEntityBase.java +++ /dev/null @@ -1,532 +0,0 @@ -package forestry.core.multiblock; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTUtil; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.Packet; -import net.minecraft.network.play.server.S35PacketUpdateTileEntity; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; - -import com.mojang.authlib.GameProfile; - -import forestry.core.access.IOwnable; -import forestry.core.config.Constants; -import forestry.core.inventory.FakeInventoryAdapter; -import forestry.core.inventory.IInventoryAdapter; -import forestry.core.tiles.IFilterSlotDelegate; -import forestry.core.tiles.ILocatable; -import forestry.core.utils.Log; -import forestry.core.utils.PlayerUtil; - -/** - * Base logic class for Multiblock-connected tile entities. Most multiblock machines - * should derive from this and implement their game logic in certain abstract methods. - */ -public abstract class MultiblockTileEntityBase extends IMultiblockPart implements ISidedInventory, IFilterSlotDelegate, IOwnable, ILocatable { - private MultiblockControllerBase controller; - private boolean visited; - - private boolean saveMultiblockData; - private NBTTagCompound cachedMultiblockData; - - private GameProfile owner; - - public MultiblockTileEntityBase() { - super(); - controller = null; - visited = false; - saveMultiblockData = false; - cachedMultiblockData = null; - } - - ///// Multiblock Connection Base Logic - @Override - public final Set attachToNeighbors() { - Set controllers = null; - MultiblockControllerBase bestController = null; - - // Look for a compatible controller in our neighboring parts. - IMultiblockPart[] partsToCheck = getNeighboringParts(); - for (IMultiblockPart neighborPart : partsToCheck) { - if (neighborPart.isConnected()) { - MultiblockControllerBase candidate = neighborPart.getMultiblockController(); - if (!candidate.getClass().equals(this.getMultiblockControllerType())) { - // Skip multiblocks with incompatible types - continue; - } - - if (controllers == null) { - controllers = new HashSet<>(); - bestController = candidate; - } else if (!controllers.contains(candidate) && candidate.shouldConsume(bestController)) { - bestController = candidate; - } - - controllers.add(candidate); - } - } - - // If we've located a valid neighboring controller, attach to it. - if (bestController != null) { - // attachBlock will call onAttached, which will set the controller. - this.controller = bestController; - bestController.attachBlock(this); - } - - return controllers; - } - - @Override - public final void assertDetached() { - if (this.controller != null) { - Log.info("[assert] Part @ (%d, %d, %d) should be detached already, but detected that it was not. This is not a fatal error, and will be repaired, but is unusual.", xCoord, yCoord, zCoord); - this.controller = null; - } - } - - ///// Overrides from base TileEntity methods - - @Override - public void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - - // We can't directly initialize a multiblock controller yet, so we cache the data here until - // we receive a validate() call, which creates the controller and hands off the cached data. - if (data.hasKey("multiblockData")) { - this.cachedMultiblockData = data.getCompoundTag("multiblockData"); - } - - if (data.hasKey("owner")) { - owner = NBTUtil.func_152459_a(data.getCompoundTag("owner")); - } - - getInternalInventory().readFromNBT(data); - } - - @Override - public void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - - if (isMultiblockSaveDelegate() && isConnected()) { - NBTTagCompound multiblockData = new NBTTagCompound(); - this.controller.writeToNBT(multiblockData); - data.setTag("multiblockData", multiblockData); - } - - if (this.owner != null) { - NBTTagCompound nbt = new NBTTagCompound(); - NBTUtil.func_152460_a(nbt, owner); - data.setTag("owner", nbt); - } - - getInternalInventory().writeToNBT(data); - } - - /** - * Generally, TileEntities that are part of a multiblock should not subscribe to updates - * from the main game loop. Instead, you should have lists of TileEntities which need to - * be notified during an update() in your Controller and perform callbacks from there. - * @see net.minecraft.tileentity.TileEntity#canUpdate() - */ - @Override - public boolean canUpdate() { - return false; - } - - /** - * Called when a block is removed by game actions, such as a player breaking the block - * or the block being changed into another block. - * @see net.minecraft.tileentity.TileEntity#invalidate() - */ - @Override - public final void invalidate() { - super.invalidate(); - detachSelf(false); - } - - /** - * Called from Minecraft's tile entity loop, after all tile entities have been ticked, - * as the chunk in which this tile entity is contained is unloading. - * Happens before the Forge TickEnd event. - * @see net.minecraft.tileentity.TileEntity#onChunkUnload() - */ - @Override - public final void onChunkUnload() { - super.onChunkUnload(); - detachSelf(true); - } - - /** - * This is called when a block is being marked as valid by the chunk, but has not yet fully - * been placed into the world's TileEntity cache. this.worldObj, xCoord, yCoord and zCoord have - * been initialized, but any attempts to read data about the world can cause infinite loops - - * if you call getTileEntity on this TileEntity's coordinate from within validate(), you will - * blow your call stack. - * - * TL;DR: Here there be dragons. - * @see net.minecraft.tileentity.TileEntity#validate() - */ - @Override - public final void validate() { - super.validate(); - MultiblockRegistry.onPartAdded(this.worldObj, this); - } - - // Network Communication - @Override - public final Packet getDescriptionPacket() { - NBTTagCompound packetData = new NBTTagCompound(); - encodeDescriptionPacket(packetData); - return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 0, packetData); - } - - @Override - public final void onDataPacket(NetworkManager network, S35PacketUpdateTileEntity packet) { - decodeDescriptionPacket(packet.func_148857_g()); - } - - ///// Things to override in most implementations (IMultiblockPart) - - /** - * Override this to easily modify the description packet's data without having - * to worry about sending the packet itself. - * Decode this data in decodeDescriptionPacket. - * @param packetData An NBT compound tag into which you should write your custom description data. - * @see forestry.core.multiblock.MultiblockTileEntityBase#decodeDescriptionPacket(NBTTagCompound) - */ - protected void encodeDescriptionPacket(NBTTagCompound packetData) { - if (this.isMultiblockSaveDelegate() && isConnected()) { - NBTTagCompound tag = new NBTTagCompound(); - getMultiblockController().formatDescriptionPacket(tag); - packetData.setTag("multiblockData", tag); - } - } - - /** - * Override this to easily read in data from a TileEntity's description packet. - * Encoded in encodeDescriptionPacket. - * @param packetData The NBT data from the tile entity's description packet. - * @see forestry.core.multiblock.MultiblockTileEntityBase#encodeDescriptionPacket(NBTTagCompound) - */ - protected void decodeDescriptionPacket(NBTTagCompound packetData) { - if (packetData.hasKey("multiblockData")) { - NBTTagCompound tag = packetData.getCompoundTag("multiblockData"); - if (isConnected()) { - getMultiblockController().decodeDescriptionPacket(tag); - } else { - // This part hasn't been added to a machine yet, so cache the data. - this.cachedMultiblockData = tag; - } - } - } - - @Override - public final boolean hasMultiblockSaveData() { - return this.cachedMultiblockData != null; - } - - @Override - public final NBTTagCompound getMultiblockSaveData() { - return this.cachedMultiblockData; - } - - @Override - public final void onMultiblockDataAssimilated() { - this.cachedMultiblockData = null; - } - - ///// Game logic callbacks (IMultiblockPart) - - @Override - public abstract void onMachineAssembled(MultiblockControllerBase multiblockControllerBase); - - @Override - public abstract void onMachineBroken(); - - @Override - public abstract void onMachineActivated(); - - @Override - public abstract void onMachineDeactivated(); - - ///// Miscellaneous multiblock-assembly callbacks and support methods (IMultiblockPart) - - @Override - public final boolean isConnected() { - return (controller != null); - } - - @Override - public final MultiblockControllerBase getMultiblockController() { - return controller; - } - - @Override - public final CoordTriplet getWorldLocation() { - return new CoordTriplet(this.xCoord, this.yCoord, this.zCoord); - } - - @Override - public final void becomeMultiblockSaveDelegate() { - this.saveMultiblockData = true; - } - - @Override - public final void forfeitMultiblockSaveDelegate() { - this.saveMultiblockData = false; - } - - @Override - public final boolean isMultiblockSaveDelegate() { - return this.saveMultiblockData; - } - - @Override - public final void setUnvisited() { - this.visited = false; - } - - @Override - public final void setVisited() { - this.visited = true; - } - - @Override - public final boolean isVisited() { - return this.visited; - } - - @Override - public final void onAssimilated(MultiblockControllerBase newController) { - assert (this.controller != newController); - this.controller = newController; - } - - @Override - public void onAttached(MultiblockControllerBase newController) { - this.controller = newController; - } - - @Override - public final void onDetached(MultiblockControllerBase oldController) { - this.controller = null; - } - - @Override - public abstract MultiblockControllerBase createNewMultiblock(); - - @Override - public final IMultiblockPart[] getNeighboringParts() { - CoordTriplet[] neighbors = new CoordTriplet[]{ - new CoordTriplet(this.xCoord - 1, this.yCoord, this.zCoord), - new CoordTriplet(this.xCoord, this.yCoord - 1, this.zCoord), - new CoordTriplet(this.xCoord, this.yCoord, this.zCoord - 1), - new CoordTriplet(this.xCoord, this.yCoord, this.zCoord + 1), - new CoordTriplet(this.xCoord, this.yCoord + 1, this.zCoord), - new CoordTriplet(this.xCoord + 1, this.yCoord, this.zCoord) - }; - - TileEntity te; - List neighborParts = new ArrayList<>(); - IChunkProvider chunkProvider = worldObj.getChunkProvider(); - for (CoordTriplet neighbor : neighbors) { - if (!chunkProvider.chunkExists(neighbor.getChunkX(), neighbor.getChunkZ())) { - // Chunk not loaded, skip it. - continue; - } - - te = this.worldObj.getTileEntity(neighbor.x, neighbor.y, neighbor.z); - if (te instanceof IMultiblockPart) { - neighborParts.add((IMultiblockPart) te); - } - } - IMultiblockPart[] tmp = new IMultiblockPart[neighborParts.size()]; - return neighborParts.toArray(tmp); - } - - @Override - public final void onOrphaned(MultiblockControllerBase controller, int oldSize, int newSize) { - this.markDirty(); - worldObj.markTileEntityChunkModified(xCoord, yCoord, zCoord, this); - } - - //// Helper functions for notifying neighboring blocks - public void notifyNeighborsOfBlockChange() { - worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); - } - - protected void notifyNeighborsOfTileChange() { - worldObj.func_147453_f(xCoord, yCoord, zCoord, getBlockType()); - } - - ///// Private/Protected Logic Helpers - /* - * Detaches this block from its controller. Calls detachBlock() and clears the controller member. - */ - protected void detachSelf(boolean chunkUnloading) { - if (this.controller != null) { - // Clean part out of controller - this.controller.detachBlock(this, chunkUnloading); - - // The above should call onDetached, but, just in case... - this.controller = null; - } - - // Clean part out of lists in the registry - MultiblockRegistry.onPartRemovedFromWorld(worldObj, this); - } - - /* IOwnable */ - @Override - public boolean isOwned() { - return owner != null; - } - - @Override - public GameProfile getOwner() { - return owner; - } - - @Override - public void setOwner(GameProfile owner) { - this.owner = owner; - } - - @Override - public boolean isOwner(EntityPlayer player) { - return PlayerUtil.isSameGameProfile(owner, player.getGameProfile()); - } - - /* INVENTORY */ - public IInventoryAdapter getInternalInventory() { - return FakeInventoryAdapter.instance(); - } - - public boolean allowsAutomation() { - return false; - } - - @Override - public final int getSizeInventory() { - return getInternalInventory().getSizeInventory(); - } - - @Override - public final ItemStack getStackInSlot(int slotIndex) { - return getInternalInventory().getStackInSlot(slotIndex); - } - - @Override - public final ItemStack decrStackSize(int slotIndex, int amount) { - return getInternalInventory().decrStackSize(slotIndex, amount); - } - - @Override - public final ItemStack getStackInSlotOnClosing(int slotIndex) { - return getInternalInventory().getStackInSlotOnClosing(slotIndex); - } - - @Override - public final void setInventorySlotContents(int slotIndex, ItemStack itemstack) { - getInternalInventory().setInventorySlotContents(slotIndex, itemstack); - } - - @Override - public final int getInventoryStackLimit() { - return getInternalInventory().getInventoryStackLimit(); - } - - @Override - public final void openInventory() { - getInternalInventory().openInventory(); - } - - @Override - public final void closeInventory() { - getInternalInventory().closeInventory(); - } - - @Override - public final String getInventoryName() { - return getInternalInventory().getInventoryName(); - } - - @Override - public final boolean isUseableByPlayer(EntityPlayer player) { - return getInternalInventory().isUseableByPlayer(player); - } - - @Override - public final boolean hasCustomInventoryName() { - return getInternalInventory().hasCustomInventoryName(); - } - - @Override - public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { - return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); - } - - @Override - public final int[] getAccessibleSlotsFromSide(int side) { - if (allowsAutomation()) { - return getInternalInventory().getAccessibleSlotsFromSide(side); - } else { - return Constants.SLOTS_NONE; - } - } - - @Override - public final boolean canInsertItem(int slotIndex, ItemStack itemStack, int side) { - if (allowsAutomation()) { - return getInternalInventory().canInsertItem(slotIndex, itemStack, side); - } else { - return false; - } - } - - @Override - public final boolean canExtractItem(int slotIndex, ItemStack itemStack, int side) { - if (allowsAutomation()) { - return getInternalInventory().canExtractItem(slotIndex, itemStack, side); - } else { - return false; - } - } - - @Override - public final boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - return getInternalInventory().canSlotAccept(slotIndex, itemStack); - } - - @Override - public final boolean isLocked(int slotIndex) { - return getInternalInventory().isLocked(slotIndex); - } - - - public void openGui(EntityPlayer player) { - - } - - /* ILocatable */ - @Override - public ChunkCoordinates getCoordinates() { - return getMultiblockController().getCoordinates(); - } - - @Override - public final World getWorld() { - return worldObj; - } -} diff --git a/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java b/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java new file mode 100644 index 000000000..fe213e3da --- /dev/null +++ b/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java @@ -0,0 +1,202 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTUtil; +import net.minecraft.world.World; + +import com.mojang.authlib.GameProfile; + +import forestry.api.multiblock.IMultiblockLogic; +import forestry.api.multiblock.MultiblockTileEntityBase; +import forestry.core.access.IOwnable; +import forestry.core.config.Constants; +import forestry.core.inventory.FakeInventoryAdapter; +import forestry.core.inventory.IInventoryAdapter; +import forestry.core.tiles.IFilterSlotDelegate; +import forestry.core.tiles.ILocatable; +import forestry.core.utils.PlayerUtil; + +public abstract class MultiblockTileEntityForestry extends MultiblockTileEntityBase implements ISidedInventory, IFilterSlotDelegate, IOwnable, ILocatable { + private GameProfile owner; + + public MultiblockTileEntityForestry(T multiblockLogic) { + super(multiblockLogic); + } + + /** + * Called by a structure block when it is right clicked by a player. + */ + public void openGui(EntityPlayer player) { + + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + + if (data.hasKey("owner")) { + owner = NBTUtil.func_152459_a(data.getCompoundTag("owner")); + } + + getInternalInventory().readFromNBT(data); + } + + @Override + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + + if (this.owner != null) { + NBTTagCompound nbt = new NBTTagCompound(); + NBTUtil.func_152460_a(nbt, owner); + data.setTag("owner", nbt); + } + + getInternalInventory().writeToNBT(data); + } + + /* IOwnable */ + @Override + public boolean isOwned() { + return owner != null; + } + + @Override + public GameProfile getOwner() { + return owner; + } + + @Override + public void setOwner(GameProfile owner) { + this.owner = owner; + } + + @Override + public boolean isOwner(EntityPlayer player) { + return PlayerUtil.isSameGameProfile(owner, player.getGameProfile()); + } + + /* INVENTORY */ + public IInventoryAdapter getInternalInventory() { + return FakeInventoryAdapter.instance(); + } + + public boolean allowsAutomation() { + return false; + } + + @Override + public final int getSizeInventory() { + return getInternalInventory().getSizeInventory(); + } + + @Override + public final ItemStack getStackInSlot(int slotIndex) { + return getInternalInventory().getStackInSlot(slotIndex); + } + + @Override + public final ItemStack decrStackSize(int slotIndex, int amount) { + return getInternalInventory().decrStackSize(slotIndex, amount); + } + + @Override + public final ItemStack getStackInSlotOnClosing(int slotIndex) { + return getInternalInventory().getStackInSlotOnClosing(slotIndex); + } + + @Override + public final void setInventorySlotContents(int slotIndex, ItemStack itemstack) { + getInternalInventory().setInventorySlotContents(slotIndex, itemstack); + } + + @Override + public final int getInventoryStackLimit() { + return getInternalInventory().getInventoryStackLimit(); + } + + @Override + public final void openInventory() { + getInternalInventory().openInventory(); + } + + @Override + public final void closeInventory() { + getInternalInventory().closeInventory(); + } + + @Override + public final String getInventoryName() { + return getInternalInventory().getInventoryName(); + } + + @Override + public final boolean isUseableByPlayer(EntityPlayer player) { + return getInternalInventory().isUseableByPlayer(player); + } + + @Override + public final boolean hasCustomInventoryName() { + return getInternalInventory().hasCustomInventoryName(); + } + + @Override + public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { + return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); + } + + @Override + public final int[] getAccessibleSlotsFromSide(int side) { + if (allowsAutomation()) { + return getInternalInventory().getAccessibleSlotsFromSide(side); + } else { + return Constants.SLOTS_NONE; + } + } + + @Override + public final boolean canInsertItem(int slotIndex, ItemStack itemStack, int side) { + if (allowsAutomation()) { + return getInternalInventory().canInsertItem(slotIndex, itemStack, side); + } else { + return false; + } + } + + @Override + public final boolean canExtractItem(int slotIndex, ItemStack itemStack, int side) { + if (allowsAutomation()) { + return getInternalInventory().canExtractItem(slotIndex, itemStack, side); + } else { + return false; + } + } + + @Override + public final boolean canSlotAccept(int slotIndex, ItemStack itemStack) { + return getInternalInventory().canSlotAccept(slotIndex, itemStack); + } + + @Override + public final boolean isLocked(int slotIndex) { + return getInternalInventory().isLocked(slotIndex); + } + + /* ILocatable */ + @Override + public final World getWorld() { + return worldObj; + } +} diff --git a/src/main/java/forestry/core/multiblock/MultiblockUtil.java b/src/main/java/forestry/core/multiblock/MultiblockUtil.java new file mode 100644 index 000000000..6fc01d37a --- /dev/null +++ b/src/main/java/forestry/core/multiblock/MultiblockUtil.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.multiblock; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.world.World; +import net.minecraft.world.chunk.IChunkProvider; + +import net.minecraftforge.common.util.ForgeDirection; + +import forestry.api.multiblock.IMultiblockComponent; + +public class MultiblockUtil { + /** + * Returns an array containing references to neighboring IMultiblockComponent tile entities. + * Primarily a utility method. Only works after tileentity construction. + * + * This method is chunk-safe on the server; it will not query for parts in chunks that are unloaded. + * Note that no method is chunk-safe on the client, because ChunkProviderClient is stupid. + * @return An array of references to neighboring IMultiblockComponent tile entities. + */ + public static List getNeighboringParts(World world, IMultiblockComponent part) { + ChunkCoordinates partCoord = part.getCoordinates(); + + List neighbors = new ArrayList<>(ForgeDirection.VALID_DIRECTIONS.length); + for (ForgeDirection forgeDirection : ForgeDirection.VALID_DIRECTIONS) { + ChunkCoordinates neighborCoord = new ChunkCoordinates(partCoord); + neighborCoord.posX += forgeDirection.offsetX; + neighborCoord.posY += forgeDirection.offsetY; + neighborCoord.posZ += forgeDirection.offsetZ; + neighbors.add(neighborCoord); + } + + List neighborParts = new ArrayList<>(); + IChunkProvider chunkProvider = world.getChunkProvider(); + for (ChunkCoordinates neighbor : neighbors) { + if (!chunkProvider.chunkExists(neighbor.posX >> 4, neighbor.posZ >> 4)) { + // Chunk not loaded, skip it. + continue; + } + + TileEntity te = world.getTileEntity(neighbor.posX, neighbor.posY, neighbor.posZ); + if (te instanceof IMultiblockComponent) { + neighborParts.add((IMultiblockComponent) te); + } + } + return neighborParts; + } +} diff --git a/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java b/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java index a2f833c12..fc338e875 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java @@ -8,10 +8,13 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.api.multiblock.IMultiblockLogic; import forestry.core.utils.Log; /** @@ -25,23 +28,23 @@ public class MultiblockWorldRegistry { private World worldObj; - private final Set controllers; // Active controllers - private final Set dirtyControllers; // Controllers whose parts lists have changed - private final Set deadControllers; // Controllers which are empty + private final Set controllers; // Active controllers + private final Set dirtyControllers; // Controllers whose parts lists have changed + private final Set deadControllers; // Controllers which are empty // A list of orphan parts - parts which currently have no master, but should seek one this tick // Indexed by the hashed chunk coordinate // This can be added-to asynchronously via chunk loads! - private Set orphanedParts; + private Set orphanedParts; // A list of parts which have been detached during internal operations - private final Set detachedParts; + private final Set detachedParts; // A list of parts whose chunks have not yet finished loading // They will be added to the orphan list when they are finished loading. // Indexed by the hashed chunk coordinate // This can be added-to asynchronously via chunk loads! - private final HashMap> partsAwaitingChunkLoad; + private final HashMap> partsAwaitingChunkLoad; // Mutexes to protect lists which may be changed due to asynchronous events, such as chunk loads private final Object partsAwaitingChunkLoadMutex; @@ -67,8 +70,8 @@ public class MultiblockWorldRegistry { */ public void tickStart() { if (controllers.size() > 0) { - for (MultiblockControllerBase controller : controllers) { - if (controller.worldObj == worldObj && controller.worldObj.isRemote == worldObj.isRemote) { + for (IMultiblockControllerInternal controller : controllers) { + if (controller.getWorld() == worldObj && controller.getWorld().isRemote == worldObj.isRemote) { if (controller.isEmpty()) { // This happens on the server when the user breaks the last block. It's fine. // Mark 'er dead and move on. @@ -87,12 +90,12 @@ public class MultiblockWorldRegistry { */ public void processMultiblockChanges() { IChunkProvider chunkProvider = worldObj.getChunkProvider(); - CoordTriplet coord; + ChunkCoordinates coord; // Merge pools - sets of adjacent machines which should be merged later on in processing - List> mergePools = null; + List> mergePools = null; if (orphanedParts.size() > 0) { - Set orphansToProcess = null; + Set orphansToProcess = null; // Keep the synchronized block small. We can't iterate over orphanedParts directly // because the client does not know which chunks are actually loaded, so attachToNeighbors() @@ -106,13 +109,13 @@ public class MultiblockWorldRegistry { } if (orphansToProcess != null && orphansToProcess.size() > 0) { - Set compatibleControllers; + Set compatibleControllers; // Process orphaned blocks // These are blocks that exist in a valid chunk and require a controller - for (IMultiblockPart orphan : orphansToProcess) { - coord = orphan.getWorldLocation(); - if (!chunkProvider.chunkExists(coord.getChunkX(), coord.getChunkZ())) { + for (IMultiblockComponent orphan : orphansToProcess) { + coord = orphan.getCoordinates(); + if (!chunkProvider.chunkExists(coord.posX >> 4, coord.posZ >> 4)) { continue; } @@ -121,18 +124,19 @@ public class MultiblockWorldRegistry { continue; } - if (worldObj.getTileEntity(coord.x, coord.y, coord.z) != orphan) { + if (worldObj.getTileEntity(coord.posX, coord.posY, coord.posZ) != orphan) { // This block has been replaced by another. continue; } // THIS IS THE ONLY PLACE WHERE PARTS ATTACH TO MACHINES // Try to attach to a neighbor's master controller - compatibleControllers = orphan.attachToNeighbors(); - if (compatibleControllers == null) { + compatibleControllers = attachToNeighbors(orphan); + if (compatibleControllers.size() == 0) { // FOREVER ALONE! Create and register a new controller. // THIS IS THE ONLY PLACE WHERE NEW CONTROLLERS ARE CREATED. - MultiblockControllerBase newController = orphan.createNewMultiblock(); + MultiblockLogic logic = (MultiblockLogic) orphan.getMultiblockLogic(); + IMultiblockControllerInternal newController = logic.createNewController(worldObj); newController.attachBlock(orphan); this.controllers.add(newController); } else if (compatibleControllers.size() > 1) { @@ -143,8 +147,8 @@ public class MultiblockWorldRegistry { // THIS IS THE ONLY PLACE WHERE MERGES ARE DETECTED // Multiple compatible controllers indicates an impending merge. // Locate the appropriate merge pool(s) - List> candidatePools = new ArrayList<>(); - for (Set candidatePool : mergePools) { + List> candidatePools = new ArrayList<>(); + for (Set candidatePool : mergePools) { if (!Collections.disjoint(candidatePool, compatibleControllers)) { // They share at least one element, so that means they will all touch after the merge candidatePools.add(candidatePool); @@ -159,8 +163,8 @@ public class MultiblockWorldRegistry { candidatePools.get(0).addAll(compatibleControllers); } else { // Multiple pools- merge into one, then add the compatible controllers - Set masterPool = candidatePools.get(0); - Set consumedPool; + Set masterPool = candidatePools.get(0); + Set consumedPool; for (int i = 1; i < candidatePools.size(); i++) { consumedPool = candidatePools.get(i); masterPool.addAll(consumedPool); @@ -178,10 +182,10 @@ public class MultiblockWorldRegistry { // into the "master" machine. // To do this, we combine lists of machines that are touching one another and therefore // should voltron the fuck up. - for (Set mergePool : mergePools) { + for (Set mergePool : mergePools) { // Search for the new master machine, which will take over all the blocks contained in the other machines - MultiblockControllerBase newMaster = null; - for (MultiblockControllerBase controller : mergePool) { + IMultiblockControllerInternal newMaster = null; + for (IMultiblockControllerInternal controller : mergePool) { if (newMaster == null || controller.shouldConsume(newMaster)) { newMaster = controller; } @@ -192,7 +196,7 @@ public class MultiblockWorldRegistry { } else { // Merge all the other machines into the master machine, then unregister them addDirtyController(newMaster); - for (MultiblockControllerBase controller : mergePool) { + for (IMultiblockControllerInternal controller : mergePool) { if (controller != newMaster) { newMaster.assimilate(controller); addDeadController(controller); @@ -207,7 +211,7 @@ public class MultiblockWorldRegistry { // Any controllers which have had parts removed must be checked to see if some parts are no longer // physically connected to their master. if (dirtyControllers.size() > 0) { - for (MultiblockControllerBase controller : dirtyControllers) { + for (IMultiblockControllerInternal controller : dirtyControllers) { if (controller == null) { continue; } @@ -215,7 +219,7 @@ public class MultiblockWorldRegistry { // It should return a set of parts which are no longer connected. // POSTCONDITION: The controller must have informed those parts that // they are no longer connected to this machine. - Set newlyDetachedParts = controller.checkForDisconnections(); + Set newlyDetachedParts = controller.checkForDisconnections(); if (!controller.isEmpty()) { controller.recalculateMinMaxCoords(); @@ -224,7 +228,7 @@ public class MultiblockWorldRegistry { addDeadController(controller); } - if (newlyDetachedParts != null && newlyDetachedParts.size() > 0) { + if (newlyDetachedParts.size() > 0) { // Controller has shed some parts - add them to the detached list for delayed processing detachedParts.addAll(newlyDetachedParts); } @@ -235,7 +239,7 @@ public class MultiblockWorldRegistry { // Unregister dead controllers if (deadControllers.size() > 0) { - for (MultiblockControllerBase controller : deadControllers) { + for (IMultiblockControllerInternal controller : deadControllers) { // Go through any controllers which have marked themselves as potentially dead. // Validate that they are empty/dead, then unregister them. if (!controller.isEmpty()) { @@ -253,28 +257,64 @@ public class MultiblockWorldRegistry { // Process detached blocks // Any blocks which have been detached this tick should be moved to the orphaned // list, and will be checked next tick to see if their chunk is still loaded. - for (IMultiblockPart part : detachedParts) { + for (IMultiblockComponent part : detachedParts) { // Ensure parts know they're detached - part.assertDetached(); + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); + logic.assertDetached(part); } addAllOrphanedPartsThreadsafe(detachedParts); detachedParts.clear(); } + ///// Multiblock Connection Base Logic + private Set attachToNeighbors(IMultiblockComponent part) { + Set controllers = new HashSet<>(); + IMultiblockControllerInternal bestController = null; + + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); + Class controllerClass = logic.getControllerClass(); + // Look for a compatible controller in our neighboring parts. + List partsToCheck = MultiblockUtil.getNeighboringParts(worldObj, part); + for (IMultiblockComponent neighborPart : partsToCheck) { + IMultiblockLogic neighborLogic = neighborPart.getMultiblockLogic(); + if (neighborLogic.isConnected()) { + IMultiblockControllerInternal candidate = (IMultiblockControllerInternal) neighborLogic.getController(); + if (!controllerClass.isAssignableFrom(candidate.getClass())) { + // Skip multiblocks with incompatible types + continue; + } + + if (!controllers.contains(candidate) && (bestController == null || candidate.shouldConsume(bestController))) { + bestController = candidate; + } + + controllers.add(candidate); + } + } + + // If we've located a valid neighboring controller, attach to it. + if (bestController != null) { + // attachBlock will call onAttached, which will set the controller. + bestController.attachBlock(part); + } + + return controllers; + } + /** * Called when a multiblock part is added to the world, either via chunk-load or user action. * If its chunk is loaded, it will be processed during the next tick. * If the chunk is not loaded, it will be added to a list of objects waiting for a chunkload. * @param part The part which is being added to this world. */ - public void onPartAdded(IMultiblockPart part) { - CoordTriplet worldLocation = part.getWorldLocation(); + public void onPartAdded(IMultiblockComponent part) { + ChunkCoordinates worldLocation = part.getCoordinates(); - if (!worldObj.getChunkProvider().chunkExists(worldLocation.getChunkX(), worldLocation.getChunkZ())) { + if (!worldObj.getChunkProvider().chunkExists(worldLocation.posX >> 4, worldLocation.posZ >> 4)) { // Part goes into the waiting-for-chunk-load list - Set partSet; - long chunkHash = worldLocation.getChunkXZHash(); + Set partSet; + long chunkHash = ChunkCoordIntPair.chunkXZ2Int(worldLocation.posX >> 4, worldLocation.posZ >> 4); synchronized (partsAwaitingChunkLoadMutex) { if (!partsAwaitingChunkLoad.containsKey(chunkHash)) { partSet = new HashSet<>(); @@ -296,10 +336,10 @@ public class MultiblockWorldRegistry { * This part is removed from any lists in which it may be, and its machine is marked for recalculation. * @param part The part which is being removed. */ - public void onPartRemovedFromWorld(IMultiblockPart part) { - CoordTriplet coord = part.getWorldLocation(); + public void onPartRemovedFromWorld(IMultiblockComponent part) { + ChunkCoordinates coord = part.getCoordinates(); if (coord != null) { - long hash = coord.getChunkXZHash(); + long hash = ChunkCoordIntPair.chunkXZ2Int(coord.posX >> 4, coord.posZ >> 4); if (partsAwaitingChunkLoad.containsKey(hash)) { synchronized (partsAwaitingChunkLoadMutex) { @@ -319,8 +359,9 @@ public class MultiblockWorldRegistry { orphanedParts.remove(part); } } - - part.assertDetached(); + + MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); + logic.assertDetached(part); } /** @@ -372,7 +413,7 @@ public class MultiblockWorldRegistry { * * @param deadController The controller which is dead. */ - public void addDeadController(MultiblockControllerBase deadController) { + public void addDeadController(IMultiblockControllerInternal deadController) { this.deadControllers.add(deadController); } @@ -382,7 +423,7 @@ public class MultiblockWorldRegistry { * * @param dirtyController The dirty controller. */ - public void addDirtyController(MultiblockControllerBase dirtyController) { + public void addDirtyController(IMultiblockControllerInternal dirtyController) { this.dirtyControllers.add(dirtyController); } @@ -392,25 +433,21 @@ public class MultiblockWorldRegistry { * * @return An (unmodifiable) set of controllers which are active in this world. */ - public Set getControllers() { + public Set getControllers() { return Collections.unmodifiableSet(controllers); } /* *** PRIVATE HELPERS *** */ - private void addOrphanedPartThreadsafe(IMultiblockPart part) { + private void addOrphanedPartThreadsafe(IMultiblockComponent part) { synchronized (orphanedPartsMutex) { orphanedParts.add(part); } } - private void addAllOrphanedPartsThreadsafe(Collection parts) { + private void addAllOrphanedPartsThreadsafe(Collection parts) { synchronized (orphanedPartsMutex) { orphanedParts.addAll(parts); } } - - private String clientOrServer() { - return worldObj.isRemote ? "CLIENT" : "SERVER"; - } } diff --git a/src/main/java/forestry/core/multiblock/rectangular/RectangularMultiblockControllerBase.java b/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java similarity index 58% rename from src/main/java/forestry/core/multiblock/rectangular/RectangularMultiblockControllerBase.java rename to src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java index 7331fe878..43213c138 100644 --- a/src/main/java/forestry/core/multiblock/rectangular/RectangularMultiblockControllerBase.java +++ b/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java @@ -1,40 +1,42 @@ -package forestry.core.multiblock.rectangular; +package forestry.core.multiblock; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -import forestry.core.multiblock.CoordTriplet; -import forestry.core.multiblock.MultiblockControllerBase; -import forestry.core.multiblock.MultiblockValidationException; +import forestry.api.multiblock.IMultiblockComponent; -public abstract class RectangularMultiblockControllerBase extends MultiblockControllerBase { +public abstract class RectangularMultiblockControllerBase extends MultiblockControllerForestry { - protected RectangularMultiblockControllerBase(World world) { + private final IMultiblockSizeLimits sizeLimits; + + protected RectangularMultiblockControllerBase(World world, IMultiblockSizeLimits sizeLimits) { super(world); + this.sizeLimits = sizeLimits; } @Override protected void isMachineWhole() throws MultiblockValidationException { - int minX = getMinimumXSize(); - int minY = getMinimumYSize(); - int minZ = getMinimumZSize(); + int minX = sizeLimits.getMinimumXSize(); + int minY = sizeLimits.getMinimumYSize(); + int minZ = sizeLimits.getMinimumZSize(); - if (connectedParts.size() < getMinimumNumberOfBlocksForAssembledMachine()) { + if (connectedParts.size() < sizeLimits.getMinimumNumberOfBlocksForAssembledMachine()) { throw new MultiblockValidationException(StatCollector.translateToLocalFormatted("for.multiblock.error.small", minX, minY, minZ)); } - CoordTriplet maximumCoord = getMaximumCoord(); - CoordTriplet minimumCoord = getMinimumCoord(); + ChunkCoordinates maximumCoord = getMaximumCoord(); + ChunkCoordinates minimumCoord = getMinimumCoord(); // Quickly check for exceeded dimensions - int deltaX = maximumCoord.x - minimumCoord.x + 1; - int deltaY = maximumCoord.y - minimumCoord.y + 1; - int deltaZ = maximumCoord.z - minimumCoord.z + 1; + int deltaX = maximumCoord.posX - minimumCoord.posX + 1; + int deltaY = maximumCoord.posY - minimumCoord.posY + 1; + int deltaZ = maximumCoord.posZ - minimumCoord.posZ + 1; - int maxX = getMaximumXSize(); - int maxY = getMaximumYSize(); - int maxZ = getMaximumZSize(); + int maxX = sizeLimits.getMaximumXSize(); + int maxY = sizeLimits.getMaximumYSize(); + int maxZ = sizeLimits.getMaximumZSize(); if (maxX > 0 && deltaX > maxX) { throw new MultiblockValidationException(StatCollector.translateToLocalFormatted("for.multiblock.error.large.x", maxX)); @@ -58,20 +60,20 @@ public abstract class RectangularMultiblockControllerBase extends MultiblockCont // Now we run a simple check on each block within that volume. // Any block deviating = NO DEAL SIR TileEntity te; - RectangularMultiblockTileEntityBase part; + IMultiblockComponent part; Class myClass = this.getClass(); - for (int x = minimumCoord.x; x <= maximumCoord.x; x++) { - for (int y = minimumCoord.y; y <= maximumCoord.y; y++) { - for (int z = minimumCoord.z; z <= maximumCoord.z; z++) { + for (int x = minimumCoord.posX; x <= maximumCoord.posX; x++) { + for (int y = minimumCoord.posY; y <= maximumCoord.posY; y++) { + for (int z = minimumCoord.posZ; z <= maximumCoord.posZ; z++) { // Okay, figure out what sort of block this should be. te = this.worldObj.getTileEntity(x, y, z); - if (te instanceof RectangularMultiblockTileEntityBase) { - part = (RectangularMultiblockTileEntityBase) te; + if (te instanceof IMultiblockComponent) { + part = (IMultiblockComponent) te; // Ensure this part should actually be allowed within a cube of this controller's type - if (!myClass.equals(part.getMultiblockControllerType())) { + if (!myClass.equals(part.getMultiblockLogic().getController().getClass())) { throw new MultiblockValidationException(StatCollector.translateToLocalFormatted("for.multiblock.error.invalid.part", x, y, z, myClass.getSimpleName())); } } else { @@ -81,37 +83,37 @@ public abstract class RectangularMultiblockControllerBase extends MultiblockCont // Validate block type against both part-level and material-level validators. int extremes = 0; - if (x == minimumCoord.x) { + if (x == minimumCoord.posX) { extremes++; } - if (y == minimumCoord.y) { + if (y == minimumCoord.posY) { extremes++; } - if (z == minimumCoord.z) { + if (z == minimumCoord.posZ) { extremes++; } - if (x == maximumCoord.x) { + if (x == maximumCoord.posX) { extremes++; } - if (y == maximumCoord.y) { + if (y == maximumCoord.posY) { extremes++; } - if (z == maximumCoord.z) { + if (z == maximumCoord.posZ) { extremes++; } if (extremes >= 1) { // Side - int exteriorLevel = y - minimumCoord.y; + int exteriorLevel = y - minimumCoord.posY; if (part != null) { - part.isGoodForExteriorLevel(exteriorLevel); + isGoodForExteriorLevel(part, exteriorLevel); } else { isBlockGoodForExteriorLevel(exteriorLevel, this.worldObj, x, y, z); } } else { if (part != null) { - part.isGoodForInterior(); + isGoodForInterior(part); } else { isBlockGoodForInterior(this.worldObj, x, y, z); } @@ -120,5 +122,8 @@ public abstract class RectangularMultiblockControllerBase extends MultiblockCont } } } - + + protected abstract void isGoodForExteriorLevel(IMultiblockComponent part, int level) throws MultiblockValidationException; + + protected abstract void isGoodForInterior(IMultiblockComponent part) throws MultiblockValidationException; } diff --git a/src/main/java/forestry/core/multiblock/rectangular/PartPosition.java b/src/main/java/forestry/core/multiblock/rectangular/PartPosition.java deleted file mode 100644 index 7b502f386..000000000 --- a/src/main/java/forestry/core/multiblock/rectangular/PartPosition.java +++ /dev/null @@ -1,28 +0,0 @@ -package forestry.core.multiblock.rectangular; - -public enum PartPosition { - Unknown, - Interior, - FrameCorner, - Frame, - TopFace, - BottomFace, - NorthFace, - SouthFace, - EastFace, - WestFace; - - public static boolean isFace(PartPosition position) { - switch (position) { - case TopFace: - case BottomFace: - case NorthFace: - case SouthFace: - case EastFace: - case WestFace: - return true; - default: - return false; - } - } -} diff --git a/src/main/java/forestry/core/multiblock/rectangular/RectangularMultiblockTileEntityBase.java b/src/main/java/forestry/core/multiblock/rectangular/RectangularMultiblockTileEntityBase.java deleted file mode 100644 index 0bb463c7b..000000000 --- a/src/main/java/forestry/core/multiblock/rectangular/RectangularMultiblockTileEntityBase.java +++ /dev/null @@ -1,105 +0,0 @@ -package forestry.core.multiblock.rectangular; - -import net.minecraftforge.common.util.ForgeDirection; - -import forestry.core.multiblock.CoordTriplet; -import forestry.core.multiblock.MultiblockControllerBase; -import forestry.core.multiblock.MultiblockTileEntityBase; -import forestry.core.multiblock.MultiblockValidationException; - -public abstract class RectangularMultiblockTileEntityBase extends MultiblockTileEntityBase { - - PartPosition position; - ForgeDirection outwards; - - public RectangularMultiblockTileEntityBase() { - super(); - - position = PartPosition.Unknown; - outwards = ForgeDirection.UNKNOWN; - } - - // Positional Data - public ForgeDirection getOutwardsDir() { - return outwards; - } - - public PartPosition getPartPosition() { - return position; - } - - // Handlers from MultiblockTileEntityBase - @Override - public void onAttached(MultiblockControllerBase newController) { - super.onAttached(newController); - recalculateOutwardsDirection(newController.getMinimumCoord(), newController.getMaximumCoord()); - } - - - @Override - public void onMachineAssembled(MultiblockControllerBase controller) { - CoordTriplet maxCoord = controller.getMaximumCoord(); - CoordTriplet minCoord = controller.getMinimumCoord(); - - // Discover where I am on the reactor - recalculateOutwardsDirection(minCoord, maxCoord); - } - - @Override - public void onMachineBroken() { - position = PartPosition.Unknown; - outwards = ForgeDirection.UNKNOWN; - } - - // Positional helpers - public void recalculateOutwardsDirection(CoordTriplet minCoord, CoordTriplet maxCoord) { - outwards = ForgeDirection.UNKNOWN; - position = PartPosition.Unknown; - - int facesMatching = 0; - if (maxCoord.x == this.xCoord || minCoord.x == this.xCoord) { - facesMatching++; - } - if (maxCoord.y == this.yCoord || minCoord.y == this.yCoord) { - facesMatching++; - } - if (maxCoord.z == this.zCoord || minCoord.z == this.zCoord) { - facesMatching++; - } - - if (facesMatching <= 0) { - position = PartPosition.Interior; - } else if (facesMatching >= 3) { - position = PartPosition.FrameCorner; - } else if (facesMatching == 2) { - position = PartPosition.Frame; - } else { - // 1 face matches - if (maxCoord.x == this.xCoord) { - position = PartPosition.EastFace; - outwards = ForgeDirection.EAST; - } else if (minCoord.x == this.xCoord) { - position = PartPosition.WestFace; - outwards = ForgeDirection.WEST; - } else if (maxCoord.z == this.zCoord) { - position = PartPosition.SouthFace; - outwards = ForgeDirection.SOUTH; - } else if (minCoord.z == this.zCoord) { - position = PartPosition.NorthFace; - outwards = ForgeDirection.NORTH; - } else if (maxCoord.y == this.yCoord) { - position = PartPosition.TopFace; - outwards = ForgeDirection.UP; - } else { - position = PartPosition.BottomFace; - outwards = ForgeDirection.DOWN; - } - } - } - - ///// Validation Helpers (IMultiblockPart) - - public abstract void isGoodForExteriorLevel(int level) throws MultiblockValidationException; - - public abstract void isGoodForInterior() throws MultiblockValidationException; -} diff --git a/src/main/java/forestry/farming/FarmHelper.java b/src/main/java/forestry/farming/FarmHelper.java index 18acd2273..aad125448 100755 --- a/src/main/java/forestry/farming/FarmHelper.java +++ b/src/main/java/forestry/farming/FarmHelper.java @@ -19,7 +19,7 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import forestry.api.farming.FarmDirection; -import forestry.api.farming.IFarmComponent; +import forestry.api.multiblock.IFarmComponent; import forestry.core.utils.vect.MutableVect; import forestry.core.utils.vect.Vect; import forestry.core.utils.vect.VectUtil; diff --git a/src/main/java/forestry/farming/gui/ContainerFarm.java b/src/main/java/forestry/farming/gui/ContainerFarm.java index 833be190e..983ab9207 100755 --- a/src/main/java/forestry/farming/gui/ContainerFarm.java +++ b/src/main/java/forestry/farming/gui/ContainerFarm.java @@ -68,7 +68,7 @@ public class ContainerFarm extends ContainerSocketed { } public IFluidTank getTank(int slot) { - return tile.getFarmController().getTankManager().getTank(slot); + return tile.getMultiblockLogic().getController().getTankManager().getTank(slot); } } diff --git a/src/main/java/forestry/farming/gui/GuiFarm.java b/src/main/java/forestry/farming/gui/GuiFarm.java index 22cc9ca93..0340f6348 100755 --- a/src/main/java/forestry/farming/gui/GuiFarm.java +++ b/src/main/java/forestry/farming/gui/GuiFarm.java @@ -28,7 +28,7 @@ import forestry.core.gui.widgets.Widget; import forestry.core.gui.widgets.WidgetManager; import forestry.core.proxy.Proxies; import forestry.core.utils.StringUtil; -import forestry.farming.multiblock.IFarmController; +import forestry.farming.multiblock.IFarmControllerInternal; import forestry.farming.tiles.TileFarm; public class GuiFarm extends GuiForestry { @@ -52,7 +52,7 @@ public class GuiFarm extends GuiForestry { @Override public void initGui() { super.initGui(); - IFarmController farmController = inventory.getFarmController(); + IFarmControllerInternal farmController = inventory.getMultiblockLogic().getController(); ledgerManager.add(new ClimateLedger(ledgerManager, farmController)); ledgerManager.add(new FarmLedger(ledgerManager, farmController.getFarmLedgerDelegate())); ledgerManager.add(new OwnerLedger(ledgerManager, farmController)); @@ -70,7 +70,7 @@ public class GuiFarm extends GuiForestry { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); // Fuel remaining - int fertilizerRemain = inventory.getFarmController().getStoredFertilizerScaled(16); + int fertilizerRemain = inventory.getMultiblockLogic().getController().getStoredFertilizerScaled(16); if (fertilizerRemain > 0) { drawTexturedModalRect(guiLeft + 81, guiTop + 94 + 17 - fertilizerRemain, xSize, 17 - fertilizerRemain, 4, fertilizerRemain); } @@ -86,7 +86,7 @@ public class GuiFarm extends GuiForestry { } private IFarmLogic getLogic() { - return inventory.getFarmController().getFarmLogic(farmDirection); + return inventory.getMultiblockLogic().getController().getFarmLogic(farmDirection); } private IIcon getIconIndex() { @@ -125,7 +125,7 @@ public class GuiFarm extends GuiForestry { } toolTip.add(getLogic().getName()); toolTip.add("Fertilizer: " + getLogic().getFertilizerConsumption()); - toolTip.add("Water: " + getLogic().getWaterConsumption(inventory.getFarmController().getFarmLedgerDelegate().getHydrationModifier())); + toolTip.add("Water: " + getLogic().getWaterConsumption(inventory.getMultiblockLogic().getController().getFarmLedgerDelegate().getHydrationModifier())); } }; } diff --git a/src/main/java/forestry/farming/multiblock/FakeFarmController.java b/src/main/java/forestry/farming/multiblock/FakeFarmController.java index 7ca73476e..9b23de5dc 100644 --- a/src/main/java/forestry/farming/multiblock/FakeFarmController.java +++ b/src/main/java/forestry/farming/multiblock/FakeFarmController.java @@ -35,13 +35,14 @@ import forestry.core.fluids.FakeTankManager; import forestry.core.fluids.ITankManager; import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; +import forestry.core.multiblock.FakeMultiblockController; import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.farming.gui.IFarmLedgerDelegate; import io.netty.util.internal.EmptyArrays; -public class FakeFarmController implements IFarmController { +public class FakeFarmController extends FakeMultiblockController implements IFarmControllerInternal { public static final FakeFarmController instance = new FakeFarmController(); private FakeFarmController() { @@ -83,11 +84,6 @@ public class FakeFarmController implements IFarmController { return EmptyArrays.EMPTY_INTS; } - @Override - public World getWorld() { - return null; - } - @Override public boolean doWork() { return false; diff --git a/src/main/java/forestry/farming/multiblock/FarmController.java b/src/main/java/forestry/farming/multiblock/FarmController.java index cf09f0c76..5eb77c238 100644 --- a/src/main/java/forestry/farming/multiblock/FarmController.java +++ b/src/main/java/forestry/farming/multiblock/FarmController.java @@ -26,6 +26,7 @@ import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.StatCollector; import net.minecraft.world.World; @@ -43,11 +44,12 @@ import forestry.api.core.EnumTemperature; import forestry.api.core.IErrorLogic; import forestry.api.farming.FarmDirection; import forestry.api.farming.ICrop; -import forestry.api.farming.IFarmComponent; import forestry.api.farming.IFarmInventory; import forestry.api.farming.IFarmListener; import forestry.api.farming.IFarmLogic; import forestry.api.farming.IFarmable; +import forestry.api.multiblock.IFarmComponent; +import forestry.api.multiblock.IMultiblockComponent; import forestry.core.access.EnumAccess; import forestry.core.config.Config; import forestry.core.config.Constants; @@ -59,12 +61,9 @@ import forestry.core.fluids.tanks.StandardTank; import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.InventoryAdapter; -import forestry.core.multiblock.CoordTriplet; -import forestry.core.multiblock.IMultiblockPart; -import forestry.core.multiblock.MultiblockControllerBase; -import forestry.core.multiblock.MultiblockTileEntityBase; +import forestry.core.multiblock.IMultiblockControllerInternal; import forestry.core.multiblock.MultiblockValidationException; -import forestry.core.multiblock.rectangular.RectangularMultiblockControllerBase; +import forestry.core.multiblock.RectangularMultiblockControllerBase; import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.tiles.ILiquidTankTile; @@ -76,9 +75,10 @@ import forestry.farming.FarmHelper; import forestry.farming.FarmTarget; import forestry.farming.gui.IFarmLedgerDelegate; import forestry.farming.logic.FarmLogicArboreal; +import forestry.farming.tiles.TileFarmPlain; import forestry.farming.tiles.TileGearbox; -public class FarmController extends RectangularMultiblockControllerBase implements IFarmController, ILiquidTankTile { +public class FarmController extends RectangularMultiblockControllerBase implements IFarmControllerInternal, ILiquidTankTile { private enum Stage { CULTIVATE, HARVEST; @@ -134,7 +134,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen private BiomeGenBase cachedBiome; public FarmController(World world) { - super(world); + super(world, FarmMultiblockSizeLimits.instance); this.resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY, FluidRegistry.WATER); this.tankManager = new TankManager(this, resourceTank); @@ -168,19 +168,19 @@ public class FarmController extends RectangularMultiblockControllerBase implemen private BiomeGenBase getBiome() { if (cachedBiome == null) { - CoordTriplet coords = getReferenceCoord(); - cachedBiome = worldObj.getBiomeGenForCoords(coords.x, coords.z); + ChunkCoordinates coords = getReferenceCoord(); + cachedBiome = worldObj.getBiomeGenForCoords(coords.posX, coords.posZ); } return cachedBiome; } @Override - public void onAttachedPartWithMultiblockData(IMultiblockPart part, NBTTagCompound data) { + public void onAttachedPartWithMultiblockData(IMultiblockComponent part, NBTTagCompound data) { this.readFromNBT(data); } @Override - protected void onBlockAdded(IMultiblockPart newPart) { + protected void onBlockAdded(IMultiblockComponent newPart) { if (newPart instanceof IFarmComponent.Listener) { IFarmComponent.Listener listenerPart = (IFarmComponent.Listener) newPart; farmListeners.add(listenerPart.getFarmListener()); @@ -192,7 +192,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen } @Override - protected void onBlockRemoved(IMultiblockPart oldPart) { + protected void onBlockRemoved(IMultiblockComponent oldPart) { if (oldPart instanceof IFarmComponent.Listener) { IFarmComponent.Listener listenerPart = (IFarmComponent.Listener) oldPart; farmListeners.remove(listenerPart.getFarmListener()); @@ -208,7 +208,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen super.isMachineWhole(); boolean hasGearbox = false; - for (IMultiblockPart part : connectedParts) { + for (IMultiblockComponent part : connectedParts) { if (part instanceof TileGearbox) { hasGearbox = true; break; @@ -227,47 +227,26 @@ public class FarmController extends RectangularMultiblockControllerBase implemen } @Override - protected int getMinimumNumberOfBlocksForAssembledMachine() { - return 3 * 3 * 4; + public void isGoodForExteriorLevel(IMultiblockComponent part, int level) throws MultiblockValidationException { + if (level == 2 && !(part instanceof TileFarmPlain)) { + throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.farm.error.needPlainBand")); + } } @Override - protected int getMaximumXSize() { - return 5; + public void isGoodForInterior(IMultiblockComponent part) throws MultiblockValidationException { + if (!(part instanceof TileFarmPlain)) { + throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.farm.error.needPlainInterior")); + } } @Override - protected int getMaximumZSize() { - return 5; - } - - @Override - protected int getMaximumYSize() { - return 4; - } - - @Override - protected int getMinimumXSize() { - return 3; - } - - @Override - protected int getMinimumZSize() { - return 3; - } - - @Override - protected int getMinimumYSize() { - return 4; - } - - @Override - protected void onAssimilate(MultiblockControllerBase assimilated) { + public void onAssimilate(IMultiblockControllerInternal assimilated) { } @Override - protected void onAssimilated(MultiblockControllerBase assimilator) { + public void onAssimilated(IMultiblockControllerInternal assimilator) { } @@ -356,18 +335,18 @@ public class FarmController extends RectangularMultiblockControllerBase implemen @Override public ChunkCoordinates getCoordinates() { - CoordTriplet coord = getReferenceCoord(); - return new ChunkCoordinates(coord.x, coord.y, coord.z); + ChunkCoordinates coord = getReferenceCoord(); + return new ChunkCoordinates(coord); } @Override public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { if (oldAccess == EnumAccess.SHARED || newAccess == EnumAccess.SHARED) { // pipes connected to this need to update - for (IMultiblockPart part : connectedParts) { - if (part instanceof MultiblockTileEntityBase) { - MultiblockTileEntityBase tile = (MultiblockTileEntityBase) part; - tile.notifyNeighborsOfBlockChange(); + for (IMultiblockComponent part : connectedParts) { + if (part instanceof TileEntity) { + TileEntity tile = (TileEntity) part; + tile.getWorldObj().notifyBlocksOfNeighborChange(tile.xCoord, tile.yCoord, tile.zCoord, tile.getBlockType()); } } markDirty(); @@ -405,8 +384,8 @@ public class FarmController extends RectangularMultiblockControllerBase implemen @Override public EnumTemperature getTemperature() { - CoordTriplet coords = getReferenceCoord(); - return EnumTemperature.getFromBiome(getBiome(), coords.x, coords.y, coords.z); + ChunkCoordinates coords = getReferenceCoord(); + return EnumTemperature.getFromBiome(getBiome(), coords.posX, coords.posY, coords.posZ); } @Override @@ -416,8 +395,8 @@ public class FarmController extends RectangularMultiblockControllerBase implemen @Override public float getExactTemperature() { - CoordTriplet coords = getReferenceCoord(); - return getBiome().getFloatTemperature(coords.x, coords.y, coords.z); + ChunkCoordinates coords = getReferenceCoord(); + return getBiome().getFloatTemperature(coords.posX, coords.posY, coords.posZ); } @Override @@ -432,8 +411,8 @@ public class FarmController extends RectangularMultiblockControllerBase implemen @Override public int[] getCoords() { if (coords == null) { - CoordTriplet centerCoord = getCenterCoord(); - coords = new int[]{centerCoord.x, centerCoord.y, centerCoord.z}; + ChunkCoordinates centerCoord = getCenterCoord(); + coords = new int[]{centerCoord.posX, centerCoord.posY, centerCoord.posZ}; } return coords; } @@ -541,11 +520,11 @@ public class FarmController extends RectangularMultiblockControllerBase implemen private void setUpFarmlandTargets() { Vect targetStart = new Vect(getCoords()); - CoordTriplet max = getMaximumCoord(); - CoordTriplet min = getMinimumCoord(); + ChunkCoordinates max = getMaximumCoord(); + ChunkCoordinates min = getMinimumCoord(); - int sizeNorthSouth = Math.abs(max.z - min.z) + 1; - int sizeEastWest = Math.abs(max.x - min.x) + 1; + int sizeNorthSouth = Math.abs(max.posZ - min.posZ) + 1; + int sizeEastWest = Math.abs(max.posX - min.posX) + 1; // Set the maximum allowed extent. allowedExtent = Math.max(sizeNorthSouth, sizeEastWest) * Config.farmSize + 1; @@ -770,7 +749,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen Collection harvested = crop.harvest(); if (harvested == null) { - Log.fine("Failed to harvest crop: " + crop.toString()); + Log.fine("Failed to harvest crop: " + crop); return true; } diff --git a/src/main/java/forestry/farming/multiblock/FarmMultiblockSizeLimits.java b/src/main/java/forestry/farming/multiblock/FarmMultiblockSizeLimits.java new file mode 100644 index 000000000..4b625cf0f --- /dev/null +++ b/src/main/java/forestry/farming/multiblock/FarmMultiblockSizeLimits.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.multiblock; + +import forestry.core.multiblock.IMultiblockSizeLimits; + +class FarmMultiblockSizeLimits implements IMultiblockSizeLimits { + public static final FarmMultiblockSizeLimits instance = new FarmMultiblockSizeLimits(); + + private FarmMultiblockSizeLimits() { + + } + + @Override + public int getMinimumNumberOfBlocksForAssembledMachine() { + return 3 * 3 * 4; + } + + @Override + public int getMaximumXSize() { + return 5; + } + + @Override + public int getMaximumZSize() { + return 5; + } + + @Override + public int getMaximumYSize() { + return 4; + } + + @Override + public int getMinimumXSize() { + return 3; + } + + @Override + public int getMinimumZSize() { + return 3; + } + + @Override + public int getMinimumYSize() { + return 4; + } +} diff --git a/src/main/java/forestry/farming/multiblock/IFarmController.java b/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java similarity index 77% rename from src/main/java/forestry/farming/multiblock/IFarmController.java rename to src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java index 5b584d538..b5eea9497 100644 --- a/src/main/java/forestry/farming/multiblock/IFarmController.java +++ b/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java @@ -10,17 +10,17 @@ ******************************************************************************/ package forestry.farming.multiblock; -import forestry.api.core.IErrorLogicSource; -import forestry.api.farming.IFarmHousing; +import forestry.api.multiblock.IFarmController; import forestry.core.access.IRestrictedAccess; import forestry.core.circuits.ISocketable; import forestry.core.fluids.ITankManager; import forestry.core.inventory.IInventoryAdapter; +import forestry.core.multiblock.IMultiblockControllerInternal; import forestry.core.network.IStreamableGui; import forestry.core.tiles.IClimatised; import forestry.farming.gui.IFarmLedgerDelegate; -public interface IFarmController extends IFarmHousing, ISocketable, IClimatised, IRestrictedAccess, IErrorLogicSource, IStreamableGui { +public interface IFarmControllerInternal extends IFarmController, IMultiblockControllerInternal, ISocketable, IClimatised, IRestrictedAccess, IStreamableGui { IFarmLedgerDelegate getFarmLedgerDelegate(); IInventoryAdapter getInternalInventory(); diff --git a/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java b/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java new file mode 100644 index 000000000..67075e14c --- /dev/null +++ b/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.multiblock; + +import net.minecraft.world.World; + +import forestry.api.multiblock.IMultiblockLogicFarm; +import forestry.core.multiblock.MultiblockLogic; + +public class MultiblockLogicFarm extends MultiblockLogic implements IMultiblockLogicFarm { + public MultiblockLogicFarm() { + super(IFarmControllerInternal.class); + } + + @Override + public IFarmControllerInternal getController() { + if (super.isConnected()) { + return controller; + } else { + return FakeFarmController.instance; + } + } + + public IFarmControllerInternal createNewController(World world) { + return new FarmController(world); + } +} diff --git a/src/main/java/forestry/farming/tiles/TileControl.java b/src/main/java/forestry/farming/tiles/TileControl.java index 741d02ac8..0600d18af 100644 --- a/src/main/java/forestry/farming/tiles/TileControl.java +++ b/src/main/java/forestry/farming/tiles/TileControl.java @@ -16,9 +16,9 @@ import net.minecraftforge.common.util.ForgeDirection; import forestry.api.farming.DefaultFarmListener; import forestry.api.farming.FarmDirection; -import forestry.api.farming.IFarmComponent; import forestry.api.farming.IFarmListener; import forestry.api.farming.IFarmLogic; +import forestry.api.multiblock.IFarmComponent; import forestry.core.utils.vect.Vect; public class TileControl extends TileFarm implements IFarmComponent.Listener { diff --git a/src/main/java/forestry/farming/tiles/TileFarm.java b/src/main/java/forestry/farming/tiles/TileFarm.java index 774a8805f..6d7e1538f 100644 --- a/src/main/java/forestry/farming/tiles/TileFarm.java +++ b/src/main/java/forestry/farming/tiles/TileFarm.java @@ -16,13 +16,14 @@ import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.StatCollector; +import net.minecraft.util.ChunkCoordinates; import forestry.api.circuits.ICircuitSocketType; import forestry.api.core.ForestryAPI; import forestry.api.core.IErrorLogic; import forestry.api.core.IErrorLogicSource; -import forestry.api.farming.IFarmComponent; +import forestry.api.multiblock.IFarmComponent; +import forestry.api.multiblock.IMultiblockController; import forestry.core.access.EnumAccess; import forestry.core.access.IAccessHandler; import forestry.core.access.IRestrictedAccess; @@ -30,19 +31,15 @@ import forestry.core.circuits.ISocketable; import forestry.core.config.Config; import forestry.core.gui.IHintSource; import forestry.core.inventory.IInventoryAdapter; -import forestry.core.multiblock.MultiblockControllerBase; -import forestry.core.multiblock.MultiblockValidationException; -import forestry.core.multiblock.rectangular.RectangularMultiblockTileEntityBase; +import forestry.core.multiblock.MultiblockTileEntityForestry; import forestry.core.network.DataInputStreamForestry; import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.GuiId; import forestry.core.network.IStreamableGui; -import forestry.farming.multiblock.FakeFarmController; -import forestry.farming.multiblock.FarmController; -import forestry.farming.multiblock.IFarmController; +import forestry.farming.multiblock.MultiblockLogicFarm; import forestry.farming.render.EnumFarmBlockTexture; -public abstract class TileFarm extends RectangularMultiblockTileEntityBase implements IFarmComponent, IHintSource, ISocketable, IStreamableGui, IErrorLogicSource, IRestrictedAccess { +public abstract class TileFarm extends MultiblockTileEntityForestry implements IFarmComponent, IHintSource, ISocketable, IStreamableGui, IErrorLogicSource, IRestrictedAccess { public static final int TYPE_PLAIN = 0; public static final int TYPE_REVERSE = 1; @@ -55,32 +52,30 @@ public abstract class TileFarm extends RectangularMultiblockTileEntityBase imple private EnumFarmBlockTexture farmBlockTexture = EnumFarmBlockTexture.BRICK_STONE; - @Override - public void openGui(EntityPlayer player) { - if (this.isConnected()) { - player.openGui(ForestryAPI.instance, GuiId.MultiFarmGUI.ordinal(), worldObj, xCoord, yCoord, zCoord); - } + protected TileFarm() { + super(new MultiblockLogicFarm()); } @Override - public void onMachineAssembled(MultiblockControllerBase controller) { - super.onMachineAssembled(controller); + public void openGui(EntityPlayer player) { + player.openGui(ForestryAPI.instance, GuiId.MultiFarmGUI.ordinal(), worldObj, xCoord, yCoord, zCoord); + } - notifyNeighborsOfBlockChange(); + @Override + public void onMachineAssembled(IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord) { + worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); markDirty(); } @Override public void onMachineBroken() { - super.onMachineBroken(); - - notifyNeighborsOfBlockChange(); + worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); markDirty(); } @Override public IInventoryAdapter getInternalInventory() { - return getFarmController().getInternalInventory(); + return getMultiblockLogic().getController().getInternalInventory(); } @Override @@ -129,48 +124,6 @@ public abstract class TileFarm extends RectangularMultiblockTileEntityBase imple setFarmBlockTexture(farmBlockTexture); } - @Override - public void onMachineActivated() { - - } - - @Override - public void onMachineDeactivated() { - - } - - @Override - public MultiblockControllerBase createNewMultiblock() { - return new FarmController(worldObj); - } - - @Override - public Class getMultiblockControllerType() { - return FarmController.class; - } - - public IFarmController getFarmController() { - if (isConnected()) { - return (IFarmController) super.getMultiblockController(); - } else { - return FakeFarmController.instance; - } - } - - @Override - public void isGoodForExteriorLevel(int level) throws MultiblockValidationException { - if (level == 2 && !(this instanceof TileFarmPlain)) { - throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.farm.error.needPlainBand")); - } - } - - @Override - public void isGoodForInterior() throws MultiblockValidationException { - if (!(this instanceof TileFarmPlain)) { - throw new MultiblockValidationException(StatCollector.translateToLocal("for.multiblock.farm.error.needPlainInterior")); - } - } - /* IHintSource */ @Override public List getHints() { @@ -180,48 +133,48 @@ public abstract class TileFarm extends RectangularMultiblockTileEntityBase imple /* ISocketable */ @Override public int getSocketCount() { - return getFarmController().getSocketCount(); + return getMultiblockLogic().getController().getSocketCount(); } @Override public ItemStack getSocket(int slot) { - return getFarmController().getSocket(slot); + return getMultiblockLogic().getController().getSocket(slot); } @Override public void setSocket(int slot, ItemStack stack) { - getFarmController().setSocket(slot, stack); + getMultiblockLogic().getController().setSocket(slot, stack); } @Override public ICircuitSocketType getSocketType() { - return getFarmController().getSocketType(); + return getMultiblockLogic().getController().getSocketType(); } /* IStreamableGui */ @Override public void writeGuiData(DataOutputStreamForestry data) throws IOException { - getFarmController().writeGuiData(data); + getMultiblockLogic().getController().writeGuiData(data); } @Override public void readGuiData(DataInputStreamForestry data) throws IOException { - getFarmController().readGuiData(data); + getMultiblockLogic().getController().readGuiData(data); } /* IErrorLogicSource */ @Override public IErrorLogic getErrorLogic() { - return getFarmController().getErrorLogic(); + return getMultiblockLogic().getController().getErrorLogic(); } @Override public IAccessHandler getAccessHandler() { - return getFarmController().getAccessHandler(); + return getMultiblockLogic().getController().getAccessHandler(); } @Override public void onSwitchAccess(EnumAccess oldAccess, EnumAccess newAccess) { - getFarmController().onSwitchAccess(oldAccess, newAccess); + getMultiblockLogic().getController().onSwitchAccess(oldAccess, newAccess); } } diff --git a/src/main/java/forestry/farming/tiles/TileFarmPlain.java b/src/main/java/forestry/farming/tiles/TileFarmPlain.java index e2cbaa2e2..458cba95d 100644 --- a/src/main/java/forestry/farming/tiles/TileFarmPlain.java +++ b/src/main/java/forestry/farming/tiles/TileFarmPlain.java @@ -10,17 +10,17 @@ ******************************************************************************/ package forestry.farming.tiles; -import forestry.core.multiblock.MultiblockControllerBase; +import net.minecraft.util.ChunkCoordinates; + +import forestry.api.multiblock.IMultiblockController; public class TileFarmPlain extends TileFarm { - - @Override - public void onMachineAssembled(MultiblockControllerBase controller) { - super.onMachineAssembled(controller); + public void onMachineAssembled(IMultiblockController multiblockController, ChunkCoordinates minCoord, ChunkCoordinates maxCoord) { + super.onMachineAssembled(multiblockController, minCoord, maxCoord); // set band block meta - int bandY = controller.getMaximumCoord().y - 1; + int bandY = maxCoord.posY - 1; if (yCoord == bandY) { this.worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 1, 2); } diff --git a/src/main/java/forestry/farming/tiles/TileGearbox.java b/src/main/java/forestry/farming/tiles/TileGearbox.java index 652296b69..6e9e712e0 100644 --- a/src/main/java/forestry/farming/tiles/TileGearbox.java +++ b/src/main/java/forestry/farming/tiles/TileGearbox.java @@ -14,10 +14,10 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import forestry.api.farming.IFarmComponent; +import forestry.api.multiblock.IFarmComponent; +import forestry.api.multiblock.IFarmController; import forestry.core.tiles.IPowerHandler; import forestry.energy.EnergyManager; -import forestry.farming.multiblock.IFarmController; public class TileGearbox extends TileFarm implements IPowerHandler, IFarmComponent.Active { @@ -70,7 +70,7 @@ public class TileGearbox extends TileFarm implements IPowerHandler, IFarmCompone } if (workCounter >= WORK_CYCLES && (tickCount % 5 == 0)) { - IFarmController farmController = getFarmController(); + IFarmController farmController = getMultiblockLogic().getController(); if (farmController.doWork()) { workCounter = 0; previousDelays = 0; diff --git a/src/main/java/forestry/farming/tiles/TileHatch.java b/src/main/java/forestry/farming/tiles/TileHatch.java index 5b2b24300..1bf45440a 100644 --- a/src/main/java/forestry/farming/tiles/TileHatch.java +++ b/src/main/java/forestry/farming/tiles/TileHatch.java @@ -21,7 +21,7 @@ import net.minecraftforge.common.util.ForgeDirection; import cpw.mods.fml.common.Optional; -import forestry.api.farming.IFarmComponent; +import forestry.api.multiblock.IFarmComponent; import forestry.core.inventory.AdjacentInventoryCache; import forestry.core.tiles.AdjacentTileCache; import forestry.core.utils.InventoryUtil; @@ -58,7 +58,7 @@ public class TileHatch extends TileFarm implements ISidedInventory, IFarmCompone @Override public void updateServer(int tickCount) { if (tickCount % 40 == 0) { - IInventory productInventory = getFarmController().getFarmInventory().getProductInventory(); + IInventory productInventory = getMultiblockLogic().getController().getFarmInventory().getProductInventory(); if (!InventoryUtil.moveOneItemToPipe(productInventory, tileCache, dumpDirections)) { InventoryUtil.moveItemStack(productInventory, inventoryCache.getAdjacentInventories()); @@ -81,7 +81,7 @@ public class TileHatch extends TileFarm implements ISidedInventory, IFarmCompone @Optional.Method(modid = "BuildCraftAPI|statements") @Override public Collection getExternalTriggers(ForgeDirection side, TileEntity tile) { - if (!isConnected()) { + if (!getMultiblockLogic().isConnected()) { return Collections.emptyList(); } diff --git a/src/main/java/forestry/farming/tiles/TileValve.java b/src/main/java/forestry/farming/tiles/TileValve.java index 76c522f6a..4a19e7db7 100644 --- a/src/main/java/forestry/farming/tiles/TileValve.java +++ b/src/main/java/forestry/farming/tiles/TileValve.java @@ -54,6 +54,6 @@ public class TileValve extends TileFarm implements ILiquidTankTile, IFluidHandle @Override public ITankManager getTankManager() { - return getFarmController().getTankManager(); + return getMultiblockLogic().getController().getTankManager(); } } diff --git a/src/main/java/forestry/farming/triggers/TriggerLowFertilizer.java b/src/main/java/forestry/farming/triggers/TriggerLowFertilizer.java index 4a77ce9ea..e273faabb 100755 --- a/src/main/java/forestry/farming/triggers/TriggerLowFertilizer.java +++ b/src/main/java/forestry/farming/triggers/TriggerLowFertilizer.java @@ -43,7 +43,7 @@ public class TriggerLowFertilizer extends Trigger { } TileHatch tileHatch = (TileHatch) tile; - IInventory fertilizerInventory = tileHatch.getFarmController().getFarmInventory().getFertilizerInventory(); + IInventory fertilizerInventory = tileHatch.getMultiblockLogic().getController().getFarmInventory().getFertilizerInventory(); return InventoryUtil.containsPercent(fertilizerInventory, threshold); } } diff --git a/src/main/java/forestry/farming/triggers/TriggerLowGermlings.java b/src/main/java/forestry/farming/triggers/TriggerLowGermlings.java index 8857db06b..38eaed399 100644 --- a/src/main/java/forestry/farming/triggers/TriggerLowGermlings.java +++ b/src/main/java/forestry/farming/triggers/TriggerLowGermlings.java @@ -46,7 +46,7 @@ public class TriggerLowGermlings extends Trigger { } TileHatch tileHatch = (TileHatch) tile; - IInventory germlingsInventory = tileHatch.getFarmController().getFarmInventory().getGermlingsInventory(); + IInventory germlingsInventory = tileHatch.getMultiblockLogic().getController().getFarmInventory().getGermlingsInventory(); return InventoryUtil.containsPercent(germlingsInventory, threshold); } } diff --git a/src/main/java/forestry/farming/triggers/TriggerLowLiquid.java b/src/main/java/forestry/farming/triggers/TriggerLowLiquid.java index 2ccfb45b8..e62f0f4f7 100755 --- a/src/main/java/forestry/farming/triggers/TriggerLowLiquid.java +++ b/src/main/java/forestry/farming/triggers/TriggerLowLiquid.java @@ -47,7 +47,7 @@ public class TriggerLowLiquid extends Trigger { } TileHatch tileHatch = (TileHatch) tile; - ITankManager tankManager = tileHatch.getFarmController().getTankManager(); + ITankManager tankManager = tileHatch.getMultiblockLogic().getController().getTankManager(); IFluidTank tank = tankManager.getTank(0); if (tank.getCapacity() == 0) { diff --git a/src/main/java/forestry/farming/triggers/TriggerLowSoil.java b/src/main/java/forestry/farming/triggers/TriggerLowSoil.java index d61d8ba84..394ae641d 100755 --- a/src/main/java/forestry/farming/triggers/TriggerLowSoil.java +++ b/src/main/java/forestry/farming/triggers/TriggerLowSoil.java @@ -17,9 +17,9 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; import forestry.api.farming.IFarmInventory; +import forestry.api.multiblock.IFarmController; import forestry.core.triggers.Trigger; import forestry.core.utils.InventoryUtil; -import forestry.farming.multiblock.IFarmController; import forestry.farming.tiles.TileHatch; import buildcraft.api.statements.IStatementContainer; @@ -65,7 +65,7 @@ public class TriggerLowSoil extends Trigger { } TileHatch tileHatch = (TileHatch) tile; - IFarmController farmController = tileHatch.getFarmController(); + IFarmController farmController = tileHatch.getMultiblockLogic().getController(); IFarmInventory farmInventory = farmController.getFarmInventory(); if (parameter == null || parameter.getItemStack() == null) { diff --git a/src/main/java/forestry/plugins/PluginCore.java b/src/main/java/forestry/plugins/PluginCore.java index 0cda8f0b6..dae80d48e 100644 --- a/src/main/java/forestry/plugins/PluginCore.java +++ b/src/main/java/forestry/plugins/PluginCore.java @@ -30,6 +30,7 @@ import forestry.api.circuits.ChipsetManager; import forestry.api.core.ForestryAPI; import forestry.api.core.Tabs; import forestry.api.genetics.AlleleManager; +import forestry.api.multiblock.MultiblockManager; import forestry.api.storage.ICrateRegistry; import forestry.api.storage.StorageManager; import forestry.core.CreativeTabForestry; @@ -71,6 +72,7 @@ import forestry.core.items.ItemOverlay.OverlayInfo; import forestry.core.items.ItemPipette; import forestry.core.items.ItemWithGui; import forestry.core.items.ItemWrench; +import forestry.core.multiblock.MultiblockLogicFactory; import forestry.core.network.GuiId; import forestry.core.proxy.Proxies; import forestry.core.recipes.RecipeUtil; @@ -103,6 +105,8 @@ public class PluginCore extends ForestryPlugin { alleleRegistry.initialize(); AlleleHelper.instance = new AlleleHelper(); + + MultiblockManager.logicFactory = new MultiblockLogicFactory(); } @Override