Add API for multiblock components

This commit is contained in:
mezz committed 2015-11-10 02:44:18 -08:00
1 parent 14bdab069e
commit 731d15fbd5
56 files changed
+1828 -1951

No files matched your search

@@ -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;
}
}
@@ -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();
}
}
}
@@ -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<ContainerAlveary, TileAlvearyP
protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) {
super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY);
IAlvearyController alvearyController = inventory.getAlvearyController();
IAlvearyControllerInternal alvearyController = inventory.getMultiblockLogic().getController();
drawHealthMeter(guiLeft + 20, guiTop + 37, alvearyController.getHealthScaled(46), EnumTankLevel.rateTankLevel(alvearyController.getHealthScaled(100)));
}
@@ -46,7 +46,7 @@ public class GuiAlveary extends GuiForestryTitled<ContainerAlveary, TileAlvearyP
public void initGui() {
super.initGui();
IAlvearyController alvearyController = inventory.getAlvearyController();
IAlvearyControllerInternal alvearyController = inventory.getMultiblockLogic().getController();
ledgerManager.add(new OwnerLedger(ledgerManager, alvearyController));
}
@@ -16,6 +16,7 @@ import java.util.Set;
import net.minecraft.block.Block;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.StatCollector;
import net.minecraft.util.Vec3;
@@ -25,9 +26,6 @@ import net.minecraft.world.biome.BiomeGenBase;
import com.mojang.authlib.GameProfile;
import forestry.api.apiculture.BeeManager;
import forestry.api.apiculture.DefaultBeeModifier;
import forestry.api.apiculture.IAlvearyComponent;
import forestry.api.apiculture.IBeeGenome;
import forestry.api.apiculture.IBeeHousingInventory;
import forestry.api.apiculture.IBeeListener;
import forestry.api.apiculture.IBeeModifier;
@@ -35,22 +33,22 @@ import forestry.api.apiculture.IBeekeepingLogic;
import forestry.api.core.EnumHumidity;
import forestry.api.core.EnumTemperature;
import forestry.api.core.IClimateControlled;
import forestry.api.multiblock.IAlvearyComponent;
import forestry.api.multiblock.IMultiblockComponent;
import forestry.apiculture.AlvearyBeeModifier;
import forestry.apiculture.InventoryBeeHousing;
import forestry.core.access.EnumAccess;
import forestry.core.inventory.FakeInventoryAdapter;
import forestry.core.inventory.IInventoryAdapter;
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.proxy.Proxies;
import forestry.core.utils.BlockUtil;
public class AlvearyController extends RectangularMultiblockControllerBase implements IAlvearyController, IClimateControlled {
public class AlvearyController extends RectangularMultiblockControllerBase implements IAlvearyControllerInternal, IClimateControlled {
private final InventoryBeeHousing inventory;
private final IBeekeepingLogic beekeepingLogic;
@@ -64,13 +62,12 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple
private final Set<IBeeListener> beeListeners = new HashSet<>();
private final Set<IAlvearyComponent.Climatiser> climatisers = new HashSet<>();
private final Set<IAlvearyComponent.Active> activeComponents = new HashSet<>();
private final Set<IAlvearyComponent> 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<IAlvearyComponent> 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;
}
}
}
@@ -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;
}
}
@@ -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<IAlvearyComponent> 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;
@@ -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<IAlvearyComponent> getComponents();
int getHealthScaled(int i);
}
@@ -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<IAlvearyControllerInternal> 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);
}
}
@@ -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<MultiblockLogicAlveary> 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<? extends MultiblockControllerBase> 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<IBeeModifier> getBeeModifiers() {
return getAlvearyController().getBeeModifiers();
return getMultiblockLogic().getController().getBeeModifiers();
}
@Override
public Iterable<IBeeListener> 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);
}
}
@@ -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;
@@ -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;
@@ -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();
}
}
@@ -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;
@@ -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 {
@@ -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;
@@ -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) {
@@ -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);
}
}
}
@@ -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();
@@ -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);
}
}
@@ -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;
}
}
}
@@ -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<IMultiblockComponent> checkForDisconnections() {
return Collections.emptySet();
}
@Nonnull
@Override
public Set<IMultiblockComponent> detachAllBlocks() {
return Collections.emptySet();
}
@Override
public boolean isAssembled() {
return false;
}
@Override
public void reassemble() {
}
@Override
public String getLastValidationError() {
return null;
}
@Override
@Nonnull
public Collection<IMultiblockComponent> getComponents() {
return Collections.emptyList();
}
@Override
public void readFromNBT(NBTTagCompound nbttagcompound) {
}
@Override
public void writeToNBT(NBTTagCompound nbttagcompound) {
}
}
@@ -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<IMultiblockComponent> 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<IMultiblockComponent> detachAllBlocks();
}
@@ -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<? extends MultiblockControllerBase> 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<MultiblockControllerBase> 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();
}
@@ -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();
}
File diff suppressed because it is too large. Load diff
@@ -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<GameProfile> 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<GameProfile> 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);
}
}
@@ -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<T extends IMultiblockControllerInternal> implements IMultiblockLogic {
private final Class<T> controllerClass;
private boolean visited;
private boolean saveMultiblockData;
private NBTTagCompound cachedMultiblockData;
protected T controller;
protected MultiblockLogic(Class<T> 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<T> 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;
}
}
}
}
@@ -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();
}
}
@@ -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<MultiblockControllerBase> getControllersFromWorld(World world) {
public static Set<IMultiblockControllerInternal> getControllersFromWorld(World world) {
if (registries.containsKey(world)) {
return registries.get(world).getControllers();
}
@@ -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<MultiblockControllerBase> attachToNeighbors() {
Set<MultiblockControllerBase> 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<IMultiblockPart> 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;
}
}
@@ -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<T extends IMultiblockLogic> extends MultiblockTileEntityBase<T> 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;
}
}
@@ -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<IMultiblockComponent> getNeighboringParts(World world, IMultiblockComponent part) {
ChunkCoordinates partCoord = part.getCoordinates();
List<ChunkCoordinates> 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<IMultiblockComponent> 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;
}
}
@@ -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<MultiblockControllerBase> controllers; // Active controllers
private final Set<MultiblockControllerBase> dirtyControllers; // Controllers whose parts lists have changed
private final Set<MultiblockControllerBase> deadControllers; // Controllers which are empty
private final Set<IMultiblockControllerInternal> controllers; // Active controllers
private final Set<IMultiblockControllerInternal> dirtyControllers; // Controllers whose parts lists have changed
private final Set<IMultiblockControllerInternal> 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<IMultiblockPart> orphanedParts;
private Set<IMultiblockComponent> orphanedParts;
// A list of parts which have been detached during internal operations
private final Set<IMultiblockPart> detachedParts;
private final Set<IMultiblockComponent> 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<Long, Set<IMultiblockPart>> partsAwaitingChunkLoad;
private final HashMap<Long, Set<IMultiblockComponent>> 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<Set<MultiblockControllerBase>> mergePools = null;
List<Set<IMultiblockControllerInternal>> mergePools = null;
if (orphanedParts.size() > 0) {
Set<IMultiblockPart> orphansToProcess = null;
Set<IMultiblockComponent> 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<MultiblockControllerBase> compatibleControllers;
Set<IMultiblockControllerInternal> 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<Set<MultiblockControllerBase>> candidatePools = new ArrayList<>();
for (Set<MultiblockControllerBase> candidatePool : mergePools) {
List<Set<IMultiblockControllerInternal>> candidatePools = new ArrayList<>();
for (Set<IMultiblockControllerInternal> 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<MultiblockControllerBase> masterPool = candidatePools.get(0);
Set<MultiblockControllerBase> consumedPool;
Set<IMultiblockControllerInternal> masterPool = candidatePools.get(0);
Set<IMultiblockControllerInternal> 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<MultiblockControllerBase> mergePool : mergePools) {
for (Set<IMultiblockControllerInternal> 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<IMultiblockPart> newlyDetachedParts = controller.checkForDisconnections();
Set<IMultiblockComponent> 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<IMultiblockControllerInternal> attachToNeighbors(IMultiblockComponent part) {
Set<IMultiblockControllerInternal> 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<IMultiblockComponent> 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<IMultiblockPart> partSet;
long chunkHash = worldLocation.getChunkXZHash();
Set<IMultiblockComponent> 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<MultiblockControllerBase> getControllers() {
public Set<IMultiblockControllerInternal> 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<? extends IMultiblockPart> parts) {
private void addAllOrphanedPartsThreadsafe(Collection<? extends IMultiblockComponent> parts) {
synchronized (orphanedPartsMutex) {
orphanedParts.addAll(parts);
}
}
private String clientOrServer() {
return worldObj.isRemote ? "CLIENT" : "SERVER";
}
}
@@ -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<? extends RectangularMultiblockControllerBase> 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;
}
@@ -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;
}
}
}
@@ -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;
}
@@ -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;
@@ -68,7 +68,7 @@ public class ContainerFarm extends ContainerSocketed<TileFarm> {
}
public IFluidTank getTank(int slot) {
return tile.getFarmController().getTankManager().getTank(slot);
return tile.getMultiblockLogic().getController().getTankManager().getTank(slot);
}
}
@@ -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<ContainerFarm, TileFarm> {
@@ -52,7 +52,7 @@ public class GuiFarm extends GuiForestry<ContainerFarm, TileFarm> {
@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<ContainerFarm, TileFarm> {
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<ContainerFarm, TileFarm> {
}
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<ContainerFarm, TileFarm> {
}
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()));
}
};
}
@@ -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;
@@ -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<ItemStack> harvested = crop.harvest();
if (harvested == null) {
Log.fine("Failed to harvest crop: " + crop.toString());
Log.fine("Failed to harvest crop: " + crop);
return true;
}
@@ -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;
}
}
@@ -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();
@@ -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<IFarmControllerInternal> 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);
}
}
@@ -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 {
@@ -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<MultiblockLogicFarm> 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<? extends MultiblockControllerBase> 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<String> 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);
}
}
@@ -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);
}
@@ -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;
@@ -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<ITriggerExternal> getExternalTriggers(ForgeDirection side, TileEntity tile) {
if (!isConnected()) {
if (!getMultiblockLogic().isConnected()) {
return Collections.emptyList();
}
@@ -54,6 +54,6 @@ public class TileValve extends TileFarm implements ILiquidTankTile, IFluidHandle
@Override
public ITankManager getTankManager() {
return getFarmController().getTankManager();
return getMultiblockLogic().getController().getTankManager();
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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) {
@@ -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) {
@@ -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